Q: Using the split function in Python I am working with the CSV module, and I am writing a simple program which takes the names of several authors listed in the file, and formats them in this manner: john.doe
So far, I've achieved the results that I want, but I am having trouble with getting the code to exclude titles such as "Mr."Mrs", etc. I've been thinking about using the split function, but I am not sure if this would be a good use for it.
Any suggestions? Thanks in advance!
Here's my code so far:
import csv

books = csv.reader(open("books.csv","rU"))

for row in books:

     print '.'.join ([item.lower() for item in [row[index] for index in (1, 0)]])

A: It depends on how much messy the strings are, in worst cases this regexp-based solution should do the job:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
x.sub("", text)

(I'm using re.compile() here since for some reasons Python 2.6 re.sub doesn't accept the flags= kwarg..)
UPDATE: I wrote some code to test that and, although I wasn't able to figure out a way to automate results checking, it looks like that's working fine.. This is the test code:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
names = ["".join([a,b,c,d]) for a in ['', ' ', '   ', '..', 'X'] for b in ['mr', 'Mr', 'miss', 'Miss', 'mrs', 'Mrs', 'ms', 'Ms'] for c in ['', '.', '. ', ' '] for d in ['Aaaaa', 'Aaaa Bbbb', 'Aaa Bbb Ccc', ' aa ']]
print "\n".join([" => ".join((n,x.sub('',n))) for n in names])

A: Depending on the complexity of your data and the scope of your needs you may be able to get away with something as simple as stripping titles from the lines in the csv using replace() as you iterate over them.
Something along the lines of:
titles = ["Mr.", "Mrs.", "Ms", "Dr"] #and so on

for line in lines:
    line_data = line
    for title in titles:
        line_data = line_data.replace(title,"")
    #your code for processing the line

This may not be the most efficient method, but depending on your needs may be a good fit.
How this could work with the code you posted (I am guessing the Mr./Mrs. is part of column 1, the first name):
import csv

books = csv.reader(open("books.csv","rU"))

for row in books:
     first_name = row[1]
     last_name = row[0]
     for title in titles:
          first_name = first_name.replace(title,"")
     print '.'.(first_name, last_name)


Q: Cannot reach spring-boot-starter-parent dependencies I'm using https://start.spring.io/ to create Spring Boot project and in development I can't reach spring boot starters these dependencies:
<dependency>
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws-support</artifactId>
        <version>3.0.10.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
        <version>5.3.2</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
</dependency>

<dependency>
    <groupId>com.sun.xml.messaging.saaj</groupId>
    <artifactId>saaj-impl</artifactId>
        <version>1.5.2</version>
</dependency>

I get warning messages:
Overriding managed version 5.3.1 for spring-oxm
Overriding managed version 5.3.1 for spring-oxm
Duplicating managed version 4.5.13 for httpclient
Duplicating managed version 1.5.2 for saaj-impl

I've searched for how to fix it, one of the workaround some people refers to use <!--$NO-MVN-MAN-VER$ --> at the end of the </version> tag to ignore the warning.
My question is how to make these (and other future dependencies) be seen from spring boot?
EDIT #1: pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>xx.xx.xxx</groupId>
    <artifactId>yyyy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>yyyy</name>
    <description>zzzzz</description>

    <properties>
        <java.version>11</java.version>

        <apache.cxf.version>3.4.1</apache.cxf.version>
        <apache.httpcomponents.version>4.5.13</apache.httpcomponents.version>
        <jaxb2.maven2.version>0.14.0</jaxb2.maven2.version>

        <springframework.version>5.3.2</springframework.version>
        <springframework.ws.version>3.0.10.RELEASE</springframework.ws.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${apache.cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>${jaxb2.maven2.version}</version>
            <type>maven-plugin</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-support</artifactId>
            <version>${springframework.ws.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${apache.httpcomponents.version}</version>
        </dependency>
    </dependencies>
</project>

A: Solution is to remove <version>...</version>, let Spring boot handle the versions.
Thanks to tgdavies.


Q: XCode 6 infinite building I have really strange problem. I'm writing swift ios project. It has some swift files. One of them is internet requester, which contains some small methods (5-6 rows). If i write 8 methods, my project builds in a second and runs well. But if i add extra method (it can be empty), builder stucks at "compiling swift files" for an inifinite time, PC starts lagging hardly and sometimes "source kit service" terminates. Can you help me?


Q: Shim config not supported in Node, may or may not work I am working on a project which works fine on browser , now we are trying to run it on server side using nodejs.
I have below configurations :

*

*node : v4.2.1

*npm : v2.14.7

and when I am trying to run my project on nodejs , getting the error as :
Shim config not supported in Node, may or may not work

Since the modules and dependencies (AMD) are working fine on browser I assume the shims config are correct .
Please let me know if I am missing something ?
https://github.com/jrburke/requirejs/issues/1443
Regards
Manish

A:
Since the modules and dependencies (AMD) are working fine on browser I assume the shims config are correct .

That's an incorrect assumption. The problem is that Node.js operates with a set of basic assumptions that are very different from how browsers work. Consider this statement:
var foo = "something";

If you execute this at the top of your scope in Node.js, you've created a variable which is local to the file Node is executing. If you really want to make it global, then you have to explicitly shove it into global.
Now, put the same statement at the top of the scope of a script you load in a browser with the script element. The same statement creates a global variable. (The variable is global whether or not var is present.)
RequireJS' shim configuration is used for scripts that expect the second behavior. They expect a) that anything they declare at the top of their scope is leaked to the global space and b) that anything that has been leaked to the global space by scripts they depend on is available in the global space. Both expectations are almost always false in Node. (It would not be impossible for a module designed for node to manipulate global but that's very rare.)
The author of RequireJS explained in this issue report that he does not see it advisable for RequireJS to try to replicate the browser behavior in Node. I agree with him. If you want to run front-end code in the back-end you should replace those modules that need shim in the browser with modules that are designed to run in Node.


Q: Authentication not working with Supabase and Node.js I am not sure even this is possible but I am trying to use Supabase with Node.js. I get the code from a React front-end, this link, which works okay.
Below is my code
client.js
const { createClient } = require('@supabase/supabase-js')

const supabaseUrl = "MY_URL"
const public_anon_key = "MY_ANON_KEY"
const supabase = createClient(supabaseUrl,public_anon_key)

exports.supabase = supabase

app.js
const { supabase }  = require('./client')

async function signOut() {
        /* sign the user out */
        await supabase.auth.signOut();
}

async function signInWithGithub() {
        /* authenticate with GitHub */
        await supabase.auth.signIn({
                provider: 'github'
        });
}

async function printUser() {
        const user = supabase.auth.user()
        console.log(user.email)
}

signInWithGithub()
printUser()
signOut()

I am new to Node.js and I suspect something wrong with Promises is missing.
Is it possible to retrieve the user data from Supabase, if so, what is my code missing?
Thanks
Edit : title

A: I don't know what Supabase does but the problem seems to be Promise related
Try to change your app.js as follow
const { supabase }  = require('./client')

function signOut() {
        /* sign the user out */
        supabase.auth.signOut();
}

function signInWithGithub() {
        /* authenticate with GitHub */
        return  supabase.auth.signIn({
                provider: 'github'
        });
}
function printUser() {
        const user = supabase.auth.user()
        console.log(user.email)
}

signInWithGithub().then(() => {
   printUser()
   return signOut()

})


Q: C++ and member function pointers
I'm trying to send an address of a member function to my "Thread" class so I can activate it from there.
I read that I can use functors but I want it to be generic in a way that I can send it to my "Thread" constructor and functors need templates, so it won't be enough for me...
Does anybody know a way to do this?
thanks :)

A: If I may suggest a different approach: derive from your thread class and make a virtual Run() function.
The reason is that although it is possible to call a function pointer from the static thread entry function, you face problem after problem. For example, you can solve the problem of having the right function signature with templates and variadic parameters, but it is not of much avail, because the entry function won't know what to send to your function.
On the other hand, deriving from Thread is easy and straightforward. You put into the contructor whatever the thread needs to know. Or, optionally, you can call any number of other functions and set any number of members before you create the thread. Once you do create the thread, the static thread entry function will simply call the virtual Run function. Now... the Run function is part of the thread object, so it knows anything the class knows -- no problem.
The extra overhead of a single virtual function call and of one pointer in the vtable is also ridiculously small compared to how easy it is.

A: I suggest you look at the treatment of this topic in the C++ FAQ Lite. In short, pointers to member functions are problematic, but there are several work-arounds, as well as a number of reasons why they should be avoided for certain purposes.

A: Finally I decided to use a stub function as suggested in this thread:
Create thread is not accepting the member function
thanks everbody :)


Q: Why does (ps -f) create no subshell but a separate process? I need some help because I don't get something. From what I read from Internet, a subshell is created when we execute a shell script or if we run command in brackets: ( )
I tried to test this with a script which contains only the following command:
ps -f

When I run it I see the following result:
ID      PID  PPID  C STIME TTY          TIME CMD
me     2213  2160  0 08:53 pts/14   00:00:00 bash
me     3832  2213  0 18:41 pts/14   00:00:00 bash
me     3833  3832  0 18:41 pts/14   00:00:00 ps -f

Which is good, because I see that my bash process has spawned another bash process for my script.
But when I do:
( ps -f )

it produces:
UID     PID  PPID  C STIME TTY          TIME CMD
me     2213  2160  0 08:53 pts/14   00:00:00 bash
me     3840  2213  0 18:46 pts/14   00:00:00 ps -f

So if brackets spawn a subshell why it is not shown in the processes? And why does ps -f is counted as another process? Does every command run as a separate process?

A: It seems you've caught bash in a little bit of an optimization.  if a subshell contains only a single command, why really make it a subshell?
$ ( ps -f )
UID        PID  PPID  C STIME TTY          TIME CMD
jovalko  29393 24133  0 12:05 pts/10   00:00:00 bash
jovalko  29555 29393  0 12:07 pts/10   00:00:00 ps -f

However, add a second command, say : (the bash null command, which does nothing) and this is the result:
$ ( ps -f ; : )
UID        PID  PPID  C STIME TTY          TIME CMD
jovalko  29393 24133  0 12:05 pts/10   00:00:00 bash
jovalko  29565 29393  0 12:08 pts/10   00:00:00 bash
jovalko  29566 29565  0 12:08 pts/10   00:00:00 ps -f

