Q: C++: Issues with manipulating a PPM file I'm working on a program that can perform various effects and manipulations on a PPM file. However for testing reasons, it uses cin rather than an input file. It is supposed to be able to perform multiple effects at once, but I am having trouble even getting one right. I'll run a removeBlue() on a line that will work, then try again with different values and it will remove red or green instead. That sort of thing. There's a lot of code, so I'll try to include only what is necessary.
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

class SimpleImageEffect
{
public:
    virtual void processImage(vector<Point> &points) = 0;
};

class RemoveRed : public SimpleImageEffect
{
public:

    virtual void processImage(vector<Point> &points)
    {
        for (Point& p : points)
        {
            p.setRed(0);
        }
    }
};
//Just an example of one of the effect classes.
//The code in them is correct, so I won't include the others unless needed.

vector<Point> parse_line(string line)
{
    istringstream scanner{line};
    vector<Point> result{};
    int red = -1;
    int green = -1;
    int blue = -1;
    int counter = 0;

    while(scanner.good())
    {
        if (counter == 0)
        {
            counter++;
            scanner >> red;
        }
        else if (counter == 1)
        {
            counter++;
            scanner >> green;
        }
        else if (counter == 2)
        {
            scanner >> blue;
            Point p{ red, green, blue };
            result.push_back(p);
            counter = 0;
        }
    }
    return result;
}

void readFromCin()
{
    string line = "";

    vector<string> lines_in_file{};
    int i, effect_choice;
    SimpleImageEffect *effect = nullptr;

    getline(cin, line);

    while (line.length() > 0)
    {
        lines_in_file.push_back(line);
        getline(cin, line);
    }

    for (int i = 0; i < lines_in_file.size(); i++)
    {
        if (lines_in_file[i] != "P3")
        {
            effect_choice = strToInt(lines_in_file[i]);
        }

        else if (lines_in_file[i] == "P3")
        {
            cout << lines_in_file[i] << endl;
            cout << lines_in_file[i+1] << endl;
            cout << lines_in_file[i+2] << endl;
        }

        vector<Point> points = parse_line(lines_in_file[i]);

        if (effect_choice == 1) effect = new RemoveRed;
        if (effect_choice == 2) effect = new RemoveGreen;
        if (effect_choice == 3) effect = new RemoveBlue;
        if (effect_choice == 4) effect = new NegateRed;
        if (effect_choice == 5) effect = new NegateGreen;
        if (effect_choice == 6) effect = new NegateBlue;
        if (effect_choice == 7) effect = new AddNoise;
        if (effect_choice == 8) effect = new HighContrast;
        if (effect_choice == 9) effect = new ConvertToGrayscale;

        effect->processImage(points);

        for (auto p : points)
        {
            cout << p;
            cout << endl;
        }
    }
}

int main(int argc, char** argv)
{
    string menu_choice;
    getline(cin, menu_choice);
    if (menu_choice == "1")
    {
        readFromFile();
    }
    else
    {
        readFromCin();
    }
    return 0;
}

So for example, running it with an input of
2
1
P3
1 1
255
50 50 50

will return
P3
1 1
255
0 50 50

but if I run it with
2
3
P3
1 2
255
50 50 50
1 2 3

it returns
P3
1 2
255
0 50 50
0 2 3

I have absolutely no idea what's causing the issue, so any help at all would be greatly appreciated. Thanks.

A: Your algorithm logic structure smells a lot, this is what I see:

*

*read all non empty lines into lines_in_file (looks good to me)

*for EVERY line (problematic, requires additional logic in inner loop):

*

