text:
Q: IndexPath for UITableView Not Working I'm trying to determine the indexPath of the select row of my UITableView so I can pass the relevant data accordingly.  Right now it keeps logging 0 no matter what cell I select.  Any ideas why?  (Yes, the IBOutlet for the table is hooked up properly).
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"patientChart"])
    {
        UITabBarController *tabBar = (UITabBarController *)segue.destinationViewController;
        PatientChartViewController *vc = [tabBar.childViewControllers objectAtIndex:0];
        NSIndexPath *path = [self.appointmentTableView indexPathForSelectedRow];
        vc.appointmentDictionary = [self.appointmentArray objectAtIndex:path.row];
    }
}

A: Method indexPathForSelectedRow will return index of selected row if row is selected or 0 otherwise.
So, for example, if cell has been selected and later deselected then you won't get its index path by calling [tableView indexPathForSelectedRow]; because no one cell is selected at that time.

A: If using iOS5 the solution for this is declare an instance in .h and set property to copy as shown below.
NSIndexPath *path;
@property (nonatomic, copy) NSIndexPath *path;

Assign the indexpath value to the instance i.e path in cellForRowAtIndexPath method.
I encountered this issue when tried to execute this on iOS5 and get it resolved as mentioned above. Hope this help u.


text:
Q: Circular histogram in ggplot2 with even spacing of bars and no extra lines I'm working on making a circular histogram in ggplot2 that shows how the number of calls varies over 24 hours. My dataset starts at 0 and goes to 23, with the number of calls per hour:
df = data.frame(xvar = 0:23,
                y = c(468,520,459,256,397,241,117,120,45,100,231,398,340,276,151,134,157,203,308,493,537,462,448,383))

I'm using the following code to create the circular histogram:
ggplot(df, aes(xvar, y)) +
    coord_polar(theta = "x", start = -.13, direction = 1) +
    geom_bar(stat = "identity", fill = "maroon4", width = .9) +
    geom_hline(yintercept = seq(0, 500, by = 100), color = "grey80", size = 0.3) +
    scale_x_continuous(breaks = seq(0, 24), labels = seq(0, 24)) +
    xlab("Hour") +
    ylab("Number of Calls") +
    ggtitle("Number of Calls per Hour") +
    theme_bw()

I really like the resulting plot:

but I can't figure out how to get the same spacing between the 23 and 0 bars as is present for the other bars. Right now, those two bars are flush against one another and nothing I've tried so far will separate them. I'm also interested in removing the lines between the different hours (ex. the line between 21 and 22) since it's somewhat distracting and doesn't convey any information. Any advice would be much appreciated, particularly on spacing the 23 and 0 bars!

A: You can use the expand parameter of scale_x_continuous to adjust. Simplified a little,
ggplot(df, aes(x = xvar, y = y)) +
    coord_polar(theta = "x", start = -.13) +
    geom_bar(stat = "identity", fill = "maroon4", width = .9) +
    geom_hline(yintercept = seq(0, 500, by = 100), color = "grey80", size = 0.3) +
    scale_x_continuous(breaks = 0:24, expand = c(.002,0)) +
    labs(x = "Hour", y = "Number of Calls", title = "Number of Calls per Hour") +
    theme_bw()

redpajama_set_name: RedPajamaStackExchange


text:
Q: View is not rendering in android 5.1.1 devices but working perfect on below versions I have developed cross platform app with sencha framework.I have targeted  it for android API 22 which is 5.1.1 and with Cordova 5.0.0 .Works perfectly fine with 5.0.2 device but in 5.1.1 it doesn't render its view just shows a blank white screen after splash screen ,no idea on whats going wrong please little help is appreciated .
One wired senario :When run the app on 5.1.1 device and lock the phone at app initialize and when unlock the phone after some time  the view is rendered .


text:
Q: Mac Mini with Intel HD 5000 or Intel Iris Graphics, what exactly is supported OpenGL version? Apple's site does not appear to have the information.  I found a site that says Intel HD Graphics 5000 supports DX11.1 and OpenGL4.0.  Anyone have specific information about the exact OpenGL version for the Mac Mini with either of these graphics options?  I want to upgrade from my older Mac Mini but require support for compute shaders (GPGPU), which means OpenGL 4.3 or later.

A: On OSX, OpenGL is part of the Operating System API. As a result, the OpenGL version is limited by the OSX version no matter what the GPU is capable of.
Currenly (as of mid 2015), OSX 10.10 will support at most GL 4.1. There is no support for OpenGL compute shaders at all, on this platform.
Have a look at Apple's OpenGL capabilities tabe for more details. (Version 10.10 is not in this table currently, but the GL 4.1 limit applies there, too).


text:
Q: How to send keys to a python pdb shell from bash script? I am trying to create a bash script that runs a python3 script with pdb trace set. As such, in my bash script I have the following lines:
python3 path/to/my_script.py
n

What I want to happen is for bash to run the python script, which will then open the python debugger. Then, the bash script will send the key 'n' to the pdb shell so that pdb executes the first line in the python script.
The script does not work as expected and bash waits until the python script has completed (or exited) to execute 'n' in the command line which just opens node.
I thought this might be a problem unique to pdb shells so I tried executing the following in bash:
python3
print("Hello")

However, again, we observe that the script creates a python3 shell and then waits for the shell to exit before executing print("Hello") in the terminal. I understand that I could use python3 -c for this case, but that does not address the case of passing commands to the pdb shell in the context of the running script.
Is there any way to send the 'n' command to the pdb shell that the python script generates?

A: Your code will try to run two commands. First, it will run your python script, then it will try to run a command called n. Assuming your script needs you read from stdin you can do one of the following:
Use a herestring:
python3 path/to/my_script.py <<< "n"
Use a pipeline:
One example echo "n" | python3 path/to/my_script.py
Echo is not the only command you can use. You can also use printf or even yes for this use case.

A: You can use a coprocess to send and receive from pdb.
#! /bin/bash

send() {
    echo "$1" >&${PDB[1]}
}

recv() {
    IFS= read -r -u ${PDB[0]} line
    echo $line
}

coproc PDB { /path/to/my_script.py; }
send 'n'
recv
#...
send 'n'
recv


