text:
Q: Geocoder getFromLocationName is not finding address Geocoder getFromLocationName is not returning anything if I'm searching for business places. Here are my finding so far:

*

*grocery places, commercial buildings -> no result

*schools -> finding results, but only returning Latitude and Longitude. I have to do reverse geocoding in order to get the address based on the coordinates, but the address wouldn't be accurate.

*complete address -> same as school, only returning Latitude and Longitude

*hospital and pharmacy -> returning Latitude and Longitude

I've tested this on 1.6, 2.1 and 2.2 devices that has Google Maps.
I'm trying  to find if there's a limitation explained somewhere on the SDK, but there is none except:

The amount of detail in a reverse
  geocoded location description may
  vary, for example one might contain
  the full street address of the closest
  building, while another might contain
  only a city name and postal code. The
  Geocoder class requires a backend
  service that is not included in the
  core android framework. The Geocoder
  query methods will return an empty
  list if there no backend service in
  the platform
  (http://developer.android.com/reference/android/location/Geocoder.html)

[update]
So after nights of research, I can't seems to make it work - Google simply wont give me the result. Some discussion on android-developers points a fact that getFromBusinessName was omitted when Google Navigation came out. So I'm starting to assume that Google is pulling back some of their geocoding service.
I can always create a webpage that use Google Geocoder API, but its limited to 2500 api call - and I dont think it will be legal (lol). So what are my alternatives here?

A: I've hit the same problem. I'm finding that the geocoding API often returns no results if I include the business/venue name, but by missing it off, the lat/long can be much less accurate.
I've implemented a pragmatic solution:
1. Call the API with a string including the business/venue name
2. If it fails, call it a second time without the business/venue name, just the address
I've yet to see a case where no location is returned, so it seems a decent compromise as it means I do at least get location data, if sometimes less accurate, and the cost of a second API call is mitigated with threaded calls.

A: I couldn't find the button to reply but, like you all, I have just run into the same problem.  I haven't tried it yet but it sounds pretty solid.  A potential workaround is located here:
Using Google Maps API to get Address of Business
Happy coding :)
Edit: Forget that link and check this one out: http://code.google.com/apis/maps/documentation/places/

A: Try this approach:
1) Use Geocoder to convert latitude-longitude to address
2) Make an API call to Whitepages (or similar service), specifically the reverse_address method which will get you business name for the address mentioned.


text:
Q: AWS t3.medium web traffic I have a ecommerce website running on t3.medium instance. Is there a way to find out how much web traffic can be handled by same in numbers? So if our web traffic increases do we need to buy another server?
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: disable send diagnostics data to application insights on publish settings I've created a web role on vs2013 and recently upgraded it to vs2015.
When publishing the role to Azure, the send diagnostics data to application insights is turned on.

Since I don't want to use the application insights each time, when I need to publish my role I need to uncheck the checkbox.
Is there a way to permanently uncheck this option?

A: You can avoid getting the "Diagnostics" tab in the publish dialog by following these steps:

*

*Open the Properties page for one of the roles in your project

*Under Diagnostics, check the "Send diagnostics data to Application Insights" checkbox

*Select to manually specify the Application Insights instrumentation key