*if not "P3", try to parse [EVERY] line as integer and set effect_choice (it's not clear from your code, what happens on lines where several integers are provided, but judging from your problem description the first integer is successfully parsed by strToInt function)

*if "P3", the current line and next two are copied to output

*[EVERY] line is parsed as vector of triplets of numbers

*effect is set by new effect for actual value of effect_choice (for EVERY line, also you don't delete the effect at end, so you are leaking memory in per-line counts. Also your current effects look like they may be implemented as static functions of "process" function type, so you don't need to allocate each of them, just store the particular memory address of requested function. And you call it processImage, while you are processing only line, not whole image.

*effect is run for current line triplets

*the line triplets are outputted

*loop to next line (!)

So for example for input:
2
3
P3
1 2
255
50 50 50
1 2 3

I believe (can't run it, as you didn't provide lot of code) this happens:
lines are read, and per particular line this happens:
line "2": effect_choice = 2, effect = RemoveGreen, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed (ie nothing).
line "3": effect_choice = 3, effect = RemoveBlue, zero triplets parsed into points, RemoveBlue::processImage() run over empty vector, empty vector printed.
line "P3": Lines: {"P3", "1 2", "255"} are printed, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed.
line "1 2": effect_choice = 1, effect = RemoveRed, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed.
line "255": effect_choice = 255, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed.
line "50 50 50": effect_choice = 50, one triplet {50, 50, 50} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 50, 50}.
line "1 2 3": effect_choice = 1, effect = RemoveRed, one triplet {1, 2, 3} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 2, 3}.
All of this should be clearly visible in debugger, while stepping over the code, so you probably are not debugging it, which gets downvoting the question from me, and you will pay in tremendous pain over time, as debugging without debugger is lot more difficult.
Also writing code without thinking about algorithm and code architecture makes the need of debugging lot more likely, so you wasted even more time here, by starting by writing the code.
You should have first design some algorithm and code architecture (what data are processed, how, when new memory is needed, how it will be freed, where the code need to loop, where it need to skip over, or run only once, etc).
Write only overview of how it will work into single-line comments, then split too generic comments into simpler steps until they can be implemented by few lines of C++ code, and move/modify them around until you feel the wanted algorithm will be implemented with minimal "cruft" added (most of the comments does, what is really requested, like "set red in point to zero", and any processing/preparations/moving/etc is minimized only to cases where you can't avoid it by smarter design). (for example in your current code you can read through the header of the file without looping, and start looping only after the pixel data pours in)
Then write the code, start probably with some empty function definition so you can already "run" it in debugger and verify the emptiness works, then implement the comment (or small group of them) which you feel is clear enough to be implemented and can be tested easily (no big dependency on yet-to-implement parts). Debug + test new code. If it works, try to clean up the source to remove anything not really needed, work-in-progress variable names, etc... Then verify it works in final version.
And do it again for another comment (group of), until the implementation is done.
Using unit-testing makes the write-short-code, test+debug, clean-up-source rounds even easier, especially in cases like this, where I/O are pure data, so it's easy to feed specialized test input data into test, and verify the expected output data were produced.


Q: Image processing with sub pixel accuracy I'm writing a user interface program which controls industrial machinery.
The machine is an automatic inline screen printer used in the electronic production industry. The exact purpose of the machine is to print solder paste onto bare PCBs.
The system includes 2 cameras which form a vision system used to locate fiducials and automate the process that the machinery is involved in.
The issue I have is that I need to be able to locate shapes and objects within images taken from the cameras, which is straight forward enough, but - in order to get the required accuracy I need to be able to do this with sub pixel accuracy.
The two cameras form one twin vision camera, with one camera will be looking up at a stencil, and the other looking down at a PCB. The twin vision camera is on a moving carriage that moves in X and Y. The PCB is clamped onto a table than can move in X, Y and theta. The vision system is used to detect the difference between PCB position and stencil position, and the table is then adjusted to align the two together.
EDIT:
This is a partial screen shot taken from an existing UI program:

The stencil image is the top image, the PCB is the bottom, the images here are grayscale images - in the new system I am looking at using colour but will use grayscale is required.
NOTE: As you're reading this you're probably thinking "well why don't you just use whatever you use in the existing UI?" The existing UI is written in VB6, something I want to move away from, and the vision side of the program is an .ocx written by a third party company who no longer exists.
I have played with AForge.NET a little bit and found it was really easy to use and I was able to use it to locate various different shapes and find the center of them which was great, but it doesn't have the sub pixel accuracy. However I could possibly use this as a starting point then apply a sub pixel algorithm to the individual center pixel or even the whole shape.
EDIT:
Here is a sample image taken from the test program I've written using AForge:

The red outline and crosshair is what I've added as a visual aid/ experiment. This was taken with the camera that I'm likely to use, which has a resolution of 1280 x 1024, however the lens is not the actual lens I'll use, which is why the image is slightly 'fisheyed'. Also the objects of interest will be better light than this.
In the actual system the lens will look at a 10mm x 8mm sqaure on both stencil and PCB, meaning each pixel will represent 7.8125um^2, however I can move the XYY table by increments of 1.25um at a time, which is essentially useless if I can't see those movements with the camera.
I require 1um (sub) pixel accuracy.
Does anyone know of anything I can use to do this? I have been searching for quite a while now but all I ever seem to find is information on rendering images with sub pixel accuracy.
Or, better still, does anyone know how I could write something to do this myself? I wouldn't even know where to begin!
Any feedback will be greatly appreciated.

A: new info tells a lot... I think you should be more focused on the paste application accuracy then the carriage position precision. My bet is that the printer has far bigger dot size and error then 1 um and also the desired accuracy is dependent on the PCB usage (wiring and gaps widths). Anyway I would do this:

*

*linearize image geometry
you need to de-fisheye image. As you camera/optics setup will be fixed (especially focus and distance to PCB) you should for each PCB thickness make an image of a chess board grid. then create mapping that will linearize the chessboard to real rectangles so you discard deviations before the next process.

*normalize lighting conditions

*

*see Enhancing dynamic range and normalizing illumination

*sub pixel accuracy
each pixel of the image is integration of all the stuff in its area. So if we know the 2 colors (c0,c1) of any boundary (background/foreground) then we can estimate their sub-pixel position. Let start with axis aligned rectangles. I see it like this:

Each square of the grid represents a pixel area. c0 is the gray and c1 is the green color. In the camera image you got the final color as combination of all the colors inside each pixel:

*

*c = s0*c0 + s1*c1
where c is the final pixel color and s0,s1 are area coresponding to c0,c1 colors in range <0,1> where s0+s1=1.0. Now we want to compute the s0,s1 to obtain sub-pixel precision. So first detect the pixel position on the boundary as one of these:

*

*horizontal edge

*vertical edge

*corner

this can be done by inspecting the neighboring pixels. c0,c1 can be obtained from pixels with saturated color (all neighbors have the same color) These are in inside areas pixels. I would ignore the corner pixels as their position can be obtained from nearest H/V edge pixels (it is not possible to get both x,y coordinates from the equation above). So now for each H,V edge just solve system:
I.  c = s0*c0 + s1*c1
II. s0 + s1 = 1.0;

compute the s0,s1 and the edge position for vertical edges is one of these:
x=x0 + pixel_size*s0 // if c0 is on the left
x=x0 + pixel_size*s1 // if c1 is on the left

horizontal edges are like this:
y=y0 + pixel_size*s0 // if c0 is on the top
y=y0 + pixel_size*s1 // if c1 is on the bottom

where x0,y0 is pixels top left position in pixels and the coordinate system is x+ is going to right and y+ is going down. If you got different setup just change the equations ...
Now if you got non axis aligned edges then you need to compute the slope (how many pixels it takes in one axis to change in the other dy/dx. and handle the areas accordingly:

So the only thing what changes is the conversion from computed s0,s1 to actual edge position. now you need to compute the left/right side or up/down. if you use the equation from the axis aligned example then you obtain the edge position in the middle of pixel. So you just shift it by the slope on both sides by x +/- 0.5*dx/dy or y +/- 0.5*dy/dx where dx,dy is the edge slope.

To obtain dx,dy just search along the edge for fully saturated pixels and if found then (dx,dy) is the distance between 2 closest such pixels...
[Notes]
you can do this on booth grayscale and RGB. Hope this helps a bit.


Q: apt-get and outdated packages Why is it that many packages in apt-get are outdated? For example, I would like to get the latest implementation of the clojure programming language onto my machine. However, running the command apt-cache search clojure I get the following:
clojure - a Lisp dialect for the JVM
clojure-contrib - user contributed set of libraries for clojure
clojure1.2 - Lisp dialect for the JVM
clojure1.3 - Lisp dialect for the JVM
leiningen - simple build system for Clojure
libclojure-maven-plugin-java - Clojure plugin for Maven
libclucy-clojure - Clojure interface to the Lucene search engine
libjava-jdbc-clojure - Clojure interface to sql databases via jdbc
librobert-hooke-clojure - Function wrapper library for Clojure
libtools-logging-clojure - Logging macros for Clojure

All the clojure implementations are old (clojure is version 1.1). The newest release of the clojure programming language is 1.5.
Why is it that packages are not up to date? Do I need to reconfigure my apt-get program?

A: According to me, apt-get has the same philosophy as the Ubuntu updater, which doesn't proceed to any OS upgrades which are not "Long Term Support" (except if you configure it differently).
I think the basic sources only target "stable" and "safe" packages. When a program is updated by its provider, it is very unlikely for the new version to appear in the base repositories quickly. We have this behaviour with the LibreOffice suite : you'll get stuck on version 4.0.2.2 (as far as I remember) even if 4.0.3 has already been released. For this example, you needed to add the LibreOffice repository (ppa:libreoffice/libreoffice-4-0) in order to get a recent package. In some other cases, such as php, the name of the package changes between major versions (php became php5 or php53 on some distributions).
That's the same for most applications. Get the provider's PPA, or if it's not available, download the sources and compile them, it's pretty easy, given that you'll often find a INSTALL file in the source tarballs.
Some useful commands :
sudo add-apt-repository [ppa] # Adds a PPA to apt sources.
sudo apt-get update # Reloads the packages list from the current apt sources.
sudo apt-get dist-upgrade # Proceeds to packages update.

To me, this characteristic is a flaw in the apt-get conception. I agree on the fact that it provides some security to beginners (no downloads for uncertified "safe" applications), but for developers, or just for more advanced users, it can become quite disturbing.


Q: Keyboard from EditText destroing Layout I have EditText, when i toutch this, keyboard will show, but instead of covering the bottom part of the application, it shifts all the elements at the top and makes them smaller, everything looks distorted ...
How do I display the keyboard so that it does not affect our layout?

A: Please check this Link:
You can add in your menifest for the activity you want to prevent such issue.
Also make sure if you are having a bit more content use scrollView as a parent.
And soft input mode as "adjustResize"
android:windowSoftInputMode="adjustResize"

or
android:windowSoftInputMode="adjustPan"

you can use as per your need.

adjustResize
to ensure that the system resizes your layout to the available space—which ensures that all of your layout content is accessible (even though it probably requires scrolling)—use this one.
adjustPan
The activity's main window is not resized to make room for the soft keyboard, and the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing.
adjustNothing
Do nothing with layouts


Q: Incrase WebView HTML5 Canvas in QT I'm porting a current HTML5 Canvas application to a QT wrapper. however its performance is quite low. This HTML5 canvas app runs at 60fps in Chrome and IE11, however it still at 10fps on QTWebView.
How can I increase the render speed of this existent HTML5 canvas application inside a QT project?
the question is about if there is any parameter to use some more fast renderer (like GPU)
Note. this project was created using the default qt creator wizard for HTML5 applications.


Q: SAML and Java Standalone application without browser? I am testing SSO with SP (Spring-SAML) and IDP (WSO2IS). They are working fine on browser.
Now I want to bring it to a Java standalone application. Providing user credentials and SP URL, then a user can log in the application and access SP.
To implement this, basically I need to use HTTPClient (for handling Cookie, POST, Redirect, Auto-POST) and follow the SAML message flow as it happens on browser.
I would like to know the most efficient way to do it. Is there any library or example?
Your help is highly appreciated.

A: I managed to create a relatively simple solution using the HtmlUnit headless browser. In my case i had to download a PDF file from a website which required SAML authentication.
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

...

private static byte[] samlAuthenticateAndDownloadFile(String url, String username, String password) throws Exception {
    byte[] fileBytes;
    try (final WebClient webClient = new WebClient()) {
      final HtmlPage loginPage = webClient.getPage(url);

      final HtmlForm loginForm = loginPage.getForms().get(0);

      final HtmlSubmitInput button = loginForm.getInputByName("login");
      final HtmlTextInput usernameField = loginForm.getInputByName("username");
      final HtmlPasswordInput passwordField = loginForm.getInputByName("password");

      usernameField.setValueAttribute(username);
      passwordField.setValueAttribute(password);

      final UnexpectedPage pdfPage = button.click();

      InputStream inputStream = pdfPage.getInputStream();

      fileBytes = IOUtils.toByteArray(inputStream);
    }

    return fileBytes;
  }


Q: Is there an edit distance algorithm that takes "chunk transposition" into account? I put "chunk transposition" in quotes because I don't know whether or what the technical term should be. Just knowing if there is a technical term for the process would be very helpful.
The Wikipedia article on edit distance gives some good background on the concept.
By taking "chunk transposition" into account, I mean that
Turing, Alan.

should match
Alan Turing

more closely than it matches
Turing Machine

I.e. the distance calculation should detect when substrings of the text have simply been moved within the text. This is not the case with the common Levenshtein distance formula.
The strings will be a few hundred characters long at most -- they are author names or lists of author names which could be in a variety of formats. I'm not doing DNA sequencing (though I suspect people that do will know a bit about this subject).

A: In the case of your application you should probably think about adapting some algorithms from bioinformatics.
For example you could firstly unify your strings by making sure, that all separators are spaces or anything else you like, such that you would compare "Alan Turing" with "Turing Alan". And then split one of the strings and do an exact string matching algorithm ( like the Horspool-Algorithm ) with the pieces against the other string, counting the number of matching substrings.
If you would like to find matches that are merely similar but not equal, something along the lines of a local alignment might be more suitable since it provides a score that describes the similarity, but the referenced Smith-Waterman-Algorithm is probably a bit overkill for your application and not even the best local alignment algorithm available.
Depending on your programming environment there is a possibility that an implementation is already available. I personally have worked with SeqAn lately, which is a bioinformatics library for C++ and definitely provides the desired functionality.
Well, that was a rather abstract answer, but I hope it points you in the right direction, but sadly it doesn't provide you with a simple formula to solve your problem.

A: Have a look at the Jaccard distance metric (JDM). It's an oldie-but-goodie that's pretty adept at token-level discrepancies such as last name first, first name last. For two string comparands, the JDM calculation is simply the number of unique characters the two strings have in common divided by the total number of unique characters between them (in other words the intersection over the union). For example, given the two arguments "JEFFKTYZZER" and "TYZZERJEFF," the numerator is 7 and the denominator is 8, yielding a value of 0.875. My choice of characters as tokens is not the only one available, BTW--n-grams are often used as well.

A: One of the easiest and most effective modern alternatives to edit distance is called the Normalized Compression Distance, or NCD.  The basic idea is easy to explain.  Choose a popular compressor that is implemented in your language such as zlib.  Then, given string A and string B, let C(A) be the compressed size of A and C(B) be the compressed size of B.  Let AB mean "A concatenated with B", so that C(AB) means "The compressed size of "A concatenated with B".  Next, compute the fraction (C(AB) - min(C(A),C(B))) / max(C(A), C(B))   This value is called NCD(A,B) and measures similarity similar to edit distance but supports more forms of similarity depending on which data compressor you choose.  Certainly, zlib supports the "chunk" style similarity that you are describing.  If two strings are similar the compressed size of the concatenation will be near the size of each alone so the numerator will be near 0 and the result will be near 0.  If two strings are very dissimilar the compressed size together will be roughly the sum of the compressed sizes added and so the result will be near 1.  This formula is much easier to implement than edit distance or almost any other explicit string similarity measure if you already have access to a data compression program like zlib.  It is because most of the "hard" work such as heuristics and optimization has already been done in the data compression part and this formula simply extracts the amount of similar patterns it found using generic information theory that is agnostic to language.   Moreover, this technique will be much faster than most explicit similarity measures (such as edit distance) for the few hundred byte size range you describe.  For more information on this and a sample implementation just search Normalized Compression Distance (NCD) or have a look at the following paper and github project:
 http://arxiv.org/abs/cs/0312044 "Clustering by Compression"
 https://github.com/rudi-cilibrasi/libcomplearn C language implementation
There are many other implementations and papers on this subject in the last decade that you may use as well in other languages and with modifications.

A: I think you're looking for Jaro-Winkler distance which is precisely for name matching.

A: You might find compression distance useful for this.  See an answer I gave for a very similar question.
Or you could use a k-tuple based counting system:

*

*Choose a small value of k, e.g. k=4.

*Extract all length-k substrings of your string into a list.

*Sort the list. (O(knlog(n) time.)

*Do the same for the other string you're comparing to.  You now have two sorted lists.

*Count the number of k-tuples shared by the two strings.  If the strings are of length n and m, this can be done in O(n+m) time using a list merge, since the lists are in sorted order.

*The number of k-tuples in common is your similarity score.

With small alphabets (e.g. DNA) you would usually maintain a vector storing the count for every possible k-tuple instead of a sorted list, although that's not practical when the alphabet is any character at all -- for k=4, you'd need a 256^4 array.

A: I'm not sure that what you really want is edit distance -- which works simply on strings of characters -- or semantic distance -- choosing the most appropriate or similar meaning.  You might want to look at topics in information retrieval for ideas on how to distinguish which is the most appropriate matching term/phrase given a specific term or phrase.  In a sense what you're doing is comparing very short documents rather than strings of characters.


Q: How can I manipulate the data in receiving CAN frame via CAPL script and forward it into the same CAN bus? For example, I'm receiving a CAN frame from ECU with id 0x100 with some data inside in CAN channel 1. I want to change only byte 7 to 0xFF and forward this frame further in channel 1. My code is below:
on message 0x100
{
  message 0x100 msg;
  msg = this;
  msg.byte(7) = 0xFF;
  output(msg);
}

But, in CAN trace, I see the message as it is, without byte 7 changed. What I do wrong? Maybe there is something that I do not understand..
I have one assumption to solve it, but this requires wiring changes to my hardware. If I make one channel for input and another channel for output, then I can use CAPL as a gateway and send frame from CAN1 to CAN2 inside one CAN-bus.
Any ideas are welcome. Thank you.


Q: Why is it not possible to shadow a local variable in a loop? I got this situation I can't understand about shadowing. For example the following code:
class Foo {
   int a = 5;
   void goFoo(int a) {
       // No problem naming parameter as same as instance variable
       for (int a = 0; a < 5; a++) { }
       // Now the compiler complains about the variable a on the for loop
       // I thought that the loop block had its own scope so I could shadow
       // the parameter, why the compiler didn't throw an error when i named
       // the parameter same as the instance variable?
   }
}

A: void goFoo(int a) {

       for (int a = 0; a < 5; a++) { }

}

it is similar to
void goFoo() {
       int a;
       for (int a = 0; a < 5; a++) { }

}

so multiple declaration of a on the same scope, it is not acceptable.
or simply it is similar to
void goFoo() {
  int a;
  int a;
}

Also See

*

*java-variable-scope-shadowing

A: You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter).
From the Java Language Specification, section 14.4.3:

If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable.

Note the "field name" part - it's specifying that it has to be a field that is shadowed.
And from section 8.4.1:

The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.
These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor.

(It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.)

A: The scope of the variable depends on the hierarchy of the block as well.
ie if u use like this
void goFoo(int a) {
       // No problem naming parameter as same as instance variable
       for (int b = 0; b < 5; b++) { }
       //Now the compiler complains about the variable a on the for loop
       // i thought that the loop block had its own scope so i could shadow
       // the parameter, why the compiler didnt throw an error when i named
       // the parameter same as the instance variable?

       int b; // you can do this.

   }

That is if a variable is declared in the outer block then you can not declare the same in the block which is inner. the other way you can do it.

A: But you don't declare the second "a" in that new scope, as your code shows.  It's in the scope of the goFoo() block itself.

A: The problem isn't that the loop is shadowing the class field, the name is already used by the parameter.
Two options:  One is to change the loop:
for (a = 0; a < 5; a++) { }

This uses the parameter as the index variable.  Not clear why you would have a parameter, but all the same...
The other option is to rename the loop variable or the parameter to something else.

A: It is not shadowing, it is a conflict here. Both a are in the method scope. One cannot define two variables of same name in the same scope.

A: In Java (unlike, say, in c++) you cannot declare a local variable when another local variable with the same name is "in scope".
You cannot do this in Java
void foo() {
    int a;
    {
         int a;  // You cannot declare 'a' here because a
                 // from the outer block is still in scope
                 // here. Local variables in Java cannot be
                 // shadowed by another local variable with
                 // the same name. Only instance variables
                 // can be shadowed by the local variables
                 // with the same name.
    }
}

However c++ allows you to do this
void foo()
{
    int a;
    a = 10;
    cout << a << endl;  // prints 10 duh
    {
        int a;   // this declaration shadows the local
                 // variable 'a' from the outer scope.

        a = 20;  // assigns 20 to the variable 'a' in
                 // current inner scope, like you'd expect.
        cout << a << endl;  // prints 20.
    }
    cout << a << endl;  // prints 10
}


Q: Proof of Hales–Jewett number In the Wikipedia page: https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem, and the Polymath site http://michaelnielsen.org/polymath1/index.php?title=Coloring_Hales-Jewett_theorem, it says that the Hales–Jewett number $H(3, 2)=4$. However, I am unable to construct a $3 \times 3 \times 3$ cube with two colours which avoids a combinatorial line of the same colour. If the Polymath site is correct, then there is such a colouring.
So my question is: Is there a colouring, and if so, what is it?

A: Here is a valid coloring of the $3 \times 3 \times 3$ cube.

The $(1,1,1)$ cell is the bottom left cell of the leftmost square.
Note the antidiagonal line in the third square with all three cells colored red. (And another antidiagonal line in the first square with all three cells colored blue. There might be more.) This is okay, because it's not a combinatorial line: one coordinate is increasing while another is decreasing.
If you consider the geometric variant of Hales-Jewett, and forbid any three collinear cells from having the same color, then my SAT solver tells me that there is no valid coloring.

Edit: A less ad-hoc way of coloring the cube than the above (which was found by a SAT solver) is to use the lower bound from van der Waerden's theorem. We can color the set $\{1, 2, \dots, 7\}$ red and blue while avoiding monochromatic arithmetic progressions of length $3$: color $\{1,3,6\}$ red and $\{2,4,5,7\}$ blue. Then color the $3 \times 3 \times 3$ cube by giving $(x,y,z)$ the color of $x+y+z-2$. This produces the following coloring (with "layers" of $x+y+z=c$ indicated by shading):

So now it's straightforward to check that this coloring works. We can extend the coloring of $\{1, 2, \dots, 7\}$ to $\{1, 2, \dots, 8\}$ by coloring $8$ red, but to color the $3 \times 3 \times 3 \times 3$ cube, we would need a coloring of $\{1, 2, \dots, 9\}$, which (unsurprisingly) doesn't exist.

A: Here is a $2-$coloring of a $3×3×3$ cube which avoids a combinatorial line of the same colour.
The bottom layer is colored as:
\begin{array}{|c|c|}
\hline
0& 1 & 0  \\ \hline
0& 0& 1 \\ \hline
1&  0& 1\\ \hline
\end{array}
The middle layer is colored as:
\begin{array}{|c|c|}
\hline
0& 0 & 1  \\ \hline
 1& 1& 0\\ \hline
 0&  1& 0\\ \hline
\end{array}
The top layer is colored as:
\begin{array}{|c|c|}
\hline
1& 1 & 0  \\ \hline
 0& 0& 1 \\ \hline
 1&  0& 0 \\ \hline
\end{array}
We can easily check manually that the $4$ body diagonals are not monochromatic as well. Hence, this is the desired coloring!


Q: ¿Como puedo validar que exista almenos una casilla marcada? Estoy haciendo validaciones en mi formulario, pero llegue a una sección en donde tengo varios checkbox, intenté ponerle un required a los input dentro de estos, pero al darle botón enviar me pide obligatoriamente que marque cada una de ellas, intenté también hacer una función en javascript que apuntará a una id de un div pero tampoco obtuve resultados.
Apunte : Anteriormente tenia la linea de la clase de esta manera, pero tampoco obtuve resultados.

   Seleccionar uno o más lenguajes de programación de un interés

      <input type="checkbox" class="form-check-input" id="opcion1" name="lenguajes" value="1">
        Python

      <input type="checkbox" class="form-check-input" id="opcion2" name="lenguajes" value="2" >
       TypeScript

      <input type="checkbox" class="form-check-input" id="opcion3" name="lenguajes" value="3" >
       C++

      <input type="checkbox" class="form-check-input" id="opcion4" name="lenguajes" value="4" >
       C#

   <input type="checkbox" class="form-check-input" id="opcion5" name="lenguajes" value="5" >
       PHP

A: Debes crear los elementos como arreglo agregando corchetes en el nombre, de lo contrario, cada nuevo elemento va a remplazar el anterior a la hora de procesar el formulario.
Ya con los campos como arreglo es muy fácil obtenerlos por nombre con querySelectorAll() y agregando :checked para buscar solo los que están marcados:

document.querySelector('#verificar').addEventListener('click', e => {
    // Cancelar evento, para evitar que se procese el formulario
    // Puedes omitir este paso si haces la verificación con el evento submit
    e.preventDefault();
    // Obtener checkboxes marcados
    let checked = document.querySelectorAll('[name="lenguajes[]"]:checked');
    // Verificar si se marcó alguno
    if(checked.length == 0) {
        console.log('Selecciona al menos un lenguaje');
    } else {
        // Saber cuántos se marcaron
        console.log(checked.length);
    }
});

   Seleccionar uno o más lenguajes de programación de un interés

      <input type="checkbox" class="form-check-input" id="opcion1" name="lenguajes[]" value="1">
        Python

      <input type="checkbox" class="form-check-input" id="opcion2" name="lenguajes[]" value="2" >
       TypeScript

      <input type="checkbox" class="form-check-input" id="opcion3" name="lenguajes[]" value="3" >
       C++

      <input type="checkbox" class="form-check-input" id="opcion4" name="lenguajes[]" value="4" >
       C#

   <input type="checkbox" class="form-check-input" id="opcion5" name="lenguajes[]" value="5" >
       PHP

<button id="verificar">Verificar</button>


Q: Como posso fazer um objeto se 'auto-deletar' em JavaScript? Tentei algo como:
function Objeto(){
  this.del = function(){
    delete this;
  }
}

var a = new Objeto();

a.del();

Mas a variável a ainda está existindo

Eu conheço o método citado na resposta do @bfavaretto, mas para o código em que estou trabalhando não consigo 'subir um nível' na estrutura de variáveis para executar este delete, ou obj = null;
Eis o trecho em que pretendo utilizar isto:
Bullet.prototype.step = function() {
    for (var i = 0; i < mobs.length; i++){
        if ((this.x >= mobs[i].x && this.x <= mobs[i].x + mobs[i].size) && (this.y >= mobs[i].y && this.y <= mobs[i].y + mobs[i].size)){
            mobs[i].getHit(this.damage);
            delete this;
        }
    }
};

Ou a referência completa:http://codepen.io/GabrielMaia/pen/LEmROB

A: Você pode simplesmente definir todas as referências ao objeto como null:
a = null;

Mas precisa ser todas mesmo. Por exemplo:
var b = a;
a = null;
b = null; // não esqueça!

Pergunta relacionada: Como funciona o coletor de lixo do JavaScript?

Considerando seu comentário que diz se tratar de uma array de bullets, de onde você precisa retirar uma dessas balas: crie uma função para isso, que receba a bala em questão e remova a posição correspondente da array. Você pode encontrar a posição com indexOf, e remover com splice. Algo assim:
var bulletArray = []; // considere populada
function removeBullet(bullet) {
    var index = bulletArray.indexOf(bullet);
    bulletArray.splice(index, 1);
}


Q: writing to a json file from python how do i edit/change a particular field in a json file using python code:
{
   "EZMessage":{
      "action":"account.cash",
      "data":{
         "authToken":"123456",
         "account":"#ACCOUNTID#",
         "portfolio":"true",
         "historical":"true"
      }
   }
}

in this json code, i want to replace 123456 with 789123
string replace only works if i know what is written there. in my code, i would only know what to write, and the identifier "authToken". Is there a way to overwrite the 123456 by identifying that it is the value of "authToken" ?
thanks,
RS

A: Use the json module to convert the string to a set of nested dict objects, make your changes, and then dump the dictionary back to a json string.
import json
jstr = '''{
   "EZMessage":{
      "action":"account.cash",
      "data":{
         "authToken":"123456",
         "account":"#ACCOUNTID#",
         "portfolio":"true",
         "historical":"true"
      }
   }
}'''

j = json.loads(jstr)
j['EZMessage']['data']['authToken'] = 654321
jstr = json.dumps(j)

For how to read-from/write-to a file see the fine tutorial.

A: Convert the JSON object to a Python object, then change the value just like any other Python object.


Q: Excel VBA. Matching the BackColor of a TextBox to the .Interior.Color of a cell I can't seem to find an answer for this.  I have a spreadsheet with a userform, and I'm trying to match the back colour of TextBox47 with the corresponding cell on the sheet, the value of which is fetched via a Listbox.  What I need is to be able to click on the list item, and the text box to fill with that colour.
I have the following code to colour the cells in the sheet, according to date, and with named ranges for parameters.. and this runs on UserForm Initialise()
Dim cell As Range
      With Range("data_table[Date Test]")

    For Each cell In Range("data_table[Date Test]")
        If cell.Value < Range("Today") Then
            cell.Interior.ColorIndex = 6
            ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then
            cell.Interior.ColorIndex = 3
            ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then
            cell.Interior.ColorIndex = 45
            ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 43
            ElseIf cell.Value > Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 18

         End If

    Next cell
    End With

This works fine, I then tried the following to colour the textbox
 Private Sub TextBox47_Change()
    Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
    Dim cell As Range
For Each cell In Range("data_table[Date Test]")
          With Range("data_table[Date Test]")
    Me.TextBox47.BackColor = .Interior.Color
        Next cell

    End With

I think I need to add the following somewhere..
TextBox47.Value = Me.ListBox1.List(ListBox1.ListIndex, 65)

Which is the ListBox reference for the TextBox.. but I'm starting to get very confused now.  I've been looking at this for a couple of days.

Edit to add Listbox code as asked.
    Private Sub ComboBox8_Change()

Dim i As Long

Me.ListBox1.Clear
For i = 2 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A"))
If Sheet1.Cells(i, 10).Value = Me.ComboBox8.Value Then

Me.ListBox1.AddItem Sheet1.Cells(i, 10).Value
'ID Number
Me.ListBox1.List(ListBox1.ListCount - 1, 0) = Sheet1.Cells(i, 1).Value
'Title
Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value

So would it be more something like this..
 Private Sub TextBox47_Change()
    Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
Me.TextBox47.BackColor = .Interior.Color
    End Sub

Which gives a Compile Error
1
Newer code
I've now changed it to this..
Private Sub TextBox47_Change()
    Dim cell As Range
        Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
            With Range("data_table[Date Test]")
                Me.TextBox47.BackColor = Range("data_table[Date Test]").Interior.Color
            End With
End Sub

Which at least doesn't throw up an error, but on every selection the BackColor is black.  I started with ..
Private Sub TextBox47_Change()
        Dim cell As Range
            Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
                With Range("data_table[Date Test]")
                    Me.TextBox47.BackColor = Range("cell").Interior.Color
                End With
    End Sub

But that just stopped at a Run Time error 1004
Yet another edit.. please tell me if continual adding to this post is the wrong way to do it.

This, when hovering over is actually picking up the correct info from the cell that I'm after (I've tried different ones to make sure), in the Listbox selection that I'm clicking on, so I guess now it's a case of telling the Interior.Colour to look at the cell that is chosen?

A: I managed to get it to work.. although not sure if it's the most elegant solution.  :)
To save confusing it with the code above, which has gotten a bit disjointed and messy, here's all the new working code and the explanation I came up with
Code to colour cells in sheet:
Dim cell As Range

      For Each cell In Range("data_table[Date Reviewed]")
        If cell.Value < Range("Today") Then
            cell.Interior.ColorIndex = 7  'Magenta
            ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then
            cell.Interior.ColorIndex = 3  'Red
            ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then
            cell.Interior.ColorIndex = 45  'Orange
            ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 4  'Green
            ElseIf cell.Value > Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 19  'Beige
        End If

    Next cell

This is in UserForm_Initialize()
And then to match the cell colour with TextBox.BackColor, I've used the ListBox.ListIndex to get the date, using the following code:
Private Sub TextBox47_Change()

      Me.TextBox47.Text = Format(TextBox47.Text, "dd/mm/yyyy")

                    If (Me.ListBox1.List(ListBox1.ListIndex, 65)) < Range("Today") Then
                     TextBox47.BackColor = RGB(255, 0, 255)  'Magenta
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) >= Range("Today") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Thirty_Days") Then
                     TextBox47.BackColor = RGB(255, 0, 0)  'Red
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Thirty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Sixty_Days") Then
                     TextBox47.BackColor = RGB(255, 153, 0)  'Orange
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Sixty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Ninety_Days") Then
                     TextBox47.BackColor = RGB(0, 255, 0)  'Green
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Ninety_Days") Then
                     TextBox47.BackColor = RGB(255, 255, 204)  'Beige
        End If

     End Sub