text:
Q: Can someone explain the logic here? So I was doing some practice on creating a python class to convert int to roman numerals, my solution works but it would be an extremely long code to convert all possible numbers so I checked the solution on the page (code below) which obviously works but I don't understand the logic in the for loop, could someone please explain it?
class py_solution:
    def int_to_Roman(self, num):
        val = [
            1000, 900, 500, 400,
            100, 90, 50, 40,
            10, 9, 5, 4,
            1
            ]
        syb = [
            "M", "CM", "D", "CD",
            "C", "XC", "L", "XL",
            "X", "IX", "V", "IV",
            "I"
            ]
        roman_num = ''
        i = 0
        while  num > 0:
            for _ in range(num // val[i]):
                roman_num += syb[i]
                num -= val[i]
            i += 1
        return roman_num

print(py_solution().int_to_Roman(0))
print(py_solution().int_to_Roman(1400))

A: Well, first you need to notice the // operator, which is floor division.
In the case of int_to_Roman(0) the program doesn't not get into the while nor for because num is not greater than 0.
In the second case, int_to_Roman(1400), the range is 1. Because 1400/1000 is 1.
Then roman_num would be M and num = 400 (1400-1000).
Now the value of i is 1.
Since num is greater than 0, we enter the for loop again. This time val[1] is 900, thus the result of 400 // 900 is 0, nothing to do, go to next step.
Now i=2 and val[2] is 500, again the range is 0. Next step.
i=3, val[3] is 400, now the range is 1 (400 // 400).
roman_num is M + CD and num = 0.

End of the while and the returned value is MCD.

A: What specifically do you not understand? Try commenting what each line is doing, e.g.:
i = 0
while  num > 0:
    for _ in range(num // val[i]): # Loop the number of times current value divides num
        roman_num += syb[i]        # Add the current symbol to the answer
        num -= val[i]              # Subtract current value from number
    i += 1                         # Go to the next value/symbol

This could be simplified:
i = 0
while num > 0:
    x = num // val[i]
    num -= val[i]*x
    roman_num += syb[i]*x          # Add x times the current symbol
    i += 1

Note:
num -= val[i]*x   # x = num // val[i]

Is equivalent to:
num %= val[i]     # The remainder (modulus)

The while loop isn't really doing anything because num will always be 0 for the last value of 1, so you can just loop over the indexes of value and symbol:
for i in range(len(val)):
    x = num // val[i]
    num %= val[i]
    roman_num += syb[i]*x

Note:
x = num // val[i]
num %= val[i]

Is equivalent to:
x, num = divmod(num, val[i])

Looping over an index is considered not very pythonic, when you can iterate directly over the values and symbols:
for v, s in zip(val, syb):
    x, num = divmod(num, v)
    roman_num += s*x

Note: the value and symbols have to be in descending order for either of these loops to work.


text:
Q: Calling PHP function from wordpress using admin ajax? i have a function in wordpress and would like to call it in ajax using wordpress admin ajax
this is the function
add_action( 'after_setup_theme', 'pixel_cookie_consent2' );

function pixel_cookie_consent2() {

$cookie = ( isset( $_COOKIE['moove_gdpr_popup'] ) ) ? $_COOKIE['moove_gdpr_popup'] : false;
$cookie = stripslashes( $cookie );
$cookie = json_decode( $cookie, true );

// disabled by default
deactivate_plugins( '/woocommerce-conversion-tracking/conversion-tracking.php' );

// enabled based on user setting
if ( $cookie['thirdparty'] == 1 ) {
        activate_plugins( '/woocommerce-conversion-tracking/conversion-tracking.php' );
   }
}

this function disables the plugin before user accepts cookies (gdpr law).
When user accepts cookies the plugin is enabled and cookie is fired.
My problem is when i turn cache on this does not work properly because page is cached with plugin off and then it does not turn on, so i thought calling the function using ajax.
Can anyone help me how to achieve this?


text:
Q: How Can we use Nashorn with Java 17? I know that, Java Nashorn has been removed onwards java 15.
I want to know, how can we use external openjdk nashorn engine(https://search.maven.org/artifact/org.openjdk.nashorn/nashorn-core/15.0/jar) in a java code.
It would be better, if anyone can explain with an example

A: It should be pretty much a drop-in replacement so everything written in Nashorn User's Guide within Oracle Java 14 documentation (with examples) should be a good place to start. If you depend in your Java code on Nashorn, you'll need to update the package names in imports from jdk.scripting.nashorn to org.openjdk.nashorn.
Make sure to download the latest version from Maven Central, though (15.4 at this time, not 15.0 which you linked in your post.) Also make sure you have the ASM library dependencies in your classpath as well.


text:
Q: Help with PostInstall Test Method Assert I'm having trouble adding an Assert to the Test Method in my PostInstall Email Class.  Can anyone point me to a resource or identify where I'm going wrong in my code?  Thanks!
global class PostInstallEmail implements InstallHandler {
  global void onInstall(InstallContext context) {
    if(context.previousVersion() == null) {

      User u = [Select Id, Email from User where Id =:context.installerID()];
      String toAddress= u.Email;
      String[] toAddresses = new String[]{toAddress};
      Messaging.SingleEmailMessage mail =
        new Messaging.SingleEmailMessage();
      mail.setToAddresses(toAddresses);
      mail.setReplyTo('noone@gmail.com');
      mail.setSenderDisplayName('App Support');
      mail.setSubject('Complete Your App Installation');
      mail.setPlainTextBody('Thanks for installing my app!');
      Messaging.sendEmail(new Messaging.Email[] { mail });
      }
    }

    @isTest
    static void testInstallScript() {
        PostInstallEmail postinstall = new PostInstallEmail ();
        Test.testInstall(postinstall, null);
  }

  }

A: I'm not sure if limits are available in InstallHandler, but it's worth a try to check Limits.getEmailInvocations() before and after.
@isTest
static void testInstallScript() {
    Integer beforeInstall = Limits.getEmailInvocations();
    PostInstallEmail postinstall = new PostInstallEmail ();
    Test.testInstall(postinstall, null);
    system.assert(Limits.getEmailInvocations() > beforeInstall);
}


text:
Q: Adding numbers to running total in jquery loop I have a variable that is supposed to hold a running total. On each pass of this loop, and amount should be added to the running total. I must be missing something, since I get either undefined or NaN.
$('#btnSubmit').click(function(e) {
    var totalSqft;
    $('.fieldset').each(function() {
        var sqft;
        var width = $(this).find('input:eq(0)').val();
        var height = $(this).find('input:eq(1)').val();
        var type = $(this).find('select').val();
        if (type == 'tri') {
            sqft = (width * height) / 2;
        } else {
            sqft = (width * height);
        };
        totalSqft += sqft;
        alert('this ' + type + ' is ' + width + ' wide and ' + height + ' high, for a total of ' + sqft + ' square feet');
    });
    alert('Done.  Total Sq Ft is ' + totalSqft);
})

A: You need to initialize the value to 0:
var totalSqft = 0;

Otherwise, it gets initialized to undefined, and undefined + a number is NaN.


text:
Q: Binding ViewModel to ViewController (ReactiveCocoa) iOS i am implementing simple facebook/google login for now. But trying to apply MVVM pattern with ReactiveCocoa in my project. I am not able to bind the viewModel with viewControllers . Tried CocoaActions but not able to make it work.
View Model :
let name = MutableProperty<String>("")
let email = MutableProperty<String>("")
let phoneNo = MutableProperty<String>("")
let referal = MutableProperty<String>("")

var fbLoginAction:Action<OnboardingViewController,Bool,NSError>

View Controller :
        //MARK: Signup Binding
    let loginCocoaAction = CocoaAction(viewModel.fbLoginAction., input:())
    signupView.fbBtn.addTarget(loginCocoaAction, action: CocoaAction.selector, forControlEvents: .TouchUpInside)

A: Its been a while since this question was posted. Since then, RAC 5.0.0 has been released which makes this a lot easier, thanks to UI Bindings:
Assuming, you have fbLoginAction ready as defined in the View Model, you can bind this action to a button in the View Controller like this:
signupView.fbBtn.reactive.pressed = CocoaAction(fbLoginAction, input: self)

Your original problem was probably because you provided () as input, but the input of your fbLoginAction is defined as OnboardingViewController.
Depends on whether you actually meant to do that and need the OnboardingViewController as input to the fbLoginAction, you can do it as posted above with input: self, or if you don't actually need the input, you can change it to
let fbLoginAction:Action<(),Bool,NSError>

and
signupView.fbBtn.reactive.pressed = CocoaAction(fbLoginAction)


text:
Q: C - How to write linked list pointer contents to a text file I have a program that has an array of pointers such as:
INTLIST* myArray[countOfRows];

each myArray pointer points to a linked list, basically it becomes an M*N matrix.
So for example:
3 2 1
2 1 0
1 9 8

So myArray[0] is a linked list with 3->2->1 and myArray[1] is a linked list with 2->1->0.. and so on.  I have a function that prints the matrix which basically does this:
for(int i = 0; i<countOfRows; i++)
   list_print(myArray[i]);

And then my list_print function is like so:
 void list_print(INTLIST* list)
  { /* This function simply prints the linked list out */
     INTLIST* temp=NULL;  //temp pointer to head of list

     /* loops through each node of list printing its datum value */
     for(temp=list; temp!=NULL; temp=temp->next)
        {
           printf("%d ", temp->datum);         //print datum value
        }
     printf("\n");
  }

This is all great and working fine, (I know i could optimize and clean up and I promise to do so).  Now my next question is I need to write this matrix out to a text file.  So I tried this:
 char* outputFileName = "out.txt";
 FILE* ofp;

 ofp=fopen(outputFileName, "w");

 if(ofp == NULL)
 {
        printf("Cannot open writeable file!");
        return -1;
 }

 for(i=0; i<fileLineCount; i++)
  {
     fprintf(ofp, list_print(aList[i]);
  }

But I take it its not that simple.  Can anyone show me how to print this out to a text file...
Thanks

A: Use the fprintf function in your list_print function using a FILE * parameter as shown in the example:
void list_print(INTLIST* list, FILE *fp)
  { /* This function simply prints the linked list out */
     INTLIST* temp=NULL;  //temp pointer to head of list

     /* loops through each node of list printing its datum value */
     for(temp=list; temp!=NULL; temp=temp->;next)
        {
           fprintf(fp, "%d ", temp->datum);         //print datum value
        }
     fprintf(fp, "\n");
  }

Would be done like this:
int main(){
   FILE *fp;
   fp = fopen("data.txt", "w");
   for(i=0; i<fileLineCount; i++)
   {
      list_print(alist[i], fp);
   }
   fclose(fp);
}

Or
If you wish to retain the binary dump of the linked list from memory to disk (this is the simple way of explaining it), top off my head:
for(i=0; i<fileLineCount; i++)
{
     fwrite(alist[i], sizeof(alist[i]), 1, ofp);
}

Then when reading from it,
for(i=0; i<fileLineCount; i++)
{
     fread(&alist[i], sizeof(alist[i]), 1, ofp);
}

Edit: I was hesitant to include the above, but paxdiablo pointed out a flaw in my fread(...) and fwrite(...) code above, and realized he is right. When doing the binary write of the linked list, the memory addresses references in the linked-list will be invalid when read in the next time. Thanks paxdiablo!

A: You can't use printf function to write to file. You need to replace all printf calls with fprintf and pass the FILE pointer along of course.
You can change the list_print to accept FILE* so you can write your data to file. Something according to this scheme:
void list_print(FILE* fp, INTLIST* list)
{
    /* ... rest of your code */

    fprintf(fp, "%d ", temp->datum);

    /* ... rest of your code */
}

A: There's a couple of things I would do to your list_print function:

*

*pass a FILE* variable so you can specify where the file is to go.

*not initialise temp to NULL since you set it in the for statement anyway.

That would give you something like:
void list_print(FILE *fOut, INTLIST* list) {
    INTLIST *temp;
    for (temp = list; temp != NULL; temp = temp->next)
        fprintf (fOut, "%d ", temp->datum);
    fprintf (fOut, "\n");
}

In order to use it to print to the standard output, just use:
list_print (stdout, list);

since stdout is simply a FILE* for standard output (and you can also use stderr if you wish). If you want to write it to a file:
FILE *fp = fopen ("output_file.txt", "w");
if (fp == NULL) {
    // Flag an error.
} else {
    list_print (fp, list);
    fclose (fp);
}

There's also a change you can make to get rid of the extraneous space at the end of each line when the particular list is not empty. At the moment, a list (1,2,3) will print as (the _ characters are spaces):
1_2_3_

If you change the function to be:
void list_print(FILE *fOut, INTLIST* list) {
    INTLIST *temp;
    char *sep = "";
    for (temp = list; temp != NULL; temp = temp->next) {
        fprintf (fOut, "%s%d", sep, temp->datum);
        sep = " ";
    }
    fprintf (fOut, "\n");
}

it will get rid of that extraneous space at the end. Whether this is actually necessary is a decision for you to make - I've often done this to have a specific output format without making the code too much uglier but it may well be that the space at the end doesn't cause you any trouble.

A: list_print needs to use fprintf or it's output will got to standard out rather than to the file.
Which means you need to pass ofp as a parameter to list_print
also, it makes no sense to fprintf(..., list_print()), since list_doesn't return anything.
just call list_print in that loop.

A: You're trying to print out the result of list_print(), which is void.
You'll need to write a new version of your list_print function, which accepts a FILE* and a list, and replace printf there with fprintf
To save the common code, you could replicate your original by something like the following:
void list_fprint (FILE * out, INTLIST * list) {
   . . . // as described above
}

void list_print (INTLIST * list) {
   list_fprint(stdout, list);
}


text:
Q: how to see the activation values of hidden layer in tensorflow I implement stacked autoencoder using tensorflow library. it work properly. now i am trying to see hidden layer activation values (y1,y2,y3,y4,y5). but i do not find any way to see that. here is my code.
x= tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder(tf.float32,[None,6])
k=190
l=180
m=150
n=130
o=100
num_of_epoch=10
w1=tf.Variable(tf.truncated_normal([784,k],stddev=0.1))
b1=tf.Variable(tf.zeros([k]))
w2=tf.Variable(tf.truncated_normal([k,l],stddev=0.1))
b2=tf.Variable(tf.zeros([l]))
w3=tf.Variable(tf.truncated_normal([l,m],stddev=0.1))
b3=tf.Variable(tf.zeros([m]))
w4=tf.Variable(tf.truncated_normal([m,n],stddev=0.1))
b4=tf.Variable(tf.zeros([n]))
w5=tf.Variable(tf.truncated_normal([n,o],stddev=0.1))
b5=tf.Variable(tf.zeros([o]))
w6=tf.Variable(tf.truncated_normal([o,6],stddev=0.1))
b6=tf.Variable(tf.zeros([6]))
y1=tf.nn.relu(tf.matmul(x,w1)+b1)
y2=tf.nn.relu(tf.matmul(y1,w2)+b2)
y3=tf.nn.relu(tf.matmul(y2,w3)+b3)
y4=tf.nn.relu(tf.matmul(y3,w4)+b4)
y5=tf.nn.relu(tf.matmul(y4,w5)+b5)
y=tf.nn.softmax(tf.matmul(y5,w6)+b6)
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),
reduction_indices=[1]))
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for i in range(num_of_epoch):
        train_data = {x:x_train,y_:y_train}
        sess.run(train_step,feed_dict=train_data)
    currect_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
    accuracy=tf.reduce_mean(tf.cast(currect_prediction,tf.float32))
    sess.run(accuracy,feed_dict={x:x_train,y_:y_train})
    currect_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
    accuracy=tf.reduce_mean(tf.cast(currect_prediction,tf.float32))
    sess.run(accuracy,feed_dict=   {x:x_test,y_:y_test})

if you know the way please share with me or give the any effective link where i can find the wright answer. thank in advance.


text:
Q: make multiple calls to same async tasks with different data c# I have a list which contains some documents (for simplicity strings). Now the list is getting populated slowly. What I want to do is when the size of the list reaches 20 I want to call another function that will print these strings asynchronously without stopping the main method. After lot of searching I have managed to put together this code
public void DoStuff()
{
    Class1 p = new Class1();
    List<string> list = new List<string> { };
    var TList = new List<Task>();
    int i = 0;
    while (i < 90)
    {
        list.Add(i.ToString());
        if (list.Count == 20)
        {
            Console.WriteLine("List contents when calling: " + list[0]);
            TList.Add(Task.Run(() => publishDoc(list)));
            list.Clear();
        }
        i++;
    }
    if (list.Count != 0)
    {
        TList.Add(Task.Run(() => publishDoc(list)));
    }
    Task.WhenAll(TList).Wait();
    Console.WriteLine("Done DoStuff");
}

public async Task publishDoc(List<string> docs)
{
    Console.WriteLine(iter++ + " " + docs[0]);
    await Task.Run(() => Thread.Sleep(1000));
    foreach (var val in docs)
    {
        Console.Write(val + " ");
    }
    Console.WriteLine();
}

This is what I am getting as output
List contents when calling: 0
List contents when calling: 20
List contents when calling: 40
List contents when calling: 60
1 80
3 80
0 80
2 80
4 80
80 80 80 80 81 82 83 84 85 86 87 88 89
81 82 83 84 85 86 87 88 89
81 82 83 84 85 86 87 88 89
81 82 83 84 85 86 87 88 89
80 81 82 83 84 85 86 87 88 89
Done DoStuff
Done Main

I can't figure out why it is only printing the last passed data i.e. why the passed list is getting overwritten.
Now if I do this
public void DoStuff()
{
    Program2 p = new Program2();
    List<string> list = new List<string> { };
    int i = 0;
    while (i < 90)
    {
        list.Add(i.ToString());
        if (list.Count == 20)
        {
            Console.WriteLine("List contents when calling: " + list[0]);
            var tasks = publishDoc(list);
            if (tasks.Result == "Done")
            {
                Console.WriteLine("Done " + list[0]);
            }
            list.Clear();
        }
        i++;
    }
    if (list.Count != 0)
    {
        var tasks = publishDoc(list);
        if (tasks.Result == "Done")
        {
            Console.WriteLine("Done " + list[0]);
        }
    }
    Console.WriteLine("Done DoStuff");
}

public async Task<string> publishDoc(List<string> docs)
{
    Console.WriteLine(iter++ + " " + docs[0]);
    foreach (var val in docs)
    {
        Console.Write(val + " ");
    }
    Console.WriteLine();
    return await Task.Run(() => "Done");
}

I get this output
List contents when calling: 0
0 0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Done 0
List contents when calling: 20
1 20
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
Done 20
List contents when calling: 40
2 40
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
Done 40
List contents when calling: 60
3 60
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
Done 60
4 80
80 81 82 83 84 85 86 87 88 89
Done 80
Done DoStuff
Done Main

This is giving the correct output but is doing it synchronously which I don't want. Please help and thanks in advance.

A: you have to do like this , as in loop it points to same instance of list every time that might causing issue , so I suggest you create copy of list before passing it to function publishDoc
while (i < 90)
    {
        list.Add(i.ToString());
        if (list.Count == 20)
        {
            List<string> copy = list.ToList();
            Console.WriteLine("List contents when calling: " + copy[0]);
            TList.Add(Task.Run(() => publishDoc(copy)));
            list.Clear();
        }
        i++;
    }

Refer this answer also : Starting Tasks In foreach Loop Uses Value of Last Item


text:
Q: AJAX get multipart response I'm working in a Phonegap project with Restfull Web Services and I need to obtain a PDF file by one of them. I can obtain response using Ajax but I don't know how to work with multipart response. If I read response as always and write a .pdf file with info between "%PDF-1.4" and "EOF", the result file it's a white PDF without information.
I had tried mpAjax project like this:
jQuery.ajax({
   async: false,
   url: urlWS,
   data: info,
   contentType:'application/json;charset=UTF-8',
   type: 'post',
   success:{
     "application/json": function (response) {alert('info: ');},
     "application/pdf":callback_handleData
   },
   error: function (xhr, ajaxOptions, thrownError) {
         alert('AJAX ERROR');
   }
});

But no alert was thrown.
Response example:
--uuid:7c26de68-83e9-456a-a986-65dfa8e74d88

Content-Type: application/json;charset=UTF-8

Content-Transfer-Encoding: binary

Content-ID: <ROOT>

{"attachedContenId":"DOC","document":{"docName":"38522672H ","mimeType":"application/pdf","itemType":"FACTURASSIC","nodeId":"cm://FACTURASSIC/ITEMID:A1001001A13G04A93633J51684","size":1120990},"props":[{"atribute":"IDCLIENTE","value":"38522672H "},{"atribute":"NUMPOL","value":"000413SC "},{"atribute":"NUMFACTURASIC","value":"AB20130622824"},{"atribute":"FECHA","value":"2013-01-25"},{"atribute":"ENTIDAD","value":"2013 "},{"atribute":"APARTADO","value":"0056"},{"atribute":"FECHAFACT","value":"2013-01-16"},{"atribute":"TIPODOC","value":"FACTURA1CA_12031"}],"error":""}

--uuid:7c26de68-83e9-456a-a986-65dfa8e74d88

Content-Type: application/pdf

Content-Transfer-Encoding: binary

Content-ID: <DOC>

%PDF-1.4
%����
3 0 obj
<</Length 25

Any idea?


text:
Q: WebBrowser control get form action I have a Windows Form with a WebBrowser control in it. I'm going to a page and I want the action of the form on that page.
SO when the HTML of the page looks like this:
<!doctype html>
<head>
    <title>testing</title>
</head>
<body>
    <form action="http://www.testing.nl/form.php?hoi=true" >

    </form>
</body>
</html>

I want to receive http://www.testing.nl/form.php?hoi=true in C#. How can I do that?
-note- The URL is fake, just to show what i want...

A: This will go through all the forms in the webpage and extract the action attribute for each one:
var actions = new List<string>();
if (webBrowser1.Document != null)
{
    actions.AddRange(from HtmlElement form in webBrowser1.Document.Forms select form.GetAttribute("action"));
}

You have to make sure that the page is fully loaded.


text:
Q: How do javascript libraries ignore certain parameters, or make certain function parameters "optional"? I will use Node.js as an example but I see this in many docs:
(From the net module documentation):

net.createConnection(port, [host], [connectListener])
Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as an listener for the 'connect' event.

This is followed with example code such as the following:
a = net.createConnection(8080, function(c){
    console.log('do something');
});

My question is that the createConnection function takes from 1 - 3 parameters. Above, I passed in two.  How is it that Node is able to know the function argument I passed in is meant as the connectListener argument and not the host argument?

A: If the parameters have different types, you can simply test for them. Here port is probably a number, host a string and connectionListener is a function.
For example:
function createConnection(port, host, connectionListener) {
    if (typeof host === 'function') {
        conectionListener = host;
        host = null;
    }
    if (!host) {
        host = 'localhost';
    }
    // ...
}

Of course this doesn't work if the parameters are of the same type. There is no a general solution for that case.

A: I don't specifically know the implementation of createConnection, but one possible way to do this would be to count the arguments passed to the function as well as checking their type, something like:
function createConnection(port, host, connectListener) {
    var f = connectListener;
    if(arguments.length === 2 && typeof host === "function") {
        f = host;
        host = "localhost";
    }
    console.log("Host: " + host);
    console.log("Port: " + port);
    f();
}

createConnection(8080, function() {
    console.log("Connecting listener...");
});

Here is a fiddle.

A: Maybe it is internally calling net.createConnection(options, [connectionListener]), so that the parameters are mapped properly.
Reference:
http://nodejs.org/api/net.html#net_net_createconnection_options_connectionlistener

A: The type can be inspected, thus checking parameter 2 is a function allows such behavior Handling optional parameters in javascript


text:
Q: Filter on different fields on array of objects In Elasticsearch, say I have the document like this:
{
  "id": "testId",
  "inputs": [
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-06-10T00:00:00.000Z"
    },
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    },
    {
      "status": "ENDED",
      "lastUpdatedTime": "2020-06-11T00:00:00.000Z"
    }
  ]
}