*Enter some value in the textbox (doesn't matter what value) and click OK

*After the dialog closes, the value you have entered will appear in a textbox under the checkbox mentioned in the previous step

*Delete that value and click save

After doing this, you should no longer see the option to send diagnostics data to Application Insights during the publish process. Also, because a valid instrumentation key wan't provided, the extention that sends the diagnostics data to Application Insights will not be started.


text:
Q: Puzzling performance/output behavior with rank-2 polymorphism in Haskell The below code (annotated inline with locations) gives a minimal example of the puzzling behavior I'm experiencing.
Essentially, why does (2) result in terrible space/time performance while (1) does not?
The below code is compiled and run as follows on ghc version 8.4.3:
ghc -prof -fprof-auto -rtsopts test.hs; ./test +RTS -p
{-# LANGUAGE Rank2Types #-}

import Debug.Trace

-- Not sure how to get rid of the record
data State = State {
    -- (0) If vstate :: Float, the extra "hello"s go away
    vstate :: forall a . (Fractional a) => a
}

step :: State -> State
step s =
    -- (1) one "hello" per step
    -- let vs = trace "hello" (vstate s) in
    -- s { vstate = vs `seq` vstate s }

    -- (2) increasing "hello"s per step
    s { vstate = (trace "hello" (vstate s)) `seq` vstate s }

main :: IO ()
main = do
    let initState = State { vstate = 0 }

    -- (3) step 3 times
    -- let res = step $ step $ step initState
    -- print $ vstate res

    -- (4) step 20 times to profile time/space performance
    let res = iterate step initState
    print $ vstate $ last $ take 20 res

    print "done"

a. With (1) and (3) commented in, compiled without -O2, the code only outputs "hello" three times, as I expect it to.
b. With (2) and (3) commented in, compiled without -O2, the code outputs "hello" eight times. It seems to output one additional "hello" per step. I don't understand why this is happening.
c. With (1) and (4) commented in, compiled without -O2, the code runs extremely fast.
d. With (2) and (4) commented in, compiled without -O2, the code runs very slowly, and the performance report (included below) shows that makes many more calls to vstate and uses much more memory than variant c. I also don't understand why this is happening.
e. With (2) and (4) commented in, compiled with -O2, the code behaves the same as variant c. So clearly ghc is able to optimize away whatever pathological behavior is happening in variant d.
Here is the profiling report for variant c (fast):
    Mon Aug 13 15:48 2018 Time and Allocation Profiling Report  (Final)

       partial +RTS -p -RTS

    total time  =        0.00 secs   (0 ticks @ 1000 us, 1 processor)
    total alloc =     107,560 bytes  (excludes profiling overheads)

COST CENTRE MODULE           SRC                        %time %alloc

CAF         GHC.IO.Handle.FD <entire-module>              0.0   32.3
CAF         GHC.IO.Encoding  <entire-module>              0.0    3.1
main        Main             partial.hs:(24,1)-(35,16)    0.0   13.4
main.res    Main             partial.hs:32:9-36           0.0    1.6
step        Main             partial.hs:(15,1)-(18,36)    0.0    1.1
step.vs     Main             partial.hs:17:9-37           0.0   46.1

                                                                                individual      inherited
COST CENTRE           MODULE                SRC                       no.     entries  %time %alloc   %time %alloc

MAIN                  MAIN                  <built-in>                114          0    0.0    0.6     0.0  100.0
 CAF                  Main                  <entire-module>           227          0    0.0    0.1     0.0   52.2
  main                Main                  partial.hs:(24,1)-(35,16) 228          1    0.0    2.7     0.0   52.1
   vstate             Main                  partial.hs:11:5-10        230         20    0.0    0.0     0.0    0.0
    main.initState    Main                  partial.hs:25:9-40        239          0    0.0    0.0     0.0    0.0
    main.res          Main                  partial.hs:32:9-36        234          0    0.0    0.0     0.0    0.0
     step             Main                  partial.hs:(15,1)-(18,36) 235          0    0.0    0.0     0.0    0.0
   main.initState     Main                  partial.hs:25:9-40        233          1    0.0    0.0     0.0    0.0
   main.res           Main                  partial.hs:32:9-36        231          1    0.0    1.6     0.0   49.4
    step              Main                  partial.hs:(15,1)-(18,36) 232         19    0.0    1.1     0.0   47.8
     step.vs          Main                  partial.hs:17:9-37        236         19    0.0   46.1     0.0   46.7
      vstate          Main                  partial.hs:11:5-10        237        190    0.0    0.0     0.0    0.6
       main.initState Main                  partial.hs:25:9-40        238          0    0.0    0.6     0.0    0.6
 CAF                  Debug.Trace           <entire-module>           217          0    0.0    0.2     0.0    0.2
 CAF                  GHC.Conc.Signal       <entire-module>           206          0    0.0    0.6     0.0    0.6
 CAF                  GHC.IO.Encoding       <entire-module>           189          0    0.0    3.1     0.0    3.1
 CAF                  GHC.IO.Encoding.Iconv <entire-module>           187          0    0.0    0.2     0.0    0.2
 CAF                  GHC.IO.Handle.FD      <entire-module>           178          0    0.0   32.3     0.0   32.3
 CAF                  GHC.IO.Handle.Text    <entire-module>           176          0    0.0    0.1     0.0    0.1
 main                 Main                  partial.hs:(24,1)-(35,16) 229          0    0.0   10.7     0.0   10.7

Here is the profiling report for variant d (slow; without -O2):
    Mon Aug 13 15:25 2018 Time and Allocation Profiling Report  (Final)

       partial +RTS -p -RTS

    total time  =        1.48 secs   (1480 ticks @ 1000 us, 1 processor)
    total alloc = 1,384,174,472 bytes  (excludes profiling overheads)

COST CENTRE    MODULE    SRC                        %time %alloc

step           Main      partial.hs:(15,1)-(21,60)   95.7   98.8
main.initState Main      partial.hs:25:9-40           3.0    1.2
vstate         Main      partial.hs:11:5-10           1.4    0.0

                                                                                individual      inherited
COST CENTRE        MODULE                SRC                       no.     entries  %time %alloc   %time %alloc

MAIN               MAIN                  <built-in>                114          0    0.0    0.0   100.0  100.0
 CAF               Main                  <entire-module>           227          0    0.0    0.0   100.0  100.0
  main             Main                  partial.hs:(24,1)-(35,16) 228          1    0.0    0.0   100.0  100.0
   vstate          Main                  partial.hs:11:5-10        230    1048575    1.4    0.0   100.0  100.0
    main.initState Main                  partial.hs:25:9-40        236          0    3.0    1.2     3.0    1.2
    main.res       Main                  partial.hs:32:9-36        234          0    0.0    0.0    95.7   98.8
     step          Main                  partial.hs:(15,1)-(21,60) 235          0   95.7   98.8    95.7   98.8
   main.initState  Main                  partial.hs:25:9-40        233          1    0.0    0.0     0.0    0.0
   main.res        Main                  partial.hs:32:9-36        231          1    0.0    0.0     0.0    0.0
    step           Main                  partial.hs:(15,1)-(21,60) 232         19    0.0    0.0     0.0    0.0
 CAF               Debug.Trace           <entire-module>           217          0    0.0    0.0     0.0    0.0
 CAF               GHC.Conc.Signal       <entire-module>           206          0    0.0    0.0     0.0    0.0
 CAF               GHC.IO.Encoding       <entire-module>           189          0    0.0    0.0     0.0    0.0
 CAF               GHC.IO.Encoding.Iconv <entire-module>           187          0    0.0    0.0     0.0    0.0
 CAF               GHC.IO.Handle.FD      <entire-module>           178          0    0.0    0.0     0.0    0.0
 CAF               GHC.IO.Handle.Text    <entire-module>           176          0    0.0    0.0     0.0    0.0
 main              Main                  partial.hs:(24,1)-(35,16) 229          0    0.0    0.0     0.0    0.0

Here are some notes/guesses/questions on why this is happening:

*

*What's the relationship of the degrading performance to the increasing "hello" count? The pathological version seems to output one more "hello" with each additional step. Why?

*I'm aware that polymorphism in Haskell is slow, as detailed in this StackOverflow question. That might be part of the problem, since the pathological behavior goes away when vstate is monomorphized as vstate :: Float. But I don't see why the lack of a let-binding, as in location (2), would cause such bad time/space performance.

*This is the minimal version of a performance bug in a larger codebase, which we fixed by "monomorphizing" floating-type numbers using realToFrac (the commit is here in case anyone is curious). I know that compiling with -O2 fixes the behavior in the minimal example, but I tried it in the larger codebase and it does not fix the performance issues. (The reason we need rank-2 polymorphism in the larger codebase is to use the ad library for autodiff.) Is there a more principled fix than using realToFrac, such as an inline specialization that can be applied?

A: forall a . (Fractional a) => a is a function type.
It has two arguments, a type (a :: *) and an instance with type Fractional a. Whenever you see =>, it's a function operationally, and compiles to a function in GHC's core representation, and sometimes stays a function in machine code as well. The main difference between -> and => is that arguments for the latter cannot be explicitly given by programmers, and they are always filled in implicitly by instance resolution.
Let's see the fast step first:
step :: State -> State
step (State f) =
    let vs = trace "hello" f
    in State (vs `seq` f)

Here, vs has an undetermined Fractional type which defaults to Double. If you turn on -Wtype-defaults warning, GHC will point this out to you. Since vs :: Double, it's just a numeric value, which is captured by the returned closure. Right, vs `seq` f is a function, since it has a functional type forall a . (Fractional a) => a, and it's desugared to an actual lambda expression by GHC. This lambda abstracts over the two arguments, captures vs as free variable, and passes along both arguments to f.
So, each step creates a new function closure which captures a vs :: Double. If we call step three times, we get three closures with three Doubles inside, each closure referring to the previous one. Then, when we write vstate (step $ step $ step initState), we again default to Double, and GHC calls this closure with the Fractional Double instance. All the vs-es call previous closures with Fractional Double, but every vs is evaluated only once, because they are regular lazy Double values which are not recomputed.
However, if we enable NoMonomorphismRestriction, vs is generalized to forall a. Fractional a => a, so it becomes a function as well, and its calls are not memoized anymore. Hence, in this case the fast version behaves the same as the slow version.
Now, the slow step:
step :: State -> State
step (State f) = State ((trace "hello" f) `seq` f)

This has exponential number of calls in the number of steps, because step f calls f twice, and without optimizations no computation is shared, because both calls occur under a lambda. In (trace "hello" f) `seq` f, the first call to f defaults to Fractional Double, and the second call just passes along the implicit Fractional a instance as before.
If we switch on optimization, GHC observes that the first f call does not depend on the function parameters, and floats out trace "hello" f to a let-binding, resulting in pretty much the same code as in the fast version.


text:
Q: How do I accomplish the following in LDAP? I would like to accomplish this goal using AD/ADAM

*

*The ability to make an email or other attributeClass as part of inetOrgPerson globally unique across entries

*The ability to attach a regular expression to an attribute for validation purposes

*The ability to provide a constraint of enumerated choices such as choosing from a list of valid state codes in a state attributeClass

A: You can't do any of that in AD or ADAM.  They're just the data storage repository: I'm afraid you'll have to build the validation code yourself.


text:
Q: Hexagonal Grid (Flat Top) Distance Calculation I have been working on creating a hexagonal (flat top) grid for a simulation I am working on. I have attempted to work out the distance between the hexagons, from a specified target hexagon.
The solution I have works for most of the time, apart from every odd column from the target hexagon north of the target is shifted up by 1. I know that sounds confusing but I have attached an image to explain what I mean:

As you guys can see, the bottom half of the grid below the target hexagon and every other column above the target Hexagon is correct. I cannot understand why :S
Here is an explanation of the Axial & Cube Co-ords.
http://www.redblobgames.com/grids/hexagons/#coordinates
Here is the code responsible for converting the Axial Co-ords to Cube Co-ords.
public void setQR(int theQ, int theR){

    this.q = theQ;
    this.r = theR;

    this.x = this.q;
    this.z = this.r - (this.q - (this.q&1)) /2;
    this.y = -(this.x + this.z);
}

And heres the code for working out distance.
FYI,  the Hexagons are created from a CentrePoint (CPx, CPy).
    private double distance = 0;

public double workOutDistance(Hexagon hexagon, HexagonFood target){

    double targetX = target.getCPX();
    double targetY = target.getCPY();

    double hexagonX = hexagon.getCPX();
    double hexagonY = hexagon.getCPY();

    double deltaX = (targetX-hexagonX)*-1;
    double deltaY = (targetY-hexagonY)*-1;

    double deltaXRadius = (deltaX/(SimField.hexSize)/1.5);
    double deltaYApothem = (deltaY/(SimField.hexSize/1.155)/2);

    hexagon.setQR((int)deltaXRadius, (int)deltaYApothem);

    ArrayList<Integer> coords = new ArrayList<>();

    coords.add(
    Math.abs(hexagon.getX() - target.getX())
    );

    coords.add(
    Math.abs(hexagon.getZ() - target.getZ())
    );

    coords.add(
    Math.abs(hexagon.getY() - target.getY())
    );

    System.out.println(coords);
    distance = Collections.max(coords);

    return distance;
}

Can anyone please tell me why this is happening ? Would be greatly appreciated.
EDIT:
After changing Int to Double as suggested by Tim, I get this.
http://i.stack.imgur.com/javZb.png
**
SOLUTION
**
after experimenting with the answers given, This small tweak solves the problem.
changing this..
public void setQR(int theQ, int theR){

    this.q = theQ;
    this.r = theR;

    this.x = this.q;
    this.z = this.r - (this.q - (this.q&1)) /2;
    this.y = -(this.x + this.z);
}

to this..
public void setQR(int theQ, int theR){

    this.q = theQ;
    this.r = theR;

    this.x = this.q;
    if (this.r>0){
        this.z = this.r - (this.q - (this.q&1))/2;
    }
    else {
        this.z = this.r - (this.q + (this.q&1))/2;
    }
    this.y = -(this.x + this.z);
}

A: You're casting a double to an int when calling setQR(); are you sure that's doing what you expect?  Doubles use floating point math, so the number you'd expect to be 2.0 might actually be 1.999999989, which would then be rounded down to 1 when cast to an int.
I'm also skeptical of the line that reads this.z = this.r - (this.q - (this.q&1)) /2;.  You're adding 1 when the number is odd, which seems to be the failure case you're experiencing; I'd make sure that line is doing what you're expecting, too.
If you're not stepping through this with a debugger and examining the values, you're doing it wrong.

A: You could also take an entirely different approach to this problem.  You know the X/Y (cartesian) coordinates of your two hexagons, which means you can get each hexagon's cubic coordinates relative to the origin of your hexagonal space.  The distance between the two hexagons is simply the sum of the absolute values of the differences between the two hexagons' X, Y and Z cubic coordinates.  (That is, dist = |h2.X - h1.X| + |h2.Y - h1.Y| + |h2.Z - h1.Z|)  So rather than trying to compute the vector between the two centerpoints and then convert that into cubic coordinates, you could just compute the distance directly in cubic coordinates (just like you would if these were squares in cartesian coordinates)...
Even if you take this approach, though, I'd strongly recommend that you debug what's going on with your original approach.  Even if you end up throwing away the code, the exercise of debugging will probably teach you valuable lessons that you'll be able to apply in the future.
Note to readers: "cubic" coordinates aren't 3-dimensional cartesian coordinates, they're a hexagon-specific coordinate system for which a link was provided by the OP.

A: The fact that the computation (that is, the conversion from offset- to cube coordinates, and the computation of the distance in cube coordinates) seems to be correct suggests that Tim was right with his assumption about the floating point errors.
You should try to change the line
hexagon.setQR((int)deltaXRadius, (int)deltaYApothem);

from your original code to something like
hexagon.setQR((int)Math.round(deltaXRadius), (int)Math.round(deltaYApothem));

Which could solve the issue in this case.
If not ... or... in any case, here's a small example, basically doing the same as you did, but as a MVCE...
import java.awt.Point;

public class HexagonsTest
{
    public static void main(String[] args)
    {
        // Above and below
        test(8,6, 8,5,  1);
        test(8,6, 8,7,  1);

        // Left
        test(8,6, 7,5,  1);
        test(8,6, 7,6,  1);

        // Right
        test(8,6, 9,5,  1);
        test(8,6, 9,6,  1);

        // The first one that was wrong:
        test(8,6, 7,4,  2);
    }

    private static void test(int x0, int y0, int x1, int y1, int expected)
    {
        int distance = computeStepsDistance(x0, y0, x1, y1);
        System.out.println(
            "Distance of (" + x0 + "," + y0 + ") to " +
            "(" + x1 + "," + y1 + ") is " + distance +
            ", expected " + expected);
    }

    private static int computeStepsDistance(int x0, int y0, int x1, int y1)
    {
        Point cp0 = convertOffsetToCubeCoordinates(x0, y0, null);
        Point cp1 = convertOffsetToCubeCoordinates(x1, y1, null);
        int cx0 = cp0.x;
        int cy0 = cp0.y;
        int cz0 = -cx0-cy0;
        int cx1 = cp1.x;
        int cy1 = cp1.y;
        int cz1 = -cx1-cy1;
        int dx = Math.abs(cx0 - cx1);
        int dy = Math.abs(cy0 - cy1);
        int dz = Math.abs(cz0 - cz1);
        return Math.max(dx, Math.max(dy, dz));
    }

    private static Point convertOffsetToCubeCoordinates(
        int ox, int oy, Point p)
    {
        int cx = ox;
        int cz = oy - (ox - (ox&1)) / 2;
        int cy = -cx-cz;
        if (p == null)
        {
            p = new Point();
        }
        p.x = cx;
        p.y = cy;
        return p;
    }

}


text:
Q: svg fill url not working in any Chrome Extension pages but working on any websites and local files I'm working on my Chrome Extension:zzllrr Imager Geek and find svg fill url not working in any Chrome Extension pages (URLs start with chrome-extension://).
But on normal webpages(http:,https:, file://.) it works like a charm. Below is the code:
<svg id="LRectSq30821072" xmlns="http://www.w3.org/2000/svg" style="position: absolute; left: 66px; top: 155px; width: 76px; height: 76px; z-index: 2001; filter: none; transform: none;">
<defs>
<linearGradient id="LRectSq30821072linearfill" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#3f377d;stop-opacity:1"></stop>
<stop offset="34%" style="stop-color:#da310a;stop-opacity:1"></stop>
<stop offset="68%" style="stop-color:#cd2c78;stop-opacity:1"></stop>
<stop offset="100%" style="stop-color:#82a462;stop-opacity:1"></stop>
</linearGradient>
</defs>
<rect x="1" y="1" width="74" height="74" stroke-width="2" stroke="#585c1a" stroke-opacity="1" fill="url(#LRectSq30821072linearfill)" fill-opacity="1" stroke-dasharray="" stroke-dashoffset="1" stroke-linecap="butt" stroke-linejoin="miter"></rect>
</svg>


text:
Q: Android component to play video I have tried to play different formats and codecs in android (4.4) webview and videoview and found the following for API level 19:

*

*videoview plays mp4 of some codecs, 3gp, flv but fails to play few mp4 codecs and mkv.

*webview plays mp4 of all codecs, but fails to play video of any other format.
Vexed with the inconsistency in android components, what can be done to universally support all formats in any one or combination of components in android ?
Can I use external libraries to convert in runtime or abstract or bypass the complication of format/cedecs ?
P.S The question strictly pertains to API level 19, which is Android 4.4

A: Youcan try library of video or audio player
https://github.com/rtoshiro/FullscreenVideoView
or
https://github.com/yixia/VitamioBundle/tree/master/vitamio


text:
Q: Show category in menu blade laravel 7 I'm trying to show the categories in a drop down menu, but I'm having some trouble in the blade. The categories don't show, but I'm not getting an error.
This is my blade:

         PRODUCTEN

        Alle producten
        <a class="dropdown-item"
          @foreach(\App\Category::all() as $cat)
            id }}">{{ $cat->categoryName }}
          @endforeach

A: You are using an extra anchor tag, which  does not need here, try this :

         PRODUCTEN

        Alle producten
          @foreach(\App\Category::all() as $cat)
            id }}">{{ $cat->categoryName }}
          @endforeach