One of the main reasons to use a subshell is that you can perform operations like I/O redirection on a group of commands instead a single command, but if your subshell contains only a single command there's not much reason to really fork a new bash process first.
As to ps counting as a process, it varies. Many commands you use like ls, grep, awk are all external programs. But, there are builtins like cd, kill, too.
You can determine which a command is in bash using the type command:
$ type ps
ps is hashed (/bin/ps)
$ type cd
cd is a shell builtin

A: The main part of the question is:

Does every command run as a separate process?

YES!. Every command what isn't built-in into bash (like declare and such), runs as separate process. How it is works?
When you type ps and press enter, the bash analyze what you typed, do usual things as globbing, variable expansionas and such, and finally when it is an external command

*

*the bash forks itself.

The forking mean, than immediatelly after the fork, you will have two identical bash processes (each one with different process ID (PID)) - called as "parent" and "child", and the only difference between those two running bash programs is, than the "parent" gets (return value from the fork) the PID of the child but the child don't know the PID of the parent. (fork for the child returns 0).

*

*after the fork, (bash is written this way) - the child replaces itself with the new program image (such: ps) - using the exec call.

*after this, the child bash of course doesn't exist anymore, and running only the newly executed command - e.g. the ps.

Of course, when the bash going to fork itself, do many other things, like I/O redirections, opens-closes filehandles, changes signal handling for the child and many-many other things.


Q: customizing the NSPredicateEditor I want to customize the NSPredicateEditorRowTemplate, but I needn't the subtraction sign in the first RowTemplate, the second, and the third, like the Finder application.

A: If you tell the NSPredicateEditor that it cannot remove all the rows in the editor, then the editor will automatically remove the (-)  button when necessary.
You can do this by unchecking the "Can Remove All Rows" checkbox when editing the predicate editor in a xib, or by doing it programmatically with the -setCanRemoveAllRows: method.


Q: Python Selenium: How can I print the link? How can I print the value of the href attribute?

How can I print the link aaaaa.pdf with python selenium?
HTML:

A: You can do like this:
print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href'))

A: Try the below:
   pName = driver.find_element_by_css_selector(".xxxx").text
    print(pName)

or
   pName = driver.find_element_by_css_selector(".xxxx").get_attribute("href")
   print(pName)

A: div.xxxx a

first, check if this CSS_SELECTOR is representing the desired element.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the css and see, if your desired element is getting highlighted with 1/1 matching node.
If yes, then use explicit waits:
wait = WebDriverWait(driver, 20)
print(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.xxxx a"))).get_attribute('href'))

Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: The value of the href attribute i.e. aaaaa.pdf is within the  tag which is the only descendant of the
 tag.

Solution
To print the value of the href attribute you can use either of the following locator strategies:

*

*Using css_selector:
print(driver.find_element(By.CSS_SELECTOR, "div.xxxx > a").get_attribute("href"))

*Using xpath:
print(driver.find_element(By.XPATH, "//div[@class='xxxx']/a").get_attribute("href"))

To extract the value ideally you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.xxxx > a"))).get_attribute("href"))

*Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xxxx']/a"))).get_attribute("href"))

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


Q: How to get Cartesian product from different group member? As the title mentioned, I have some problems in C++.
If I have a std::vector<std::vector<int> >tmpvec
vector < vector <int> > tmpvec = {
    {1,2,3},
    {4,5},
    {6,7,8,9},
    {10,11}
};

how can I generate all possible combination of a vector of vector
1,4,6,10

1,4,6,11

1,4,7,10

1,4,7,11

......

There are at most 48 different combination.

A: You may do
bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::vector<int>>& v,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        // TODO: manage case where v[i] is empty if relevant.
        std::cout << v[i][it[i]] << " ";
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::vector<int>>& v)
{
    std::vector<std::size_t> it(v.size(), 0u);

    do {
        do_job(v, it);
    } while (increase(v, it));
}

Live Demo


Q: How to correctly move ownership from raw pointer to std::unique_ptr? My approach is:
class SomeClass
{
    std::vector<std::unique_ptr<MyObject>> myObjects;
public:
    void takeOwnership(MyObject *nowItsReallyMyObject)
    {
        myObjects.emplace_back(std::move(nowItsReallyMyObject));
    }
};

Am I doing everything correctly or are there any better solutions?

A: You should accept the unique_ptr from the get-go:
class SomeClass
{
    std::vector<std::unique_ptr<MyObject>> myObjects;
public:
    // tells the world you 0wNz this object
    void takeOwnership(std::unique_ptr<MyObject> myObject)
    {
        myObjects.push_back(std::move(myObject));
    }
};

This way you make it clear you take ownership and you also help other programmers to avoid using raw pointers.
Further reading: CppCoreGuidelines R.32

A: The move is redundant.
Myself, I'd do this:
void takeOwnership(std::unique_ptr<MyObject> nowItsReallyMyObject)
{
    myObjects.emplace_back(std::move(nowItsReallyMyObject));
}

because I would want to move the unique_ptr ownership semantics as far "out" as possible.
I might write this utility function:
template<class T>
std::unique_ptr<T> wrap_in_unique( T* t ) {
  return std::unique_ptr<T>(t);
}

so callers can:
foo.takeOwnership(wrap_in_unique(some_ptr));

but even better, then can push the borders of unique_ptr semantics out as far as they reasonably can.
I might even do:
template<class T>
std::unique_ptr<T> wrap_in_unique( T*&& t ) {
  auto* tmp = t;
  t = 0;
  return std::unique_ptr<T>(tmp);
}
template<class T>
std::unique_ptr<T> wrap_in_unique( std::unique_ptr<T> t ) {
  return std::move(t);
}

which lets callers transition their T* into unique_ptrs easier.  All of their T*->unique_ptr<T> is now wrapped in a std::move, and zeros the source pointer.
So if they had
struct I_am_legacy {
  T* I_own_this = 0;
  void GiveMyStuffTo( SomeClass& sc ) {
    sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
  }
};

the code can be transformed into:
struct I_am_legacy {
  std::unique_ptr<T> I_own_this;
  void GiveMyStuffTo( SomeClass& sc ) {
    sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
  }
};

and it still compiles and works the same.  (Other interaction with I_own_this may have to change, but part of it will already be unique_ptr compatible).