Now, I wanted to filter all the documents such that I would get all the documents with status as ENDED and lastUpdatedTime should be highest in the input array. Eg. in above case, it will return this document as 2020-06-11T00:00:00.000Z > 2020-06-10T00:00:00.000Z and 2020-05-11T00:00:00.000Z and status is ENDED. But say, for below document, it won't return:
{
  "id": "testId2",
  "inputs": [
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-06-10T00:00:00.000Z"
    },
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    },
    {
      "status": "ENDED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    }
  ]
}

This is because in this document STARTED has the largest lastUpdatedTime. How can I do this kind of filtering in Elasticsearch easily or it is not possible?

A: By this, below query you will get the result such that lastUpdatedTime should be highest in the input array corresponding to the STATUS="ENDED"
But this just solves only 1 part of your answer, the same query will not give you the desired result (i.e will not work for your second case where highest value of lastUpdatedTime is for STARTED)
Mapping:
{
  "mappings": {
    "properties": {
      "inputs": {
        "type": "nested"
      },
      "lastUpdatedTime": { "type": "date" }
    }
  }
}

Search Query:
{
  "query": {
    "nested": {
      "path": "inputs",
      "query": {
        "match": {"inputs.status":"ENDED"}
      },

      "inner_hits": {
        "sort": [
    {
      "lastUpdatedTime": {
        "order": "desc"
      }
    }
  ],
  "size": 1
      }

    }
  }
}

Result:
"inner_hits": {
      "inputs": {
        "hits": {
          "total": {
            "value": 1,
            "relation": "eq"
          },
          "max_score": null,
          "hits": [
            {
              "_index": "my_index",
              "_type": "_doc",
              "_id": "-s2KpnIBXf9A6l_vBbmP",
              "_nested": {
                "field": "inputs",
                "offset": 2
              },
              "_score": null,
              "_source": {
                "status": "ENDED",
                "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
              },
              "sort": [
                -9223372036854775808
              ]
            }
          ]
        }
      }
    }


text:
Q: Swift transition animation does not work when subclassing UIView When applying this animation to a UIView, UIButton or UILabel after connecting it to my ViewController and calling from ViewDidAppear, it works fine:
 UIView.transition(with: self.myButton, duration: 5, options: .transitionFlipFromRight, animations: nil, completion: nil)

However, the problem is, when I input that animation in a custom class inheriting from UIView, set it to that object in my storyboard, and pass "self" into the "with:" parameter, and put it on AwakeFromNib, it does not work:
class myAnimatedView: UIView {

    override func awakeFromNib() {
         self.layoutIfNeeded()
         UIView.transition(with: self, duration: 15, options: .transitionFlipFromRight, animations: nil, completion: nil)}
    }

}

Other animations I have applied work fine on AwakeFromNib on such a subclass -
 for example this  works fine :