A: You are trying to loop in anchor tag.
Just remove 1st line of loop and last  tag.

A: Try with this:

        Alle producten

          @foreach(\App\Category::all() as $cat)
            id }}">{{ $cat->categoryName }}
          @endforeach


text:
Q: networkx graph: drawing the graph for a network after deleting nodes Can anyone help with this. I am getting a network and drawing it as a graph as bellow:
g = nx.DiGraph()
//creating the graph......
print(nx.info(g))

nx.info(g) is giving me that number of nodes is 18772.
I got the graph plot for it as follows:

however after deleting 30% of the most important nodes as bellow:
thirty_percent = int(g.number_of_nodes() * 0.30)
temp_g = g.copy()
print('initial number of nodes:', g.number_of_nodes())
print('nodes deleted (30%):', thirty_percent)
mostImportantNodes = sorted(nx.degree_centrality(g).items(), key=lambda x: x[1], reverse=True)
for n in range(0, thirty_percent):
    node = mostImportantNodes[n][0]
    temp_g.remove_node(node)
print(nx.info(temp_g))
# drawing the network graph
print('Graph after removing 30% of the most important nodes:')
print(datetime.now())
plt.clf()
pos = nx.spring_layout(temp_g)
nx.draw_networkx_nodes(temp_g, pos, node_size=10)
nx.draw_networkx_edges(temp_g, pos, edge_color='black', alpha=0.1, arrows=True)
plt.show()
print(datetime.now())

It is giving the right info about the new graph, but the graph plot is very bad, it seems like the nodes were added not
deleted!
initial number of nodes: 18772
nodes deleted (30%): 5631
Name:
Type: DiGraph
Number of nodes: 13141
Number of edges: 44911
Average in degree:   3.4176
Average out degree:   3.4176
highest 5 degrees:  [40, 40, 38, 36, 36]


text:
Q: L'Hôpital's rule to approximate a function I came across a simple problem:
Show $\sqrt{1+x}\approx 1 + \frac{x}{2}$ holds near $0$.
Interesting to me was the way the author solved this using l'Hôpital's rule:
Since $\lim_{x\rightarrow 0}\frac{\sqrt{1+x}-(1+\frac{x}{2})}{x^2}$ exists and is constant ( by l'Hôpital's rule), we can conclude $\sqrt{1+x}=1+\frac{x}{2}+\mathcal{O}(x^2)$.
This seems intuitive. My question is, how to formally come up with the limit expression? Does this technique generalize?

A: Well, the idea is to expand the LHS into Taylor series around the point in question. Here, expanding $f(x) = (1+x)^{1/2}$ to Taylor series, first term is $f(0) = 1$, then
$$
f'(x) = \frac{1}{2} (1+x)^{-1/2},
$$
so $f'(0) = 1/2$. Along the same lines,
$$
f''(x) = \frac{-1}{4} (1+x)^{-3/2},
$$
and $f''(0) = -1/4$. Thus, for a 2 term expansion, you get
$$
f(x) \approx f(0) + xf'(0) = 1+x/2 + O(x^2),
$$
or for a 3-term expansion,
$$
f(x) \approx f(0) + xf'(0) + \frac{x^2}{2!} f''(0) = 1+x/2 - \frac{x^2}{8} + O(x^3).
$$

The reason why this works, is if $f(x) = \sum_{k=0}^N a_k x^k + O(x^{N+1})$ (where $a_k$ you get from Taylor series), then
$$
\frac{f(x) - \sum_{k=0}^{N-1} a_k x^k}{x^N} = \frac{a_N x^N + O(x^{N+1})}{x^N} = a_N + O(x) \to a_N,
$$
as $x \to 0$.

A: Indipendetly form Taylor's series concept, by little-o and Big-O notation we have that
$$f(x)=o(g(x)) \iff \lim_{x\to x_0} \frac{f(x)}{g(x)}=0$$
form here, by standard limits, we can obtain the following foundamental expansions

*

*$\lim_{x\to 0} \frac{\sin x-x}{x}=0 \implies \sin x =x + o(x)=x + O(x^2)$

*$\lim_{x\to 0} \frac{\cos x-\left(1-\frac12x^2\right)}{x^2}=0 \implies \cos x =1-\frac12x^2 + o(x^2)=1-\frac12x^2+ O(x^3)$

*$\lim_{x\to 0} \frac{\log(1+x)-x}{x}=0 \implies \log(1+x) =x + o(x)=x + O(x^2)$

*$\lim_{x\to 0} \frac{e^x-(1+x)}{x}=0 \implies e^x =1+x + o(x)=1+x + O(x^2)$

*$\ldots$
therefore in this case we have
$$\lim_{x\rightarrow 0}\frac{\sqrt{1+x}-(1+\frac{x}{2})}{x}=0 \implies \sqrt{1+x}=1+\frac{x}{2}+o(x)=1+\frac{x}{2}+O(x^2)$$
and
$$\lim_{x\rightarrow 0}\frac{\sqrt{1+x}-(1+\frac{x}{2}-\frac18x^2)}{x^2}=0 \implies \sqrt{1+x}=1+\frac{x}{2}-\frac18x^2+o(x^2)=1+\frac{x}{2}-\frac18x^2+O(x^3)$$


text:
Q: Docker automated build not showing Dockerfile after completion I setup some automated builds in github and the Dockerfile tab is showing empty for some reason.  The builds are successful and I can see the dockerfile contents in the build details, but for some reason its not populating the Dockerfile tab.  Am I missing a step somewhere?

A: Solved my own problem.  In the build settings it by default is creating two entries under monitored repositories, one for the master branch and a blank one.  Delete the entry for the blank one and all is well.


text:
Q: How do I add a column in a dataframe in python whose value depends on multiple columns say I want to add a column called as "Category". It takes value "1" if the value of another column "High" holds the value "True", otherwise, it takes the value "2" if another column "Medium" holds value "true" otherwise, it takes up "0".
Note:- High, medium, and low are already present columns that have value as either "True" or "False".
I need code in Python

A: It's knind of unclear what you mean. But I think you want something like this...
"""
        Name        Type 1  Type 2  HP  AT  DE  SpA SpD Spe Gen Legendary
0   1   Bulbasaur   Grass   Poison  45  49  49  65  65  45  1   False
1   2   Ivysaur     Grass   Poison  60  62  63  80  80  60  1   False
2   3   Venusaur    Grass   Poison  80  82  83  100 100 80  1   False
.....................................................................
"""

Say we had this data frame, and you wanted the sum of HP, AT and DE as a new column. Then we could do something like this...
# df['Total']  This will tell us what we want the new column to be called.
# df.iloc[:, 4:7] The : will select the whole row. and 4:7 will get the values of the
# colums. So were only getting HP, AT, DE as ints.
# And .sum will get the sum of the three. And axis=1 represents columns
df['Total'] = df.iloc[:, 4:7].sum(axis=1)

Or...
df['Total'] = df['HP'] + df["AT"] + df["DE"]

So Then the data frame should like something like this...
"""
        Name        Type 1  Type 2  HP  AT  DE  SpA SpD Spe Gen Legendary Total
0   1   Bulbasaur   Grass   Poison  45  49  49  65  65  45  1   False     143
1   2   Ivysaur     Grass   Poison  60  62  63  80  80  60  1   False     185
2   3   Venusaur    Grass   Poison  80  82  83  100 100 80  1   False     245
.....................................................................
  (These are the columns we added)  ^^  ^^  ^^  (And now the sum is here) ^^^
"""

If you're using bools, you could just use a different method like...
df['High HP'] = (df['HP'] > 100)  # Create a new column with a value based off the "HP" column.

A: import pandas as pd

def getValue(index, df):
    if df['high'][index]:
        return 1
    if df['medium'][index]:
        return 2
    return 0

df = pd.DataFrame({'medium':[True,False,True,False],'high':[True, True, False, False],'low':[False, False, True, True]})

df['Category'] = [ getValue(index,df) for index in range(len(df.values)) ]

this results in:
    medium  high    low     Category
0   True    True    False   1
1   False   True    False   1
2   True    False   True    2
3   False   False   True    0


text:
Q: Android RadioButton like Behaviour Greetings,
I'm trying to create a single-choice android control, in a horizontal layout, by making use of the RadioGroup behaviour. I can assign the drawable just fine, but i would like to position the label of each RadioButton inside the drawable, is this possible using the standard APIs?
<RadioGroup
    android:id="@+id/switchcontainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:checkedButton="@+id/RadioButton02"
    android:padding="3dip">

    <RadioButton
        android:text="id RadioButton02"
        android:id="@+id/RadioButton02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/radio_button"
        android:paddingRight="2dip" />

    <RadioButton
        android:text="@+id/RadioButton03"
        android:id="@+id/RadioButton03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/radio_button"
        android:paddingRight="2dip" />>

</RadioGroup>

A: Okay, i found a way.
Just use @null in the attribute button, and move the drawable reference to the attribute background like this:
<RadioGroup
    android:id="@+id/switchcontainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:checkedButton="@+id/RadioButton02">

    <RadioButton
        android:text="id RadioButton02"
        android:id="@+id/RadioButton02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button"
        android:button="@null"/>

    <RadioButton
        android:text="@+id/RadioButton03"
        android:id="@+id/RadioButton03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button"
        android:button="@null"/>

</RadioGroup>

A: I'm not sure about with the RadioGroup; however, it should be possible to accomplish this with a ListView.
Set the ListView choiceMode to singleChoice.
Provide an ArrayAdapter or SimpleAdapter with a custom layout file for the row.  This allows you to configure the position of the label.
For a quick intro to ListView's, see Hello ListView