Q: Delete a record in MySql database by clicking a dynamically generated button in Winforms I'm new to programming and hoping someone will help me with my problem. I'm developing an e-commerce application and looking to add buttons to a dynamically generated list of items in the cart. I used a loop statement to go through each row of the table and show the results but I don't know how to remove a record once the user clicks a button. Here is the code for the cart. Please advise. end result screenshot
 private void CartPage_Load(object sender, EventArgs e)
    {

        DB db = new DB();

        DataTable table = new DataTable();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand("SELECT * FROM `Product_Info` WHERE `Cart_Number` = @cart", db.getConnection());

        command.Parameters.Add("@cart", MySqlDbType.Int32).Value = Global.cart;

        adapter.SelectCommand = command;
        adapter.Fill(table);

        int rowcount = table.Rows.Count;

        if (rowcount > 0)
        {

            //MessageBox.Show("You have products");
            int Left = 45;
            int Top = 100;
            int rownumb = 0;

            for (int i = 0; i < rowcount; i++)
            {

                Label ProdName_label = new Label();
                this.Controls.Add(ProdName_label);
                Label Name_label = new Label();
                this.Controls.Add(Name_label);

                Label ProdNo_label = new Label();
                this.Controls.Add(ProdNo_label);
                Label No_label = new Label();
                this.Controls.Add(No_label);

                Label ProdQty_label = new Label();
                this.Controls.Add(ProdQty_label);
                Label Qty_label = new Label();
                this.Controls.Add(Qty_label);

                Label ProdPrice_label = new Label();
                this.Controls.Add(ProdPrice_label);
                Label Price_label = new Label();
                this.Controls.Add(Price_label);

                Label PrdSub_label = new Label();
                this.Controls.Add(PrdSub_label);
                Label Sub_label = new Label();
                this.Controls.Add(Sub_label);

                Button Remove_button = new Button();
                this.Controls.Add(Remove_button);

                Panel Product_panel = new Panel();
                this.Controls.Add(Product_panel);

                Product_panel.BackColor = System.Drawing.Color.White;
                Product_panel.Controls.Add(Remove_button);
                Product_panel.Controls.Add(PrdSub_label);
                Product_panel.Controls.Add(Sub_label);
                Product_panel.Controls.Add(ProdNo_label);
                Product_panel.Controls.Add(No_label);
                Product_panel.Controls.Add(ProdQty_label);
                Product_panel.Controls.Add(Qty_label);
                Product_panel.Controls.Add(ProdPrice_label);
                Product_panel.Controls.Add(Price_label);
                Product_panel.Controls.Add(ProdName_label);
                Product_panel.Controls.Add(Name_label);
                Product_panel.Location = new System.Drawing.Point(Left, Top);
                Product_panel.Name = "Product_panel";
                Product_panel.Size = new System.Drawing.Size(200, 200);
                Product_panel.TabIndex = 2;

                //
                // ProdName_label
                //

                ProdName_label.AutoSize = true;
                ProdName_label.Location = new System.Drawing.Point(28, 25);
                ProdName_label.Name = "ProdName_label";
                ProdName_label.Size = new System.Drawing.Size(195, 32);
                ProdName_label.TabIndex = 3;
                ProdName_label.Text = "Product Name:";

                Name_label.AutoSize = true;
                Name_label.Location = new System.Drawing.Point(145, 25);
                Name_label.Name = "Name_label";
                Name_label.Size = new System.Drawing.Size(195, 32);
                Name_label.TabIndex = 3;
                Name_label.Text = table.Rows[rownumb]["Prod_Name"].ToString();

                ////
                //// ProdNo_label
                ////
                ProdNo_label.AutoSize = true;
                ProdNo_label.Location = new System.Drawing.Point(28, 45);
                ProdNo_label.Name = "ProdNo_label";
                ProdNo_label.Size = new System.Drawing.Size(220, 32);
                ProdNo_label.TabIndex = 4;
                ProdNo_label.Text = "Product Number:";

                No_label.AutoSize = true;
                No_label.Location = new System.Drawing.Point(145, 45);
                No_label.Name = "No_label";
                No_label.Size = new System.Drawing.Size(220, 32);
                No_label.TabIndex = 4;
                No_label.Text = "1";
                No_label.Text = table.Rows[rownumb]["Prod_Number"].ToString();

                //
                // ProdPrice_label
                //
                ProdPrice_label.AutoSize = true;
                ProdPrice_label.Location = new System.Drawing.Point(28, 65);
                ProdPrice_label.Name = "ProdPrice_label";
                ProdPrice_label.Size = new System.Drawing.Size(80, 32);
                ProdPrice_label.TabIndex = 4;
                ProdPrice_label.Text = "Price:";

                Price_label.AutoSize = true;
                Price_label.Location = new System.Drawing.Point(145, 65);
                Price_label.Name = "Price_label";
                Price_label.Size = new System.Drawing.Size(80, 32);
                Price_label.TabIndex = 4;
                Price_label.Text = table.Rows[rownumb]["Prod_Price"].ToString();

                ////
                //// ProdQty_label
                ////
                ProdQty_label.AutoSize = true;
                ProdQty_label.Location = new System.Drawing.Point(28, 85);
                ProdQty_label.Name = "ProdQty_label";
                ProdQty_label.Size = new System.Drawing.Size(173, 32);
                ProdQty_label.TabIndex = 4;
                ProdQty_label.Text = "Product Q-ty:";

                Qty_label.AutoSize = true;
                Qty_label.Location = new System.Drawing.Point(145, 85);
                Qty_label.Name = "ProdQty_label";
                Qty_label.Size = new System.Drawing.Size(173, 32);
                Qty_label.TabIndex = 4;
                Qty_label.Text = table.Rows[rownumb]["Prod_Qty"].ToString();

                ////
                //// PrdSub_label
                ////
                PrdSub_label.AutoSize = true;
                PrdSub_label.Location = new System.Drawing.Point(28, 105);
                PrdSub_label.Name = "PrdSub_label";
                PrdSub_label.Size = new System.Drawing.Size(226, 32);
                PrdSub_label.TabIndex = 5;
                PrdSub_label.Text = "Product Subtotal:";

                Sub_label.AutoSize = true;
                Sub_label.Location = new System.Drawing.Point(145, 105);
                Sub_label.Name = "Sub_label";
                Sub_label.Size = new System.Drawing.Size(226, 32);
                Sub_label.TabIndex = 5;
                Sub_label.Text = table.Rows[rownumb]["Prod_Subtotal"].ToString();

                ////
                //// Remove_button
                ////
                Remove_button.BackColor = System.Drawing.Color.LightGreen;
                Remove_button.Location = new System.Drawing.Point(40, 150);
                Remove_button.Name = "Remove_button" + Convert.ToString(rownumb);
                Remove_button.Size = new System.Drawing.Size(120, 34);
                Remove_button.TabIndex = 3;
                Remove_button.Text = "Remove";
                Remove_button.UseVisualStyleBackColor = false;
                Remove_button.Click += new System.EventHandler(Remove_button_Click);

                Top += 220;
                rownumb += 1;
            }

        }

        else
        {
            MessageBox.Show("You don't have any products in your cart");
        }

    }

    private void Remove_button_Click(object sender, EventArgs e)
    {

        MessageBox.Show("Are you sure you want to remove this item?", "Remove", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

    }

A: Your issue apparently is "how do I know which button was clicked?".
You already know how to create a button, add it to the form and attach a click-handler:
   Button Remove_button = new Button();
   this.Controls.Add(Remove_button);

   Remove_button.Name = "Remove_button" + Convert.ToString(rownumb);
   Remove_button.Click += new System.EventHandler(Remove_button_Click);

To know which button was clicked, you can set its .Tag property:
   Remove_button.Tag = Convert.ToString(rownumb); // or whatever the primary key for this row is

Next, in the click handler, you need to read that property.
Fortunately, when the button calls the handler, it uses (a reference to) itself as the sender parameter.
So when you cast that sender to a Button, you get the real button that originated the command and you can access all its properties, such as .Tag:
    private void Remove_button_Click(object sender, EventArgs e)
    {
        Button clickedButton = (Button)sender;
        string rownumb = clickedButton.Tag;

        DialogResult selection = MessageBox.Show("Are you sure you want to remove item #" + rownumb + "?",
              "Remove", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

        // TODO execute a DELETE command for this row when the user clicked OK
    }


Q: determining the character set to use my delphi 2009 app has a basic translation system that uses GNUGetText.  i had used some win API calls to prepare the fonts.  i thought it was working correctly until recently when someone from Malta had a problem with my app failing precisely in this area.  my app is used globally.  some of this code may have become obsolete since d2009 uses unicode.
is all of this truly necessary in order for my app to work in all locales?
TForm.Font.Charset
it's been my understanding i must set the TForm instance's Font.Charset according to the user's locale.  is this correct?
TranslateCharsetInfo( ) win API function
delphi 2009's windows.pas says:
function TranslateCharsetInfo(var lpSrc: DWORD; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL;

delphi 5's windows.pas says:
function TranslateCharsetInfo(var lpSrc: DWORD; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL; stdcall;

from microsoft's MSDN:
BOOL TranslateCharsetInfo(
  __inout  DWORD FAR *lpSrc,
  __out    LPCHARSETINFO lpCs,
  __in     DWORD dwFlags
);

back when this code was written (back in delphi 5 days), the word was the inport of the function was incorrect and the correct way was:
function TranslateCharsetInfo(lpSrc: Pointer; var lpCs: TCharsetInfo;
dwFlags: DWORD): BOOL; stdcall; external gdi32;

notice that the d2009 windows.pas file copy is not stdcall.  which declaration of TranslateCharsetInfo should i be using?
The code
that aside, essentially i've been doing the following:
var
  Buffer : PChar;
  iSize, iCodePage : integer;
  rCharsetInfo: TCharsetInfo;
begin
  // SysLocale.DefaultLCID = 1802
  iSize := GetLocaleInfo(SysLocale.DefaultLCID, LOCALE_IDefaultAnsiCodePage,
              nil, 0);
  // size=14
  GetMem(Buffer, iSize);
  try
    if GetLocaleInfo(SysLocale.DefaultLCID, LOCALE_IDefaultAnsiCodePage, Buffer,
      iSize)=0 then
        RaiseLastOSError;

    // Buffer contains 0 so codepage = 0
    iCodePage:=Result := StrToInt(string(Buffer));
  finally
    FreeMem(Buffer);
  end;

  // this function is not called according to MSDN's directions for
  // TCI_SRCCODEPAGE and the call fails.
  if not TranslateCharsetInfo(Pointer(iCodePage), rCharsetInfo,
    TCI_SRCCODEPAGE) then
      RaiseLastOSError;

  // acts upon the form
  Font.Charset:= rCharsetInfo.ciCharset;
end;

i just don't know enough about this...strangely enough, years ago when i wrote this, i was persuaded that it was working correctly.  the results of...failing to check API call return code...
isn't there a smarter way to do all this?  doesn't the RTL/VCL do most/all of this automatically?  my instincts tell me i'm working too hard on this...
thank you for your help!

A: Actually, I'm not sure about Delphi 2009, but MSDN says:

Note that DEFAULT_CHARSET is not a real charset; rather, it is a constant akin to NULL that means "show characters in whatever charsets are available."

So my guess is that you just need to remove all the code that you mentioned, and it should work.

A: Not a really answer to this question, but 'small' note on possible memory corruption with this code under D2009+. Function GetLocaleInfo "MSDN: Returns the number of characters retrieved in the locale data buffer..." not BYTES, so under D2009+ you MUST allocate 2 bytes for each characters. Best way to do this is write:
GetMem(Buffer, iSize * SizeOf(Char)); //This will be safe for all delphi versions

Without this you can lead to unpredicted AVs (D2009+), function GetLocaleInfo can overwrite your memory, because you have allocated too small buffer.
Also I don't understant why you're trying change charset to user locale one, I think that you should change charset to your destination translation (like, your program is set to be translated to Russian language, but running on English OS, then you need change charset to RUSSIAN_CHARSET, not ANSI_CHARSET). And under D2009+ I not sure if this is needed, but I might be wrong.


Q: .net windows service local application data is different then in normal app In normal console app I have this
Environment.SpecialFolder.LocalApplicationData is C:\Users\Simon\AppData\Local\
In Windows service
Environment.SpecialFolder.LocalApplicationData is C:\Windows\system32\config\systemprofile\AppData\Local\
How can I specify same path in both type of application?

A: Remember that the services run under a different user profile (can be a LOCAL_SERVICE, NETWORK_SERVICE, etc.) If you'd like them to be the same, run the service under your user profile (You can specify this ServiceProcessInstaller.Account property when you create the installer, or in the Services manager of windows).


Q: What does the BluetoothGATTSetCharacteristicValue ReliableWriteContext parameter actually do? Using C++ VS2017 Win10...
I am testing some code to set a characteristic value on a BLE device.  I had originally had the default function call
HRESULT hr = BluetoothGATTSetCharacteristicValue(
                hBleService.get(),
                _pGattCharacteristic,
                gatt_value,
                NULL,
                BLUETOOTH_GATT_FLAG_NONE);

I had to switch the flag to BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE to get any sets to take place even though IsWritable and IsReadable were the only 2 properties set showing true but that is a different story and another topic.
Anyway,  before I found the problem with the flag I had tried to use the ReliableWriteContext parameter so the code changed to
    HANDLE hDevice = _bleDeviceContext.getBleDeviceHandle();
    BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext = NULL;
    HRESULT hr1 = BluetoothGATTBeginReliableWrite(hDevice,
        &ReliableWriteContext,
        BLUETOOTH_GATT_FLAG_NONE);

    HRESULT hr = BluetoothGATTSetCharacteristicValue(
        hBleService.get(),
        _pGattCharacteristic,
        gatt_value,
        ReliableWriteContext,
        BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE);

    if (NULL != ReliableWriteContext) {
        BluetoothGATTEndReliableWrite(hDevice,
            ReliableWriteContext,
            BLUETOOTH_GATT_FLAG_NONE);
    }

Once I fixed the flag issue my BluetoothGATTSetCharacteristicValue() function would work with either the NULL or the ReliableWriteContext parameters.  No difference that I could see.
My question is,then, what does the ReliableWriteContext do exactly?  MS docs only say:

The BluetoothGATTBeginReliableWrite function specifies that reliable
writes are about to begin.

Well that doesn't tell me anything.  So should I keep the reliable writes because the word "Reliable" sure sounds like it is something that I want? Or do I not use it because it does not seem to be necessary>
Any insight would be appreciated.
Ed


Q: Create a list of selected objects from S3 bucket with Boto3 I have a S3 bucket with this structure:
data/date=1900-01-01-00/id=abc123def/file1.parquet
data/date=1900-01-01-00/id=ghi456jkl/file2.parquet
data/date=2021-07-11-00/id=mno789pqr/file3.parquet
data/date=2021-07-11-00/id=stu123vwy/file4.parquet
.
.
.

the files in the folder date=1900-01-01-00 are dummy files, the others are "real file" coming from data acquisition.
I would like to create a list of S3Objects containing just the first dummy file and the first real file.
This is the code I wrote:
def __data_list(self):
    datastore_bucket = s3_resource.Bucket(S3_DATASTORE_BUCKET)

    len_dummy_file = len(
        list(
            datastore_bucket.objects.filter(
                Prefix="data/date=1900-01-01-00/"
            )
        )
    )

    data_list = list(
        datastore_bucket.objects.filter(
            Prefix="data/"
        ).limit(len_dummy_file + 1)
    )

    return [data_list[0], data_list[-1]]

I can't know the number of dummy files and I could have thousands of real files, so read all the bucket could take a lot of time and I want to avoid it.
Does anyone know a better way to create the list?

A: You can do logic on the Key returned from the object list:
first_dummy = None
first_real = None

for object in s3_resource.Bucket(BUCKET_NAME).objects.filter(Prefix='data/'):
  if not first_dummy and 'date=1900-01-01-00' in object.key:
    first_dummy = object.key
  elif not first_real and 'date=1900-01-01-00' not in object.key:
    first_real = object.key

  if first_dummy and first_real:
    break

print(first_dummy, first_real)


Q: My script does not detect the redirection URL this is the case :
Needed a responsive html5 audio player and the best I found was one made by a person called Osvalds .
The first problem I found was that the " autoplay " attribute reproduced the same song twice in Firefox. I could fix this by adding a few lines of javascript (though the play button does not change the song to be played ) .
The second problem (and this is where I need help) is that the javascript does not detect or failure with URL redirect but it does work with the final URL.
I mean, my php variable to return a URL like:
" http://www.goear.com/action/sound/get/104fc33 "
But this in turn redirects me to a final URL:
"http://live1.goear.com/listen/d6a9757a390b5d49b8584288d5589318/52eac3f1/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3"
Ok , when I used a flash-based player , there was no problem . And when I use the "audio" tag without the script there is no problem .
I tried to fix this by passing php variable to " CURL " and it worked!
But it turned out that my host does not support the " CURLOPT_FOLLOWLOCATION " .
That was another option to look at the javascript source code audio player .
This is my html:
          <audio  id="audiobox" preload="auto" controls loop>
            <source src="http://live1.goear.com/listen/d941195f4a5f477381d8a95ba666a0cb/52eac666/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3">

            <script type="text/javascript">
              function play() {
              document.getElementById('audiobox').play();
              }
                play();
            </script>

          </audio>

        <script src="jquery-1.11.0.min.js"></script>
        <script src="audioplayer.js"></script>

In this direction is the code javascript audio player:
I'm no expert in javascript but I think the problem must be in line 56: "this.attr AudioFile = $ ('src')." I think if I could define the php variable directly in the script it could run.
But do not know if there's another way:
http://pastebin.com/WxnTQmXa
This left a jsFiddle example, in this case the "src" attribute is calling the final URL that ends in MP3 and as you can see, the music plays and the player works.:
http://jsfiddle.net/aEXsL/2/
And here is the example with the problem, the same code just labeled "source" points to the URL that returns me the variable (remember that this only fails using this script):
http://jsfiddle.net/aEXsL/3/
It appears only one button (it means the player is failing).
Hope you can help me. Thanks in advance.
Edit:
Here is the link to the script author:
http://tympanus.net/Development/AudioPlayer/AudioPlayer.zip

A: Use this code
<script type="text/javascript">
var song=new Audio('http://live1.goear.com/listen/d941195f4a5f477381d8a95ba666a0cb/52eac666/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3');
song.play();
</script>

but your link not contain any MP3 i think now


Q: How long it will take the inapp purchase pending status change to success In Apple purchase history
It is a question regarding my application in-app purchase pending. I am using store kit delegate function and  code as shown below
for (SKPaymentTransaction * transaction in transactions) {

    switch (transaction.transactionState)

    {

        case SKPaymentTransactionStatePurchased:

            [self completeTransaction:transaction];

            break;

        case SKPaymentTransactionStateFailed:

            [self failedTransaction:transaction];

            break;

        case SKPaymentTransactionStateRestored:

            [self restoreTransaction:transaction];

        case SKPaymentTransactionStateDeferred:

            [self DefferedTransaction:transaction];

            break;

        case SKPaymentTransactionStatePurchasing:

            [self PurchasingTransaction:transaction];

            break;

        default:

            break;

    }

};

Then I get a pending transaction . and I update my server database with temporary value. But I want to know when the pending transaction becomes a success.

A: It was quite interesting that I have run about one week behind the inApp pending issue . And I got an answer from apple side that is when we deal the inapp purchase with the below code `for (SKPaymentTransaction * transaction in transactions) {
switch (transaction.transactionState)

{

    case SKPaymentTransactionStatePurchased:

        [self completeTransaction:transaction];

        break;

    case SKPaymentTransactionStateFailed:

        [self failedTransaction:transaction];

        break;

    case SKPaymentTransactionStateRestored:

        [self restoreTransaction:transaction];

    case SKPaymentTransactionStateDeferred:

        [self DefferedTransaction:transaction];

        break;

    case SKPaymentTransactionStatePurchasing:

        [self PurchasingTransaction:transaction];

        break;

    default:

        break;

}

when a transaction is happen without any failure it will get SKPaymentTransactionStatePurchased state and we can proceed the applications process with success methods And no need to worry about the pending transaction apple consider this as success transaction and within 48 hours the amount will credit into the account.


Q: How should I batch upload to s3 and insert to MongoDB from nodeJS webserver with a final callback? I have a web server that accepts images from client, processes them, upload them to S3, batch-insert the urls to my mongoDB, and lastly sending the json result back to the client.
Working with a single image works as follows:
router.post("/upload", function(req, res){
    var form = new multiparty.Form();

    form.parse(req,function(err,fields,files){
        s3.upload({
                Key: filename,
                Bucket: bucketname,
                ACL: "public-read",
                Body: fs.createReadStream(filepath)
         }, function(err, data){
            if(err) //error handle

            Model.collection.insert({"name": "name", "url" : data.Location}, function(err, result){
                if(err) //error handle
                res.json({result: result})
            })
        })
    })
})

This works very well as I am simply uploading the file data to s3 -> when done, insert s3's output (url) to database -> when done, send mongo's result as jsonarray to the client.
The issue is - my client html excepts multiple type=file input with the same name=images, so that i can access them in my form parser as images[i]. The above algorithm is repeated images.length times. Problem rises when  I have to return the jsonarray result back to the client as I would have to wait for all of the asynchronous S3 upload->mongo insert to finish, and I can't pinpoint how and where the callback would be for this job.
What I've tried are the following:

*

*Iterate through images, upload them to S3 first, populate an array with the resulting url ([data.Location]). Batch insert them to mongoDB and return jsonarray result to client in the call back. This didn't work as mongo insert doesn't wait for S3 upload.

*Iterate through images, upload and insert the images to S3 and mongoDB each iteration. if (currentIndex = images.length), return jsonarray result. This doesn't work accurately as I do not know which images will end last (different size).

How should I design the algorithm to batch upload s3, batch insert to mongo, return result including s3 urls, filename etc back to client as jsonarray?
Thanks, in advance!

A: I usually solve this kind of problems with Promises, see: Bluebird.
You could then do a batch upload on S3 using Promise.all(), once you get that callback you can batch insert into Mongo, when done, run the final callback. OR, you could do a batch that does both things: upload->insert to mongo, and when all of those are done, return final callback. It will depend on your server and on how many files you want to upload at once. You could also use Promise.map() with the concurrency option set to whatever concurrent tasks you want to run.
Pseudo-code example:
Lets asume that getFiles, uploadFile and uploadToMongo return a Promise object.
var maxConcurrency =  10;

getFiles()
    .map(function(file){
        return uploadFile(file)
            .then(uploadToMongo)
    },{concurrency: maxConcurrency})
    .then(function(){
            return finalCallback();
    }).catch(handleError);

Example, how to manually "promisify* S3:
function uploadMyFile(filename, filepath, bucketname) {
    return new Promise(function(resolve, reject){
        s3.upload({
            Key: filename,
            Bucket: bucketname,
            ACL: "public-read",
            Body: fs.createReadStream(filepath)
        }, function(err, data){
            //This err will get to the "catch" statement.
            if (err) return reject(err);
            // Handle success and eventually call:
            return resolve(data);
        });
    });
}

You can use this as:
uploadMyFile
        .then(handleSuccess)
        .catch(handleFailure);

All nice and pretty!

A: If you cant get promises to work, you can store the status of your calls in a local variable. You would just break up your calls into 2 functions, a single upload and a bulk upload.
This is dirty code, but you should be able to get the idea:
router.post("/upload", function(req, res){
    var form = new multiparty.Form();

    form.parse(req,function(err,fields,files){
        if (err){
            cb(err);
        } else {
            bulkUpload(files, fields, function(err, result){
                if (err){
                    cb(err);
                } else {
                    res.json({result:result});
                }
            })
        }
    })
})

function singleUpload(file, field, cb){
    s3.upload({
            Key: filename,
            Bucket: bucketname,
            ACL: "public-read",
            Body: fs.createReadStream(filepath)
     }, function(err, data){
        if(err)
            cb(err);
        } else {
            Model.collection.insert({"name": "name", "url" : data.Location}, function(err, result){
                if(err){
                    cb(err);
                } else {
                    cb(null, result);
                }
            })
        }
    })
}

function bulkUpload (files, fields, cb) {
    var count     = files.length;
    var successes = 0;
    var errors    = 0;

    for (i=0;i<files.length;i++) {
        singleUpload(files[i], fields[i], function (err, res) {
            if (err) {
                errors++
                //do something with the error?
            } else {
                successes++
                //do something with the result?
            }

            //when you have worked through all of the files, call the final callback
            if ((successes + errors) >= count) {
                cb(
                    null,
                    {
                        successes:successes,
                        errors:errors
                    }
                )
            }
        });
    }
}

This would not be my recommended method, but another user has already suggested promises. I figure an alternative method would be more helpful.
Good Luck!


Q: Use 100% div width, if 50% width is too small How could one go about creating a div, that would have a default size of XX%, however, if the screen gets too small it would switch into 100% size? I have tried using min-width property but the problem with this is that it will not be responsive after the min-width is reached and will overflow if the screen is even smaller.

A: You have to use @media queries. So let's say you have a
 that should take up only 50% of the web page and then you need to show it full width once it enters mobile phone, say 640px width:
div {
  width: 50%;
}

@media screen and (max-width: 640px) {
  div {
    width: 100%;
  }
}

A: You can do it with @media queries, e.g.:

div {
  width: 50%;
  height: 100px;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  div {width: 100%}
}

A: you must use @media for that like this :
@media screen and (min-width: 769px) {
    /* STYLES HERE */
}

@media screen and (min-device-width: 481px) and (max-device-width: 768px) {
    /* STYLES HERE */
}

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE */
}


Q: How to decode an utf8 encoded string split in two buffers right in between a 4 byte long char? A character in UTF8 encoding has up to 4 bytes. Now imagine I read from a stream into one buffer and then into the another. Unfortunately it just happens to be that at the end of the first buffer 2 chars of the 4 byte UTF8 encoded char are left and at the beginning of the the second buffer the rest 2 bytes.
Is there a way to partially decode that string (while leaving the 2 rest byte) without copying those two buffers into one big
string str = "Hello\u263AWorld";

Console.WriteLine(str);
Console.WriteLine("Length of 'HelloWorld': " + Encoding.UTF8.GetBytes("HelloWorld").Length);
var bytes = Encoding.UTF8.GetBytes(str);
Console.WriteLine("Length of 'Hello\u263AWorld': " + bytes.Length);
Console.WriteLine(Encoding.UTF8.GetString(bytes, 0, 6));
Console.WriteLine(Encoding.UTF8.GetString(bytes, 7, bytes.Length - 7));

This returns:

Hello☺World
Length of 'HelloWorld': 10
Length of 'Hello☺World': 13
Hello�
�World

The smiley face is 3 bytes long.
Is there a class that deals with split decoding of strings?
I would like to get first "Hello" and then "☺World" reusing the reminder of the not encoded byte array. Without copying both arrays into one big array. I really just want to use the reminder of the first buffer and somehow make the magic happen.

A: You should use a Decoder, which is able to maintain state between calls to GetChars - it remembers the bytes it hasn't decoded yet.
using System;
using System.Text;

class Test
{
    static void Main()
    {
        string str = "Hello\u263AWorld";

        var bytes = Encoding.UTF8.GetBytes(str);
        var decoder = Encoding.UTF8.GetDecoder();

        // Long enough for the whole string
        char[] buffer = new char[100];

        // Convert the first "packet"
        var length1 = decoder.GetChars(bytes, 0, 6, buffer, 0);
        // Convert the second "packet", writing into the buffer
        // from where we left off
        // Note: 6 not 7, because otherwise we're skipping a byte...
        var length2 = decoder.GetChars(bytes, 6, bytes.Length - 6,
                                       buffer, length1);
        var reconstituted = new string(buffer, 0, length1 + length2);
        Console.WriteLine(str == reconstituted); // true
    }
}


Q: Building an uberjar with Gradle I want to build an uberjar (AKA fatjar) that includes all the transitive dependencies of the project. What lines do I need to add to build.gradle?
This is what I currently have:
task uberjar(type: Jar) {
    from files(sourceSets.main.output.classesDir)

    manifest {
        attributes 'Implementation-Title': 'Foobar',
                'Implementation-Version': version,
                'Built-By': System.getProperty('user.name'),
                'Built-Date': new Date(),
                'Built-JDK': System.getProperty('java.version'),
                'Main-Class': mainClassName
    }
}

A: Simply add this to your java module's build.gradle.
mainClassName = "my.main.Class"
jar {
  manifest {
    attributes "Main-Class": "$mainClassName"
  }

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

This will result in [module_name]/build/libs/[module_name].jar file.

A: I found this project very useful. Using it as a reference, my Gradle uberjar task would be
task uberjar(type: Jar, dependsOn: [':compileJava', ':processResources']) {
    from files(sourceSets.main.output.classesDir)
    from configurations.runtime.asFileTree.files.collect { zipTree(it) }

    manifest {
        attributes 'Main-Class': 'SomeClass'
    }
}

A: I replaced the task uberjar(.. with the following:
jar {
    from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
        exclude "META-INF/*.SF"
        exclude "META-INF/*.DSA"
        exclude "META-INF/*.RSA"
    }

    manifest {
        attributes 'Implementation-Title': 'Foobar',
                'Implementation-Version': version,
                'Built-By': System.getProperty('user.name'),
                'Built-Date': new Date(),
                'Built-JDK': System.getProperty('java.version'),
                'Main-Class': mainClassName
    }
}

The exclusions are needed because in their absence you will hit this issue.

A: Have you tried the fatjar example in the gradle cookbook?
What you're looking for is the shadow plugin for gradle


Q: Save file from HTTP response Looking for some guidance or pointers, not necessarily the solution however I will post a solution back when done.
Using WSO2 ESB / Integrator that is calling an external service. According to the external service [1], they will respond with a file back in the HTTP response. It is this file that I am after; both to save the binary to disk and send to a user via web page redirect.
Can anybody point me in a direction in which I can take the HTTP response and create a file? I am presuming that I need to transform the response and use VFS.
Any help would be greatly appreciated.
[1] - https://support.webmerge.me/hc/en-us/articles/206526216-Webhook

A: It is fairly straight forward, the first step is to enable the transport sender for VFS (and the receiver if you also want to read files) in de axis2.xml config file.
The lines are already there and just need to be uncommented.
<transportReceiver name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportListener"/>

<transportSender name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportSender"/>

Next you will need to transform your response to whatever format you want to write to the file. You could use an xslt transformation, payload mediator or datamapper mediator for example.
After that you simple send the payload to a vfs endpoint. This can be a local file location, or a remote ftp location for example. Make sure you have the correct privileges to write a file in said location. For example if you run your esb as WSO2 user, and want to write files to /opt/wso2/fileexchange, make sure the WSO2 user has write privileges on that folder.
Then to write to that location just use a send mediator like this:
<property xmlns:ns2="http://org.apache.synapse/xsd" name="transport.vfs.ReplyFileName" value="myFile.txt" scope="transport"/>
    <property name="OUT_ONLY" value="true"/>
    <send>
        <endpoint name="FileEpr">
            <address uri="vfs:file:///opt/wso2/fileexchange"/>
        </endpoint>
    </send>

Make sure to set the transport.vfs.ReplyFileName property to the filename you want to write. And the OUT_ONLY property, since the filesystem is not going to send a nice reply back to you.
For more on this subject you can always check this blog

A: I prefer send the URI which refer to the file instead of sending the binary data. So the more efficient way is upload the file to a FileSystem, then transfer it with a String(URI). Only when you need read the file's data, then download it from FileSystem. And you should ensure the network is OK between FileSystem and the final user.


Q: Azure Service bus queues have a URL, do they also have an IP-Adress or even Range? I was wondering if there is any possibility of Service Buses or even their queues have an IP-address or even Ranges? I have been searching both in the documentation and also in azure but I couldn't find anything.
What are the possibilities here when it comes to IP-Control so to speak? is it a question of upgrading the Pricing teir for the service bus?

A: It doesn't work that way. The service is only accessible via DNS, not IP address.
Upgrading from Standard tier to Premium gives you throughput and latency commitment, but not an IP address.


Q: Is there a way to dynamically evaluate/use an angular (angular 2+) pipe? Let's say I have a pipeVar, it can be any pipe, eg.: number, uppercase, customPipe, etc
Is there a simple way to just call something like
{{ myVal | pipeVar }}

or some special syntax like
{{ myVal | #pipeVar }}

?
The closest thing I have found so far is Dynamic pipe in Angular 2

A: i have update plunkr plunkr link
Change in dynamic-pipe.ts like this
const dynamicPipe = "";
//i have give one simple logic for example if your dynamic pipe is like
this.dynamicPipe = ['number','uppercase','customPipe']; //pipe,pipe1 ... pipeN
//now create a one variable like 'number' | 'uppercase' | 'customPipe'
for (let i=0;i<this.dynamicPipe.length;i++){
     dynamicPipe = dynamicPipe + " | "+this.dynamicPipe[i];
}
@Component({
    selector: 'dynamic-comp',
    template: '{{ data ' + dynamicPipe + '}}'
})


Q: Unity Leap Motion Error Message "INPUT AXIS NOT SET UP" I'm currently doing my first VR project with Leap Motion, HTC Vive and Unity.
When I create a new project and add the LeapRig, everything is just fine, but after adding the Interaction Manager as a child of LeapRig, I get the following error message, which gets repeated multiple times a second:
INPUT AXIS NOT SET UP.  Go to your Input Manager and add a definition for  on the 9th Joystick Axis.
UnityEngine.Debug:LogError(Object)
Leap.Unity.Interaction.InteractionXRController:fixedUpdateGraspButtonState(Boolean) (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionXRController.cs:733)
Leap.Unity.Interaction.InteractionXRController:fixedUpdateGraspingState() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionXRController.cs:706)
Leap.Unity.Interaction.InteractionController:fixedUpdateGrasping() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionController.cs:1783)
Leap.Unity.Interaction.InteractionController:Leap.Unity.Interaction.IInternalInteractionController.FixedUpdateController() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionController.cs:259)
Leap.Unity.Interaction.InteractionManager:fixedUpdateInteractionControllers() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionManager.cs:372)
Leap.Unity.Interaction.InteractionManager:FixedUpdate() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionManager.cs:299)

Has anyone an idea why this happens and how to fix it?
I already worked with the interaction manager, but suddenly this error message occured.
I can run my program just fine too, but the error bothers me anyway and makes it difficult to use the console properly.
Greetings from Germany
Marc

A: From the Interaction Engine docs:

If you intend to use the Interaction Engine with Oculus Touch or Vive
  controllers, you'll need to configure your project's input settings
  before you'll be able to use the controllers to grasp objects. Input
  settings are project settings that cannot be changed by imported
  packages, which is why we can't configure these input settings for
  you. You can skip this section if you are only interested in using
  Leap hands with the Interaction Engine.
Go to your Input Manager (Edit -> Project Settings -> Input) and set
  up the joystick axes you'd like to use for left-hand and right-hand
  grasps. (Controller triggers are still referred to as 'joysticks' in
  Unity's parlance.) Then make sure each InteractionXRController has its
  grasping axis set to the corresponding axis you set up. The default
  prefabs for left and right InteractionXRControllers will look for axes
  named LeftXRTriggerAxis and RightXRTriggerAxis, respectively.
Helpful diagrams and axis labels can be found in Unity's
  documentation.


Q: CMFCPropertyGridCtrl last item not drawn? I have a CMFCPropertyGridCtrl that I'm using in an options dialog box.  I have a method in my options dialog class called InitPropertyGrid().  This method clears any properties and populates the CMFCPropertyGrid objects (using a custom Settings object for the property values) and appends them to the grid.
When I open my dialog box the first time all the properties show correctly.  However, if I then close my dialog box and reopen it, the very last property is not drawn on the screen.  All other properties are drawn normally:
First time:

All subsequent times:

As you can see, the plus/minus icon is showing minus in both cases to indicated the section is expanded.  When the last item is not showing, clicking on the +/- icon once to contract and once to expand causes the last item to be correctly shown.
Note when I close the dialog box, I do not destroy it but just reshow it.  However immediately before calling ShowWindow on the dialog I call the InitPropertyGrid() (called by UpdateToCurrentSettings) method.
if(optionsDialog_ == NULL)
{
    optionsDialog_ = new OptionsDialog(settings_, this);
    optionsDialog_->Create(OptionsDialog::IDD, this);
}

optionsDialog_->UpdateToCurrentSettings();
optionsDialog_->ShowWindow(SW_SHOW);

A: I found I can eliminate this problem simply by calling myPropertyGrid.ExpandAll(TRUE) at the end of the code where I initialize the property grid (InitPropertyGrid() for me).  This seems to force all the properties to expand.


Q: Java script object data for functions How do I acces some object data in a javascript function? All I want to do is to take some input from the html file and then if the input text is === to one of my objects in javascript i want to acces some data from that object to use within my function.
For example:
I have the html form with 2 text inputs and a button to acces the function. And in the javascript document I have two objecst called bob and susan with the data "bob.age = 25" and "susan.age = 30". So I want a function that calculates bob.age + susan.age. But I want to use the  inputs of bob and susan in my form html. So when i have the inputs bob and susan i want the function to do bob.age + susan.age
here is my html form:
<form name="mmForm">
       E1
       <input type="text" id="element1">
       E2
       <input type="text" id="element2">
       <input type="button" value="Calculate" onclick="procesForm_mm()">

Result:

   </form>

here my javascript function:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;

var e2 = document.mmForm.element2.value;

result_mm = parseInt(e1) + parseInt(e2);

document.getElementById("resultfield_mm").innerHTML += result_mm;
}

and this is the data i want to acces:
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;

A: Try this (a lot of guessing involved):
function procesForm_mm() {
    var e1 = document.mmForm.element1.value;
    var e2 = document.mmForm.element2.value;
    result_mm = parseInt(eval(e1).A) + parseInt(eval(e2).A);
    document.getElementById("resultfield_mm").innerHTML += result_mm;
}

var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;

var Co = new Object();
Co.denumire = "Cobalt";
Co.A = 59;
Co.Z = 27;
Co.grupa = "IXB";
Fe.perioada = 4;

See it working here: http://jsfiddle.net/KJdMQ/.
It's important to keep in mind that use of the JS eval function has some disadvantages: https://stackoverflow.com/a/86580/674700.
A better approach would be to keep your JS objects in an array and avoid the use of the eval function:
function procesForm_mm() {
    var e1 = document.mmForm.element1.value;
    var e2 = document.mmForm.element2.value;
    result_mm = parseInt(tabelPeriodic[e1].A) + parseInt(tabelPeriodic[e2].A);
    document.getElementById("resultfield_mm").innerHTML += result_mm;
}
var tabelPeriodic = [];

tabelPeriodic["Fe"] = new Object();
tabelPeriodic["Co"] = new Object();

var el = tabelPeriodic["Fe"];
el.denumire = "Fier";
el.A = 56;
el.Z = 26;
el.grupa = "VIIIB";
el.perioada = 4;

el = tabelPeriodic["Co"];
el.denumire = "Cobalt";
el.A = 59;
el.Z = 27;
el.grupa = "IXB";
el.perioada = 4;

(See it working here)
Note: This looks like a chemistry application, I assumed that the form is supposed to add some chemical property values for the chemical elements (i.e. A possibly being the standard atomic weight). The form would take as input the names of the JS objects (Fe and Co).


Q: root in binary tree always NULL The program should read a txt, store all the words alphabetically and print them in order, with the number of times the word appears on the txt.
The problem seems to be in the Insert method, because it never prints TEST, so it seems the pAux is always NULL for some reason. And because of that, the Print method returns in his first call.
What am I doing wrong?
tree.h
#ifndef TREE_H_
#define TREE_H_

typedef struct Item{
    char* key;
    int no;
} TItem;

typedef struct No{
    TItem item;
    struct No* pLeft;
    struct No* pRight;
} TNo;

void TTree_Insert (TNo**, char[]);
void TTree_Print (TNo*);

#endif

tree.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"

TNo* TNo_Create (char* c){
    TNo* pNo = malloc(sizeof(TNo));
    pNo->item.key = malloc(sizeof(char)*strlen(c));
    strcpy(pNo->item.key, c);
    pNo->item.no = 1;
    pNo->pLeft = NULL;
    pNo->pRight = NULL;
    return pNo;
}

void TTree_Insert (TNo** pRoot, char word[80]){
    char* c = malloc(sizeof(char)*strlen(word));
    strcpy(c, word);
    TNo** pAux;
    pAux = pRoot;
    while (*pAux != NULL){
        if (strcmp(c, (*pAux)->item.key) < 0) pAux = &((*pAux)->pLeft);
        else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight);
        else{
            (*pAux)->item.no++;
            return;
        }
    }
    *pAux = TNo_Create(c);
    return;
}

void TTree_Print (TNo *p){
    if (p == NULL) return;
    TTree_Print (p->pLeft);
    printf("%s - %d", p->item.key, p->item.no);
    TTree_Print (p->pRight);
}

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"

int main(){
    TNo* pRoot = NULL;
    FILE* txt = fopen("Loremipsum.txt", "r");
    char aux[80];
    int c, x = 0;

    while ((c = fgetc(txt)) != EOF){
        while (!(isalpha((char)c))) c = fgetc(txt);
        while (isalpha((char)c)) {
            if (isupper((char)c)) c = c+32;
            if (islower((char)c)) aux[x++] = (char)c;
            c = fgetc(txt);
        }
        aux[x] = '\0';
        TTree_Insert(&pRoot, aux);
        x = 0;
        aux[0] = '\0';
    }
    TTree_Print(pRoot);
    fclose(txt);
    return 0;
}

A: I did not look through all your code. I will answer only your question. You have to pass pRoot to TTree_Insert by reference. Otherwise you pass its copy to the function and any changes of the copy within the function do not influence the original value.
For example
void TTree_Insert ( TNo **pRoot, char word[80] ){
    char* c = malloc(sizeof(char)*strlen(word) + 1 ); // <==
    strcpy( c, word ); // <==
    TNo* pAux;
    pAux = *pRoot;
    //...

And in main you have to call the function like
TTree_Insert( &pRoot, aux );

Take into account that you have to adjust  all other code of the function. For example
void TTree_Insert( TNo **pRoot, const char word[80] )
{
    char* c = malloc( sizeof( char ) * strlen( word ) + 1 );

    strcpy( c, word );

    TNo **pAux = pRoot;

    while ( *pAux != NULL )
    {
        printf("TESTE");
        if ( strcmp(c, ( *pAux )->item.key ) < 0 )
        {
            pAux = &pAux->pLeft;
        }
        else if ( strcmp(c,  ( *pAux )->item.key ) > 0 )
        {
             pAux = &pAux->pRight;
        }
        else
        {
            ( *pAux )->item.no++;
            break;
        }
    }

    if ( *pAux == NULL ) *pAux = TNo_Create(c);

    return;
}

I hope it will work.:)

A: pRoot is initially NULL, and you never change it later.

so it seems the pAux is always NULL for some reason

Well, that's the reason... why don't you use a debugger or do some printing?


Q: which is fastest for an oracle query? This
select * from customers where id = 1;
select * from customers where id = 2;

or
select * from customers where id in(1,2);

which is faster?

A: The first one are actually two statements causing you to make two roundtrips to the database.
The second one will most likely be faster as it is just one statement.

A: Is this really what you are trying to determine? Are you asking if it is faster to make one trip returning two rows or two trips each returning one row? If that is the question, then I agree with the comments -- try it, measure it, and compare.
If you are trying to make this kind of thing efficient, then you should probably look at using bind variables instead. If your question really means what it says, then probably any answer here will do.

A: Any question with "faster" is always going to be dependent on the specifics of your database. I don't really have anything to add over plhmhck and MJB about the fact that you're talking about 2 queries vs. 1 query.
But be aware the the optimizer will usually (always?) rewrite WHERE id IN (1,2) to WHERE (id = 1 OR id = 2)


Q: .Net HotChocolate GraphQL Mutations pick from a list of stings like enum I have a bunch of data, in a .NET GRaphQL API that are basically list of strings like
Public List<string> avarageMessageSize = new List<string>{
"Up to 5 KB",
"Between 5 KB and 4 MB",
Between 4 MB and 20 MB",
"20 MB and bigger"
};

When a new Entity is made with a GraphQL Mutation, for other values that are stored in Enums I have input types that let me choose and pick in a mutation to add the correct value, is this also possible for list items, to pick and choose the correct value(string) in a Mutation?

A: You can easily make the string an enum. Essentially a GraphQL enum can be represented by any object in dotnet.
The strings have to follow the GraphQL enum rules. So Up to 5 KB would probably be represented by Up_to_5KB. But in your dotnet API you would just use the Up to 5 KB string.
The GraphQL engine would translate it to the enum in GraphQL. You also cannot have arbitrary values anymore, they must be represented by the enum values allowed in this case.


Q: How to send a notification without waking the screen on Android I have a foreground service in my app, whose persistent notification has a timer in it, which means that the notification is sent once per second to update the timer that is shown in the notification.  This means that on some devices, where notifications are set to either wake the screen entirely or show a dark version on the screen briefly, the screen is constantly awake.
Is there a way to send the notification in a way that it won't wake up the screen?  Setting it as a silent notification on the device fixes this, but the point of a foreground service notification is that it's prominent on the device, so this isn't a great solution, and not all users would know to do that.
This is how I'm building the notification:
NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Currently Reading")
            .setSound(null)
            .setContentIntent(TaskStackBuilder.create(this).run {
                addNextIntentWithParentStack(timerIntent)
                getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )
            })
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)

A: Have you tried updating the notification instead? And use setOnlyAlertOnce()
"You can optionally call setOnlyAlertOnce() so your notification interupts the user (with sound, vibration, or visual clues) only the first time the notification appears and not for later updates."
Check this link
https://developer.android.com/training/notify-user/build-notification.html#Updating

A:
setPriority(NotificationCompat.PRIORITY_DEFAULT)?

lower it, so wont be shown on lockscreen (android 7 and up)
and here we go with a small fix for this part:
setPriority(NotificationCompat.PRIORITY_LOW)
you can also add:
setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
but it'll also remove notification from lockscreen...
docs:

*

*https://developer.android.com/training/notify-user/build-notification.html#lockscreenNotification

*https://developer.android.com/training/notify-user/channels#importance
hope this helps =]


Q: How can I assign RGB color codes to a WORD? I am assigning the color values to the display frame buffer, and that buffer pointer return type is BYTE. But i am not able to assign the RGB color value into it. This i am doing to set the pixel location using directdraw on WINCE platform .Here is the snapshot code.
BYTE* pDisplayMemOffset = (BYTE*) ddsd.lpSurface;

int x = 100;

int y = 100;

pDisplayMemOffset += x*ddds.lXPitch + y*ddds.lPitch ;

***(WORD*)pDisplayMemOffset = 0x0f00;

But how i can assign RGB(100,150,100) combination in this, i have tried to put DWORD instead of WORD while assigment but it desnt work. i knw i required hex value for color in 0x000000 format(RGB), but i think BYTE cnt store such large value into it.
Can anyone tell me how to do this?

A: How this assignment can be done is very dependent on the pixel-format you specified when acquiring ddsd. See the field ddpfPixelFormat and also specifically in there: dwRGBBitCount.
Maybe you can provide this pixel format information so that i can improve my answer. However, i can easily give you an example of how you do this pixel-color assignment if e.g. the pixel-format is:
[1 byte red] [1 byte green] [1 byte blue] [1 byte unused]

Here's the example:
*(pDisplayMemOffset+0) = 0x10;// asigning 0x10 to the red-value of first pixel
*(pDisplayMemOffset+1) = 123; // asigning 123 to green-value of first pixel
                              // (no need for hex)
*(pDisplayMemOffset+4) = 200; // asigning 200 to red-value of second pixel
                              // (BYTE is unsigned)

If you have to extract the color values from an integer it largely depends on which byte-ordering and color-ordering that integer was given in, but you can try it out easily.
First i would try this:
*(((unsigned int*)pDisplayMemOffset)+0) = 0x1A2A3A4A
*(((unsigned int*)pDisplayMemOffset)+1) = 0x1B2B3B4B

If this works, then the pixel-format had either an unused 4th byte (like my example above) or an alpha-value that is now set to one of the values. Again: aside from the pixel-format also the ordering of the bytes in your integer decides whether this directly works or whether you have to do some byte-swapping.


Q: Image files stored on Google cloud storage are not displayed but only strange text I have a project that uploads an multi-image to Google cloud storage, the upload works fine, but when I download an image, it only shows strange text.
It has 2 steps to upload a file to Google cloud storage. In step 1, I will get the URL that will help me upload the file to the storage. Step 2, I will upload the file to the response URL I got from step 1. And I can download the file from the response in step 2
Step 1: get upload URL from GCS
    Options requestHeaders = await getRequestOptions(jwtBearer, hashing);
requestHeaders.headers!['Content-Type'] = 'application/json';
var signedUrlFiles = await dio.post(
  genUrlsApi,
  data: {
    ...(body != null ? body.toJson() : {}),
    'files': files
        .map((f) => FileElement(
        fileName: f.fullName, type: buildApiQuery(f.type)["type"]!)
        .toJson())
        .toList()
  },
  queryParameters: query,
  options: requestHeaders,
);
var response = DBSBaseResponse.fromJsonFactory(signedUrlFiles.data);
GCSUploadFileResponse result = GCSUploadFileResponse.fromJsonFactory(response.data);

step 2 : upload file from GCS URL
for(var file in result.files){
    var file = files.firstWhere((f) => f.fullName == url.fileName);
    FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile(
      file.uri,
      filename: url.fileName,
    ),
  });
  var result = await dio.put(
    url.url,
    data: formData,
    onSendProgress: (
      int sent,
      int total,
    ) {
     //show logger
    },
  );

}
I can not show the image because the company policy. sorry for this trouble


Q: My function click() dont work with href of this site, how i can fix and make work? from selenium import webdriver
from selenium.webdriver.chrome.service import Service
#Service("local do diretorio do chromeDriver")

driver = webdriver.Firefox('/home/arch/Downloads/bot/')
driver.get("https://blaze.com/pt/?modal=auth&tab=login")

element=driver.find_element_by_name("username").send_keys("email")
driver.find_element_by_name("password").send_keys("pass")
#link da url desejada

driver.find_element_by_xpath('/html/body/div[1]/main/div[3]/div/div[2]/div[2]/form/div[4]/button').click()
driver.find_element_by_xpath('/html/body/div[1]/main/div[1]/div[4]/div[2]/div[1]/div/div/div[4]/div[1]/div/div[3]/div/a')

I have this code in python that opens in blazer.com and makes login but when i try to click o game mines which in this href:
<a href="/pt/games/mines"/>

and doesnt work justs stops , someone could help with this error

A: You probably forgot to click the "mines" button. Don't forget the .click() at the end of your code, like this:
driver.find_element_by_xpath('/html/body/div[1]/main/div[1]/div[4]/div[2]/div[1]/div/div/div[4]/div[1]/div/div[3]/div/a').click()

And you also might want to give the site some time to load by importing time and using time.sleep(x) which sleeps the code for x seconds.
import time

time.sleep(2) # Use this between the .click() lines to give the site time to load after clicking a button


Q: what does my request does not inlclude if-non-match in header I am using https://github.com/filipw/AspNetWebApi-OutputCache NUGET package to manage caching for my ASP.NET WEB API.
The server side caching works well. However I don't see it working on my browser (client side).
On request I see that max-age and etag is being returned.
However I make further request I don't see etag being supplied with request header with if-non-match parameter. This is why I get response 200 (OK) back with response data. It should have parsed data from cache itself.
https://dl.dropboxusercontent.com/u/2781659/stackoverflow/Cache.jpg
Can anybody please advise?

A: I just briefly looked at the Github project you referenced, and I wanted to throw in my $0.02, for whatever it's worth -
Breeze.js is responsible for taking care of client side caching for you.  The idea is to not have to worry about what the back-end is doing and simply make a logical decision on the client on whether to proceed and hit the server for data again.  If you don't need to refresh the data, then never hit the server, just return from Breeze's cache.
The project you are referencing seems to do both - server side and client-side caching.  The decision of caching on the server is one not to be taken lightly, but this project seems to handle it pretty well.
The problem is that you are trying to mix two libraries which, at best, conflict in the area of what their concerns are.  There may be a way to marry the two up, but at what cost?  Why would you need to cache on the server that which is already cached on the client?  Why cache on the client if you plan to cache the exact same data on the server?
The only reason I can think of is for paging of data (looking at a subset of the whole) and wanting to see the next data set without having to hit the server again.  In that case, your query to the server should not match the original anyway and therefore one would expect that you need to customize the two solutions to do what you are asking for.
In general that project seems to ignore queryString parameters, from what I can tell, to support JSONP so you should have no problem coming up with a custom solution, if you still think that is necessary.


Q: Sort any random list of files by modification date Looking for generic way how to sort a random list of files by its modification time, so something like:
./make_list_of_files | some_sorter_by_mtime

my currect solution is (here the make_list_of_files is the find command):
find / -type f -print |\
  perl -nle 'push @in,$_;END {@out = sort{ (stat($a))[9] <=> (stat($b))[9] } @in; $,="\n";print @out}'

exists some simpler solution (e.g. without perl)?

A: Your some_sorter_by_mtime should be for example:
xargs stat -f "%m %N" | sort -n | cut -f2-

the idea behind is:

*

*print out file modification time and the filename

*sort the output numerically (so by modification time)

*cut out the time field

so,
find / -type f -print | xargs stat -f "%m %N" | sort -n | cut -f2-

A: Like this?
find / -type f -print | xargs ls -l --time-style=full-iso | sort -k6 -k7 | sed 's/^.* \//\//'

A: Yes, without perl:
find / -type f -exec ls -lrt '{}' \+

Guru.


Q: CSS rotate3d works correctly only on Firefox The CSS rotate3d animation seems to depend on the (modern) browser you use!!! Just test the code...
@keyframes KF_Rotate {
                       0% { transform: rotate3d(0,0,0,  0deg); }
                     100% { transform: rotate3d(0,1,0,180deg); }
                     }
.Rotate:hover { animation: KF_Rotate 3s; }

How is it possible?


Q: Authorize ARB subscription payment I am creating a subscription using Authorize.net ARB API. I can see in my account, where the subscription is created.
Its a very simple subscription, where a user would be paying $100 every month. I would like to know, if the user would be billed at the time of creation of the subscription ?
My understanding is that, he would be billed only from next month ? Any idea, how to bill the customer from the time the subscription is created ?
Thanks

A: ARBCreateSubscriptionRequest has parameter "startDate" where you can set date the subscription begins.
If first price should be different from monthly payments you can also set parameter "trialAmount" for first payment
All information you can find here
http://www.authorize.net/support/ARB_guide.pdf

A: You should always charge the first subscription payment using the AIM API. The AIM API will process immediately and act as a verification for the credit card. You will know immediately if a card is invalid and before you create the subscription. If you schedule a payment to process the same day the subscription is created it does not process immediately. That process later that night. If the credit card is invalid you lose the opportunity to have the user correct it because they are no longer present at your website.


Q: How to sync the modification date of folders within two directories that are the same? I have a Dropbox folder on one computer with all the original modification dates. Recently, after transferring my data onto another computer, due to a .DS_Store issue, some of the folder's "Date Modified" dates were changed to today. I am trying to write a script that would take the original modification date of a folder, and then be able to find the corresponding folder in my new computer, and change it using touch. The idea is to use stat and touch -mt to do this. Does anyone have any suggestions or better thoughts? Thanks.

A: Use one folder as the reference for another with --reference=SOURCE:
$ cd "$(mktemp --directory)"
$ touch -m -t 200112311259 ./first
$ touch -m -t 200201010000 ./second
$ ls -l | sed "s/${USER}/user/g"
total 0
-rw-r--r-- 1 user user 0 Dec 31  2001 first
-rw-r--r-- 1 user user 0 Jan  1  2002 second
$ touch -m --reference=./first ./second
$ ls -l | sed "s/${USER}/user/g"
total 0
-rw-r--r-- 1 user user 0 Dec 31  2001 first
-rw-r--r-- 1 user user 0 Dec 31  2001 second


Q: Overriding Rails Default Routing Helpers I'm writing an app where I need to override the default routing helpers for a model.  So if I have a model named Model, with the corresponding helper model_path() which generates "/model/[id]".  I'd like to override that helper to generate "/something/[model.name]".  I know I can do this in a view helper, but is there a way to override it at the routing level?

A: You can define to_param on your model. It's return value is going to be used in generated URLs as the id.
class Thing
  def to_param
    name
  end
end

The you can adapt your routes to scope your resource like so
scope "/something" do
  resources :things
end

Alternatively, you could also use sub-resources is applicable.
Finally you need to adapt your controller as Thing.find(params[:id]) will not work obviously.
class ThingsController < ApplicationController
  def show
    @thing = Thing.where(:name => params[:id).first
  end
end

You probably want to make sure that the name of your Thing is unique as you will observe strange things if it is not.
To save the hassle from implementing all of this yourself, you might also be interested in friendly_id which gives you this and some additional behavior (e.g. for using  generated slugs)

A: You need the scope in routes.rb
scope "/something" do
  resources :models
end


Q: iOS command-line build: How to create xcode archive from command line? I am using below command to create an signed ipa file from command line i.e. terminal.
xcrun -sdk iphoneos PackageApplication \
    "path/to/build/MyApp.app" \
    -o "output/path/to/MyApp.ipa" \
    --sign "iPhone Distribution: My Company" \
    --embed "path/to/something.mobileprovision"
As understood from above, this will create an ipa file. But, I want to create a xcarchive file which will be used to upload to app store using Application Loader. How can I modify this command to achieve that. Any help will be greatly appreciated. Thanks...

A: Just use xcodebuild archive command


Q: Teamwork Ruby on Rails I've been working with RoR for a while but now I need to work with designers and other developers. Is there a tool like github or something like dropbox where you can share with your team the files but with a URL where you can check live any change. For example for my own I just run Rails s and I can see what happen on my localhost but for a designer it isn't that simple. And also we don't want everybody running his own rails project on his localhost.
So is there a tool or what do you do guys when you have to work with others collaborates?

A: You consider to use a staging environment?

A staging environment (stage) is a nearly exact replica of a production environment for software testing. Staging environments are made to test codes, builds, and updates to ensure quality under a production-like environment before application deployment. The staging environment requires a copy of the same configurations of hardware, servers, databases, and caches. Everything in a staging environment should be as close a copy to the production environment as possible to ensure the software works correctly.

See the Font
To use it, i recommend you a application like Heroku, after configure, you can 'deploy' your app commiting in a branch (its not real time, but works for your case).
If you have a VM, i recommends you this tutorial: https://emaxime.com/2014/adding-a-staging-environment-to-rails.html

A: Open questions like this are not really best placed on StackOverflow, which is geared more toward solving specific issues, with provided code examples and errors etc.
However, in answer to your question:
I see you mention Github in your question, but do you fully understand the underlying concept of Git Version Control, or is there a speficic reason as to why it doesn't meet your needs? As far as I believe, it's main purpose is to solve your exact scenario.
https://guides.github.com/introduction/git-handbook/


Q: TabBarController status bar issue in iOS7 I added the UITabBarController view on the UIWindow. TabBarController view is messing up with Status Bar. The TabBarController is in the MainWindow.xib. How can i fix this?
window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
tabController.viewControllers = [NSArray arrayWithObjects:nearbySplit, mySplit, allSplit, messageSplit, nil];
tabController.selectedIndex = 0;
    window.rootViewController = tabController;
    [window addSubview:tabController.view];

    [window makeKeyAndVisible];

A: Add the this code in view controller
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

in your viewDidLoad method.


Q: youtube api v3 does something when a user uploads a new video How can I do that when an user uploads a new video, my javascript code in node.js execute something?
I readed the docs and I didn't fond anything.


Q: How to upload a folder to blob storage using SAS URI in storage explorer enter image description hereI'm trying to upload a folder to blob container using storage explorer via SAS URI, but the upload is failing for folder & files. How can I achieve that ? When I connect to blob storage using account name and key it works fine, but not with SAS URI.

A: I've created several tests and all succeeded with SAS URI.

I think you should check a few places:

*

*According to your screen shot. Maybe your SAS key has expired?

*The URI configuration. We should concat the connect string and the  SAS token.

The configuration is as follows:

A: First you need to check the permissions allotted to SAS and also the expiry date, there can be two cases here: one you may not have adequate access to upload and second the SAS might have expired.
If this is a one time activity and then you can use AzCopy tool as well to upload files to blob storage.


Q: Need Help To Uncheck Radio Button If Aleady Checked Using Jquery i need help to uncheck or check same radio button if button already checked? I have jquery function which is used to enable or disabled other radio buttons if already checked now i want to add some function that use for check or uncheck same radio button?
(function ($) {
  $(document).ready(function () {
    $('input:radio').click(function(){
      var $inputs = $('input:radio')

      if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
      }else{
        $inputs.prop('disabled',false);
      }
    })

  });
})(jQuery);

<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2
<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2

A: Although it is too late to answer, it could help others
I tried this solution.
Works very well for me!
$("input[type='radio'].myClass").click(function(){
        var $self = $(this);
        if ($self.attr('checkstate') == 'true')
        {
            $self.prop('checked', false);
            $self.each( function() {
                $self.attr('checkstate', 'false');
            })
        }
        else
        {
            $self.prop('checked', true);
            $self.attr('checkstate', 'true');
            $("input[type='radio'].myClass:not(:checked)").attr('checkstate', 'false');
        }
})

A: Simply replace disabled with checked:
$input.prop("checked", false);

or for this element:
this.checked = false;

However, if you are looking for form element which can be checked and unchecked, maybe input type="checkbox" /> is what you need.

A: $inputs.filter(':checked').prop('checked', false);

A: I think you need checkbox instead of radio button to uncheck the checked :
<input class="checkDisable" type="checkbox" value="Test1" />Test1
<input class="checkDisable" type="checkbox" value="Test2" />Test2
<input class="checkDisable" type="checkbox" value="Test3" />Test3
<input class="checkDisable" type="checkbox" value="Test4" />Test4

(function ($) {
$(document).ready(function () {
 $('input:checkbox.checkDisable').change(function(){
    var $inputs = $('input:checkbox.checkDisable')
    if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
    }else{
        $inputs.prop('disabled',false);
        $(this).prop('checked',false);
    }
 })

});
})(jQuery);

A: The answer of Pablo Araya is good, but ...
$self.prop('checked', true);

is superfluous here. The radio button already has a checked state for every click.


Q: Windows Phone 8 & Internet Explorer 10 caches 302 redirects We are developing a web app for mobile devices and we are experiencing a rare caching issue in Windows Phone 8 & Internet Explorer 10.
Our app is based on JSF and jQueryMobile. And we are using de "redirect-after-post" system for navigation.
When we make a call to a new page two requests should be executed and so they are in all the  OS an navigators except in our beloved Microsoft system (WP8 & IE10, Nokia Lumia 620):

*

*Navigator requests URL

*Server returns HTTP 302 status with new location

*Navigator requests new location

The fact is that WP8 & IE10 doesn`t execute the last request, and shows a cached result. We are including the "Cache-control", "Pragma" and "Expires" headers in the 302 response to make the navigator not to show a cached page, but IE10 ignores them.
Any clue to solve this problem?
thanks & regards

A: Try forcing the Uri returned in step 2 to be unique (append a random or incrementing value to the end of the query string).
This works around the caching behaviour in the HttpWebRequest class in the SDK.


Q: how do I link my src/app.js file to babel src/app.js file keeps showing it doesn't exist in git bash
I tried adding quotations
babel src/app.js --out-file=public/scripts/app.js --presets="env,react"
instead of this
babel src/app.js --out-file=public/scripts/app.js --presets=env,react but it still did not work

A: Consider looking at the .gitignor file, please. if you put src folder or src/app in .gitignor then it's not shown in git bash