UIView.animate(withDuration: 5.0, delay: 0.5, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations:({//my animations here}))

What am I doing wrong? Using Xcode 9.1, Swift 4. Many thanks

A: I think there are some problems in your code/architecture:

*

*awakeFromNib is not that right place for triggering animations, please check here

*you say that adding this
UIView.animate(withDuration: 5.0, delay: 0.5, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations:({//my animations here}))

in your awakeFromNib was fine, but I notice a delay of 0.5 so the view was ready and well awakened when the animation was being launched

eventually you might use didMoveToWindow() for auto-animate your stuff
https://developer.apple.com/documentation/uikit/uiview/1622527-didmovetowindow


text:
Q: How do I programmatically create an EndPoint for use with an HttpWebRequest in a Cmdlet? Keep in mind folks, the proxy/client WCF classes generated by SvcUtil.exe and/or Add Service Reference do NOT always work. Thus you have to do things 'by hand' / 'the hard way'.
Just say'en.
In fact, this is a problem I'm having. I have to talk to a web service written in Java and the WSDL it spits out is so .. fraked up, that generated code simply doesn't work. SO, I have to make the SOAP calls by using HttpWebRequest. This is no problem when you can at least have an app.config within which to set up the end point info.
Naturally, in my case, I'm now trying to talk to this POS Java service within a Cmdlet, which means it's in a DLL and thus can't use an app.config.
So, the question now is; how the heck do I programmatically create / use BasicHttpBinding and EndPointAddress objects (and are those even the right one's) with an HttpWebRequest?

A: I agree with you that, consuming JAVA webservice in .NET is a bit nasty especially with the faultcontracts, ReplyAction & the signature coming up with extra wrappers (like type).
The approach I took for a similar need, was by manually rewriting the reference class generated by svcutil.
If the alternative now is to invoke the Java service using HttpWebRequest, then why do we need the Bindings? Assuming, this Java Service is over http, can it not be invoked directly using post/get?
Please could you post more details.
@EDIT: Also, please refer to Consume Web Service with POST from a WCF Service


text:
Q: When is a filepath neccessary using pandas when working with an excel file? I am trying to get into pandas and I am confused here is a program that reads from an excel file and it works without giving it a filepath when the excel file is in the same folder as the python program:
import pandas as pd

excel_file = "RandomExcelNumbers.xlsx"
xldata = pd.read_excel(excel_file, sheet_name= "Sheet1")

xl_Value1 = xldata["ColTitle2"][0]
print(xl_Value1)

Now I tried something different:
import pandas as pd

filename = "Test.xlsx"

def read_value_from_excel(filename, column="C", row=3):
    """Read a single cell value from an Excel file"""
    return pd.read_excel(filename, skiprows=row - 1, usecols=column, nrows=1, header=None, names=["Value"]).iloc[0]["Value"]

print(read_value_from_excel(filename, "C", 3))

and it gives me this error message: FileNotFoundError: [Errno 2] No such file or directory: 'Test.xlsx'
Please, what's the difference between these two programs? One needs the filepath, the other does not? Why is that? Is there a way to not neccessarily give the filepath in program no. 2 and let the program compile?
Thank you!


text:
Q: Is there a way to modify a datatable, like filter the information? Actually I have a html.twig file in which I have the next datatable:
--------------------------------------
Audits       |          Areas
--------------------------------------
     1         |         Area1
     2         |         Area1     3         |         Area1     4         |         Area1
     5         |         Area2     6         |         Area2     7         |         Area2     8         |         Area2
--------------------------------------
Screen shot of the Current Datatable
But I what want to do is to show the datatable in this way:
--------------------------------------
Audits       |          Areas
--------------------------------------
1, 2, 3, 4  |         Area1
5, 6, 7, 8  |         Area2
--------------------------------------
This is how I get the info in my controller:
$em = $this->getDoctrine()->getEntityManager();

        $auditsByAuditor = $em->getRepository('FSABundle:FsaAudits')
                            ->findBy(array('idAuditor'=>$auditor->getId()));

        return $this->render('FSABundle:FsaAudits:FsaPlan.html.twig', array(
            'currentPlan' => $currentPlan,
            'auditsByAuditor' => $auditsByAuditor
        ));

This is how I have the html.twig:

                {% for message in app.session.flashbag().get('status') %}

{{message}}

                    {%endfor%}

                                Auditorias
                                Areas

                            {% for audit in auditsByAuditor %}

                                    {{ audit.idAudit }}
                                    {{ audit.idArea}}

                            {% endfor %}

Any idea or advice about how to make it?


text:
Q: Graphical User Interface I am doing development in C++. I heard that GTK is being replaced by Wayland.
Which GUI libraries are suitable for C++ for long-term?

A: Wayland is a replacement for X11. GTK+ is still the GUI toolkit used by GNOME and some other desktop environments and there are no plans to replace it.
The two big GUI libraries for Linux are Qt and GTK+. Both can be used with C++ and are likely to stay for the foreseeable future.
Which one is better for you depends on which desktop environment is your primary target. Both libraries can be used with any desktop environment but your app will have a different look and feel if it's using the "wrong" GUI toolkit for your desktop environment.
If you want your app to be used on other systems than Linux Qt is usually the better choice.

A: Glade
Although you can use C++ code to instantiate and arrange widgets, this can soon become tedious and repetitive. And it requires a recompilation to show changes. The Glade application allows you to layout widgets on screen and then save an XML description of the arrangement.
This has the following advantages:

*

*Less C++ code is required.

*UI changes can be seen more quickly, so UIs are able to improve.

*Designers without programming skills can create and edit UIs.

The user interfaces designed in Glade are stored in the well-known XML format, enabling easy integration with external tools. You will probably want to use it with tools such as libglade, which can load the XML files and create the interfaces at runtime.
To install Glade GTK+ User Interface Builder in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install glade

To install only the development files for the GTK+ library without installing Glade type:
sudo apt install libgtk-3-dev

Qt Creator
Qt Creator is a cross-platform integrated development environment (IDE)  designed to make development with the Qt application framework faster and easier.
It includes:

*

*An advanced C++ code editor

*Integrated GUI layout and forms designer

*Project and build management tools

*Integrated, context-sensitive help system

*Visual debugger

*Rapid code navigation tools

*Supports multiple platforms

*Qt Quick Designer

To install QT Creator in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install qtcreator

$ apt-cache depends qtcreator | grep qt
qtcreator
  Depends: libqt5sql5-sqlite
  Depends: qml-module-qtqml-models2
  Depends: qml-module-qtquick-controls
  Depends: qml-module-qtquick2
  Depends: qtchooser
    qtchooser:i386
  Depends: qtcreator-data
  Depends: libqbsqtprofilesetup1.10
  Depends: libqt5concurrent5
  Depends: libqt5core5a
  Depends: libqt5designer5
  Depends: libqt5designercomponents5
  Depends: libqt5gui5
  Depends: libqt5help5
  Depends: libqt5network5
  Depends: libqt5printsupport5
  Depends: libqt5qml5
  Depends: libqt5quick5
  Depends: libqt5quickwidgets5
  Depends: libqt5sql5
  Depends: libqt5widgets5
  Depends: libqt5xml5
  Depends: <qtdeclarative-abi-5-9-5>
    libqt5qml5
  Recommends: qt5-doc
  Recommends: qt5-qmltooling-plugins
  Recommends: qtbase5-dev-tools
    qtbase5-dev-tools:i386
  Recommends: qtcreator-doc
  Recommends: qtdeclarative5-dev-tools
    qtdeclarative5-dev-tools:i386
  Recommends: qttools5-dev-tools
    qttools5-dev-tools:i386
  Recommends: qttranslations5-l10n
  Recommends: qtxmlpatterns5-dev-tools
    qtxmlpatterns5-dev-tools:i386
    qterminal

(Click image to enlarge)


text:
Q: Using minitest methods in capybara ruby implementation? Im very new at ruby coding and I always use capybara native methods.
Now, I need to use some assert methods for unit testing only available in rspec matchers or minitest. Rspec was discarded because some gem trouble in system machine...so.....minitest is the choice.
My question is:
Can only access to minitest methods using class like this? (see in documentation)
require "minitest/autorun"

class myTest < Minitest::Test

If I already have my class like this:
class myTest < BasePageExample

def method1()
  "needed assert_equal(.............)"
end
end

How can I import minitest for my existant class and use assert_equal method???
Thanks!!!


text:
Q: How to get IQueryable() instead of List() using LinQ? Data structure:
class Journal
{
    public int JournalId {get; set;}
    public DateTime JournalDate {get; set;}
    public string OwnerId {get; set;}
}

class Event
{
    public string EventId {get; set;}
    public string EventName {get; set;}
}

Is there any way to get
First of all I get that List of values
var events = DBContext.Events.Where(o => o.EventName.Contains(searchParam)).AsQueryable();
var values = events.Select(x => x.EventID).ToList();

I only know how to put query results to list in foreach cycle. I created new list put there all values where events in list of values I need
JournalList  = new List<Journal>();
foreach (string eventId in values)
{
   var results = DBContext.Journals.Where(j => j.eventID.Equals   (eventId)).ToList();
   RegJournalList.AddRange(results);
}

GroupedList = JournalList.Select(t => new JournalGrouped()
{
  JournalID = t.JournalID,
  JournalDate = t.JournalDate
}).Distinct().ToList();

Is there a way to have IQueryable() instead of JournalList?

A: I suggest you look into join. It is basically what you are trying to do
var result = (from event in DBContext.Events
              where event.EventName.Contains(searchParam)
              join journal in DBContext.Journals on event.EventID equals journal.JournalID
              select new JournalGrouped()
              {
                JournalID = journal.JournalID,
                JournalDate = journal.JournalDate
              }).Distinct().ToList();

Or better still since you are using Entity Framework use navigation properties and let the framework do the work for you. After defining the navigation properties it will look something like:
from journal in DBContext.Journals.Include("full name of your Event class")
where journal.Event.EventName.Contains(searchParam)
select new JournalGrouped()
{
   JournalID = journal.JournalID,
   JournalDate = journal.JournalDate
}

If you for some reason what to stick with the way you currenly are doing it then:
var values = DBContext.Events.Where(o => o.EventName.Contains(searchParam))
                             .Select(x => x.EventID);

var GroupedList = DBContext.Journals.Where(j => values.Contain(j.eventID))
                                    .Select(t => new JournalGrouped()
                                    {
                                        JournalID = t.JournalID,
                                        JournalDate = t.JournalDate
                                    }).Distinct();


text:
Q: remove white space from only beginning of a php string i have a string like below
$string = '  florida'
how can i remove white space from beginning ONLY to form it like below.
$result_string = 'florida'
i am sorry if it is too easy question.

A: sounds like ltrim() is what you're looking for:

Strip whitespace (or other characters) from the beginning of a string.

A: Use trim() It removes leading and trailing whitespaces
Manual:

trim — Strip whitespace (or other characters) from the beginning and end of a string

Edit, ltrim (as mentioned by Oezi) removes the beginning whitespace (missed that part)

A: $string = ' florida'

$result_string = ltrim($string);

echo $result_string;// it will remove white spces from beganing

A: Look this:
$string = trim('  florida');
echo $string; // florida
For more informations: http://php.net/manual/en/function.trim.php


text:
Q: How to create a NAS/NFS distributed over multiple machines? I have multiple mac minis running Ubuntu. I'm building a mini cluster. Each has a medium sized drive. I was wondering if there was a way I could turn a portion of each drive into a shared NAS/NFS of sorts. I realize it wouldn't be the fastest solution, but I'm looking for a way to utilize all the storage.
Basically what I am looking for is a way to take 100 GB from 5 different machines and have it appear as a 500 GB shared volume. Is this even possible, or is it just a really bad idea?


text:
Q: Javascript equivalent for Inverse normal function ? eg Excel's NORMSINV() or NORMINV()? I'm trying to convert something from my excel spreadsheets into Javascript and came along the NORMSINV() macro in my spreadsheets.
The NormSInv() is nicely documented at http://office.microsoft.com/en-us/excel-help/normsinv-HP005209195.aspx. Basically it's of the form
Z = NormSInv(probability) where if you give it the probability (say 0.90), it gives you the Z value for a standard normal distribution (Z= 1.33).
I could encode the entire transformation table as per http://en.wikipedia.org/wiki/Standard_normal_table but want to avoid reinventing the wheel.
So, is there such a function in Javascript? eg. in Javascript's math libraries (if there is such a thing!).
Thanks
Sid

A: There's nothing that I know of embedded into JavaScript's core.
You might like to take a look at the JStat JavaScript library. This seems to offer a range of functions for statistical calculation.

A: i extracted the jStat.distribution.normal.inv into a standalone function you can use with webpack as a closure (or just by itself).
import normalinv from 'jsfile'
let yourMath = normalinv()
or
var yourMath = normalinv();
yourMath(p, m, d)
export default function normalinv() {
  function erfcinv(p) {
    var j = 0;
    var x, err, t, pp;
    if (p >= 2)
      return -100;
    if (p <= 0)
      return 100;
    pp = (p < 1) ? p : 2 - p;
    t = Math.sqrt(-2 * Math.log(pp / 2));
    x = -0.70711 * ((2.30753 + t * 0.27061) /
      (1 + t * (0.99229 + t * 0.04481)) - t);
    for (; j < 2; j++) {
      err = erfc(x) - pp;
      x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err);
    }
    return (p < 1) ? x : -x;
  }

  function erfc(x) {
    return 1 - erf(x);
  }

  function erf(x) {
    var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,
      -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4,
      4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6,
      1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8,
      6.529054439e-9, 5.059343495e-9, -9.91364156e-10,
      -2.27365122e-10, 9.6467911e-11, 2.394038e-12,
      -6.886027e-12, 8.94487e-13, 3.13092e-13,
      -1.12708e-13, 3.81e-16, 7.106e-15,
      -1.523e-15, -9.4e-17, 1.21e-16,
      -2.8e-17
    ];
    var j = cof.length - 1;
    var isneg = false;
    var d = 0;
    var dd = 0;
    var t, ty, tmp, res;

    if (x < 0) {
      x = -x;
      isneg = true;
    }

    t = 2 / (2 + x);
    ty = 4 * t - 2;

    for (; j > 0; j--) {
      tmp = d;
      d = ty * d - dd + cof[j];
      dd = tmp;
    }

    res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd);
    return isneg ? res - 1 : 1 - res;
  }

  return function inv(p, mean, std) {
    return -1.41421356237309505 * std * erfcinv(2 * p) + mean;
  }
}

A: I ended up implementing the NormSInv() in javascript myself. No point in including an entire stats library when I need just one function
function NormSInv(p) {
    var a1 = -39.6968302866538, a2 = 220.946098424521, a3 = -275.928510446969;
    var a4 = 138.357751867269, a5 = -30.6647980661472, a6 = 2.50662827745924;
    var b1 = -54.4760987982241, b2 = 161.585836858041, b3 = -155.698979859887;
    var b4 = 66.8013118877197, b5 = -13.2806815528857, c1 = -7.78489400243029E-03;
    var c2 = -0.322396458041136, c3 = -2.40075827716184, c4 = -2.54973253934373;
    var c5 = 4.37466414146497, c6 = 2.93816398269878, d1 = 7.78469570904146E-03;
    var d2 = 0.32246712907004, d3 = 2.445134137143, d4 = 3.75440866190742;
    var p_low = 0.02425, p_high = 1 - p_low;
    var q, r;
    var retVal;

    if ((p < 0) || (p > 1))
    {
        alert("NormSInv: Argument out of range.");
        retVal = 0;
    }
    else if (p < p_low)
    {
        q = Math.sqrt(-2 * Math.log(p));
        retVal = (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
    }
    else if (p <= p_high)
    {
        q = p - 0.5;
        r = q * q;
        retVal = (((((a1 * r + a2) * r + a3) * r + a4) * r + a5) * r + a6) * q / (((((b1 * r + b2) * r + b3) * r + b4) * r + b5) * r + 1);
    }
    else
    {
        q = Math.sqrt(-2 * Math.log(1 - p));
        retVal = -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
    }

    return retVal;
}


text:
Q: Customizing ChartJS.org Is there any chance to customize chartjs with a large amount of data? To be exact, the problem is with overlapping labels when there is more data than in it's documentation. I've worked with other charting systems and labels (represented by dates for examples) where properly scaling, but ChartJS seems to do nothing with that?

A: Try to use Chart.Scatter plugin instead the line chart.
http://dima117.github.io/Chart.Scatter/
It receives the array of points with X and Y fields. Scale parameters are calculated automatically based on chart data


text:
Q: Speech Recognition Engine Audio Device I am attempting to use a different input device with Speech Recognition Engine. I have attempted to use NAudio to achieve this, using WaveIn and the DataAvailable event, however I can't quite work out how to convert the buffer from the event into a stream usable with speech recognition engine's SetInputToAudioStream(). My current code looks like:
using System.Speech.Recognition;
using NAudio.Wave;

private SpeechRecognition sre;
private WaveInEvent wi;
private Stream st;

static void main(string[] args) {
    Choices words = new Choices(new string[] { "word", "test" });
    Grammar g = new Grammar(words);

    wi = new WaveInEvent();
    wi.DeviceNumber = 0; // Default device
    wi.DataAvailable += Wi_DataAvailable;
    wi.StartRecording();

    st = new MemoryStream();

    sre = new SpeechRecognitionEngine();
    sre.LoadGrammar(g);
    //sre.SetInputToDefaultAudioDevice();
    sre.SetInputToAudioStream(st, /* SpeechAudioFormatInfo */);
    sre.SpeechRecognized += Sre_SpeechRecognized;
    sre.RecognizeAsync(RecognizeMode.Multiple);
}

private void Wi_DataAvailable(object sender, WaveInEventArgs e) {
    // Convert e.Buffer to Stream st
}

private void Sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) {
    Console.WriteLine(e.Result.Text);
}

Could anybody help me with this? Thanks.


text:
Q: How to debug an App on Android with GDBSERVER? I'm trying to debug a native shared library that my App uses through JNI. I can attach to a running app just fine with "gdbserver --attach pid" but i need to actually launch my app when i launch the gdbserver command.
There's a million blog hits on this topic but none of them seem to be clear as to how you launch your app. They all say to just type "gdbserver 10.0.2.2:1234 ./MyProgram" but what exactly is "MyProgram". Is that MyProgram.apk? Is it MyProgram.so? Is it some other file that gets created when the app is installed? If so, what's its path?

A: While it is possible to develop free standing applications that can be launched directly from the shell as others are describing, it sounds like your code runs within the Android application framework.  Therefore, you don't have an executable and instead have an APK that contains your Dalvik class files along with other resources including your native shared object.
Launching an application in an APK involves several steps

*

*The system_server process receives an intent requesting your application.

*The zygote process is told to fork off a new process and run a method of your class.

*Your application runs in the new process.

While you can't launch an APK directly by passing an executable to gdbserver, its fairly easy to trigger a launch it from the shell using the am command.
$ adb -d shell
# am
usage: am [subcommand] [options]

    start an Activity: am start [-D] <INTENT>
        -D: enable debugging

    send a broadcast Intent: am broadcast <INTENT>

    start an Instrumentation: am instrument [flags] <COMPONENT>
        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>
        -p <FILE>: write profiling data to <FILE>
        -w: wait for instrumentation to finish before returning

    start profiling: am profile <PROCESS> start <FILE>
    stop profiling: am profile <PROCESS> stop

    <INTENT> specifications include these flags:
        [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
        [-c <CATEGORY> [-c <CATEGORY>] ...]
        [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
        [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
        [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
        [-n <COMPONENT>] [-f <FLAGS>] [<URI>]

# am start -n com.android.browser/.BrowserActivity
Starting: Intent { cmp=com.android.browser/.BrowserActivity }
#

Once your application is running, use gdbserver --attach <pid> like you have before.  If you are lucky your application waits for some user interaction before calling into your native code to give you a chance to attach and set your breakpoints in GDB.

A: Google provides an official solution to your problem:  'ndk-gdb'
It is included in the NDK.   IIRC, it requires that you have a copy of gdbserver bundled up inside your APK; IIRC, this will happen automatically if you built your APK with 'ndk-build', and specified the appropriate arguments.
Please see Google's documentation in $NDK/docs/NDK-BUILD.html and $NDK/docs/NDK-GDB.html
</ryan>

A: For the gdbserver executable, I just copied it from the NDK folder of the Android SDK:

*

*Download Android NDK from SDK tools tab of Android Studio preferences.

*Copy gdbserver to the rooted device:
adb push {android-sdk}/ndk/{version}/prebuilt/android-arm64/gdbserver/gdbserver /data/local/tmp
To run gdbserver, with the device plugged in:

*

*adb shell su -c setenforce 0

*In the device, accept superuser access rights of shell

*Launch the app you want to debug

*adb shell ps | grep {package-name}

*Copy the process id (2nd column)

*adb shell

*cd /data/local/tmp

*su -c ./gdbserver :<any-port-number> --attach <pid> (app will freeze)

For the gdbclient executable, I had to build it from the gdb source code to configure the correct architecture (arm64) for the Android device. On a separate mac terminal window/tab:

*

*cd gdb-10.1

*./configure --target=aarch64-linux-android && make -j8 && sudo make install

*aarch64-linux-android-gdb

*set sysroot

*target remote <phone-ip-address>:<port-number-above>

*continue (to unfreeze app)

*Start debugging.


text:
Q: How to know if a Basic Block PostDominate another one? I'm trying to write an analysis and one of the features that I need is to know if a node PostDominate another.
I already know that I have to use:
void LazyProfitability::getAnalysisUsage(AnalysisUsage &AU) const {
   AU.addRequired<PostDominatorTreeWrapperPas>();
   AU.setPreservesAll();
}

A: You can get a PostDominatorTree object from the analysis results:
auto PDT = &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();

And use it after that in the following manner:
// returns true iff A post-dominates B
PDT->dominates(A, B);


text:
Q: How to include indexed columns in join query rails mysql to improve performance It is know that index does not work on date columns if they are mapped with any SQL function on them.
People say, including date column with between cases or <= and >= can give indexed date column to show data based on that index (means performance got improved).
However, I found that both gives same to same results and apparently no performance taken care of.
How exactly we can minimize the query time if everything is streamlined.
Or any better solution to cope with it?
I added index on both project_times.date and project_plans.month
Example:
Query 1 without sql functions on columns project_times.date and project_plans.month that returns 87 records but time is huge. May be or may be not the indexing has done on columns:
ProjectConsultant Load (1169.8ms)  SELECT DISTINCT `project_consultants`.* FROM
 `project_consultants` LEFT OUTER JOIN `projects` ON `projects`.`id` =
 `project_consultants`.`project_id` LEFT OUTER JOIN `project_times` ON
 `project_times`.`project_id` = `projects`.`id` LEFT OUTER JOIN `project_plans` ON
 `project_plans`.`project_id` = `projects`.`id` WHERE (projects.internal =0 and
 (project_times.date >= '2021-01-01' and project_times.date <= '2021-12-31' or
 project_plans.month >= '2021-01-01' and project_plans.month <= '2021-12-31'))

Query 2 with sql functions on columns project_times.date and project_plans.month like ((extract(year from project_times.date)) and (extract(year from project_plans.month)) that returns 87 records but time is again huge (technically NO indexing is done on columns):
ProjectConsultant Load (1342.6ms)  SELECT DISTINCT `project_consultants`.* FROM
 `project_consultants` LEFT OUTER JOIN `projects` ON `projects`.`id` =
 `project_consultants`.`project_id` LEFT OUTER JOIN `project_times` ON
 `project_times`.`project_id` = `projects`.`id` LEFT OUTER JOIN `project_plans` ON
 `project_plans`.`project_id` = `projects`.`id` WHERE (projects.internal =0 and (extract(year
 from project_times.date) ='2021' or extract(year from project_plans.month) ='2021'))

Attached images shows the query plan and explain statements output too.

A: Run those queries with a 2 month range instead of a 12 month range.  Query 1 may start using the indexes.  This because there is overhead in using an index; so, if it does not provide much benefit (not very selective), it will be eschewed by the Optimizer.
Please don't use LEFT unless you need it.
Those queries seem to limit the output to projects with times and plans in 2021?  If that was not the intent, please explain.
Query 2 will definitely not use an index because functions, such as EXTRACT, are not "sargeable".
True; BETWEEN is identical in all respects to >= and <=


text:
Q: Methods to speed up sha 512 hashing? Through the use of openssl's sha 512 algorithm I'm currently able to calculate the hash of a 2GB file in between 3 - 3.3 seconds (my CPU is an i7-5820k) - including the time it takes to open, write to, and close files (open the input & write hash to text file).
I wondered if there are any known methods to speed this process up, or whether my HDD is entirely at fault, creating a bottleneck (Seagate BarraCuda Green 2TB 5900RPM SATA 6Gb/s 64MB Cache).
            FILE *ftest=fopen(hashInBuf, "rb");
            FILE *ftest2=fopen(hashOutBuf, "wt");
            //HASH FUNCTION
            SHA512_Init (&mdContext);
            while ((bytes = fread (data, 1, 1024, ftest)) != 0)
            SHA512_Update (&mdContext, data, bytes);
            SHA512_Final (c,&mdContext);
            for(i = 0; i < SHA512_DIGEST_LENGTH; i++){
              fprintf(ftest2, "%02x", c[i]);
              printf("%02x", c[i]);

(the code I'm currently using to calculate the sha 512)


text:
Q: Ace editor set text selection My text is:

My favourite singer is {Bruce Springsteen} and he was born in New Jersey.

I want to programmatically select the text between the curly braces including them. I cannot find a straightforward way.

A: you can do editor.find("{Bruce Springsteen}")
or
var Range = require("ace/range").Range;
editor.selection.setRange(new Range(0, 23, 0, 42));
// use .setRange(.., true) for setting cursor at the beginning of the selection


text:
Q: How to handling row level permissions in hbase Obviously Hbase has no implicit way of doing this.  So my next thought was to do it using ACLs at the cell level.  Unfortunately I've only seen setting the ACLs for a specific user or a map of users/permissions.  Is there any way to allow users from a specific group to have permissions?

A: Group names are prefixed using @ in the grant command.
grant '@mygroup', 'RW'

This and this talks about it in more detail.
In documentation its given how to manage group roles but not much info for implementation, as below 8.2.2 - point 3
HBase managed "roles" as collections of permissions: We will not model "roles" internally in HBase to begin with. We instead allow group names to be granted permissions, which allows external modeling of roles via group membership. Groups are created and manipulated externally to HBase, via the Hadoop group mapping service.


text:
Q: How to update mountpoint of an existing process in a different namespace Suppose an init process reads from fstab to establish an initial mountpoint list in some namespace. It spawned two child process tree A and B with cloned mountpoints.
Suppose also that I have a root shell created under tree B, how can I update the mount point of an existing process in tree A?

A: You can't. That's what the different namespaces are meant to do. Separate the process into an area that has no effect on the old process' mount points.
Of course, by "you can't", I don't necessarily mean you absolutely can't. There are tricks that can work, but I'm not sure that's what you mean. You can write a kernel module that can do anything. You can use ptrace to manipulate the other process into doing the mount command as well.
All in all, it sounds like you want the two processes to share a mount namespace, which causes me to wonder why you decided to create a new namespace to begin with.


text:
Q: SQL find partial string match from a table I have a list string that is stored from user input. The input is open text which mean user can key in anything
Example of list is as follow:

*

*MBPA-MCU-6520154 Error on registration at station no 5

*Cannot find sensor no#412. Error code 87311264

*Process on hold

*Not able to continue. Msg: 135631

And I have a table of error codes:

ErrorID
ErrorCode
Error Detail
Status

1
312451
Common error
No

2
6520154
Registration error
No

3
87311264
Sensor error
Yes

4
135631
Access denied
Yes

5
1
Next Error
Yes

In this case item number 1 and 2 in the list match with code with 'Yes' status. I've been trying to create SQL query to get this.

A: Are you looking for the free text that contains the ErrorId?  If so, this might be what you are looking for:
select ec.*
from error_codes ec
where @user_text like concat('%', ec.errorid, '%') and
      status = 'Yes';

If you want the longest match, you can use:
select top (1) ec.*
from error_codes ec
where @user_text like concat('%', ec.errorid, '%') and
      status = 'Yes'
order by ec.errorid desc;


text:
Q: How to manage Firebase RealtimeDate base Security Rule for Production App I am new in Development. I have a very basic Question but I tried to find it on google and did not understand. My question is that.
In firebase Google said that the meaning of:
{

 "rules": {

    ".read": true,
    ".write": true
 }

}

is that anyone can interrupt in this type of security rules, even a person who doesn't use your app. I got it. Now, If I want to make a chat app or a small social app then what kind of security rule should I use?
Is this rule is enough to make my app secure? that I post below:
{

 "rules": {

    ".read": "auth != null",
    ".write": "auth != null",
}

My app Goal is to authenticate a user through Firebase Authentication before using my app, My app will have chat option and simple Question posting option. Hope I clear it up. IDE is Android Studio with Flutter, Dart as language.

A: To make your data secure, your rules should allow exactly what your code uses and nothing more. It is unlikely that your code read the entire database for every signed in user, so you can probably change these rules to restrict access more without losing any functionality in your app.
Writing security rules is a pretty big topic though, and we've already covered part of it quite a few times here, so I recommend checking out the answers to:

*

*Firebase email saying my realtime database has insecure rules

*Firebase Your Realtime Database has insecure rules

*Prevent user from finding users that have blocked them Firebase

*Firebase Realtime Database - Rules with anonymous authentication


text:
Q: Intuitive introduction to gauge symmetry for non-physicist? In this video, Lawrence Krauss explains for a popular audience that the laws of electromagnetism are uniquely determined by assuming that we can "change the rules locally" (he uses as an example, that we can give one electron a positive charge, while "taking this into account when calculating its effect on other electrons and protons", without changing the laws of physics).
I don't really get what he means, because he explains it in such a non-mathematical way.
Is there a simple introduction to this idea, that the laws of electromagnetism are uniquely determined by certain symmetry assumptions?
ps. I am not a physicist but I understand basic group theory from a mathematical point of view.

A: There are three books that I would recommend, the first is by Sean Carroll: "The particle at the end of the universe".
The second is tougher to get through and it's Frank Close's "The Infinity Puzzle". This has a wider scope than Carroll's book, but they complement each other pretty well, if you read Carroll first.
Neither of them are inherently math based, which I know you ask for (but look them up on the Amazon "Look inside the Book" feature, however, they do use more math than most), but use math where necesssary. I would say they are worth reading, especially the Close book.
The popular science, but with a solid math basis book, is "Deep Down Things" by Bruce Schumm, which pretty much starts by using the complex plane  to introduce abstract spaces, and then uses covariant differentiation to lead on to and describe all of the force carriers.


text:
Q: Element not fading in at right moment - SwiperJS I have a question regarding the SwiperJS plugin. It's being used on this website: https://overnieuw.nl/. On the corresponding homepage there is an element named "section_4__inner--left" which is fading in too late, as you can see if you scroll down the page. An element before named "section_1__inner--left" does fade in on the correct time.
Unfortunately I don't have a lot of experience with SwiperJS plugin yet, so I was wondering if someone encountered this kind of problem before and can tell me what to do?


text:
Q: Check if object is Array of instance of specific object in Node.JS I have a simple class in Node JS
class Animal {
    constructor(name) {
      this.name = name;
      // more fields ...
    }
}

let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects);

What's the best way to check if this array is instanceof Animal objects , without looping over and checking instanceof of each element ?

A: Use Array.prototype.every():

class Animal {
    constructor(name) {
      this.name = name;
      // more fields ...
    }
}

let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects.every(x => x instanceof Animal));


text:
Q: fixed-width box inside section with table of contents and thumbnails I'd like to insert a fixed-width box inside a section and to have it properly displayed in the table of contents (see the thumbnails in the screenshot).
In the MWE below I have sucesfully created the box inside the main beamer frame, but it doesn't display as expected inside the thumbnail.
\documentclass[t]{beamer}
\newcommand{\PART}[1]{\protect\makebox[20pt][l]{#1}\ignorespaces}

\begin{document}
\section{\PART{I.}Part One}

\begin{frame}
\PART{I.} Part One.
\end{frame}

\section{\PART{II.} Part Two}

\begin{frame}
\PART{II.} Part Two.
\end{frame}

\section{\PART{III.}  Part Three}

\begin{frame}
\PART{III.} Part Three.
\end{frame}

\end{document}

The purpose of the fixed-width box is to have a consistent alignment of the text immediately following the numbering I., II., III., etc..
I'm not looking for automatic numbering, as these \PARTs are designed to indicate pauses in the presentation and other sections will be inserted in between them.
EDIT: While the [20pt][l] part doesn't get printed inside a \tableofcontents, the alignment is not preserved, so my objective is not achieved there either.

A: The pdf viewers I tested use a fixed width font for the bookmarks. Therefore the following manual hack could be used to align them:
\documentclass[t]{beamer}
\newcommand{\PART}[2]{\texorpdfstring{\protect\makebox[20pt][l]{#1}\ignorespaces}{#2}}

\begin{document}
\section{\PART{I.}{I.\space\space\space}Part One}

\begin{frame}
\PART{I.}{} Part One.
\end{frame}

\section{\PART{II.}{II.\space\space}Part Two}

\begin{frame}
\PART{II.}{} Part Two.
\end{frame}

\section{\PART{III.}{III.\space}Part Three}

\begin{frame}
\PART{III.}{} Part Three.
\end{frame}

\end{document}


text:
Q: Conflict with same ID on different pages of site using Jquery Mobile I am making a mobile version of an existing site using query mobile. The site is hundreds of pages with established markup that works fine for the www version. The problem is that there are many instances of the same element ID on every page like #useername or #map or #photo. This is fine on www since each page loads independently so there is no conflict. In JQM, it looks like all the pages are somehow cached together and the code refers to the previous page. For example:
Page1.html

Page 1

Link

Page2.html

Page 2

After clicking the link from page 1 to go to page 2, the alert still shows "Page 1".
In this example, it would be easy change the id on the 2nd page, but in the actual site, there are hundreds of places on different pages where the same ID is used and the JS is thousands of linea long. Surely there is a way to make JQM compatible with this.

A: Use a common class instead, jQuery Mobile has more than one page in the DOM at a time, making your "unique" id's non-unique.
$(".ui-page-active .commonclass").html()

Edit:
If id's can't be unique, the next best thing would be:
$(".ui-page-active div[id=commonid]").html()

A: I found this code which seems to remove the previous page from the cache but preserve the back button and transition.
$('div').live('pagehide', function(event, ui) {
    $(event.target).remove();
});

A: Tom Kinkaid's answer is a pro-tip.
Just cleaning it up a little to: 1) reduce overhead of removing every div from the cache, and 2) bring it up to date with new JQuery convention
$(document).on('pagehide', '.ui-page', function(event, ui) {
    $(event.target).remove();
});

Now, the cache is cleared of previous pages AND back button functionality is preserved.

A: By default when you navigate to a page in JQM the framework loads the content of the page via ajax and attaches it to the DOM, so you are ending up with multiple id's per page. You can also link to a page so that it loads a page normally via http using either 'rel="external"ordata-ajax="false"` which i think should solve your issue, you will need to make sure that the appropriate js files are linked in the head of each page though.

A: Would using:
$(document).ready(function(){
    alert('#commonIdOnEveryPage');
});

fix it?

A: I create a unique string based on the time and append it to every id.
// unique string for use in DOM ids
$unique = str_replace(array(' ', '.') ,'_', microtime());

Then in the html output:
<div id="commonIdOnEveryPage<?php echo $unique; ?>">Page 2


text:
Q: Why use this method of function pointers Yesterday I learned of this really cool way to use function pointers.
Although I think its a really cool thing to be able to do I cant see WHY and WHERE this sort of method will be used?
Could someone shed some light on this?
int Mul(int x , int y)
{
return x*y;
}

int Div(int x , int y)
{ return x/y;
}

typedef int (*FuncP)(int,int);

int compu(FuncP functionP, int x , int y)
{return functionP(x , y)}

//Calling it will look like
compu(Mul,5,10);

Thanks
Cart

A: Pointers to functions has multiple uses but, sticking to your example, pointer to funcions can help you to avoid hurge and ugly conditional branches like if's and switches:
If you create an associative array of operations characters as index and pointer to functions as value:
//implementacion in C doesn't matter for the example
operations["*"] = Mul;
operations["/"] = Div;
operations["*"] = Add;
operations["-"] = Sub;

You can do something like this:
int op1;
int op2;
char operation;

cout << "Insert first number /n";
cin >> op1;
cout << "Insert second number /n";
cin >> op2;
cout << "Insert operator /n";
cin >> operation;
cout >> compu(operations[operation],op1,op2);

A: If you need something to be dynamic based on a situation like so:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>

typedef int (*worker_operation)(int);

int check_for_new_woot(int inVal) {
  int ret = arc4random() % 10;
  if (ret < 5) {
    puts("Found new woot!");
    sleep(1);
    return 1;
  } else {
    puts("No new woot :(");
    sleep(1);
    return 0;
  }
}
int buy_current_woot(int inVal) {
  if (inVal != 0) {
    fprintf(stderr, "Insufficient funds!!!\n");
  }
  return 0;
}

int check_if_should_buy_woot(int inVal) {
  printf("Should we buy the latest woot? ");
  char input[10];
  read(STDIN_FILENO, input, 10);
  if (input[0] == 'y') {
    return 1;
  } else {
     return 0;
  }
}

void *worker_thread(void *inVal) {
  worker_operation *ops = (worker_operation *)inVal;
  int i = 0;
  worker_operation op = ops[i];
  int arg = 0;
  while (op) {
    arg = op(arg);
    op = ops[++i];
  }
  free(ops);
  return NULL;
}

pthread_t start_worker(worker_operation *ops) {
  pthread_t pt;
  pthread_create(&pt, NULL, worker_thread, ops);
  return pt;
}

int main(int argc, const char *argv[]) {
  bool autoBuy = true; // fetch whether we should automatically buy from woot.com from argv or stdin
  int numberLoops = 10; // fetch number of times to loop through the process
  int i;
  worker_operation *operations;
  if (autoBuy) {
    operations = (worker_operation *)malloc(sizeof(worker_operation) * (numberLoops * 2 + 1));
    for (i = 0; i < numberLoops; i++) {
      operations[2 * i] = check_for_new_woot;
      operations[2 * i + 1] = buy_current_woot;
    }
    operations[2 * i] = (worker_operation)NULL;
  } else {
    operations = (worker_operation *)malloc(sizeof(worker_operation) * (numberLoops * 3 + 1));
    for (i = 0; i < numberLoops; i++) {
      operations[3 * i] = check_for_new_woot;
      operations[3 * i + 1] = check_if_should_buy_woot;
      operations[3 * i + 2] = buy_current_woot;
    }
    operations[3 * i] = (worker_operation)NULL;
  }
  pthread_join(start_worker(operations), NULL);
  return 0;
}

Note that in this code snippet uses function pointers in two places. We have a function which is agnostic of how the user wants the program to perform, that is start_worker simply creates a worker thread that will work with a list of operations. This can be easily used to create a program which has multiple threads going all with different operation queues. The second place function pointers are used are with threads. The ptrhead_create call uses a function pointer in order to create a new thread (the function specified is the function to be ran on the new thread).
Generally this is called a command programming paradigm. One can easily create an operation that another part of code can call, agnostic of what the function does. For instance this could be useful for games in the following situation:

We have a game controller that gives input. The user clicks 'up'. In code call the operation that is hooked to the 'up' action.

This modular approach allows one to enable settings for the controls so someone can hook a 'jump' operation to 'up' or a 'move forward' operation, or anything really.
Hope this helps!


text:
Q: My function is not finding my word in the string I made a simple program to find words inside of strings and it works well but it can't find the last word in the string. Example: when I type in "Hello world", it will only pushback "Hello".
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<char> Buffer2;
string temp;
vector<string> FinalString;
string UserInput;

void SeperateString() {
  for (int x = 0; x < UserInput.size(); x++) {
    temp.clear();
    if (UserInput[x] == ' ') {
      for (int x = 0; x < Buffer2.size(); x++) {
        temp = temp + Buffer2[x];
      }
      FinalString.push_back(temp);
      Buffer2.clear();
    } else {
      Buffer2.push_back(UserInput[x]);
    }
  }
}
int main() {
  getline(cin, UserInput);

  SeperateString();
  for (int x = 0; x < FinalString.size(); x++) {
    cout << FinalString[x] << endl;
  }
}

A: This will probably be a better implementation for your code:
void SeperateString() {

    istringstream ss(UserInput); // needs #include <sstream>
    while (ss >> temp)
    {
        FinalString.push_back(temp);
    }
}

istringstream documentation,
stringstream documentation.
If you want to stick to your code, at the end of the loop, just check if Buffer2 has characters or not:
for (int x = 0; x < UserInput.size(); x++) {
    temp.clear();
    if (UserInput[x] == ' ') {
        for (int x = 0; x < Buffer2.size(); x++) {
            temp = temp + Buffer2[x];
        }
        FinalString.push_back(temp);
        Buffer2.clear();
    }
    else {
        Buffer2.push_back(UserInput[x]);
    }
}

if (Buffer2.size() > 0)
{
    temp.clear();
    for (int x = 0; x < Buffer2.size(); x++) {
        temp = temp + Buffer2[x];
    }
    FinalString.push_back(temp);
}

A: You need to handle the last word separately because it does not have a space after it.
void SeperateString() {
for (int x = 0; x <= UserInput.size(); x++) {
    temp.clear();
    if (UserInput[x] == ' ' || x == UserInput.size()) {
        for (int y = 0; y < Buffer2.size(); y++) {
            temp = temp + Buffer2[y];
        }
        FinalString.push_back(temp);
        Buffer2.clear();
    }
    else {
        Buffer2.push_back(UserInput[x]);
    }
   }
}


text:
Q: Load From JSON in Canvas without Clear I want to Add object in my existing canvas from JSON string without clearing existing objects. But when I click button to add it clears my canvas and then add from json string.
Please help me how can I do this ?
Below is what I have tried
var yourData = '[{"type":"group","originX":"center","originY":"center","left":161.82,"top":76.48,"width":174.38,"height":59.05,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","objects":[{"type":"line","originX":"center","originY":"center","left":0,"top":-0.01,"width":172.38,"height":1,"fill":"transparent","stroke":"transparent","strokeWidth":2,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","x1":75.6300048828125,"y1":75.98500061035156,"x2":248.00997924804687,"y2":75.98500061035156},{"type":"rect","originX":"left","originY":"top","left":-86.19,"top":-30.03,"width":172.38,"height":59.05,"fill":"yellow","stroke":"red","strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":0.3,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","rx":0,"ry":0,"x":0,"y":0}]}]';
var json = '{"objects":' + yourData + '}';

canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  fabric.log(o, object);
});


text:
Q: How make this code "more functional"? How can you apply to this OOP java code a more functional style?
class PaintCarCost
  Car car;
  Paint paint;
  PaintMaterialsMixture mixture;

  double cost () {
    double volumeToPaint = ... // calculate from car and mixture
    double necessaryVolumePaint = ... // calculate from volumeToPaint, car and paint
    double necessaryKgPaint = ... // calculate from necessaryVolumePaint and paint
    double cost = ... // calculate from necessaryKgPaint and paint
    return cost;
  }
}

I had thought split each calculation in a function:
private BiFunction <Car,PaintMaterialsMixture,Double> volumeToPaint = ...
private BiFunction <Double,Car,Paint> necessaryVolumePaint = ...
private BiFunction <Double,Paint> necessaryKgPaint = ...

but I don't know how chain all of them in an elegant way to make the final cost. Each function have to take into account the last result, but I need to pass different arguments in each function too.

A: In functional programming, you think in terms of functions (input / output relation) instead of algorithms (computation steps). You avoid side effects and state.
So instead of having a stateful PaintCarCost object, you have a stateless PaintCarCost function:
class PaintCarCost
  double cost (Car car, Paint paint, PaintMaterialsMixture mixture) {
    double volumeToPaint = ... // calculate from car and mixture
    double necessaryVolumePaint = ... // calculate from volumeToPaint, car and paint
    double necessaryKgPaint = ... // calculate from necessaryVolumePaint and paint
    double cost = ... // calculate from necessaryKgPaint and paint
    return cost;
  }
}

In my opinion, local variables are fine, of course you can always split functions into smaller functions (and should), but the real issue here in my opinion is the state you should avoid.

A:
Each function have to take into account the last result, but I need to pass different arguments in each function too.

You may be looking for currying

Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.

In java, this will normally look like using some arguments to create a new object, which includes an interface to take the remaining arguments.  (In more recent versions of Java, you are more likely to see lambda's used, but the basic idea is the same.)
double volumeToPaint = ... // calculate from car and mixture
double necessaryVolumePaint = ... // calculate from volumeToPaint, car and paint
double necessaryKgPaint = ... // calculate from necessaryVolumePaint and paint
double cost = ... // calculate from necessaryKgPaint and paint
return cost;

So in this example, we want to build a bunch of functions that accept a double as an argument, and return a double as a result, that will all get chained together.
DoubleUnaryOperator computeNecessaryVolume = someFactory.createComputeNecessaryVolume(car, paint);
DoubleUnaryOperator computeNecessaryKgPaint = someFactory.createComputeNecessaryKgPaint(paint);
DoubleUnaryOperator computeCost = someFactory.createComputeCost(paint);

double volumeToPaint = computeVolume(car, mixture);
double necessaryVolumeToPaint = computeNecessaryVolume.applyAsDouble(volumeToPaint);
double necessaryKgPaint = computeNecessaryKgPaint.applyAsDouble(necessaryVolumeToPaint);
double cost = computeCost.applyAsDouble(necessaryKgPaint);

That's the basic idea; you can possibly "simplify" it by then chaining the functions together into a pipeline, as we might do with a stream....
cost = computeVolume(car, mixture)
.map(volumeToPaint -> computeNecessaryVolume.applyAsDouble(volumeToPaint))
.map(necessaryVolumeToPaint -> computeNecessaryKgPaint.applyAsDouble(necessaryVolumeToPaint))
.map(necessaryKgPaint -> computeCost.applyAsDouble(necessaryKgPaint) )

But more likely you would just compose the functions together.
DoubleUnaryOperation doIt = computeNecessaryVolume
                            .andThen(computeNecessaryKgPaint)
                            .andThen(computeCost);

double cost = doIt.applyAsDouble(computeVolume(car, mixture))

Can you write some example about function declaration of computeNecessaryVolume, computeNecessaryKgPaint and computeCost functions?

class ComputeNecessaryVolume implements DoubleUnaryOperator {
    final Car car;
    final Mixture mixture;

    ComputeNecessaryVolume(Car car, Mixture mixture) {
        this.car = car;
        this.mixture = mixture;
    }

    @Override
    double applyAsDouble(double volumeToPaint) {
        // Do whatever you were doing before with car, mixture, and volumeToPaint
        double necessaryVolumeToPaint = ...

        return necessaryVolumeToPaint;
    }
}


text:
Q: EMACS, Function call highlight (EMACS 24.2 ) I need to highliight function call. I found this on internet
(add-hook 'c-mode-hook (lambda ()
   (font-lock-add-keywords nil '(
      ("\\<\\(\\sw+\\) ?(" . 'font-lock-function-name-face))t)))

It works but it highlight also the following open parenthesis.
I am non confident with regular expression, please, How can I modify match string to avoid parenthesis highlighting?

A: The regular expression is fine, you just need to highlight the first group in the match, not the whole of it. Replace . 'font-lock-function-name-face with 1 'font-lock-function-name-face.
Another thing to change, just a recommendation, is that font-lock-add-keywords accepts the mode name as the first argument. So you don't need to use the hook.
Result:
(font-lock-add-keywords
 'c-mode
 '(("\\<\\(\\sw+\\) ?(" 1 'font-lock-function-name-face)))


text:
Q: How do I access the JBoss data directory from inside an application? I would like to upload files to my the server/default/data directory using a simple upload servlet and be able to access them from within my application, but I can't seem to find how to access it. I tried
getServletContext().getRealPath("data");

but that didn't help.

A: to get the absolute path, just do:
System.getProperty("jboss.server.data.dir");


text:
Q: How to save BluetoothGatt Instance on Android? I'm currently developing an Android app which have interactions with BLE device.
I have successfully connect a BLE device with the GATT server using the connectGatt() method. Now I want to use the BluetoothGatt instance returned in another activity. Is there anyway that I can save this BluetoothGatt Instance and use it in another activity without reconnecting to the BLE device which is already connected?

A: Just like mercato has mentioned you would want to store you bluetooth logic in a controller class, since activities gets destoryed and recreated. If you are using the android architecture components you could also store you could implement you connection logic in a repository class whichyou can access from multiple activities.


text:
Q: Segue from one view controller embedded within UINavigationController to another UINavigationController I have a UINavigationController as my root controller, but then I segue from one view controller to another UINavigationController.
But when segueing from one view controller which is embedded within a UINavigationController to another UINavigationController the push segue comes from the bottom, presuming it is segueing as a popover. I tried using a show detail segue but still not luck.
Why is this occurring and how can I segue from one to the other using a push/replace segue ?
PS: Is this happening because the UINavigationControllers conflict and overrides the segue as a popover ? The reason I am using two separate navigation controllers is because the style from the previous view overrides the style of the detail view, i posted a separate question about that Cannot change style of UINavigationBar when using scrollViewDidScroll on separate View Controller

A: Push segue occurs only within one navigation controller. It's how it implements 'show' type segue. Making 'show' segue from navigation controller to another navigation controller is not what Xcode drawing tool considered as 'pushing'. It interprets it as popover by default.


text:
Q: Double summing of column in two different tables I've got 2 tables.
'Order details'
OrderID | Quantity | UnitPrice | ProductID
  1002  |    19    |    17     |    824
  1002  |    5     |    15     |    285
  1003  |    7     |    6      |    543
  1004  |    12    |    11     |    205

'Orders'
OrderID | CustomerID
  1002  |   224
  1003  |   348
  1005  |   224

I have to get the id of the customer that has bought maximum of products. As you can see one customer can have not only one OrderID

A: I think something like this should works fine:
SELECT TOP 1 customerid
FROM (
SELECT customerid, SUM(od.quantity) AS sum
FROM orders AS O
INNER JOIN order_details AS OD
ON O.orderid = OD.orderid
GROUP BY customerid
ORDER BY sum DESC)

Check the tables name

A: You can first aggregate, the limit the first record based on the descending order of the SUM of Quantity:
SELECT
    ord.CustomerID,
    SUM(det.Quantity) AS Quantity
FROM
    Orders ord
JOIN
    Order_Details det
    ON  (det.OrderID = ord.OrderID)
ORDER BY
    Quantity DESC
LIMIT 1;


text:
Q: NavigationDrawer(SlidingMenu): which one is best? I need to incorporate  a youtube like drawer navigation drawer for both(left,right) sides. AFAIK android apis don't provide means for the right-to-left drawer functionality. There're quite a lot of implementations out there(sliding menu) which do.
This sliding menu feature seems to present a performance issue. Should I try to rewrite original NavigationDrawer, which I expect to be the least performance-impact solution, or there is another performance-optimal library?
Thanks.

A: I would choose NavigationDrawer. I used both and I find NavigationDrawer smoother. If you try to mimic google UX then with NavigationDrawer should be enought for your needs.
I recently made a project/demo to implement NavigationDrawer with ActionBarSherlock for pre Honeycomb devices because I need for an app.
SherlockNavigationDrawer impl
Another thing to take in mind is that if you use NavigationDrawer try to avoid Tabs because all the tabs items could fit perfectly as a listview in NavigationDrawer.

A: Actually NavigationDrawer supports drawers on both edges.
You have to supply the two drawer views inside your layout xml; one with gravity:left and one with gravity:right.
Then, in your Activity you call setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) on your DrawerLayout object.
This will enable swiping either from left or right edge.

A: @Michał The question is actually implementation of both left as well as the right drawer.
@midnight NavigationDrawer right now only implements one-sided menu which you can place either on the left or the right. If you want to implement the other pane also you can make your content layout as SlidingPaneLayout.
This was also added to the latest support library along with the NavgationDrawer. For an implemented example you can look at the newest Hangouts app on how they are using it. This layout will probably suit your purposes better rather than rewriting the NavigationDrawer. In any case i'd hold off on re-writing it since it is the first release of the Layout and may undergo changes fairly quickly.

A: Since the last version of SupportLibrary there is a NavigationDrawer in Android.


text:
Q: Get file path after selection of an object I am writing a simple Eclipse-plugin that displays a UI after right-mouse click on a specific element, located inside an xml file. In the handler, i need to get first the file path, which contains the selected object. I tried the following posts unfortunately did not work for me.
How to get the Path of current selected file in Eclipse?
IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj,
            IFile.class);

Eclipse Plugin Get Code from Current Open File

IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);

note: the file need not be opened in active editor.

A: you need to retrieve the EResource from the EObject.
Please note that EObject might be in-memory and in this case there is no EResource/File associated with it.
See https://www.eclipse.org/forums/index.php?t=msg&th=796431&goto=1404419&#msg_1404419
Regards,


text:
Q: Handle directory update during DirectoryStream iteration According to the DirectoryStream documentation:

It is thread safe but does not freeze the directory while iterating,
  so it may (or may not) reflect updates to the directory that occur
  after the DirectoryStream is created.

So if I have a filter that accepts everything that isn't a .json file and create the DirectoryStream with it, it appears that if a .json file is added while I'm iterating through the stream, there's a chance that the iterator will grab it. Is there a way around this? Or do I just need to check for the json extension in my iteration as well?


text:
Q: HTML tags in Content I'm implementing full text search on a table named as tbljobs on the cloumn named as jobdescription. In front end I'm getting html tags in the description. I'm showing the records in GridView and on Gridview's RowDataBound enent I'm decoding the text. I'm using the following code on Gridview's RowDataBound event:
protected void GridNewlyPostedJobs_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
 string decodedText =      HttpUtility.HtmlDecode(((Label)e.Row.FindControl("lblJobDescription")).Text);
            ((Label)e.Row.FindControl("lblJobDescription")).Text = decodedText;
         }
    }

But nothing works..!!

A: Use DataRowView to get the Data...
protected void GridNewlyPostedJobs_RowDataBound(object sender, GridViewRowEventArgs e)
{
   DataRowView rowView = (DataRowView)e.Row.DataItem;
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
     string decodedText = HttpUtility.HtmlDecode(rowView["jobdescription"]);
     ((Label)e.Row.FindControl("lblJobDescription")).Text = decodedText;
   }
}