text:
Q: Как сделать, чтобы перед добавление новых данных добавлялись старые данные с другим атрибутом? У меня реализован запрос, который сверяет и добавляет данные в таблицу, если были изменения в столбцах. Мне надо перед добавление новых данных, добавлялась старая информация с атрибутом (counts) -1. А потом уже сама информация с (counts) 1.
ТАблица и желаемый результат ---> https://dbfiddle.uk/IYEej8hM
запрос:
INSERT INTO result_chronol (source, object, redirect, serial_number, model)
(SELECT id, date, source, object, redirect, serial_number, model
 FROM chronol_2
 EXCEPT SELECT id, date, source, object, redirect, serial_number, model
 FROM chronol_1);

По умолчанию если данные записываются то они имеют изначально 1.
Возможно ли это сделать и как?


text:
Q: multicol interline space problems I'm trying to create a template for exam forms, where you have a limited space and usually you want to fir as many formulas as you can.
So I'm using multicol package for dividing by three the usual space. But I find problems with the interline space in different colums:
\documentclass[a4paper,10pt]{article}

\usepackage{multicol}       %Múltiples columnas
\usepackage[top=0.8cm,bottom=0.8cm,left=0.8cm,right=0.8cm,columnsep=14pt]{geometry}  %Ajuste fácil de dimensiones

\setlength{\parindent}{0pt}