I can now call that TextBox.BackColor to set the associated Interior.Color of any other cell I'm forwarding on that value to, such as the Report I'm generating in Sheet2:
Sheet2.Range("D105").Value = Me.TextBox47.Text
Sheet2.Range("D105").Interior.Color = Me.TextBox47.BackColor

Thankyou for your help and patience.  It was your comment "So you have a listbox which returns a date" which helped me to see where I was actually getting the date from when hovering over the line of code, rather than it seeing a particular Cell.Address, and hence how I got the above to work.
Again, thankyou, and I hope I didn't break too many posting rules in the meantime.  :)
Apologies, but I couldn't see a thanks button anywhere.
Cheers
Liam


Q: Getting Started with EC2 Container Registry This is giving me a headache.
Here's what I've done so far

*

*Created an EC2 Virtual Server Instance, and its running

*Installed the AWS CLI

*Installed Docker on my EC2 Virtual Server after I SSH'd into it

So looking at the docs it tells you how to build an image.  Now comes my confusion.
Question 1: So am I right by assuming that one basically have an option to a) build an image off your host or b) pull an image created by others from Docker Hub?
Question 2: If I'm right about Question #1 then what am I building an image ** off of** if I am not pulling one from docker hub? with the AWS docs here?
Question 3: then I see a whole different route I can take, using Docker Compose, so I'd use that instead of all this above?  This is so confusing.
EC2 Container Registry – Now Generally Available
So again, here, it tells you to install docker on the Host.  Then immediately jumps into "create an image".  Create an image off what, that host's OS?  I don't get it, I guess that's what it means OR I can pull an image from Docker Hub and not go this route?
Same here, it's talking about creating a docker image, what off the Host?
Or..maybe I'm not understanding what "image" means but I assume going this route, instead of pulling a Docker image from Docker Hub that I'm creating an image off my EC2 virtual Instance?