\newcommand{\f}[2]{\textbullet \ \ #1 \\
\vspace{0mm}
$#2$ \\}

\begin{document}

\footnotesize

\begin{multicols*}{3}

\f{Schrodinger Equation}{$a = x^2$}
\f{H definition}{$H = a \cdot b$}

\vfill

\centering{.}
\columnbreak

\f{Lorem impsum}{$v_e = 0$}

\vfill   %No quitar esto. Modula la altura de las columnas

.
\columnbreak
\textbf{Something} \\
\f{n values}{$n = 1,2,...,\infty$}

\end{multicols*}
\end{document}

And the result is:

Where you can see that the space bewteen lines changes from the first to the other columns. How can I make that red spaces like the green one?
Thanks a lot, sorry because of my bad english...

A: Do not ignore warnings such as
Underfull \hbox (badness 10000) in paragraph at lines 19--20

Which is TeX warning you of bad (maximally bad) spacing in the document.
I also removed one set of $ your equations were set in display math, as surrounded by $$...$$ but very strangely marked up with the outer $ being supplied by the \f command and the inner $ being in the argument.
If you do want math displays just replace $...$ in each argument by [...]`

\documentclass[a4paper,10pt]{article}

\usepackage{multicol}       %Múltiples columnas
\usepackage[top=0.8cm,bottom=0.8cm,left=0.8cm,right=0.8cm,columnsep=14pt]{geometry}  %Ajuste fácil de dimensiones

\setlength{\parindent}{0pt}

\newcommand{\f}[2]{\par\textbullet\quad #1\par
#2\par
\medskip}

\begin{document}

\footnotesize

\begin{multicols*}{3}

\f{Schrodinger Equation}{$a = x^2$}
\f{H definition}{$H = a \cdot b$}

\vfill

\mbox{}%???\centering{.}
\columnbreak

\f{Lorem impsum}{$v_e = 0$}

\vfill   %No quitar esto. Modula la altura de las columnas

.
\columnbreak
\textbf{Something}
\f{n values}{$n = 1,2,...,\infty$}

\end{multicols*}
\end{document}


text:
Q: I don't get the kernel stack right by simpleperf
*

*I get the perf.data from the Android device (kernel 4.9) by the following command:
simpleperf record -p 291 -o /data/local/tmp/perf.data --duration 5 -g -f 22750

*Parse the perf.data to perf.html by
report_html.py report_html.py -i perf.data -o perf.html

*Check the flow of the mmc_blk_end_queued_req function in the
perf.html. I can't get the right flow about the

mmc_blk_end_queued_req. The stack should be mmc_blk_end_queued →
req_bio_endio → bio_end, but mmc_blk_end_queued → bio_end
from the flame graph.

Take a look here:

A: I think I get it. It should be simpler to merge the stack, because the stacks have the same instruction pointer (ip) and stack pointer (sp).

From Simpleperf:

Why we can't always get complete DWARF-based call graphs

DWARF-based call graphs are generated by unwinding thread stacks. When a sample is generated, up to 64 KB stack data is dumped by the kernel. By unwinding the stack based on dwarf information, we get a callchain. But the thread stack can be much longer than 64 KB. In that case, we can't unwind to the thread start point.

To alleviate the problem, simpleperf joins callchains after recording them. If two callchains of a thread have an entry containing the same ip and sp address, then simpleperf tries to join them to make the callchains longer. In that case, the longer we run, the more samples we get. This makes it more likely to get complete callchains, but it's still not guaranteed to get complete call graphs.


text:
Q: How can I find the newest file that contains a specific string in each directory or subdirectory? I have a server side logs folder that contains many hundreds of logs most of which are in subdirectories according to the machine the logs have come from. The task is to extract the name of the latest file in each directory containing a particular string (not all files have this string) so that analysis can be done per machine. I have included my attempt below but it seems rather clunky and long-winded and I wonder if there is an easier/better/faster/more efficient way of doing this maybe with linq?
void Main()
{
    string SourcePath = @"L:\machinelogs";
    string filemask = "*.log";
    string searchitem = @"cannot access server data";

    List<string> fileswithsearchitem = new List<string>();

    DirectoryInfo directory = new DirectoryInfo(SourcePath);
    IEnumerable<DirectoryInfo> dirs = directory.EnumerateDirectories("*",new EnumerationOptions() { RecurseSubdirectories = true, IgnoreInaccessible = true });
    dirs.Append(directory);
    foreach (var dir in dirs)
    {
        var found = false;
        var files = dir.EnumerateFiles(filemask);
        foreach(var file in files.OrderByDescending(f => f.CreationTime).ToList())
        {
            foreach (var line in File.ReadLines(file.FullName))
            {
                if(line.Contains(searchitem))
                {
                    fileswithsearchitem.Add(file.FullName + " : " + line);
                    found = true;
                    break;
                }
            }
            if(found)
            {
                break;
            }
        }
    }

    foreach (string item in fileswithsearchitem)
    {
        Console.WriteLine(item);
    }
}

A:
I wonder if there is an easier/better/faster/more efficient way of doing this

I second the suggestion to post your question on https://codereview.stackexchange.com/. I'm not being snarky or hostile. Asking for "an easier/better/faster/more efficient way" is asking for code review. You'll get better answers over there. With that out of the way...

...maybe with linq?

I have never seen Linq make anything execute faster. In fact the only times I've noticed a performance difference it was for the worse. On the other hand it is nice for making code more expressive. So I view Linq as a tradeoff. In this case yes it might be worth it to you.

The task is to extract the name of the latest file in each directory containing a particular string (not all files have this string) so that analysis can be done per machine.

I have included my attempt below but it seems rather clunky and long-winded

The code you've written isn't reusable; instead it requires:

*

*A drive letter called "L" (not common)

*A drive letter and paths separated with \ (which only happens on Windows)

*Log file names to have the extension ".log"

*The search text to be "cannot access server data"

*Text to appear in STDOUT

*A real file system

BUT are these really issues to you? Is it worth the time and effort to make abstractions? If what you have is working then why fix it? I can't answer these questions for you, but instead you'll have to do some soul searching.
Abstractions
Here are some possible abstractions, and some possible ways to use them.
An abstract file system
Having an abstract file system makes it easier to write automated tests so that you can be sure your code will continue working through changes over the coming years.
These are the methods I see you using:

*

*EnumerateDirectories

*EnumerateFiles

With sufficient little hand-waving, your code could look like this:
interface IDirectory
{
    /// <summary>
    /// Recursively yields all accessible nested directories
    /// </summary>
    IEnumerable<IDirectory> EnumerateDirectories();

    /// <summary>
    /// Yields all file paths that match the given mask. Yields them in order of
    /// newest first.
    /// </summary>
    IEnumerable<string> EnumerateFiles(string mask);
}

interface IFileSystem
{
    IDirectory OpenDirectory(string path);

    Stream OpenFile(string path);
}

class DirectoryInfoAdapter : IDirectory
{
    readonly DirectoryInfo _info;

    public IEnumerable<IDirectory> EnumerateDirectories() => _info
        .EnumerateDirectories("*", new EnumerationOptions() { RecurseSubdirectories = true, IgnoreInaccessible = true })
        .Select(x => new DirectoryInfoAdapter(x));

    public IEnumerable<string> EnumerateFiles(string mask) => _info
        .EnumerateFiles(mask)
        .Select(x => x.FullName);
}

class RealFileSystem : IFileSystem
{
    public IDirectory OpenDirectory(string path) => new DirectoryInfoAdapter(new DirectoryInfo(path));

    public Stream OpenFile(string path) => File.Open(path);
}

void DoStuff(IFileSystem fileSystem)
{
    string SourcePath = @"L:\machinelogs";
    string filemask = "*.log";
    string searchitem = @"cannot access server data";

    List<string> fileswithsearchitem = new List<string>();
    IDirectory directory = fileSystem.OpenDirectory(SourcePath);
    IEnumerable<IDirectory> dirs = directory.EnumerateDirectories();
    dirs.Append(directory);
    foreach (var dir in dirs)
    {
        var found = false;
        var files = dir.EnumerateFiles(filemask);
        foreach(var file in files)
        {
            using var stream = fileSystem.OpenFile(file);
            using var reader = new StreamReader(stream);
            while (reader.ReadLine() is {} line)
            {
                if(line.Contains(searchitem))
                {
                    fileswithsearchitem.Add(file + " : " + line);
                    found = true;
                    break;
                }
            }
            if(found)
            {
                break;
            }
        }
    }

    foreach (string item in fileswithsearchitem)
    {
        Console.WriteLine(item);
    }
}

void Main()
{
    IFileSystem fileSystem = new RealFileSystem();
    DoStuff(fileSystem);
}

Then you could write an automated test like this:
class DictionaryBackedDirectory : IDirectory
{
    readonly IReadOnlyCollection<IDirectory> _directories;
    readonly IReadOnlyCollection<string> _files;

    public DictionaryBackedDirectory(
        IReadOnlyCollection<IDirectory> directories,
        IReadOnlyCollection<string> files)
    {
        _directories = directories;
        _files = files;
    }

    public IEnumerable<IDirectory> EnumerateDirectories() => _directories;

    public IEnumerable<string> EnumerateFiles(string mask) => _files; // TODO: implement masking
}

class DictionaryBackedFileSystem : IFileSystem
{
    readonly IReadOnlyDictionary<string, IDirectory> _directories;
    readonly IReadOnlyDictionary<string, Func<Stream>> _files;

    public DictionaryBackedFileSystem(
        IReadOnlyDictionary<string, IDirectory> directories,
        IReadOnlyDictionary<string, Func<Stream>> files)
    {
        _directories = directories;
        _files = files
    }

    public IDirectory OpenDirectory(string path) => _directories[path];

    public Stream OpenFile(string path) => _files[path]();
}

void AutomatedTest()
{
    var mockFileSystem = new DictionaryBackedFileSystem(
        new Dictionary<string, IDirectory>()
        {
            [@"L:\machinelogs"] = new DictionaryBackedDirectory(
                new Dictionary<string, IDirectory>(),
                new string[]
                {
                    @"L:\machinelogs\log1.log"
                }
            )
        },
        new Dictionary<string, Func<Stream>>()
        {
            [@"L:\machinelogs\log1.log"] = () => new MemoryStream() // TODO: populate the memory stream with data for the test
        }
    )
    DoStuff(mockFileSystem);
}

Advantages of doing this:

*

*Increase reusability

*

*You could implement a remote file system if you wanted

*Make your code more testable

*

*There are a lot of advantages to having "unit-testable code", and having
abstractions that can be "mocked" gets you closer to that golden city

Output results more abstractly
Your code doesn't have to be tied to Console.WriteLine() or to a particular output encoding.
For example:
readonly struct Result
{
    public readonly string Path;
    public readonly string Line;

    public Result(string path, string line)
    {
        Path = path;
        Line = line;
    }
}

IEnumerable<Result> DoStuff(IFileSystem fileSystem)
{
    string SourcePath = @"L:\machinelogs";
    string filemask = "*.log";
    string searchitem = @"cannot access server data";

    IDirectory directory = fileSystem.OpenDirectory(SourcePath);
    IEnumerable<IDirectory> dirs = directory.EnumerateDirectories();
    dirs.Append(directory);
    foreach (var dir in dirs)
    {
        var files = dir.EnumerateFiles(filemask);
        foreach(var file in files)
        {
            using var stream = fileSystem.OpenFile(file);
            using var reader = new StreamReader(stream);
            while (reader.ReadLine() is {} line)
            {
                if(line.Contains(searchitem))
                {
                    yield return new Result(file, line)
                }
            }
        }
    }
}

void Main()
{
    IFileSystem fileSystem = new RealFileSystem();
    foreach (var result in DoStuff(fileSystem))
    {
        Console.WriteLine(result.File + " : " + result.Line);
        break; // Could easily change this to continue searching
    }
}

See how this moves the console interaction out of your code, makes the output format someone else's problem, and also lets the consumer of your code decide if they want to continue searching once you have a search hit?
This will also get your code one step closer to be unit-testable. Feel free to ask if it's not clear why.
Inject parameters
The source path, file mask, and search item don't have to be hardcoded constants.
For example:
IEnumerable<Result> DoStuff(
    IFileSystem fileSystem,
    string sourcePath,
    string fileMask,
    string searchItem)
{
    IDirectory directory = fileSystem.OpenDirectory(sourcePath);
    IEnumerable<IDirectory> dirs = directory.EnumerateDirectories();
    dirs.Append(directory);
    foreach (var dir in dirs)
    {
        var files = dir.EnumerateFiles(fileMask);
        foreach(var file in files)
        {
            using var stream = fileSystem.OpenFile(file);
            using var reader = new StreamReader(stream);
            while (reader.ReadLine() is {} line)
            {
                if(line.Contains(searchItem))
                {
                    yield return new Result(file, line)
                }
            }
        }
    }
}

void Main()
{
    IFileSystem fileSystem = new RealFileSystem();
    foreach (var result in DoStuff(
        fileSystem,
        @"L:\machinelogs",
        "*.log",
        @"cannot access server data"
    ))
    {
        Console.WriteLine(result.File + " : " + result.Line);
        break;
    }
}

See how this makes it possible to search for other things?
Use Path.Combine
This will remove one dependency on Windows--namely the backslash path separator.
void Main()
{
    IFileSystem fileSystem = new RealFileSystem();
    foreach (var result in DoStuff(
        fileSystem,
        Path.Combine("L:", "machinelogs"),
        "*.log",
        @"cannot access server data"
    ))
    {
        Console.WriteLine(result.File + " : " + result.Line);
        break;
    }
}

I wouldn't be surprised if none of my code above compiles. This was written off the cuff


text:
Q: Du shows wrong file size for about 1 minute I have a problem with "du -hs" showing a wrong file size for about 1 minute.
for example: downloading 200MB file, and checking with du right after the download has been completed will show 1.1MB. than after about 60 seconds it will show the correct size.


text:
Q: C# 5 async CTP: why is internal "state" set to 0 in generated code before EndAwait call? Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and the GetAwaiter() / BeginAwait() / EndAwait() calls.
We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand:

*

*Why the generated class contains a Dispose() method and a $__disposing variable, which never appear to be used (and the class doesn't implement IDisposable).

*Why the internal state variable is set to 0 before any call to EndAwait(), when 0 normally appears to mean "this is the initial entry point".

I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however.
Here's a very simple piece of sample code:
using System.Threading.Tasks;

class Test
{
    static async Task<int> Sum(Task<int> t1, Task<int> t2)
    {
        return await t1 + await t2;
    }
}

... and here's the code which gets generated for the MoveNext() method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names:
public void MoveNext()
{
    try
    {
        this.$__doFinallyBodies = true;
        switch (this.<>1__state)
        {
            case 1:
                break;

            case 2:
                goto Label_00DA;

            case -1:
                return;

            default:
                this.<a1>t__$await2 = this.t1.GetAwaiter<int>();
                this.<>1__state = 1;
                this.$__doFinallyBodies = false;
                if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate))
                {
                    return;
                }
                this.$__doFinallyBodies = true;
                break;
        }
        this.<>1__state = 0;
        this.<1>t__$await1 = this.<a1>t__$await2.EndAwait();
        this.<a2>t__$await4 = this.t2.GetAwaiter<int>();
        this.<>1__state = 2;
        this.$__doFinallyBodies = false;
        if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate))
        {
            return;
        }
        this.$__doFinallyBodies = true;
    Label_00DA:
        this.<>1__state = 0;
        this.<2>t__$await3 = this.<a2>t__$await4.EndAwait();
        this.<>1__state = -1;
        this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3);
    }
    catch (Exception exception)
    {
        this.<>1__state = -1;
        this.$builder.SetException(exception);
    }
}

It's long, but the important lines for this question are these:
// End of awaiting t1
this.<>1__state = 0;
this.<1>t__$await1 = this.<a1>t__$await2.EndAwait();

// End of awaiting t2
this.<>1__state = 0;
this.<2>t__$await3 = this.<a2>t__$await4.EndAwait();

In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If MoveNext() were called again at this point (either directly or via Dispose) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and MoveNext() isn't called, the change in state is irrelevant.
Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation?
Important disclaimer
Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)

A: Okay, I finally have a real answer. I sort of worked it out on my own, but only after Lucian Wischik from the VB part of the team confirmed that there really is a good reason for it. Many thanks to him - and please visit his blog (on archive.org), which rocks.
The value 0 here is only special because it's not a valid state which you might be in just before the await in a normal case. In particular, it's not a state which the state machine may end up testing for elsewhere. I believe that using any non-positive value would work just as well: -1 isn't used for this as it's logically incorrect, as -1 normally means "finished". I could argue that we're giving an extra meaning to state 0 at the moment, but ultimately it doesn't really matter. The point of this question was finding out why the state is being set at all.
The value is relevant if the await ends in an exception which is caught. We can end up coming back to the same await statement again, but we mustn't be in the state meaning "I'm just about to come back from that await" as otherwise all kinds of code would be skipped. It's simplest to show this with an example. Note that I'm now using the second CTP, so the generated code is slightly different to that in the question.
Here's the async method:
static async Task<int> FooAsync()
{
    var t = new SimpleAwaitable();

    for (int i = 0; i < 3; i++)
    {
        try
        {
            Console.WriteLine("In Try");
            return await t;
        }
        catch (Exception)
        {
            Console.WriteLine("Trying again...");
        }
    }
    return 0;
}

Conceptually, the SimpleAwaitable can be any awaitable - maybe a task, maybe something else. For the purposes of my tests, it always returns false for IsCompleted, and throws an exception in GetResult.
Here's the generated code for MoveNext:
public void MoveNext()
{
    int returnValue;
    try
    {
        int num3 = state;
        if (num3 == 1)
        {
            goto Label_ContinuationPoint;
        }
        if (state == -1)
        {
            return;
        }
        t = new SimpleAwaitable();
        i = 0;
      Label_ContinuationPoint:
        while (i < 3)
        {
            // Label_ContinuationPoint: should be here
            try
            {
                num3 = state;
                if (num3 != 1)
                {
                    Console.WriteLine("In Try");
                    awaiter = t.GetAwaiter();
                    if (!awaiter.IsCompleted)
                    {
                        state = 1;
                        awaiter.OnCompleted(MoveNextDelegate);
                        return;
                    }
                }
                else
                {
                    state = 0;
                }
                int result = awaiter.GetResult();
                awaiter = null;
                returnValue = result;
                goto Label_ReturnStatement;
            }
            catch (Exception)
            {
                Console.WriteLine("Trying again...");
            }
            i++;
        }
        returnValue = 0;
    }
    catch (Exception exception)
    {
        state = -1;
        Builder.SetException(exception);
        return;
    }
  Label_ReturnStatement:
    state = -1;
    Builder.SetResult(returnValue);
}

I had to move Label_ContinuationPoint to make it valid code - otherwise it's not in the scope of the goto statement - but that doesn't affect the answer.
Think about what happens when GetResult throws its exception. We'll go through the catch block, increment i, and then loop round again (assuming i is still less than 3). We're still in whatever state we were before the GetResult call... but when we get inside the try block we must print "In Try" and call GetAwaiter again... and we'll only do that if state isn't 1. Without the state = 0 assignment, it will use the existing awaiter and skip the Console.WriteLine call.
It's a fairly tortuous bit of code to work through, but that just goes to show the kinds of thing that the team has to think about. I'm glad I'm not responsible for implementing this :)

A: if it was kept at 1 (first case) you would get a call to EndAwait without a call to BeginAwait. If it's kept at 2 (second case) you'd get the same result just on the other awaiter.
I'm guessing that calling the BeginAwait returns false if it has be started already (a guess from my side) and keeps the original value to return at the EndAwait. If that's the case it would work correctly whereas if you set it to -1 you might have an uninitialized this.<1>t__$await1 for the first case.
This however assumes that BeginAwaiter won't actually start the action on any calls after the first and that it will return false in those cases. Starting would of course be unacceptable since it could have side effect or simply give a different result. It also assumpes that the EndAwaiter will always return the same value no matter how many times it's called and that is can be called when BeginAwait returns false (as per the above assumption)
It would seem to be a guard against race conditions
If we inline the statements where movenext is called by a different thread after the state = 0 in questions it woule look something like the below
this.<a1>t__$await2 = this.t1.GetAwaiter<int>();
this.<>1__state = 1;
this.$__doFinallyBodies = false;
this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)
this.<>1__state = 0;

//second thread
this.<a1>t__$await2 = this.t1.GetAwaiter<int>();
this.<>1__state = 1;
this.$__doFinallyBodies = false;
this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)
this.$__doFinallyBodies = true;
this.<>1__state = 0;
this.<1>t__$await1 = this.<a1>t__$await2.EndAwait();

//other thread
this.<1>t__$await1 = this.<a1>t__$await2.EndAwait();

If the assumptions above are correct the there's some unneeded work done such as get sawiater and reassigning the same value to <1>t__$await1. If the state was kept at 1 then the last part would in stead be:
//second thread
//I suppose this un matched call to EndAwait will fail
this.<1>t__$await1 = this.<a1>t__$await2.EndAwait();

further if it was set to 2 the state machine would assume it already had gotten the value of the first action which would be untrue and a (potentially) unassigned variable would be used to calculate the result

A: Could it be something to do with stacked/nested async calls ?..
i.e:
async Task m1()
{
    await m2;
}

async Task m2()
{
    await m3();
}

async Task m3()
{
Thread.Sleep(10000);
}

Does the movenext delegate get called multiple times in this situation ?
Just a punt really?

A: Explanation of actual states:
possible states:

*

*0 Initialized (i think so) or waiting for end of operation

*>0 just called MoveNext, chosing next state

*-1 ended

Is it possible that this implementation just wants to assure that if another Call to MoveNext from whereever happens (while waiting) it will reevaluate the whole state-chain again from the beginning, to reevaluate results which could be in the mean time already outdated?


text:
Q: Liquid or powder that passes through an orifice at a consistent rate This I a really odd and specific question, and I'm not sure this is even where to ask.
A few weeks ago I thought about making a clock based on water flowing from an orifice.  The obvious issue is that the flow rate would vary significantly based on environmental conditions around the clock.
Does anyone know of a liquid or maybe a powder that will flow more consistently from a container into another across normal temperature and pressure shifts?
The obvious first guess would be sand like in an hour glass, but I was hoping someone knew of a better solution because the flow rate of sand is finicky in other more unpredictable ways.
I should add that the supply container will always be topped off with more media so that the mass (pressure) of liquid or powder is not changing with time.


text:
Q: How to make a list out of a 3D array inner data PHP Below there is the code of the array. I'm trying to make a list of the field categories in the inner array and when the fiel is empty to write 'without category'. And I simply can't do it. I have been trying with two foreach nested saving the list into a new array but I can't quite get it right.
     Array(
 'type' => 'success',
 'value => array (
     0 => array (
         'id' => 1,
         'joke' => 'Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.',
          'categories' => array());
     1 => array (
          'id' => 2,
          'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.',
          'categories' => array(
            [0] => nerdy
            ));
      2 => array (
          'id' => 3,
          'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.',
          'categories' => array(
            [0] => explicit
            ));
   );
)

//this is what I am trying without luck
$output = array();

    foreach($response as $row){
        foreach($row as $cat){
            $output[] = $cat['categories'];
        }
    }

Thanks!

A: First of all there's wrong syntax in your array, semicolons instead of commas and array keys in square brackets. Here is the correct syntax.
$response = Array(
    'type' => 'success',
    'value' => array (
        0 => array ('id' => 1, 'joke' => 'Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.', 'categories' => array()),
        1 => array ('id' => 2, 'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.',
            'categories' => array(0 => 'nerdy')),
        2 => array (
          'id' => 3,
          'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.',
          'categories' => array(
            0 => 'explicit'))));

Now the output. You want an output where 'without category' field will be a string, right? So print_r of the result array would look like this.
Array
(
    [0] => without category
    [1] => Array
        (
            [0] => nerdy
        )

    [2] => Array
        (
            [0] => explicit
        )

)

If yes, here is how you need to unwrap your array.
foreach($response as $row) {
    if (is_array($row)) {
        foreach($row as $cat) {
            if (empty($cat['categories'])) {
                $output[] = 'without category';
            } else {
                $output[] = $cat['categories'];
            }
        }
    }
}


text:
Q: iPhone iOS10 orientation media query failing in Mail App I am trying to target an iPhone 7 in landscape or portrait mode within an email which only needs to be viewable in iOS 10's Mail App.
When I test the below code either in Chrome's dev tool, iOS simulator or my iPhone 7's Safari browser everything works fine. The color changes from green <=> blue when I change orientation. Unfortunately, when I send this html file as an email my mail app does not seem to recognize portrait mode.
If I comment out the landscape section and only portrait remains, none of the css gets attached; alternatively, if I only have landscape the styling remains regardless of my screen's orientation.
Any help would be appreciated!
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  .
  .
  .
  .
  @media screen
      and (min-width: 375px)
      and (max-width: 667px)
      and (-webkit-min-device-pixel-ratio: 2)
      and (orientation: landscape) {
       .handheld .test {
         background-color: green;
         }
       }

  @media screen
    and (min-width: 375px)
    and (max-width: 667px)
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait) {
       .handheld .test {
         background-color: blue;
         }
       }

A: I have had this issue for sometime as well. With emails i have noticed the email simply moves with the screen on screen rotation. Android on the other hand loads the the email again when the device orientation changes.
I found an article at Email on Acid Blog which answers your question i guess. iOS email client when rotated doesn't respond to other media queries (unless maybe when the email is opened in that device orientation).


text:
Q: Flutter http / rest server not accessible from outside Android I'm working on a project in which I need to communicate between an Android device and a computer. To initiate a connection between these two device I thought using a Rest API mechanism with the following architecture :

*

*Rest server : Android Device by using https://pub.dev/packages/jaguar

*Rest client : my computer by using Python

My current flutter snippet looks like :
Jaguar server = Jaguar(port: 8080);
server.get("/", (context) => 'Hello');
await server.serve();

When accessing to "localhost:8080" from a web browser directly on my Android device, I get the "Hello" message but when trying to do the same thing from my computer (which is on the same network), I get a timeout error (on "192.168.0.10:8080").
It seems that my flutter (or my device) does not expose the web server to the rest of my network but I don't know why.. Do you have an idea ?

A: After a while, I found the solution. It's because since the API 28, Android blocks clear text traffic.
To solve this issue, we must override android:usesCleartextTraffic="true" like
<application
        ...
        android:usesCleartextTraffic="true">
...
</application>

A: My solution was to bind the server to 0.0.0.0 instead of localhost.


text:
Q: Why does the package babel[french] destroy \@for loops? Why does this minimal example code:
\documentclass{article}
\usepackage[francais]{babel}
\begin{document}

\def\names{Toto,Titi,Tete,Tutu}
\makeatletter
\@for\next:=\names\do{\textbf{\next} }
\makeatother

\end{document}

lead to this error message:
Runaway argument?
\next :=\names \do {\textbf {\next } } \makeatother \par \end {docume\ETC.
! File ended while scanning use of \@for.

but the same code works perfectly if I delete the line
\usepackage[francais]{babel}

and of course, is there any solution that preserves the use of the [french] option?

A: French babel uses active characters. You must disable this before use :=:
\documentclass{article}
\usepackage[francais]{babel}
\begin{document}

\def\names{Toto,Titi,Tete,Tutu}
\makeatletter
\shorthandoff{:}
\@for\next:=\names\do{\textbf{\next} }
\shorthandon{:}
\makeatother

\end{document}

A: The problem is that french makes : into an active character (after \begin{document}.
Solutions.

*

*Define your own list processor in the preamble
\makeatletter
\newcommand{\bflist}[1]{\@for\next:=#1\do{\textbf{\next}}}
\makeatother

and use \bflist{\names}

*Force : to have the correct category code:
\documentclass{article}
\usepackage[francais]{babel}
\begin{document}

\def\names{Toto,Titi,Tete,Tutu}
\makeatletter
\expandafter\@for\expandafter\next\string:=\names\do{\textbf{\next} }
\makeatother

\end{document}

The package etoolbox defines some list processing macros that shouldn't have this problem.

A: You can define your own loop, which, unlike LaTeX's \@for, is even expandable:
\documentclass{article}
\usepackage[francais]{babel}
\usepackage{xcolor}
\def\amfor#1#2{\doam{#2}#1,\doam,}
\def\doam#1#2,{\ifx\doam#2\amend\fi#1{#2}\doam{#1}}
\def\amend#1\doam#2{\fi}

\begin{document}
% The equivalent of Cristo's original example:
\amfor{Toto,Titi,Tete,Tutu}\textbf
\par\bigskip

% More tests:
\def\dspace#1{\def\cspace{\def\cspace{\space#1\space}}}
\dspace\textbullet
\amfor{Toto,Titi,Tete,Tutu}{\cspace\textbf}
\par\bigskip

\dspace{\textcolor{red}\textasteriskcentered}
\def\do#1{\cspace\textbf{#1}}
\amfor{Toto,Titi,Tete,Tutu}\do
\par\bigskip

% Building a stack in an expandable fashion:
\newcount\nr\nr=2\relax
\def\eat#1{}
\def\do#1{%
  \let\noexpand#1%
  \expandafter\noexpand\csname\expandafter\eat\string#1/\romannumeral\nr\endcsname
}
\edef\x{\amfor{\cmda,\cmdb,\cmdc}\do}
\def\strippref#1>{}
{\tt\expandafter\strippref\meaning\x}
\end{document}


text:
Q: how to enable scrolling in list when content overflows in Sencha touch I have a view which is in vbox layout with two items (a calendar plugin at top and a list at bottom) and is set to scrollable false as i dont want scroll on whole component. What i require is that in the list at bottom i have a store that is populated remotely and i cannot figure out how to enable scrolling in that list if the items exceed the available space in list.
this is the parent view
Ext.define('BudgetApp.view.transaction.TransactionDetailView', {
   extend: 'Ext.Container',
   xtype: 'transactiondetailview',
   config: {
      scrollable: false,
      fullScreen: true,
      layout: 'vbox',
      items: [{
            xtype: 'calendar',
            id: 'touchCalendarView',
            itemId: 'touchCalendarView',
            viewMode: 'month',
            value: new Date(),
            flex: 1.3,
            viewConfig: {
               weekStart: 1,
               eventStore: eventStore
            },
            enableEventBars: {
               eventHeight: 'auto',
               eventBarTpl: new Ext.XTemplate(
                  '<tpl if="amount > 0">' +
                     '${amount}' +
                     '</tpl>' +
                     '<tpl if="amount == 0">' +
                     '${amount}' +
                     '</tpl>' +
                     '<tpl if="amount < 0">' +
                     '${amount}' +
                     '</tpl>' +
                     '<tpl if="!clear && clear !=null">' +
                     '
●
' +
                     '</tpl>'
               )
            }
         },
         {
            xtype: 'forcasttransactionlist',
            itemId: 'forecastTransactionList',
            scrollable: true,
            //height:'100%',
            //style: 'overflow:auto;',
            flex: 1
         }
      ]
   }
});

below is the list code
Ext.define('BudgetApp.view.transaction.ForecastTransactionList', {
   extend: 'Ext.List',
   xtype: 'forcasttransactionlist',
   config: {
      store: {
         fields: ['name', 'age'],
         data: [
             { name: 'Jamie', age: 100 },
             { name: 'Rob', age: 21 },
             { name: 'Tommy', age: 24 }/*,
             { name: 'Jacky', age: 24 },
             { name: 'Ed', age: 26 },
             { name: 'Jamie', age: 100 },
             { name: 'Rob', age: 21 },
             { name: 'Tommy', age: 24 },
             { name: 'Jamie', age: 100 },
             { name: 'Rob', age: 21 },
             { name: 'Tommy', age: 24 },
             { name: 'Jacky', age: 24 }*/
         ]
      },
      itemTpl: '
{name} is {age} years old
'
   }
});

I tried setting scrollable:true but it will display scroll even if there is just
single item in list. I also tried setting style:'overflow:auto;' to list config in parent but that didn't work.
I want to enable scroll only if list overflows the available space.
Any help please ???

A: There isn't a built-in mechanism for this, you would need to implement your own. Unless you have additional custom list settings (such as variableHeight) then it's actually not that difficult. I put together a quick Sencha Fiddle showing how it would work.
https://fiddle.sencha.com/#fiddle/8uc


text:
Q: How do I open a file in its default program How do I programmatically open a file in its default program (I'm using Windows XP).
For example, opening *.txt will open the file in notepad.

A: the function ShellExecute
Has been provided for this.


text:
Q: My windows explorer shows future dates for date modified My windows explorer shows dates like tomorrow, next week and even later this year when grouping my files with date modified. What is going on?

A: it seems to me there is one single possibility: these files came from a computer with a wrong time setting at the occasion of file transfer or that same computer had absurd sync problems with time servers.


text:
Q: Is communication between two fragments through an activity can be called as an Observer Pattern in android? I just wanted to clarify one thing related to Observer Pattern in java.

Observer pattern is used when there is a one-to-many relationship
  between objects, such as if one object is modified, its dependent
  objects are to be notified automatically. Observer pattern falls under
  behavioural pattern category.

This is the definition of an Observer Pattern that I got.
http://www.tutorialspoint.com/design_pattern/observer_pattern.htm
The link also suggests the implementation.
My query related to observer pattern is, We have the concept of event bubbling technique (or the listener technique) that we use when we want to communicate data from Fragment A to Fragment B, both hosted by same Activity C.
Simple question is - can we call this technique similar to Observer Pattern ?
If interviewer asks me, cite an example of Observer Pattern, can I quote this example.
My assumption is YES, this technique is OBSERVER PATTERN, however, I do need some confirmed opinion.

A: The definition you posted mentions one-to-many relationship between the caller and the callee, which is very true.
But considering Activity and Fragments, they're normally one-to-one relation. This is still valid when your Activity acts as a middle-man between one or more fragments.
Rather than Observer pattern, the pattern used in Activity and Fragment communication is the Callback pattern, where the target instance implements an interface with which the caller can invoke.


text:
Q: Ubuntu 14.04.2 LTS x64 live CD or live USB doesn't boot on Gigabyte GA-H97M-HD3 motherboard This is my PC:

*

*G.Skill Ares DDR3 1600 PC3-12800 8GB 2x4GB CL9

*Gigabyte GA-H97M-HD3

*Intel Core i7-4790 3.6Ghz Box

*Kingston SSDNow V300 120GB

*MSI GeForce GTX750 OC 2GB GDDR5

*Seagate Barracuda 7200.14 1TB SATA3

I have problems booting Ubuntu 14.04.2 live Cd or live USB from fresh (no Windows installed) or other SO. I want to do dual boot with W7.
I configure the motherboard like:

*

*Boot option 1: DVD

*boot option 2: Lexar USB

*Fast boot: disabled

*Windows 8 Features: Other OS

*Boot mode selection: Legacy Only

*Lan PXE Boot Option ROM: Disabled

*Storage boot option control: Legacy Only

*Other PCI Device ROM priority: Legacy Only

*Network stack: Disabled

*System Mode state: Setup

*Secure Boot state: Disabled

I have no clue what is happening. I tried different DVDs burning in windows and in linux with different Ubuntu images from 14.04.1 and 14.04.2 and 14.04.2 server.
The violet screen (with the simbols like screen and a person) appeared and after few seconds, the screen turn black and one undescore appear in the upper right corner blinking and stayed for 30 minutes. Then trying one time and another... but never appear the ubuntu main screen.
I also tryed with pendrive USB live but once the grub (only in USB, not in CD) appear and I selected "try" or "install" the screen turn to black and nothing happend (I waited like 30 minutes and nothing changed) in both cases.
I want to do dual boot with W7 but first I want to be able to start live CD at least.
Any ideas or configurations? I will appreciate so much the help.
Cheers.

A: Finally the best choice is extract the graphic card, install ubuntu and then install nvidia drivers before insert again the graphic card. It must be noveau driver which doesn't support my MSI GeForce GTX750 OC 2GB GDDR5

A: friend.I have the same question.
Flow the pattern in the under , will be ok.
Access the bios,select the "periherals"Tab.
The "Inlt display first" Change to "igfx".
Change the cable of display from graphic card to motherboard.
Restart! It will be Ubuntu Time!


text:
Q: BitNot does not flip bits in the way I expected Can anyone explain why the last result in these statements is not the bit-flipped version of arr?
(Debug) In[189]:= arr = {0, 0, 1, 0, 0, 0, 1, 0}

(Debug) Out[189]= {0, 0, 1, 0, 0, 0, 1, 0}

(Debug) In[190]:= FromDigits[%, 2]

(Debug) Out[190]= 34

(Debug) In[191]:= BitNot[%]

(Debug) Out[191]= -35

(Debug) In[192]:= IntegerDigits[%, 2, 8]

(Debug) Out[192]= {0, 0, 1, 0, 0, 0, 1, 1}

A: Without using IntegerDigits[]:
With[{n = 34},
     {n, BitXor[BitShiftLeft[1, BitLength[n]] - 1, n]} // BaseForm[#, 2] &]
   {100010₂, 11101₂}

With[{n = 34, p = 8},
     {n, BitXor[BitShiftLeft[1, p] - 1, n]} // BaseForm[#, 2] &]
   {100010₂, 11011101₂}

A: FlipBits[num_Integer, len_.] :=
 Module[{arr}, arr = IntegerDigits[num, 2, len];
  1 - arr]

A: I don't think there is a built-in function to generate the two's complement representation. Easy to implement though.
twosComplement[x_, n_] := IntegerDigits[2^x - n, 2, n]
twosComplement[35, 8]
(* {1, 1, 0, 1, 1, 1, 0, 1} *)

A: twosComplement[x_, n_] := UnitBox@IntegerDigits[x, 2, n]
twosComplement[35, 8]

{1, 1, 0, 1, 1, 1, 0, 1}


text:
Q: JavaScript -- find matching object in array of objects I am trying to search for an object in an array of objects.
Note, vals and recs objects will be DYNAMIC.
var vals = {ID: "4", LOC: "LA", SEQ: "1"};

var recs = [
  {ID:"4", LOC:"LA", SEQ:"1"},
  {ID:"4", LOC:"NY", SEQ:"1"},
  {ID:"4", LOC:"CHI",SEQ:"1"}

];

Now I need to check if all key:value pairs in vals already exist in recs . In this case, recs[0] is an exact match of vals.
Heres my attempt:
var vals =  {ID: "4", LOC: "LA", SEQ: "1"};

var recs = [
  {ID:"4", LOC:"LA", SEQ:"1"},
  {ID:"3", LOC:"NY", SEQ:"2"},
  {ID:"2", LOC:"CHI",SEQ:"3"}

];

for(var i = 0; i<recs.length; i++){
    if(recs[i]["ID"] == vals["ID"] && recs[i]["LOC"] == vals["LOC"] && recs[i]["SEQ"] == vals["SEQ"]){
      console.log(true);
    }
    else{
      console.log(false);
    }
}

The above works only because I have hardcoded the keys from the vals object. In reality, the VALS object (and recs) will be DYNAMIC with X number of key:value pairs.
So how can I modify my for loop for a dynamic vals object?
thanks!

A: You need to break it into two loops, one for each object of the array and one for each key of the object:
for(var i = 0; i<recs.length; i++){
  var found = false
  for(var key in recs[i]) {
    if(recs[i].hasOwnProperty(key)){
      if(recs[i][key] != vals[key]){
        found = true
      }
    }
  console.log(found)
}

the hasOwnProperty call will make sure it doesn't break if the object does not have that key.

A: for(var i = 0; i<recs.length; i++) {
    for (var prop in object) {
       if (recs[i][prop] != vals[prop]) {
           console.log(false);
           return;
       }

    }
    //check from both sides
    for (var prop in vals) {
       if (recs[i][prop] != vals[prop]) {
           console.log(false);
           return;
       }

    }
    console.log(true);

}

A: You could iterate over the keys; something along the lines of:

var vals = {  ID: "4",  LOC: "LA",  SEQ: "1", REGION: "USA" };

var recs = [{    ID: 4,    LOC: "LA",    SEQ: "1",    REGION: "USA"  },
            {    ID: 3,    LOC: "NY",    SEQ: "2",    REGION: "USA"  },
            {    ID: 2,    LOC: "CHI",    SEQ: "3",    REGION: "USA" }

];

var isSame = true;

for (var i = 0; i < recs.length; i++) {
  console.log( i + '----------------' );
  var isSame = true;

  // get the keys of the record
  var keys = Object.keys(recs[i]);

  for (var j = 0; j < keys.length; j++) {

    var key = keys[j];
    var record = recs[i]

    console.log( key + ": " + record[key] + '=' + vals[key] );

    if (record[key] != vals[key] ) {
        isSame = false;// not equal
        break;
    }
  }

  console.log('isSame: ' + isSame );
  console.log('------------------' );
}

A: Try this:
for (var i = 0; i < recs.length; i++) {
  var found = true;
  for (var p in vals) {
    if (vals.hasOwnProperty(p)) {
      if (recs[i][p] !== vals[p]) {
        found = false;
        break;
      }
    }
  }
  console.log(found);
}

A: You can try this:

function myFind(recs, vals) {
    return recs.some(function(obj) {
        for (var x in obj)
            if (x in vals && obj[x] != vals[x])
                return false;
        return true;
    });
}

var recs = [
    {ID:4, LOC:"LA", SEQ:"1", USA:"USA"},
    {ID:3, LOC:"NY", SEQ:"2", USA:"USA"},
    {ID:2, LOC:"CHI",SEQ:"3", USA:"USA"}
];

var vals =  {ID: "4", LOC: "LA", SEQ: "1"};

if (myFind(recs, vals)) {
    alert('found');
} else {
    alert('not found');
}

Hope it helps.

A: you can use underscorejs isEqual for this kind of problem


text:
Q: How to use unspecified array dimensions in blocks? Using unspecified array dimensions (:) is an essential feature to design flexible components for reuse. I am well aware that the actual dimension has to be fixed when the model is compiled. To my knowledge binding a variable with unspecified array dimensions to one that has clearly defined dimensions should suffice.
So I am a bit confused why the following model Test will not validate in either OpenModelica or the Wolfram System Modeler:
package VectorFunctions

  model Test
      VectorSum converter "Component taking the sum of a vector input";
      InformationSource source "Vector input";
    equation
      connect( source.y, converter.u );
  end Test;

  block VectorSum "Take the sum of an input with unspecified dimension"
      Modelica.Blocks.Interfaces.RealInput u[:];
      Modelica.Blocks.Interfaces.RealOutput y;
    equation
      y = sum(u);
  end VectorSum;

  block InformationSource "Provide some vector output"
      Modelica.Blocks.Interfaces.RealOutput y[3];
    equation
      y = ones( 3 );
  end InformationSource;

end VectorFunctions;

How can something like this be done then?

A: My guess would be that the Modelica Spec does not specify, that vector sizes can be automatically detected from connections, so the tools don't support that.
I think you have to set the vector size somehow by yourself, e.g. with a parameter which is set in your Test model as follows:
  model Test
      VectorSum converter(nu=size(source.y, 1)) "Pass in the vector size";
      InformationSource source "Vector input";
  equation
      connect(source.y, converter.u);
  end Test;

  block VectorSum "Take the sum of an input with unspecified dimension"
      Modelica.Blocks.Interfaces.RealInput u[nu];
      parameter Integer nu(min=0)=0;
      output Real y;
  equation
      y = sum(u);
  end VectorSum;

Note that Dymola complains in your example code that connect statements can only be applied to connectors. Therefore I changed input Real to Modelica.Blocks.Interfaces.RealInput(and similar in InformationSource)

A: I have been given (inofficial) feedback on Wolfram Community by someone from Wolfram MathCore (e.g. the developers of the System Modeler):

Hi, I agree with your interpretation, I think we should support it. I have filed a bug to keep track of this issue internally, unfortunately I do not see any work around. We will come back to you when we have fixed this problem.

So, hopefully flexbile array sizes will be supported for blocks as they are for functions.


text:
Q: change value inside multimap I have a
multimap<key1,pair<key2, value2>>

I want to change value2 in this multimap.
typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij>
typedef std::pair<int, comp_buf_pair> node_buf_pair;
typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij>
typedef buf_map::iterator It_buf;

buf_map bufsz_map;

bufsz_map.insert(node_buf_pair(target(*ei,g), comp_buf_pair(comp_t[target(*ei,g)], dij)));

for(It_buf it = bufsz_map.equal_range(*u_iter).first; it!= bufsz_map.equal_range(*u_iter).second;)
{
    comp_buf_pair it1 = it->second;
    if(it1.first < c_i)
    {
        std::cout << it1.first << " : " << it1.second << std::endl;
        old_c_i = it1.first;
        old_dij = it1.second;
        updated_dij = (c_i-old_c_i) + old_dij;

        // I would like to erase the it1.second value and add the updated_dij value in the bufsz_map
    }
}

What would be a better way to do it?

A: The statement it->second.second = updated_dij; will overwrite the old value. Since you don't change the key field or indicate what a new key would be, this seems sufficient.
Is this what you are looking for or do you want to insert updated_dij under a new key and delete the old key?


text:
Q: How to create shortcut for a maven command in VS Code? For some reason I must execute the following command to build my project:
mvn clean install -U -Dmaven.javadoc.skip=true -Dmaven.test.skip=true

Is there a way in VS Code that I can create a shortcut for this command instead of entering it in the terminal?

A: Use the following command : tasks: Configure Default Build Task
See https://code.visualstudio.com/docs/editor/tasks for more details.
It allows to configure the .vscode/tasks.json file like following:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "mvn clean install -U -Dmaven.javadoc.skip=true -Dmaven.test.skip=true",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Then, you will can exec the command tasks: run build task to run mvn clean install -U -Dmaven.javadoc.skip=true -Dmaven.test.skip=true.


text:
Q: string.Replace(@"\\",@"\") doesn't work I have string getting from config. it's "DONGHOANG\HOANG"
I try replace \\ with \ but it doesn't work?
Here is my code? Have any solution
string linked_sv_name =
    "[" + config.AppSettings.Settings[cbbkho.SelectedValue.ToString()].Value + "]";
linked_sv_name = linked_sv_name.Replace(@"\\", @"\");

A: Instead of replacing 2 slashes into 1, you should replacing 1 slash into 2:
string linked_sv_name = "[" + config.AppSettings.Settings[cbbkho.SelectedValue.ToString()].Value + "]";
linked_sv_name = linked_sv_name.Replace(@"\", @"\\");

When passing this into sqlCommand, the double slashes will become 1 slash.


text:
Q: javascript - multiple CreateTextRange simultaniously I have the below javascript function, which when passed a word such as "Department" will highlight in red the first instance of "Department" found on the screen.  However, i would like this code to highlight ALL instances of the given word.
function findString (str) {
    var TRange=null;
    var strFound;
    var TRange = self.document.body.createTextRange();
    TRange.findText(str);
    TRange.execCommand('foreColor', false, "#ff0000");
    return;
}

A: function findString (str) {
    var TRange=null;
    var strFound;
    var TRange = self.document.body.createTextRange();

    while(TRange.findText(str))
    {
        TRange.execCommand('foreColor', false, "#ff0000");
    }

    return;
    }

A: This code seems to have done it, but it is sloppy and a little excessive. I'm sure there must be a shorter way to do it rather than almost duplicating my execCommand line twice in the same function.
var TRange=null;
function findString (str) {

    var strFound;
    var counter = 0;

    if (TRange==null || strFound==0) {
            TRange=self.document.body.createTextRange()
            strFound=TRange.findText(str)
            if (strFound) {
                TRange.execCommand('foreColor', false, "#ff0000");
            }
    }

    TRange.collapse(false);
    while (strFound=TRange.findText(str)) {
        if (counter > 50){
            alert("Search exceeded maximum limit of 50.");
            return;
        }
        TRange.execCommand('foreColor', false, "#ff0000");
        TRange.collapse(false);
        counter += 1;
    }

    return;
}

A: function findString (str) {
    var TRange = document.body.createTextRange();

    while (TRange.findText(str)){
        TRange.execCommand("foreColor", false, "#ff0000");
        TRange.collapse(false);
    }
}

A: Take a look at this link: http://www.nsftools.com/misc/SearchAndHighlight.htm
The script used on that page is a different approach to what you're taking but the end result is exactly what you're looking for.


text:
Q: I have / There are two (of them) What would be the most natural way of saying that there are two things you would choose rather than one.
For example, when someone asks you a question like

What is the car of your dreams?

or

What is your favorite color?

What would sound more natural as a reply?
I have two.
I have two of them.
There are two.
There are two of them.

[e.g. one is Porsche and the other is Mercedes and one is green and the other is blue]

A: To me, "of them" comes across as slightly wrong, because it's partitive. Consider:

*

*"There were six apples on the table; Susie ate two of them."

*"Susie eats apples often. This morning, she ate two."

A quantity of something implies part of a whole: Susie ate a part of the whole set of six apples. But in the second sentence, which isn't partitive, one would not ordinarily say "she ate two of them".
Another example:

*

*"My two sisters go to church every Sunday."

*"Two of my sisters go to church every Sunday."

The of construction in the second sentence clearly suggests that I have more sisters than two, whereas its absence in the first clearly indicates that I have only two sisters.
Similarly with your favorite colors, or the cars of your dreams: you have a fixed quantity, and you're speaking of the entire set. So you might say "Two of my dream cars are a BMW and a Mercedes" if you mean that you also dream about a Porsche and a Jaguar. However, if the first two are the only ones you dream about, you'd simply say "I have two dream cars, a BMW and a Mercedes." Therefore, when answering the hypothetical question, the elliptical form to use would be simply "I have two," not "I have two of them."
As for "there are two": it's better than either of the "of them" alternatives, and there isn't all that much to choose between it and "I have two."


text:
Q: fatal error: unexpectedly found nil while unwrapping an Optional value Parse sign up I'm trying to do a signup page but for some reason I keep getting the same error "fatal error: unexpectedly found nil while unwrapping an Optional value" on the line "let username = self.usernameField.text" when I test it out in the simulator. I know the error has something to do with a value being nil but cant figure out how to fix it please help :(
Code =
@IBOutlet weak var emailField: UITextField?
@IBOutlet weak var usernameField: UITextField?
@IBOutlet weak var passwordField: UITextField?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func signUpAction(sender: AnyObject) {

    let username = self.usernameField!.text
    let password = self.passwordField!.text
    let email = self.emailField!.text
    let finalEmail = email!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

    // Validate the text fields
    if username?.characters.count < 5 {
        let alert = UIAlertView(title: "Invalid", message: "Username must be greater than 5 characters", delegate: self, cancelButtonTitle: "OK")
        alert.show()

    } else if password?.characters.count < 8 {
        let alert = UIAlertView(title: "Invalid", message: "Password must be greater than 8 characters", delegate: self, cancelButtonTitle: "OK")
        alert.show()

    } else if email?.characters.count < 8 {
        let alert = UIAlertView(title: "Invalid", message: "Please enter a valid email address", delegate: self, cancelButtonTitle: "OK")
        alert.show()

    } else {
        // Run a spinner to show a task in progress
        let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
        spinner.startAnimating()

        let newUser = PFUser()

        newUser.username = username
        newUser.password = password
        newUser.email = finalEmail

        // Sign up the user asynchronously
        newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in

            // Stop the spinner
            spinner.stopAnimating()
            if ((error) != nil) {
                let alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
                alert.show()

            } else {
                let alert = UIAlertView(title: "Success", message: "Signed Up", delegate: self, cancelButtonTitle: "OK")
                alert.show()
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Home")
                    self.presentViewController(viewController, animated: true, completion: nil)
                })
            }
        })

A: Try this...
import Foundation
import Parse
import UIKit

class LoginViewController: UIViewController {

@IBOutlet weak var userNameTF: UITextField!
@IBOutlet weak var passWordTF: UITextField!
@IBOutlet weak var emailTF: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func SignUp(sender: AnyObject) {

    signUp()
}

@IBAction func Login(sender: AnyObject) {
    login()
}

func signUp() {

    let user = PFUser()
    user.username = userNameTF.text
    user.password = passWordTF.text
    user.email = emailTF.text

    // other fields can be set if you want to save more information
   // user["phone"] = "650-555-0000"

    user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
        if error == nil {
           print("Sign Up Succesful")
        } else {
           print("Sign Up Failed")
        }
    }

}

func login() {
    let user = PFUser()
    user.username = userNameTF.text
    user.password = passWordTF.text

    PFUser.logInWithUsernameInBackground(userNameTF.text!, password:    passWordTF.text!, block: {
        (user: PFUser?, Error: NSError?) -> Void in

        if Error == nil {
            dispatch_async(dispatch_get_main_queue()) {
            var Storyboard = UIStoryboard(name: "Main", bundle: nil)
            var AfterLoginVC: UIViewController =    Storyboard.instantiateViewControllerWithIdentifier("AfterLoginVC") as!  UINavigationController
                self.presentViewController(AfterLoginVC, animated: true,  completion: nil)
            }

        } else {
         print("Login Error, check credentials")
        }

    })

}

}

"AterLoginVC" is the storyboard identifier of the view controller that you want to instantiate after a successful attempt at login. From this you can then add you if/else statements to evaluate conditions and return the error to the user accordingly