A: A1: No. You can't build an image off your host.
You can create an new image according to your requirement like which Operating Sytem (Ubuntu, Fedora), Stack(LAMP, LEMP) and many other things.
Or you can pull an image which will be pre-configured with all the packages like Wordpress Stack image, Magento stack image, Bitnami image which you can pull from docker-hub.
A2: As I have mentioned earlier you can build an image of any operating system you want(Ubuntu, Fedora, Debian) but not off the host.
You just need to pull image from docker-hub. e.g docker pull ubuntu will pull mininmal image of Ubuntu-14.04. And if you need specific version of Ubuntu
like Ubuntu-12.04 version e.g docker pull ubuntu:12.04 will pull minimal image of Ubuntu-12.04
A3: Docker-compose is a tool for defining and running multi-container docker applications. docker-compose conatins a compose file
in which you can configure your application services.
And finally Amazon EC2 Container Registry is little bit different thing. The Idea is the same as docker but Amazon is providing
this as a EC2 Container Service with many other functionality which docker doesn't have right now.
Hope it hepls:-)


Q: What does Qt do if an error occurs in a constructor? It is generally recommended to raise an exception if an error occurs in the constructor of a class.
In Qt, none of the classes throw an exception (as far as I know).
How does Qt handle errors that occur in constructors?

A: As you said Qt does not use exceptions, building a QObject will not fail on the Qt side (still the C++ memory allocation could fail).
What kind of error in constructor do you have in mind?
Qt will create object with an invalid state if necessary, in my opinion it is not a constructor error that should cancel the object creation but more of a not-fully-initialized-yet-to-work-well object-state.
Examples:
QRegExp regex1; // isValid() : false
QRegExp regex2("nop{"); // isValid() : false
// regex2.errorString() => "bad repetition syntax"

QSqlDatabase db; // isValid() : false

QDate date1; // isValid() : false
QDate date2(0, 0, 0); // isValid() : false
QDate date3(-1, 0, 1024); // isValid() : false

QString str1; // isNull() : true, isEmpty() : true
QString str2(""); // isNull() : false, isEmpty() : true


Q: Is it possible to create single SQL query for dozens of UPDATE statements? Should it increase performace? How should it look like in my case? I have a problem. In code below there is a foreach loop, where is created query string for each object truck inside of trucks collection. The loop iterates 100 times (100 objects in the collection, for the example). And method with the loop is called 2000 times.
I resigned from using of ORM to get better performance. But, unfortunatelly, I am still disapointed a bit with code execution speed.
Please note, that for each iterated object there is created string query, that looks, for the example, like this:
UPDATE dbo.Trucks
SET OfficialNumber = '5124095'
, Status = 'Undefined'
, PerformancesUpdate = @PerformancesUpdate
, PictureLink = 'http://www.somewebsite.com/photos/middle////.jpg'
WHERE TruckId = 405664;

and next, after parsing command.Parameters, if they exists (in this case @PerformancesUpdate), the query is sent via library method with int rows = command.ExecuteNonQuery(); //execute SQL. And so on, 100 times. Please note, that query string depends on object properties, so every case will be different a bit.
Here are my questions. I am wondering, is it possible to create one query for all 100 objects in the loop and sending it at once? If yes, should it increase performance? If yes, How the sample query should look like?
And here is the code that creates loop, where are created and executed SQL queries:
using (SqlConnection connection = GetConnection(_connectionString))
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();

                    foreach (SomeObject truck in trucks)
                    {
                        Console.WriteLine("Updating " + counter++ + " of " + trucks.Count);

                        //clean up string for basic data
                        truck.Status = CleanUpStringCases(truck.Status);
                        truck.Destination = CleanUpStringCases(truck.Destination);
                        //clean up string for full AIS data
                        if (dataType == "full")
                        {
                            truck.TruckType = CleanUpStringCases(truck.TruckType);
                        }

                        //PARSE

                        SomeObject existing = new SomeObject();

                        //find existing truck to be updated
                        if (truck.OfficialNumber > 0) existing = _context.trucks.Where(v => v.OfficialNumber == truck.OfficialNumber).FirstOrDefault();
                        StringBuilder querySb = new StringBuilder();

                        if (existing != null)
                        {
                            //update for basic data
                            querySb.Append("UPDATE dbo." + _trucksTableName + " SET OfficialNumber = '" + truck.OfficialNumber + "'");
                            if (existing.MNCI == 0) if (truck.MNCI.HasValue) querySb.Append(" , MNCI = '" + truck.MNCI + "'");
                            if (truck.LatestActivity.HasValue) querySb.Append(" , LatestActivity = @LatestActivity");
                            if (truck.ETA.HasValue) querySb.Append(" , ETA = @ETA");
                            if (!string.IsNullOrEmpty(truck.Status)) querySb.Append(" , Status = '" + truck.Status + "'");
                            if (!string.IsNullOrEmpty(truck.Destination)) querySb.Append(" , Destination = '" + truck.Destination + "'");
                            if (!string.IsNullOrEmpty(truck.Area)) querySb.Append(" , Area = '" + truck.Area + "'");

                            if (truck.HeadingTo.HasValue) querySb.Append(" , HeadingTo = @HeadingTo");
                            if (truck.Lat.HasValue) querySb.Append(" , Lat = @Lat");
                            if (truck.Lon.HasValue) querySb.Append(" , Lon = @Lon");
                            if (truck.Speed.HasValue)
                            {
                                querySb.Append(" , Speed = @Speed");
                                if ((existing.SpeedMax < truck.Speed || existing.SpeedMax == null) && truck.Speed != 0) querySb.Append(" , SpeedMax = @Speed"); //update speed max
                            }

                            //string for full AIS data
                            if (dataType == "full")
                            {
                                if (truck.PerformancesUpdate.HasValue) querySb.Append(" , PerformancesUpdate = @PerformancesUpdate");
                                if (!string.IsNullOrEmpty(truck.TruckType)) querySb.Append(" , TruckType = '" + truck.TruckType + "'");
                                if (!string.IsNullOrEmpty(truck.PictureLink)) querySb.Append(" , PictureLink = '" + truck.PictureLink + "'");
                                if (truck.LOA.HasValue) querySb.Append(" , LOA = '" + truck.LOA + "'");
                                if (truck.Height.HasValue) querySb.Append(" , Height = '" + truck.Height + "'");
                            }

                            querySb.Append(" WHERE truckId = " + existing.truckId + "; ");
                        }

                        try
                        {
                            string query = querySb.ToString();

                            command.CommandText = query;
                            if (query.Contains("LatestActivity ="))
                                command.Parameters.AddWithValue("@LatestActivity", truck.LatestActivity);
                            if (query.Contains("ETA ="))
                                command.Parameters.AddWithValue("@ETA", truck.ETA);
                            if (query.Contains("PerformancesUpdate ="))
                                command.Parameters.AddWithValue("@PerformancesUpdate", truck.PerformancesUpdate);
                            if (query.Contains("HeadingTo ="))
                                command.Parameters.AddWithValue("@HeadingTo", truck.HeadingTo);
                            if (query.Contains("Lat ="))
                                command.Parameters.AddWithValue("@Lat", truck.Lat);
                            if (query.Contains("Lon ="))
                                command.Parameters.AddWithValue("@Lon", truck.Lon);
                            if (query.Contains("Speed ="))
                                command.Parameters.AddWithValue("@Speed", truck.Speed);

                            command.CommandTimeout = 30;
                            command.CommandType = CommandType.Text;

                            int rows = command.ExecuteNonQuery(); //execute SQL
                            command.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    connection.Close();
                }

Solution:
Martin`s approach is marked as a solution. And answering question about increasing performance, after testing his approach on local DB I can tell, that DB update speed increases directly proportional on quantity of updated rows in single query. For the example, when updating 300 rows, it took me around 30s, together with API requests. When updating 1000 rows, it all takes around 80s. And, as guys mentioned, the only limitation is the number of parameters, so I am just converting doubles and DateTime to SQL format, getting rid of parameters, and voila.

A: Yes, it is possible to send multiple update commands on one operation.
You would need to add the commands to your string builder and number the SQL parameters.
SqlCommand command = connection.CreateCommand()
var querySb = new Stringbuilder();

for(int i = 0; i < trucks.Count; i++)
{
    [...]

    if (truck.Speed.HasValue)
    {
        querySb.Append(" , Speed = @Speed" + i);
        command.Parameters.AddWithValue("@Speed" + i, truck.Speed);
    }

    querySb.AppendLine();
}
command.CommandText = querySb.ToString();
command.ExecuteNonQuery();

You might create smaller batches of rows (not send all rows at once), maximum number of parameters in one command is 2,098.

A: I recommend using some kind of bulk operations, since multiple separate db roundtrips produces excess overhead (as you have noticed).
Bulk updates can be implemented i.e with following methods:

*

*By using external library which is specialized on high-speed Bulk operations

*By crafting sql stored procedure which takes array of data as parameter. More information about table-valued parameters can be found in https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine

*Store all the rows with a BULK INSERT operation to a temporary table and run the T-SQL MERGE operation from temp table to actual data table with a single database transaction.


Q: change the format of \ref (enumerate package) I am writing a list of questions using enumerate package.
Something like this :
\documentclass[a4paper,10pt]{scrreprt}
\usepackage{enumerate}
\begin{document}

\begin{enumerate}
\item \label{itm:1} This is the question 1
\item \begin{enumerate}[(a)]
\item \label{itm:2a} This is the question 2.(a)
\item This is the question 2.(b)
\item \begin{enumerate}[-i)]
\item \label{itm:2ci}This is the question 2.(c)-i)
\item This is the question 2.(c)-ii)
\end{enumerate}
\end{enumerate}
\end{enumerate}

\ref{itm:1},\ref{itm:2a} and \ref{itm:2ci}

\end{document}

\ref{itm:1},\ref{itm:2a} and \ref{itm:2ci} gives respectively 1, 2a and 2(c)i
how can I change the format of \ref to get

*

*, 2.(a) and 2.(c)-i)

if possible show how can I apply the solution locally and globally for all enumerate of the document.

A: I don't know how your objective may be accomplished with the tools of the enumerate package (though David Carlisle probably could!), but I know how to accomplish it with the enumitem package.
One of the many nice features of the enumitem package is that labels of enumerated items and the format of cross-references to these items can be set in a very straightforward way. For first-level items, only the ref part needs to be modified (by affixing a "." to \theenumi); the second- and third-level items both the label and the ref parts are modified.
(The code below uses the hyperref package to make obvious what the cross-references look like.)

\documentclass[a4paper,10pt]{scrreprt}
\usepackage{enumitem}
\usepackage[colorlinks]{hyperref} %% just for this example
\begin{document}

\begin{enumerate}[ref=\theenumi.]
\item This is question 1 \label{itm:1}
\item \begin{enumerate}[label=(\alph*),
                        ref=\theenumi(\theenumii)]
      \item This is question 2.(a) \label{itm:2a}
      \item This is question 2.(b)
      \item \begin{enumerate}[label=-\roman*),
                              ref=\theenumii-\theenumiii)]
            \item This is question 2.(c)-i) \label{itm:2ci}
            \item This is question 2.(c)-ii)
            \end{enumerate}
      \end{enumerate}
\end{enumerate}

Questions \ref{itm:1}, \ref{itm:2a}, and \ref{itm:2ci} \dots

\end{document}

Your formatting goals, for both the labels and the cross-references, could also be achieved without the aid of any package, by using the following low-level LaTeX instructions instead. Note, though, that these instructions apply to all subsequent enumerated environments.
\makeatletter
\renewcommand\labelenumi{\arabic{enumi}.}
\renewcommand\theenumi{\arabic{enumi}.}
\renewcommand\labelenumii{(\alph{enumii})}
\renewcommand\theenumii{(\alph{enumii})}
\renewcommand\labelenumiii{-\roman{enumiii})}
\renewcommand\theenumiii{-\roman{enumiii})}
\renewcommand\p@enumiii{\theenumi\theenumii}
\makeatother

If you have several enumerated lists of this type, it is handy to create a dedicated enumerate-like environment that sets up all the formatting instructions, using the \newlist and \setlist instructions of the enumitem package. For instance, you might set up the following code (no new screenshot, as the output is the same as in the preceding example):
\documentclass[a4paper,10pt]{scrreprt}

\usepackage{enumitem}
\newlist{qenum}{enumerate}{3}  % create a new enumerate-like environment
\setlist[qenum,1]{label=\arabic*.,
                  ref=\arabic*.}
\setlist[qenum,2]{label=(\alph*),
                  ref=\theqenumi(\alph*)}
\setlist[qenum,3]{label=-\roman*),
                  ref=\theqenumii-\roman*)}

\usepackage[colorlinks]{hyperref} %% just for this example

\begin{document}

\begin{qenum}
\item This is question 1 \label{itm:1}
\item \begin{qenum}
      \item This is question 2.(a) \label{itm:2a}
      \item This is question 2.(b)
      \item \begin{qenum}
            \item This is question 2.(c)-i) \label{itm:2ci}
            \item This is question 2.(c)-ii)
            \end{qenum}
      \end{qenum}
\end{qenum}

Questions \ref{itm:1}, \ref{itm:2a}, and \ref{itm:2ci} \dots

\end{document}


Q: Nightwatch: Basic auth with access_key not working I created nightwatch.json file like below (with username and access_key properties):
"test_settings": {
        "default": {
            "launch_url": "http://localhost",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "silent": true,
            "cli_args": {
                "webdriver.firefox.profile": "testprofile"
            },
            "screenshots": {
                "enabled": false,
                "path": "screenshots/"
            },
            "desiredCapabilities": {
                "browserName": "firefox",
                "javascriptEnabled": true,
                "acceptSslCerts": true
            },
            "username": "examplelogin",
            "access_key": "password"
        }

but basic auth don't work and I get login window to fill my password and login after running tests. I looked at packets in fiddler and no authorization header was present. Any ideas what I'm doing wrong?
Nightwatch v0.9.6

A: from: https://groups.google.com/d/msg/nightwatchjs/n-B4HnnzYg8/rmaipXiTsuwJ

Replying to my own post before - please don't confuse the username and
  access_key vars as 'basic auth' ones. They are selenium based
  authenticators which can optionally be used for authenticating against
  cloud solutions. Best solution for basic auth is the good old URL way.
  Try:  ``` browser.url('https://' + userName + ':' + password + '@' +
  yourUrl)

A: You can do this in globals.js. It will preserve credentials and skip basic auth prompt.
beforeEach: function (browser, cb) {
  if (browser.globals.basic_auth_url) {
    browser.url(browser.globals.basic_auth_url, cb);
  } else {
    cb();
  }
},

basic_auth_url - add full URL with credentials.
Do not add credentials to launch_url


Q: Javascript Rich Text Editor and associated class to filter and clean the input? I realise there are several rich text editors for jQuery but I cannot find any that have an associated class that does the filtering and cleaning required to accept the input into a database.
Does such a class exist?
I am particularly interested for a PHP library, but .NET would be interesting too.

A: If you would use FCKeditor it would allow to you get clean HTML or XHTML (editor.GetXHTML()) which you could then write into DB.
Actually it's not that much important what you write into DB, because usially you write original HTML (you can always strip from it saspicious tags if needed). In order to prevent XSS attacks it is essential to properly encode content before displaying it on the web-page. For .NET there is AntiXSS library for that at CodePlex.com
For PHP you may want to look at the following libraries:

*

*Zend_Filter

*HTML Sanitizer

*PHP Input Filter
And also this article:

*

*Avoiding XSS security attacks to sites that use HTML editors


Q: Ionic 3: Menutoggle keeps getting hidden I have implemented a hamburgermenu in Ionic 3, but I am facing an issue. When I run the application on my Android device the hamburgermenu keeps disappearing i.e. the button to open the side menu is gone. However, it only happens sometimes. I tried to run the application while inspecting it with Google Chrome, and what I noticed is that the menutoggle gets hidden for some reason, but I don't know why. I don't control the visibility in the .ts class.
<ion-header>
  <div>
    <ion-navbar>
      <button ion-button menuToggle> // this becomes "<button ion-button menuToggle hidden>"
        <ion-icon name="menu"></ion-icon>
      </button>
      <ion-title>Frontpage</ion-title>
    </ion-navbar>
  </div>
</ion-header>

A: I am having similar issue for menu toggle.
I added below code for my page.
Header html code:
<ion-header>
 <ion-navbar text-center color="navBar">
  <ion-buttons right>
   <button class="menu" ion-button menuToggle="right" icon-only>
    <ion-icon name="menu"></ion-icon>
   </button>
  </ion-buttons>
  <ion-title>Password Reset</ion-title>
 </ion-navbar>
</ion-header>

Header css code:
.menu {
    display: block !important;
}


Q: Comparison test for the series I want to test that the given series is convergent or divergent.
$\Sigma_{n=2}\frac {(-i)^n}{\ln n} $, ($z_n = \frac {(-i)^n}{\ln n}$)
I know that for $n >1 $, $\ln n< n$ holds. So by using the comparison test, $\Sigma_{n=2} \frac{1}{n} $ diverges so $\Sigma_{n=2}\frac {1}{\ln n} $ diverges too. But what about $\Sigma_{n=2}\frac {(-i)^n}{\ln n} $? I must check the divergence of series $z_n$, not for the series $|z_n|$ and I got confused...
p.s. When checking the convergence of series, it's quite obvious to only test for  the series $|z_n|$ case because absolute convergence implies convergence. But what about the divergence case?

A: Your p.s. is wrong. There are series like $\sum (-1/n)^n$ which converge while the series of the absolute values diverges.
Your series is one of this. Indeed we can write
$$\sum _{n=2}^{\infty } \frac{(-i)^n}{\log (n)}=\sum _{n=1}^{\infty } \frac{(-i)^{2 n}}{\log (2 n)}+\sum _{n=1}^{\infty } \frac{(-i)^{2 n+1}}{\log (2 n+1)}$$
The first one can be rewritten as
$$\sum _{n=1}^{\infty } \frac{(-1)^{ n}}{\log (2 n)}$$
which converges for the Leibniz criterion because general term tends to zero
The other series can be written as
$$\sum _{n=1}^{\infty } \frac{(-i)^{2 n+1}}{\log (2 n+1)}=i\sum _{n=1}^{\infty } \frac{(-1)^{n+1}}{\log (2 n+1)}$$
which converges for the same test as above.


Q: delete Single Core Data Item from a uicollectionviewCell using a button I am trying to delete a single element of the coreData set using a button inside a collectionviewcell. So the cell has a label with the result of the core data fetch. When I hit the button it should delete the cell making it no longer appear. Also the the core data single set item should be perementley deleted. I have scence this used before in protocols but not using core data.The core data is var itemName.
class CustomCell: UICollectionViewCell {
 @objc func delete() {
}}
class ViewController: UIViewController {
    var itemName : [Item] = []
}

A: In My Case Working 100%
Try This
import CoreData

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell Identifier name ", for: indexPath) as! Cellname
    cell.YourButtonNamw.tag = indexPath.row
    cell.YourButtonNamw.addTarget(self, action: #selector(delete), for: .touchUpInside)
     return cell
    }

     @objc func delete(_ sender:UIButton){
      let itemName1 = itemName[sender.tag]
     let context = APP_DELEGATE.persistentContainer.viewContext
            var albums = [YourTableName]()
            let request = NSFetchRequest<YourTableName>(entityName: YourTableName)
            request.predicate = NSPredicate(format: "itemName = %@" , itemName1)
            do
            {
                albums = try context.fetch(request)

                for entity in albums {
                    context.delete(entity)
                    do
                    {
                        try context.save()

                    }
                    catch let error as Error?
                    {
                        print(error!.localizedDescription)

                    }
                }

            }
            catch _ {
                print("Could not delete")

            }

    }


Q: Counting unique variables within a unique variables [R] Suppose this is my data:
X   Y   Z
1   1   2323
1   1   45
1   1   67
1   2   1
1   2   90
1   3   34
1   3   1267
1   3   623
1   4   81
1   4   501
2   1   456
2   1   78
2   2   41
2   2   56
2   3   90
2   3   71
2   4   24
2   4   98
2   5   42
2   5   361

How do I count the values of Z for each unique variable Y for each separate X so that I can get a dataframe that looks like:
X   Y   Z
1   1   2435
1   2   91
1   3   1924
1   4   582
2   1   534
2   2   97
2   3   161
2   4   122
2   5   403

A: Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate:
 > aggregate( Z ~ X + Y, data=dat, FUN=sum)

  X Y    Z
1 1 1 2435
2 2 1  534
3 1 2   91
4 2 2   97
5 1 3 1924
6 2 3  161
7 1 4  582
8 2 4  122
9 2 5  403

Could also have used xtabs which returns a table object and then turn it into a dataframe with as.data.frame:
 as.data.frame( xtabs( Z ~ X+Y, data=dat) )


Q: Git Stash - Local Changes - Git Stash - Git Stash Apply - Undo Need some help, I screwed up. Please reserve judgement.
Alright, this is what I did.

*

*git stash

*made some changes to the code.

*git stash (again)

*git stash apply
Is there any way I can get back to the code I had before the first git stash.
Any help would be appreciated.
Thanks, in advance.

A: Appreciate that applying or popping a Git stash just alters the working directory and/or stage.  It does not make a new commit.  Therefore, simply doing a hard reset should get you back to where you were before the first stash:
# from your branch
git reset --hard

That being said, if you wanted to retain some permutation of the changes since the first stash, that is another story and would require more work and thought to pull off.
Note: Generally speaking, popping a Git stash is risky, because if something goes wrong along the way, you can't reapply the same stash as it has already been popped from the stack.  Use git stash apply for best results.

A: git stash list
<shows all the saved stashes>

git stash show 'stash{0}'
<displays changes in this stash>
<change index according to the one you want, 0 is the last saved stash>

git stash apply 'stash{0}'
<applies the stash>


Q: Triggering events from async/await functions in the right order I have problems ensuring the order of events in my asynchronous task. The class from which other async tasks inherit has the following functions and takes the EventHandlers (ExecutionProgress, ExecutionStarted, ExecutionCompleted) in the constructor arguments:
public abstract Task Operation(IProgress<EventArgs> progress);

public virtual void Execute()
{
    ExecuteAsync()
}

private void ReportProgress(EventArgs args)
{
    if(ExecutionProgress != null) ExecutionProgress(this, args);
}
private async Task ExecuteAsync()
{
    if(ExecutionStarted != null) ExecutionStarted(this, EventArgs.Empty)
    await Operation(new Progress<EventArgs>(ReportProgress));
    if(ExecutionCompleted != null) ExecutionCompleted(this, EventArgs.Empty)

}

Now in one of my classes, that inherits from asynchronous tasks, i override Operation with the following:
public override async Task Operation(IProgress<EventArgs> progress)
{
    // run the synchronous function in another thread
    JobResults results = await Task.Run(() => worker.DoYourJob());
    progress.Report(results);
}

Running this code often, but not always, results in NullReference Exception in the ExecutionCompleted event handler when trying to access the JobResults. This is because ExecutionProgress event which writes the member variable usually gets fired after ExecutionCompleted for whatever reason. I think the standard says nothing about event ordering, but I'm looking for a nice solution to ensure deterministic ordering here.  I want to fire ExecutionCompleted only after all ExecutionProgress events have been handled.
What would be a nice looking solution here? Is there any way to await until all progress reporting events have been handled.

A: The events are all fired in order.  If your event handlers are asynchronous, which seems to be the case, then the code firing the events is going to continue executing as soon as it starts the event handlers, not when they complete.
If the code firing the events needs to not continue on until all of the handlers have finished, then you need to restructure this class such that the event handlers have some means of indicating to this class when they're done.  There are any number of ways to do this, from passing a parameter in the event that allows handlers to tell it when they're done, or to having the signature of the event handlers return a Task rather than being void (you'll need to await those tasks when firing the event).


Q: Copy Woocommerce product short description to ACF I want to copy the short description of all the products to an acf custom field that i created. The custom field's name is sxolia . I don't know how can i catch this ACF Field with a query to the database.
UPDATE `wp_posts`
SET `post_excerpt` = `?`
WHERE `post_type` = 'product'
AND `post_status` = 'publish'

A: You can use ACF function update_field($selector, $value, $post_id); to set the value of a specific field.
More info here: https://www.advancedcustomfields.com/resources/update_field/


Q: testing monaca backend only possible on device, why? When I test my app on my device I'm able to connect to the backend user and collection features. Why isn't that working when I preview the app in the browser (Chrome)? Or is it possible and what should I do to fix this...

A: As stated in the Monaca Backend API Reference Guide, Monaca backend requires a phonegap plugin thus the browser does not have these installed and therefore you will not be able to access those systems.
Ultimately, there is nothing you can do other than to test in the app, although if you use the Monaca Cloud IDE, you do gain a web interface to manage the backend.  It is very useful.
Hope this helps!


Q: 2 SELECT in a query with ORDER BY I need to create a MYSQL query that will return the following:
excel
this is my query
    SELECT  t1.fecha_salida,
        t1.agencia,
        t2.fecha_salida,
        t2.directa
FROM   (SELECT fecha_salida, COUNT(*) AS agencia
        FROM   ventas
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id !=2
        GROUP BY fecha_salida) AS t1,
       (SELECT fecha_salida, COUNT(*) AS directa
        FROM   ventas
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id =2
        GROUP BY fecha_salida) AS t2
        GROUP BY t1.fecha_salida

my table is:
|------ |Columna|Tipo|Nulo|Predeterminado |------
   |//**venta_id**//|int(11)|No| |usuario_id|int(11)|No|
   |tour_id|int(11)|No| |cliente_id|int(11)|No| |vehiculo_id|int(11)|No|
   |cashflow_id|int(11)|No| |total_compra|int(6)|No|
   |total_pagado|int(6)|No| |total_iva|int(6)|No|
   |total_comision|int(11)|No| |a_pagar|int(11)|No|
   |fecha_venta|datetime|No| |fecha_salida|date|No|
   |concretada|tinyint(1)|No| |pasajeros|int(3)|No|
   |nombre|varchar(500)|Sí|NULL |direccion|varchar(500)|Sí|NULL
   |observaciones|varchar(500)|Sí|NULL |forma_pago|tinyint(2)|No|
   |eliminado|tinyint(1)|No|

Can you help me

A: You can use UNION to combine two queries that have same structure , also you should select from combined result and then order them
SELECT * FROM (

    SELECT fecha_salida, COUNT(*) AS agencia
    FROM ventas
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
    and ventas.eliminado = 0
    AND ventas.cliente_id = 2
    GROUP BY fecha_salida

    UNION

    SELECT fecha_salida, COUNT(*) AS agencia
    FROM ventas
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
    and ventas.eliminado = 0
    AND ventas.cliente_id != 2
    GROUP BY fecha_salida

) RESULT
ORDER BY agencia


Q: How can you use subdirectories in a GitHub wiki checkout? I'd like to organize my GitHub wiki pages in subdirectories.  How do we refer to the pages in subdirectories?

A: github wiki / gollum-wiki doesn't inherently provide anything explicit for organizing pages into sub-directories. Any page can be linked from any other page irrespective of where it logically belongs. This is a powerful feature that makes wikis very flexible.
One way to implement a sub-directories structure would be to follow a naming convention.
Example: Having all pages related to subject1 have names that start with subject1, and so on.


Q: How can I build a regex to match a value? I need a regex that matches this kind of strings:
brand-new-car
brand-new-car-1
brand-new-car-100
307

and I just need to catch the "name" regardless of whether the string has -count; like this:
brand-new-car
brand-new-car
brand-new-car
307

This regex does not work properly. Its $1 is the full string, not without -count.
(\S+)(?:-\d+|)$

A: You need to make the first capture group "lazy" or non-greedy.
var re = new RegExp("^(\\S+?)(?:-\\d+)?$");

var testStrings = [
    "brand-new-car",
    "brand-new-car-1",
    "brand-new-car-100",
    "307"
];

for (var i=0; i<testStrings.length; i++) {
    var result = re.exec(testStrings[i]);
    say("result: " + result);
}

The results:
result: brand-new-car,brand-new-car
result: brand-new-car-1,brand-new-car
result: brand-new-car-100,brand-new-car
result: 307,307

A: Try this (?xms)(^[\w-]+.*?)(?=[\w-]+|\Z)
Here, below is an image of regex buddy
where you can catch the "name" regardless of whether the string has -count the yellow and blue foreground highlights the different selections.

A: Just remove the pipe '|', then it works
(\S+)(?:-\d+)$

Checked here rubular


Q: Is there a way to parameterize a jquery function name and call it? I'm trying to make a plugin for a modal and I want the users to be able to initialize the animate function picking from a jquery list of functions like fadeIn , SlideDown etc.
var myModal = new createModal({
    content: myContent,
   appendTo: ".modalSection"
});

$(".modal_trigger").on("click", function () {
   myModal.open();
});

createModal.prototype.open = function () {
    var functionVar = this.options.animateType;
    $(this.modal).fadeIn();
    //i want to replace this above line with the function name in this.options.animateType
}

Any way to do this ?

A: As a jQuery object is, as the name implies, an object, you can access its properties as you would any standard object.
In this case you can use bracket notation to call a function held in one of those properties. For example:
createModal.prototype.open = function () {
  var functionVar = this.options.animateType;
  $(this.modal)[functionVar]();
}


Q: Ending a while loop when it reaches matching numbers I need to end this while loop when it reaches a matching number such as 88, 77, and so on.
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int userNum = scan.nextInt();
      if ((userNum >= 20) && (userNum <= 98)){
         System.out.print(userNum + " ");
         while ((userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)){
         userNum = userNum - 1;
           System.out.print(userNum + " ");
         }

      }
      else{
         System.out.print("Input must be 20-98");
      }
      System.out.print("\n");
   }
}

However, when it runs it never leaves the loop, even when the number reaches one of the matching ones I had in the while loop. please help.

A: if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)

Will always be true, because userNum cannot be all of those values at once. Substitute || for &&:
if(userNum != 11) && (userNum != 22) && (userNum != 33) && (userNum != 44) && (userNum != 55) && (userNum != 66) && (userNum != 77) && (userNum != 88) && (userNum != 99)

This can be made easier using the modulus operator:
if(userNum % 11 != 0)

A: The problem lies in this line.
if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)
If userNum is any number, it cannot be 11, 22, 33, 44, 55, 66, 77, 88, and 99 at once, which means your program will keep running. As @Carcigenicate stated, you want && (and) operators.

A: Try using the && operator here instead of OR
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int userNum = scan.nextInt();
      if ((userNum >= 20) && (userNum <= 98)){
         System.out.print(userNum + " ");
         while (userNum != 11 && userNum != 22&& userNum != 33 && userNum != 44 && userNum != 55 && userNum != 66 && userNum != 77&& userNum != 88 && userNum != 99){
         userNum = userNum - 1;
           System.out.print(userNum + " ");
         }

      }
      else{
         System.out.print("Input must be 20-98");
      }
      System.out.print("\n");
   }
}

A: Your code appears to be searching for multiples of 11, so I would prefer testing the remainder of eleven. Also, you can use x-- instead of x = x - 1. Finally, a do-while loop would make this a bit cleaner. Like,
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if (userNum >= 20 && userNum <= 98) {
    do {
        System.out.print(userNum + " ");
        userNum--;
    } while (userNum % 11 != 0);
    System.out.println();
}

A: You can use following code to ending a while loop when it reaches matching numbers using array.
public class stopWhileTest{
    public static void main(String arg[]) {
        int[] number = {11, 22, 33, 44, 55, 66, 77, 88};
        Scanner scan = new Scanner(System.in);
        int userNum = scan.nextInt();
        if ((userNum >= 20) && (userNum <= 98)){
            System.out.print(userNum + " ");
            while(!contains(number,userNum)){
                userNum = userNum - 1;
                System.out.print(userNum + " ");
            }
        }
        else{
            System.out.print("Input must be 20-98");
        }
        System.out.print("\n");
        scan.close();
    }

    public static boolean contains(final int[] array, final int v) {
        boolean result = false;
        for(int i : array){
            if(i == v){
                result = true;
                break;
            }
        }
        return result;
    }
}

Hope this solution works.


Q: Set the title for the navigation control I converted window based application into navigation based but I am not able to set the title for the navigation bar.
controller = [[bookDisplayViewController alloc] initAndCreateView];

UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
nav.title=@"Application";
[window addSubview:nav.view];

A: Is it possible for you to place
self.navigationItem.title = @"YourName";

in the viewDidLoad of the other view? I'd try it that way and see if it works.

A: You must set the title from within the UIViewController. Try this:

controller.navigationItem.title=@"Application";

Infact apple docs on UINavigationItem for the "title" property  states that:

title
A localized string that represents the view that this controller manages.

@property(nonatomic, copy) NSString *title
Discussion
Subclasses should set the title to a human-readable string that represents the view to the user. If the receiver is a navigation controller, the default value is the top view controller’s title.

Availability
Available in iOS 2.0 and later.


Q: What is the meaning of ms-lim? I came across an expression as follows:
$$I^{(\alpha)} = ms-\lim_{n \rightarrow \infty} I_n^{(\alpha)}(t)$$
What does this "ms-lim" mean?
Edit 1:
Thanks for all the comments. "ms-lim" indeed means "mean-square limit".


Q: Error connecting web3js to react native application I ran into a problem connecting web3 to a React Native app.
Initially, the connection was made according to this guide.
Everything worked, but as soon as I restart the application, an error appears:

ReferenceError: Property 'Buffer' doesn't exist, js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered
callable module (calling runApplication). A frequent cause of the
error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine:
hermes

Then I comment on these lines in Live reloading mode
const Web3 = require('web3')
const web3Rospen = new Web3('https://ropsten.infura.io/v3/myKey')

I save the code, the application works, again, in Live reloading mode, I uncomment these lines back - the application works.
But initially, just taking and running the application from web3 does not work. Maybe someone faced such a problem?
Versions:
"react-native": "0.66.4",
"web3": "^1.7.3"


Q: JAXB default value for null elements when marshalling At the time of marshalling of JAXB object I want to set some defult value to the resulting XML.
I do not want to use nillable=true as it generates empty tag with unnecessary xsi:nil="true", and this is not for setting default value. Instead I want to generate the XML with some placeholder characters such as '?'.
Use case :  I am going to build a tool for WebService testing. There I need to present the entire request xml to the user (Like SOAPUI).

A:
Use case : I am going to build a tool for WebService testing. There I
  need to present the entire request xml to the user (Like SOAPUI).

The idea of the place holder character isn't really going to work.  For example ? is an ok default value for a string, but not an int, boolean, or for most complex values (i.e. representing the nested address information for a customer).  Instead you will want a value that reflects the type.

Then I would have to write large and complex reflection based code. Just assume that
  that is almost not possible in my case.

This reflection code probably won't be as bad as you are imagining.  A quick search will probably also reveal libraries that populate objects with "dummy" data.  When hooking it up with JAXB you could leverage a Marshaller.Listener to populate the object on the before marshal event.


Q: Update on blur the first time only I can defer model updating until blur with ng-model-options="{ updateOn: 'blur' }".  This prevents annoying the user with changing validation states while entering input the first time around.  However, when a user returns to a failed validation to revise it, the updateOn: 'blur' prevents the validation state from being updated when the user has fixed it (but before they leave the field).
How can I reset the updateOn option to allow the default model update schedule after one blur?

A: ngModelOptions directive $evals its value, but doesn't observe it for changes. In other words, you cannot achieve what you are looking for with something like the following:
<input ng-model="foo" ng-model-options="fooOptions">

and then change it in the controller:
$scope.fooOptions = {updateOn: "blur"};
$scope.changeOptions = function(){
  $scope.fooOptions = {updateOn: "default"};
}

For simple cases, you could add another variable that changes how you show validation messages:
<form name="form1">
   <input name="foo"
          ng-model="foo" ng-model-options="{updateOn: 'default'}"
          ng-blur="startShowingErrors = true" minlength="3">

   invalid entry
</form>

But, if you want the actual form state not update, then you'd need another directive as a facade to ngModelOptions to cause a $compile on every change.


Q: AJAX not rendering as it should I am at a loss with what’s stopping my code not rendering AJAX where it should be, I have a less serious JS ‘Parse error’ which I can’t work out also.
I have a default prevented rails form_for where upon submit event jQuery finds the element and its attribute values, posts them to the model via appropriate action, model then responds with the new object and is supposed to render the JSON  via a jbuilder form.
All is fine when I  get the page to render via a redirect, but not by a render ‘create’, content_type: :json, error displayed is  a missing template error. I also see from network response that it ‘failed to load response data’.  views/reviews/create.json.jbuilder is saved is in the correct place I believe, class and id names are all correct I believe, files and folders are named correctly and in the right place I believe, I can’t see anything wrong? Unsure whether it’s a jbuilder error, a controller syntax error, or a jQuery syntax error. Here is my code:
controllers/reviews_controller.rb:
def create
    @restaurant = Restaurant.find(params[:restaurant_id])
    @review = @restaurant.reviews.new(params[:review].permit(:thoughts, :rating))

    if @restaurant.reviews.find_by user_id: current_user.id
      flash[:notice] = "You already reviewed this restaurant!"
      redirect_to restaurants_path
    else
      @review.user = current_user
      @review.save
      # redirect_to restaurants_path, will do a redirect, but defeats AJAX purpose!
      render 'create', content_type: :json # results in a missing template error #'missing templete reviews/create' error
    end
  end

Assets/restaurants/restaurants.js:
$(document).ready(function(){
  $('.new_review').on('submit', function(event){
    event.preventDefault();
    var reviewList = $(this).siblings('ul');
    var currentRestaurant = $(this).parent();
    $.post($(this).attr('action'), $(this).serialize(), function(review){
      if review # This line results in Uncaught SyntaxError: Unexpected Identifier
      var newReview = Mustache.render($('#review_template').html(), review);
        reviewList.append(newReview);

        currentRestaurant.find('.review_count').text(review.restaurant.review_count)
        currentRestaurant.find('.average_rating_number').text(review.restaurant.average_rating);
        currentRestaurant.find('.average_rating_stars').text(review.restaurant.average_rating_stars);
    }, 'json');
  });
});

views/restaurants/index.html.erb (jbuilder template element):
<template id='review_template'>

    {{ star_rating }} -*- {{ thoughts }}

</template>

views/reviews/create.json.jbuilder:
json.thoughts @review.thoughts
json.star_rating star_rating(@review.rating)

json.restaurant do
  json.average_rating number_with_precision(@restaurant.average_rating,
  precision: 1)
  json.average_rating_stars star_rating(@restaurant.average_rating)
  json.review_count pluralize(@restaurant.reviews.count, 'reviews')
end

Been on this for hours now trying to solve this one, pfff!! any idea where I’m going wrong folks? Am I doing something really dim somewhere here? Thank you.

A: As you can see in the error message, rails is looking for a file called reviews/create[extension] or application/create[extension] and extensions allowed are .erb, .builder, .raw, .ruby, .coffee or .jbuilder.
I suggest to change you ajax call to ask for js, not json, create a file called reviews/create.js.erb, and add this kind of code :
<% if @restaurant.reviews.find_by user_id: current_user.id %>
  // do the code to show the error message in javascript
<% else %>
  reviewList.append("<%= j(render('create')) %>");
  currentRestaurant.find('.review_count').text(<%= pluralize(@restaurant.reviews.count, 'reviews') %>)
  currentRestaurant.find('.average_rating_number').text(<%= number_with_precision(@restaurant.average_rating, precision: 1) %>);
  currentRestaurant.find('.average_rating_stars').text(<%=star_rating(@restaurant.average_rating) %>);
<% end %>

This code should be executed after the success of the creation. You also have to create a file called reviews/_create.html.erb with the html you want to show. Finally, you have to delete some logic in  the javascript and in the controller.


Q: Bohr magneton to teslas Now, I'm an engineer who needs some physics help, this document on the cryogenic magnetic properties of gadolinium, terbium and holmium, containsing some magnetic measurements regarding said elements,

Cornforth, Clarence Michael, "High magnetic field properties of gadolinium, terbium, and holmium " (1969). Retrospective Theses and
  Dissertations, Iowa State University. 4648.

I only need to know the saturation magnetic field of these materials. Although I have an appreciable grasp on physics, some sentences seem out of this world, so could anyone please take a quick look and convert from physics to engineering the saturation flux density? The document uses Bohr magneton and other terms which I know but am not very clear with, so please convert from whatever units to teslas.

A: The document you linked to doesn't quite use Bohr magnetons - it quotes the saturation magnetization per atom in Bohr magnetons. The Bohr magneton is a measure of magnetic dipole moment and it is given in SI units by
$$
\mu_\mathrm B= \frac{e\hbar}{2m_e} = 9.274\,009\,994(57)\times 10^{-24} \:\mathrm{J/T}.
$$
The magnetization, by contrast, is a volumetric density of magnetic dipole moment, so whatever conversions you use will necessarily pass by the volumetric number density $\rho$ of your material, i.e. $\rho$ is the number of atoms of your chosen species per unit volume, with dimensions $[\rho]=1/L^3$.
With that, then, if you know that your chosen species has saturation magnetization of $m=x\,\mu_\mathrm B$ per atom, where $x$ is dimensionless, then a sample of volumetric number density $\rho$ will have saturation magnetization
$$
M=\rho m = \rho x \,\mu_\mathrm B,
$$
so therefore $M= (\rho\,\mathrm m^3)x \times 9.274\times 10^{-24} \:\mathrm{J\:m^3/T}= (\rho\,\mathrm m^3)x \times 9.274\times 10^{-24} \:\mathrm{A/m},$ where $\rho\,\mathrm m^3$ is the numerical value of the volumetric number density in cubic meters.
From there, you say you want a saturation magnetic flux density in teslas, which means that you want the magnetic $B$ field, and there my knowledge of ferromagnetism thins out a bit, so make sure to double check it. Generally, the magnetic flux density is given by
$$
B=\mu_0(H+M);
$$
before saturation the bulk of the contributions to that flux density comes from the term in $\mu_0M$, whereas after saturation the magnetization can no longer grow and you get only a small linear increase in $B$ coming directly from the term in $H$. Given this, the saturation flux density is simply given by the dominant term, $B=\mu_0M$, or more explicitly
$$
B = \mu_0M=\rho x \, \mu_0\mu_\mathrm B = (\rho\,\mathrm m^3)x \times 1.165\times 10^{-29} \:\mathrm{T}.
$$
Here the numerical coefficient looks small, but it's multiplied by the number $\rho\:\rm m^3$ of atoms in a cubic meter of your metal, which is in the $10^{28+}$ regime, so checks out at least as far as order-of-magnitude goes.

A: As Emilio Pisanty said, the saturation magnetization and saturation applied field are independent quantities that cannot be calculated from each other. The applied saturation field tells you how hard it is to fully magnetize the material, and the saturation magnetization tells you the value of that full magnetization. This article only reports the latter (by basically reporting measurements of the effective Lande $g$ factor in these materials). I don't quite understand the article because it repeatedly mentions the "saturation magnetization," but the plots show the magnetization continuing to increase over the whole plotted range of applied field, which would seem to indicated that they did not reach the saturation applied field. (I also don't understand what they mean by "saturation susceptibility," which seems like it is zero by definition.)
For an antiferromagnet at low temperature, the saturation applied field is typically on the order of the interspin exchange coupling $J$ divided by the saturation magnetization $\mu_\text{sat}$ reported in this article, but the details vary by material.


Q: where does llvm.memcpy.p0i8.p0i8.i64 come from i test clang and compile a simple C file including struct asigning.when I see the  LLVM code ,there is llvm.memcpy.p0i8.p0i8.i64 ,where is from ? I not see the defination only see its declare as a fucntion.

A: It is a LLVM intrinsic function. As per the language reference:

LLVM provides intrinsics for a few important standard C library
  functions. These intrinsics allow source-language front-ends to pass
  information about the alignment of the pointer arguments to the code
  generator, providing opportunity for more efficient code generation.

The llvm.memcpy intrinsic specifically:

The ‘llvm.memcpy.*’ intrinsics copy a block of memory from the source
  location to the destination location.
Note that, unlike the standard libc function, the llvm.memcpy.*
  intrinsics do not return a value, takes extra isvolatile arguments and
  the pointers can be in specified address spaces.