text:
Q: Java indexOf method for multiple matches in String I had a question about the indexOf method. I want to find multiple cases of "X" in a string.
Suppose my string is "x is x is x is x", I want to find x in all of its index positions.
But how do you do this for multiple cases? Is this even possible with indexOf?
I did int temp = str.indexOf('x');
It find the first x. I tried to do a for loop where i is initialized to length of string and this did not work since I kept finding the first x over and over.
for (int y = temp1; y >= 0;y-- )
{
    int temp = str.indexOf('x');
    System.out.println(temp);
}

But this does not work. Am I supposed to use regex? Because I don't really know how to use regex method.
Any help would be appreciated, thanks!

A: There is a second variant of the indexOf method, which takes a start-index as a parameter.
i = str.indexOf('x');
while(i >= 0) {
     System.out.println(i);
     i = str.indexOf('x', i+1);
}

A: You can specify the start index with indexOf. So, in your loop you store the last position of 'x', then search again using that index + 1.

A: Here is the solution with Streams API :
String text = "Lets search for E ?";

final char key = 'e';
int[] indices = IntStream.range(0, text.length())
    .filter(i -> text.charAt(i) == key)
    .toArray();

Output will be like this :
//1
//6

If you want to add upper case letters into your result, you need to change the filter's argument closure with :
.filter(i -> Character.toLowerCase(text.charAt(i)) == key)

Then the output will be like this :
//1
//6
//16

Additionally if you just want to use the results or print it out for quick testing purposes you can do it with using forEach terminal operation:
IntStream.range(0, text.length())
    .filter(i -> text.charAt(i) == key)
    .forEach(System.out::println);

A: There's a another version of indexOf method, taking fromIndex as parameter.
So, you can call it in a loop, each time passing prevPosition + 1 as a second parameter.
Documentation:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(int, int)

A: String name = "alameer kaiser aziz";
String found = "a";
int num = name.indexOf(found);
while (num >=0) {
    System.out.println(num);
    num = name.indexOf(found,num+1);
}


text:
Q: Show that all the intervals in $\mathbb{R}$ are uncountable
Question:
Show that all the intervals in $\mathbb{R}$ are uncountable.

I have already proven that $\mathbb{R}$ is uncountable by using the following:
Suppose $\mathbb{R}$ is countable. Then every infinite subset of $\mathbb{R}$ is also countable. This contradicts the fact that $\mathbb{I} \subset \mathbb{R}$ is uncountable. Consequently, $\mathbb{R}$ must be uncountable.
However, how can I show that ALL the intervals in $\mathbb{R}$ are uncountable?

A: Let $f_s:\mathbb{R} \to \mathbb{R}$ be a scaling function $x \mapsto sx$ for some positive scaling factor $s$; then $f_s$ maps the unit interval to an interval of length $s$. Then let $g_t:\mathbb{R} \to \mathbb{R}$ be a shifting function $x \mapsto x+t$ for some shift $t$. Then to show that an arbitrary interval from $a$ to $b$, $a \neq b$, is uncountable, note that $g_a \circ f_{b-a}$ maps the unit interval to the interval from $a$ to $b$. $f_s$ and $g_t$ are both bijective, so the interval from $a$ to $b$ must have the same cardinality as the unit interval. Therefore the interval from $a$ to $b$ is uncountable. Since $a$ and $b$ are arbitrary, every interval of $\mathbb{R}$ is uncountable. Q.E.D.
Note: I'm assuming a priori that we know $\mathbb I$ is uncountable, but since you used that in your prior proof, that seems OK.

A: I'll show you geometrically a one-to-one correspondence between $(0,1)$ and $(0,2)$, showing that they have the same cardinality.

To figure out where $x$ goes to, draw a line from the point $P$ on top, through $x$ on the copy of $(0,1)$, until it hits the copy of $(0,2)$. Like this:

You see, we know how to pair up any two points because one line joins exactly one point of $(0,1)$ with one point of $(0,2)$.
In fact, you could do this to pair up any sets $(a,b)$ and $(c,d)$, or $[a,b]$ and $[c,d]$.
Now, to show that these are all uncountable, it suffices to provide a one-to-one correspondence between $(0,1)$ and $\mathbb R$.
So, what I'm going to do is take the interval $(0,1)$ and curve it up into a half-circle:

We do the same thing we did before. We have a point at the top; each point $x$ of $(0,1)$ is paired with the point $f(x)$ of $\mathbb R$ that is on the line joining the point at the top with $x$:

As we get closer and closer to the boundary of $(0,1)$, it gets stretched out more and more. It would be getting stretched out infinitely far at $0$ or $1$, but it's OK because those points aren't there! And we get to take this finite thing and distort it, a lot, to cover this infinite thing! (Since we're doing $(0,1)$, $0$ and $1$ aren't included in the set we're trying to pair up.)
Script and images stolen from here: http://www.artofproblemsolving.com/school/mathjams-transcripts?id=196
Now, one thing I haven't yet shown you is a one-to-one correspondence between $(0,1)$ and $(0,1]$ (or, for that matter, between either of those and $[0,1]$.) I haven't been able to find an image for this — I might edit this later if I find one. (Or I could draw it and photograph it with my phone.) However, hopefully I've convinced you that these are all uncountable, and that's all you really wanted to do, so this detail isn't essential.

A: Hint: Consider $\phi : \mathbb R \to (-1,1)$ defined by $$\phi(x) = \frac{x}{1  +|x|}$$ and notice that $f: (-1,1) \to (a,b)$ defined by $$f(x) = \frac{1}{2}\bigg((b-a)x + a+ b\bigg)$$
 is a bijection.

A: HINT: Find an injection from $\Bbb R$ into the interval $(0,1)$. Then show there is a bijection between any two intervals $(a,b)$ and $(c,d)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to get margin top of 10px for all my elements of the form Im doing a login box with a form, that asks for email and password.
I have all my elements in vertical, and Im trying to align all elements to stay with 10px margin top and bottom, to get every element with the same space.
But Im not having sucess to this goal, can you give some help understanding what I have wrong?
I give some backgrounds to my elements to be more easy to see how are the margins, and some backgrounds do not appear as they should, it seems there should also be some problem with floats.
This is my jsfiddle with what Im getting:
http://jsfiddle.net/Hp8zV/1/
My html:

Login Form:

    Enter your acess data.
    <form name="login">

            <input placeholder="Email" type="text" />

            <input type="password" placeholder="Pass"  class="pass"  />
            <input type="submit" value="Login" class="btn" />
            Forgot

    </form>

My Css:
*{margin:0; padding:0;}
body{overflow:hidden;}

.loginbox{position:absolute; left:50%; top:50%;background:#f7f7f7; width:360px; height:340px;}
.loginbox{margin-left:-180px; margin-top:-162px; background:pink;}
.loginbox h1{padding:20px; font-weight:200; color:#fff; background:brown; font-size:30px;}
.loginbox form{padding:20px; background:yellow;}
.loginbox form .label{display:block; margin-bottom:10px; margin-top:10px; float:left; width:320px;background:green;}
.loginbox form .label input{padding:10px; font-size:16px; border:1px solid #CCC; width:299px; float:left;}
.loginbox form .label .pass{width:299px; float:left;}
.loginbox form .label .btn{float:right; width:auto; display:block; background:brown; border:none; text-transform:uppercase; margin:20px auto;}
.loginbox form .label .btn{padding:11px 10px 11px; color:#fff; font-weight:bold; cursor:pointer; width:320px;}
.loginbox form .link {text-align:center; text-decoration:none; color:#000; background:blue;}

.ms{padding:20px 10px 5px 20px;float:left;display:block;  width:320px; background:red;

}

A: Here is your new code:

Login Form:

    Enter your acess data.
    <form name="login">
            <input placeholder="Email" type="text"/>
            <input type="password" placeholder="Pass"/>
            <input type="submit" value="Login" class="btn"/>
            Forgot
    </form>

*{
    margin:0;
    padding:0;
    border: 0;
}
.loginbox *{
    box-sizing:border-box;
}
.loginbox{
    position:absolute;
    left:50%;
    top:50%;
    background:#f7f7f7;
    width:360px;
    height:290px;
    margin-left:-180px;
    margin-top:-162px;
    background:pink;
}
.loginbox h1{
    padding:20px;
    font-weight:200;
    color:#fff;
    background:brown;
    font-size:30px;
}
.loginbox form{
    padding:20px;
    background:yellow;
}
.loginbox form input{
    margin-top: 10px;
    padding:10px;
    font-size:16px;
    width:100%;
    float:left;
}
.loginbox form .btn{
    background:brown;
    text-transform:uppercase;
    margin:10px auto;
    padding:10px;
    color:#fff;
    font-weight:bold;
    cursor:pointer;
    width:100%;}

.ms{
    padding:10px 10px 10px 20px;
    float:left;
    width:100%;
    background:red;
}
.loginbox form a {
    text-align:center;
    text-decoration:none;
    color:#000;
    background:blue;
}

Here is the fiddle
Hope i helped you


text:
Q: SQL Server Insert hangs - blocked by a process when i try to run an insert within an application, it hangs and eventually times out.
i ran the EXEC SP_WHO2 while it was still running and noticed that it was blocked by another process and there was a "lock" in the "wait type"
what does this mean? how do i fix it? i'm so lost.
the process that was in the "Blocked By" field had a delete statement in it. i validated the statement and it works fine.

A: Seems like your previous transaction is in open state due to some error in your stored procedure which prevents commiting /rollbacking the transaction in the absence of exception handling. This causes the table locking and application
gets hang in next request
Below is the recommended approach...
set xact_abort on
Begin Try
  Begin Tran
    //SQl Query
  Commit Tran
End Try

Begin Catch
   Rollback Tran
End Catch


text:
Q: Why Camera.ScreenPointToRay is not accurate in 3d world? Here is the video
I'm trying to hover the player over the cursor, but it doesn't work exactly, here's the code:
var playerPlane = new Plane(Vector3.up, transform.position);

// Generate a ray from the cursor position
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

// Determine the point where the cursor ray intersects the plane.
// This will be the point that the object must look towards to be looking at the mouse.
// Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
//   then find the point along that ray that meets that distance.  This will be the point
//   to look at.
float hitdist = 0.0f;
// If the ray is parallel to the plane, Raycast will return false.
if (playerPlane.Raycast(ray, out hitdist)) {
    // Get the point along the ray that hits the calculated distance.
    var targetPoint = ray.GetPoint(hitdist);

    // Determine the target rotation.  This is the rotation if the transform looks at the target point.
    var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

    // Smoothly rotate towards the target point.
    transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}

Here is the player hierarchy
The player and his scripts:(further child objects)

*

*mesh

*the same mesh that changes position depending on the rotation of its parent


text:
Q: How to remove Google Play Services from GenyMotion? I installed Google Play Services in GenyMotion(latest version including Virtual Box) referring How to install Google Play Services in a Genymotion VM (with no drag and drop support)?.
Now I want to remove Google Play Services and make GenyMotion back to its previous state. How can I do it ? (I use a Windows 8 system)

A: Installing the gapps zip into Genymotion writes many files into the system partition of the virtual machine. If you want to see a list, take a look at the META-INF/MANIFEST.MF file inside the zip file.
Installing a sideloaded zip like this is not really reversible unless you manually remove things and put back the originals of overwritten files.  In other words, it will be much easier for you to backup whatever you need from the device, delete it, and create a new one.


text:
Q: What am I missing in rendering JSON object - AngularJS In this Plunker why am I not able to access
{{ cartItem.selectedSeller.registered_name }}

Code

  {{ cartItem.selectedSeller }} // I can access this

 Registered Seller Name:

  {{ cartItem.selectedSeller.registered_name }} // but not this
  ===============================

from what I know we put [] in case of an array else we can access object attributes using . . I am surely missing some tiny logic here. I want to show Seller name for each cart products.

A: Your json has an invalid format. Try check it here
"selectedSeller":"{\"registered_name\": \"6bc0317c-0b8b-4b39-96d4-c3377e64acfd_seller\", \"rating\": 1, \"id\": 64, \"delivers_to\": \"[{\\\"city_name\\\": \\\"Pune\\\", \\\"country\\\": \\\"India\\\", \\\"pin_code\\\": \\\"411057\\\"},{\\\"city_name\\\": \\\"Kolkata\\\", \\\"country\\\": \\\"India\\\", \\\"pin_code\\\": \\\"411058\\\"},{\\\"city_name\\\": \\\"Delhi\\\", \\\"cou

by the key selectedSeller you access string but not a object, where presented register_name property
Also, it is a good idea to use json filter, but it depends what version angular you are using.
{{ foo | json }}

Here I can see an advise about parse json, it resolve your problem, also, but I am not recommend for you that way, keep a json backend data in a consistent format and not remap it on the client side through the parsers or some custom methods.

A: cartItem.selectedSeller is a string, simply parse the string as a JSON like so in your controller:
$scope.cartItems = [];
$http({
    method: 'GET',
    url: 'data.json'
  }).success(function(data) {
    data.forEach(function(a){
      a.selectedSeller = JSON.parse(a.selectedSeller);
      $scope.cartItems.push(a);
    });
  });


text:
Q: Filter CKQuery by key value My scenario:
I have a list of records of a certain record type in the public database. When someone presses a button, I want to only show records that contains the value "1" in the "Example" key. Any idea how to do this while the array of CKRecords is being created? This is how I currently build the array:
- (void)queryCloudKit
{
    CKQuery *query = [[CKQuery alloc] initWithRecordType:@"NewArticle"
                                               predicate:[NSPredicate predicateWithValue:YES]];
    query.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:NO]];

    [self.publicDatabase performQuery:query
                         inZoneWithID:nil
                         completionHandler:^(NSArray *results, NSError *error) {

        if (!error) {
            // CK convenience methods completion
            // arent executed on the callers thread.
            // more info: http://openradar.appspot.com/radar?id=5534800471392256
            @synchronized(self){
                self.results = [results mutableCopy];
                // make sure it executes on main thread
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.collectionView reloadData];
                });
            }
        }
        else {
            NSLog(@"FETCH ERROR: %@", error);
        }
    }];
}

Thanks!

A: You might try
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"NewArticle"
                                           predicate:[NSPredicate predicateWithFormat:@"Example == 1"]];
NSPredicate Programming Guide


text:
Q: Making this code with Map and Set more Scala-ish How do I make these line of codes more scala-ish (shorter?). I still get the Java feeling in it (which I want to stay away from). Thanks in advance!
import scala.collection.mutable
val outstandingUserIds: mutable.LinkedHashSet[String] = mutable.LinkedHashSet[String]()

val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
val userObj = tweetJson.get("user")
tweetJson.get("user").foreach(userObj => {
  userObj.asInstanceOf[Map[String, AnyRef]].get("id_str").foreach(idStrObj => {
    if (outstandingUserIds.exists(outstandingIdStr => outstandingIdStr.equals(idStrObj))) {
      outstandingUserIds.remove(idStrObj.asInstanceOf[String])
    }
  })
})

A: One thing you want to do in Scala is take advantage of type inference. That way, you don't need to repeat yourself on the LHS:
val outstandingUserIds = mutable.LinkedHashSet[String]()

You also don't need the inner braces after the closure variable userObj =>. Instead, use braces after foreach {} to execute multiple statements:
tweetJson.get("user").foreach { userObj =>

}

In fact, you could use the anonymous variable '_' and say:
tweetJson.get("user").foreach {
   _.get("id_str").foreach ...
}

Scala encourages the use of immutable collections. One way to simplify the above even further would be to use collect (instead of exists+delete) which would return a new collection with only the elements you want.


text:
Q: Route not recognized in rails3 application I was tinkering with this a few days ago and it seemed to be working.  But now I went back to this application setup and I can't seem to get to the home page with
http://localhost:3000

Here is my routes.rb configuration
  devise_for :users

  resources :home
  get "home/index"

  resources :formats
  get "formats/index" #display all formats

root :to => "home#index"

Any idea why I am getting the error that the route is not recognized?
Thanks!

A: When having routing problems, always check the output of rake routes to be sure it's listed correctly. Generally the correct way to route the / path is using the root method as you've done there.
The second thing to check is that you're connecting to the correct application. You may have more than one instance of rails server running on different ports.
Make sure that you're seeing updates to log/development.log when you make your request.


text:
Q: Is it possible to serve Apache's default internal pages with charset utf-8? This question is specifically about the charset Apache (2.2 in my case) uses when serving it's default internal pages. For example, mod_autoindex directory listings, not-found ErrorDocument pages, 500-Internal Error pages, etc.
The charset Apache is currently using for these built-in pages is iso-8859-1 (see screenshot).

Here are my relevant Apache settings:
# apache2.conf:

AddDefaultCharset utf-8

My OS is Debian 7 and I'm using it's default prefork binary. I was thinking the charsets on these pages might not be changeable. Or maybe there is a compile-time option that affects the default charset?
And in my (Debian-specific) /etc/apache2/envvars, I sourced my default locale:
$ cat /etc/apache2/envvars
. /etc/default/locale

$ cat /etc/default/locale
LANG="en_US.UTF-8

$ env | grep LANG
LANG=en_US.UTF-8

Modifying the Content-Type header with mod_headers has no affect on Apache's default internal pages.

A: Yes it is possible. You can do this with a combination of ErrorDocument, <Location> and ForceType, as follows:
ErrorDocument 404 /404.html
<Location /404.html>
  ForceType "text/html; charset=utf-8"
</Location>


text:
Q: powershell select-string preserve formatting of git log Is it possible to preserve formatting (specifically colour) of a string when piped through select-string?
I'm using select-string to find entries with specific tags in a git log that's been pretty-formatted with some nice colours. Unfortunately the colour gets lost in the process, and I get something that looks like non-printing control characters scattered about. This happens even on the "line" property of the match-info object.
I've piped the output of the git log into Get-Member and it appears to be a vanilla System.String.
Extra-details:
(probably not important, but you can never tell)
powershell v4
git 1.9.5
The formatted git log command is:
git log --color --graph --pretty=format:'%C(cyan)%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

I am vaguely aware that I may be able to do something similar with git log switches, and I'm looking into this, but for this question, assume I still need to pipe the output through powershell commands keeping the colours.
Edit:
Mangled output looks something like this (slightly sanitized). Unfortunately the unicode chars didn't survive emailing off the system in question.
* [0123abc[m -[33m (tag: build-1.0.3730)[m Some Comment [32m(5 hours ago) [1;34m<Author Name>[m
* [0123xyz[m -[33m[m Some other comment [32m(6 hours ago) [1;34m<Author Name>[m

According to www.babelstone.co.uk/Unicode/whatisit.html there is a control (escape) character in the output with codepoint U+001B, immediately preceding each left square bracket in the previous example, however these were removed by email clients.


text:
Q: Create list of columns to view in data frame I have two data frames;
df1 has many columns, lets say a thru to z
df2 contains rows that hold the names of columns I want to expose from df1
df1:

A
B
C
D

1
10
100
1000

2
20
200
2000

df2:

Expose

B

D

df2 will be dynamic and manages in a database table hence the desire to dynamically read the columns to expose instead of hard coding.
I've got code that iterates df2 to create the set of columns I'm interested in and returns the string: "['B','D']" set to the variable called props
What I want to the do is create a version of df1 but just with the columns B & D.
Trying
df1 = pd.DataFrame(df1, columns: props)

I get the error that I'm passing a string not a collection which makes perfect sense.... I'm struggling to see how to create the collection to pass through as the columns.
Any help appreciated.

A: Damn, no soon as I post this I find the answer.  Instead of creating the string I create a list and use props.append() when creating the list from df2.

A: You do it all in one line:
df1 = df1[df2['Expose']]


text:
Q: What should I do before changing graphics card? I'm thinking about buying a new graphic card.
What should I do before removing the old one, other than removing proprietary drivers?

A: I like Oli's answer. :)
The only thing I might add if your paranoid about picking a new card and want to be extra cautious would be to check the Ubuntu hardware catalog for video compatibility with your specific card choice.

A: Have a cup of tea.
But seriously, that's about all you want to do and you don't even need to do that before you rip it out.
Any old-config issues can be resolved fairly swiftly when the new graphics card is in. If you have issues,

*

*Get to a terminal any way you can (login if it boots to terminal, or try a TTY via ControlAltF1, or if all else fails, hold shift on reboot and enter the recovery console.

*Remove old driver packages

*Nuke /etc/X11/xorg.conf from lower orbit.

These are things you can do before changing but it makes very little difference.


text:
Q: ActiveResource + Caching I'm building an application that consumes models through an api with ActiveResource. I noticed that the
@resource ||= @resource.do a query

doesn't work, i.e. If I put something like that in my controller, my application will still query the api. So there is no built in caching that I'm used to with ActiveRecord. Time to expand my knowledge and skill base, ok.
I found this: http://injectisforwizards.com/blog/read-through-caching-of-activeresource/, and while I don't understand this 100% yet, for controller based queries that do .find, this appears to work. But not for any custom queries I have e.g.:
@current_resource ||= Resource.get(:resource_all, :by_account=>@current_account.account_key)

(which hits a custom controller and runs a scope, returning a collection)
I'm working through this and I'll find out what is going, but I'm curious if someone could tell me simpler terms what is going on, what I can do to smooth over caching in ActiveResource to be more like ActiveRecord, how I can tailor this to cache all queries, etc. Anything really would be helpful.
EDIT:
I found this: https://github.com/Ahsizara/cached_resource which looks promising but it is new (and built off that link above)....notable is that it does not seem to handle any sort of collections, but for one resource finds/caches well.

A: Since you receive a new instance of a controller for each request, caching like that is not going to work. I'm presuming you have something like this:
def show
  @resource ||= expensive_request
end

What are you expecting @resource to be when that method executes? The result of something from a previous call to show? Not going to happen.
What you need to do is put things into Rails.cache if you want them to persist between requests. If you use memcached as a back end, this can be very efficient. See the Caching with Rails guide for more information around section 2.5.
In general, a better approach than the ||= method of caching is to define protected methods that are wrapped with memoize to save the results. For example:
def load_resource
  expensive_request
end
memoize :load_resource

Remember that this will only apply to subsequent calls to that method within the context of the same request and is not the same as using Rails.cache.


text:
Q: Why icon "car" cannot move following "path" in svg?
after click "next" the path change color but "car" cannot move

when I setState
.
But if setState in
const [position, setPosition] = useState('here!!! I set positon')

car move. What is the problem ???
full code. Sorry I cannot add code here

A: Issue
You are mutating your state in PathMove function. clone is not actually a clone of the array, but rather just a shallow copy of it. All the elements in the array are references to the elements in the original array.
const PathMove = value => {
  const clone = [...array];
  const index = clone.findIndex(x => x.id === value);
  for (let i = 0; i < index; i++) {
    clone[i].status = true; // <-- state mutation!!
  }
  return setArray(clone);
};

Solution
Along with shallow copying the array, you need to shallow copy all elements and nested state that you are updating. In this case it seems you are updating them all.
Here I'm using a functional state update to update from the previous state (not the state enclosed in the callback). Shallow copy the array and then also shallow copy the elements being updated.
const PathMove = value => {
  setArray(array => {
    const index = array.findIndex(x => x.id === value);

    return array.map((el, i) => i < index ? {
      ...el,        // <-- shallow copy element
      status: true, // <-- update status property
    } : el);
  });
};


text:
Q: How to enable a custom field on AR301000 header after the ARInvoice is released? Some user fields were added to the top-level form of the ARInvoice entry screen (AR301000). A user wishes to modify a particular user text field after the invoice is released - what would be the best way to achieve this?

A: For the ARInvoice entry screen, all UI presentation logic specific to the top-level form is only implemented within the ARInvoiceEntry BLC:
public class ARInvoiceEntry : ARDataEntryGraph<ARInvoiceEntry, ARInvoice>, PXImportAttribute.IPXPrepareItems
{
    ...
    protected virtual void ARInvoice_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
    {
        ARInvoice doc = e.Row as ARInvoice;
        if (doc == null) return;
        ...
        bool shouldDisable = doc.Released == true
                            || doc.Voided == true
                            || doc.DocType == ARDocType.SmallCreditWO
                            || doc.PendingPPD == true
                            || doc.DocType == ARDocType.FinCharge && !IsProcessingMode && cache.GetStatus(doc) == PXEntryStatus.Inserted;

        if (shouldDisable)
        {
            bool isUnreleasedWO = doc.Released != true && doc.DocType == ARDocType.SmallCreditWO;
            bool isUnreleasedPPD = doc.Released != true && doc.PendingPPD == true;

            PXUIFieldAttribute.SetEnabled(cache, doc, false);
            PXUIFieldAttribute.SetEnabled<ARInvoice.dueDate>(cache, doc, (doc.DocType != ARDocType.CreditMemo && doc.DocType != ARDocType.SmallCreditWO && doc.DocType != ARDocType.FinCharge) && doc.OpenDoc == true && doc.PendingPPD != true);
            PXUIFieldAttribute.SetEnabled<ARInvoice.discDate>(cache, doc, (doc.DocType != ARDocType.CreditMemo && doc.DocType != ARDocType.SmallCreditWO && doc.DocType != ARDocType.FinCharge) && doc.OpenDoc == true && doc.PendingPPD != true);
            PXUIFieldAttribute.SetEnabled<ARInvoice.emailed>(cache, doc, true);
            cache.AllowDelete = isUnreleasedWO || isUnreleasedPPD;
            cache.AllowUpdate = true;
            Transactions.Cache.AllowDelete = false;
            Transactions.Cache.AllowUpdate = false;
            Transactions.Cache.AllowInsert = false;

            ..
        }
        else
        {
            ...
        }
        ...
    }
    ...
}

To enable a custom field on the AR301000 top-level form after the ARInvoice is released, you should declare an extension for ARInvoiceEntry and subscribe to ARInvoice_RowSelected handler following the sample below:
public class ARInvoiceEntryExt : PXGraphExtension<ARInvoiceEntry>
{
    public void ARInvoice_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
    {
        ARInvoice doc = e.Row as ARInvoice;
        if (doc == null) return;

        bool shouldDisable = doc.Released == true || doc.Voided == true ||
            doc.DocType == ARDocType.SmallCreditWO || doc.PendingPPD == true || doc.DocType == ARDocType.FinCharge
            && !Base.IsProcessingMode && sender.GetStatus(doc) == PXEntryStatus.Inserted;

        if (shouldDisable)
        {
            PXUIFieldAttribute.SetEnabled<ARInvoiceExt.usrCustomTextField>(sender, doc, true);
        }
    }
}


text:
Q: Render part of template doesn't apply css using ajax (flask back-end) Why I can not apply css file when render part of template?
I have studied render page with model after ajax post
, for now I know I can return part of html file into specific div which is in certain html

My problem, example:
There are 2 html file names
father.html and children.html, I want to fill children.html into a div tag in father.html, its OK for me! But why tags in children.html couldn't apply css(setup on father.css)
father.html has its own external file father.css and father.js
For father.html:

    <link rel="stylesheet" href="{{ url_for('static', filename='css/father.css') }}">

For father.js
$.ajax({
    url: '/returnChildrenTemplate',
    success: function(data) {
        $('#container').html(data); // return template into container
    }
})

For father.css
canvas {
    width: 100px;
    height: 100px;
}

For children.html:

{% for r in data %}

     {{ r.id }}

        <canvas class="demo" style="background-color: {{r.color }} "></canvas>

{% endfor %}

For back-end flask script:
@app.router('/returnChildrenTemplate')
def returnChildrenTemplate():
    result = ... # query from Database
    return render_template('children.html', data=result)

It doesn't work for children.html, its canvas tag is still its original size.
It works if I set canvas style into children.html. ( It quite stupid)

...
((  the same as above ))
...

What is this issue? Is there any method to solve this ?
BTW, father.js has the same problem.


text:
Q: Unable to draw multiple charts using Xlsxwriter by calling a function I am using Xlsxwriter to draw multiple charts in a single worksheet. The problem is for different sets of data when I am calling the function to add a chart, it is overwriting the previous xlsx and drawing only the latest chart. Here is my main program:
  # Write some data to add to plot on the chart.
 data = [
            [51, 62, 33, 14, 95],
            [52, 64, 36, 18, 10],
            [53, 66, 39, 12, 15],
           ]
 meas_num = 1
 tc.power_chart_excel(data,meas_num)

and here is the function:
 def power_chart_excel(self, data, meas_num):

    workbook = xlsxwriter.Workbook('C:/Amitra/chart.xlsx')
    worksheet = workbook.add_worksheet()

    # Create a new Chart object.
    chart = workbook.add_chart({'type': 'column'})
    ---- #Other chart commands

    #Writing data to different columns for different charts
    worksheet.write_column(wr_col_num_1 + '1', data[0])
    worksheet.write_column(wr_col_num_2 + '1', data[1])
    worksheet.write_column(wr_col_num_3 + '1', data[2])
    #worksheet.write_column(wr_col_num_4 + '1', data[3])
    #worksheet.write_column(wr_col_num_5 + '1', data[4])

    # Configure the chart. In simplest case we add one or more data series.
    #chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
    chart.add_series({'values': '=Sheet1!$' + wr_col_num_1 +  '$1:$' + wr_col_num_1 +  '$5'})
    chart.add_series({'values': '=Sheet1!$' + wr_col_num_2 +  '$1:$' + wr_col_num_2 +  '$5'})
    chart.add_series({'values': '=Sheet1!$' + wr_col_num_3 +  '$1:$' + wr_col_num_3 +  '$5'})
    chart.add_series({'values': '=Sheet1!$' + wr_col_num_4 +  '$1:$' + wr_col_num_4 +  '$5'})
    chart.add_series({'values': '=Sheet1!$' + wr_col_num_5 +  '$1:$' + wr_col_num_5 +  '$5'})

    worksheet.insert_chart(chart_position, chart)

    workbook.close()

How can I call this function multiple times to draw multiple charts in the same sheet without deleting the previous one? I have tested that if I do not call a function and open the chart once and close once then multiple charts are introduced. But I can not figure out how can I do the same thing using this function.

A: Your workbook object represents a new Excel file. Xlsxwriter cannot append to an existing xlsx file. Therefore, you should keep your workbook open and add new charts in the same workbook. Your code could look like this:
workbook = xlsxwriter.Workbook('C:/Amitra/chart.xlsx')
worksheet = workbook.add_worksheet()

for d in my_data: # or a similar loop depending on your program
    tc.power_chart_excel(worksheet, d, meas_num)

def power_chart_excel(self, worksheet, data, meas_num):
    # Create a new Chart object.
    chart = workbook.add_chart({'type': 'column'})
    # rest of the code goes here
    worksheet.insert_chart(chart_position, chart)


text:
Q: Rule of thumb: What is "enough" data to consider a neural network over traditional ML algorithms? I know that neural networks require more data than "traditional" ML algorithms like e.g. kNN or linear regression, or at least will do better with larger datasets. And that with few data, those traditional ML algorithms will most likely outperform NNs.
But, as a rule of thumb, what's considered enough data (in terms of rows and columns) to choose a NN over traditional ML algorithms?


text:
Q: Android Google Sign In Failed com.google.android.gms.common.api.ApiException: 12500 So I'm trying to use Google Sign In Authentication using Firebase as provide by this link :
https://firebase.google.com/docs/auth/android/google-signin?hl=en
I followed every single step including putting my SHA-1 Fingerprint into the firebase project. I'm currently on debug mode so I only have one SHA-1 Fingerprint.
Here's my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.client_id))
            .requestEmail()
            .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    mAuth = FirebaseAuth.getInstance();

    LinearLayout gLog = (LinearLayout) findViewById(R.id.googleLogin);
    gLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signIn();
        }
    });

}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w("Error", "Google sign in failed", e);
            // ...
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d("Akun", "firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d("MsgFirebase", "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        Intent i = new Intent(login_activity.this, main_activity.class);
                        i.putExtra("nama", user.getDisplayName());
                        i.putExtra("email", user.getEmail());
                        startActivity(i);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w("MsgFirebase", "signInWithCredential:failure", task.getException());
                    }

                    // ...
                }
            });
}

And here's the error that I got :
com.google.android.gms.common.api.ApiException: 12500:
    at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
    at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
    at com.mfs.rumah_duka.login_activity.onActivityResult(login_activity.java:112)
    at android.app.Activity.dispatchActivityResult(Activity.java:6562)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3799)
    at android.app.ActivityThread.access$1500(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5555)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:118)

I tried to check if the resultCode from the SigningIntent is success. It turns our it's not Activity.RESULT_OK.
I got the error right after I choose an account on the Sign In window.
Solutions that I've tried :

*

*Changed web client ID in the Firebase Google Sign In setting to the
one from my Oath credential in my Cloud Console

*Updated my gms service library to the latest version (According to Google Sign In error 12500)

*Create an OAuth for Android in my Cloud Console

None of those gave me a solution. I tried to read the documentation as to what error code 12500 means but it seems there's no specific cause. It says that try to use another email and it's still the same.
Does anybody has any solution to this?

A: I have faced the issue after deploying my flutter app in Play Store for internal testing and SHA-1 for production key was not working (production key file was new). After a few days I have figured it out - I needed to add SHA-1 from Google Play Store > Release management > App Signing > App signing certificate - SHA-1 certificate fingerprint which is different to local key's SHA-1 (this cert is visible in Google Play Store > Release management > App Signing > Upload certificate - SHA-1 certificate fingerprint)

A: I faced the exact same issue. This is what I did. First of all I ensured that I have latest google-services.json file in my project. Then I checked that the string key that I pass into the GoogleSignInOptions builder matches with the OAuth web client key in the GCP console.
Lastly, I updated my Google Play Services and the Google Repository (from the SDK Manager) to the latest version.
Updating the Google Repository seems to have done the trick for me.

A: When your app authenticates with a backend server or accesses Google APIs from your backend server, then you must pass the OAuth 2.0 client ID that was created for your server to the requestIdToken method when you construct the GoogleSignInOptions object, for accessing the user's basic profile information. Also, don't forget to submit the support email in the OAuth consent screen found in the Credentials page in the API Console.

A: try to update your Google Play Services to latest version this may solve your problem.

A: I was getting this error but when added details for OAuth consent screen in the api console - google login started working fine


text:
Q: Port flash game to native android Alright here is the problem: the creators of a quite popular flash-based game have asked me to port their game to Android. They are not interested in any other platforms so we don't need to be worrying about iOS or PC. They want the best performance on just Android (I guess that's the point of porting a flash-based game. They could have just went with it)
They found Unity 'slow'. How would the performance (on android) of other engines compare? Are they expecting too much i.e. finding Unity slow? I am in favor of Unity since development is a little easier with more things being visual (I am not experienced as you might have guessed).
This would be an example of the type of game I am to port
Thanks!
Edit: Some detail and link

A: If it runs in flash, it should run in Unity.  Unity is written in C++, and should be much more efficient than Flash, IIRC.  Flex your developer muscles if possible and try to get them to listen to you.
Failing that, expand your question with a description of the game you're trying to port and I will edit my answer accordingly.


text:
Q: A proverb/an expression to convey "a tendency towards a very big and unrealistic objective can be indicative of a failure" In the old times, when it came to a match between our ancient wrestlers, the participants in order to define the strongest ones used to grab a rock and raise it to gain more popularity; but prior to taking that when the person tended to pick a very big rock the surrounding audience had am expression which they would use to convey the message: it is the "sign of" a failure meaning that they might not be able to lift a stone of that size!
Later, the expression turned to a proverbial sentence and today, it can be used for any unlikely, improbable or unrealistic case which is a bit far from mind to occure! Actually we use this proverb to allude to any sort of seemingly unattainable goal which is too big to be achieved.
The only equivalent I've come across in English is:

*

*Great promise, small performance. [wich you can with a simple search on google find it as a type of translation from another language]

I was wondering if there is any equivalent of such a concept in current English.
Thank you in advance.

A: A US business phrase heard frequently is

*

*Let's find a solution which doesn't require boiling the ocean
Ie, the solution requires we solve some insolubly-large sub-problem.
For the suggestion that loud people are not effective:

*

*An empty vessel makes the most sound (proverb)

Perhaps one of these fits your circumstance.

A: I am not aware of an identical expression. However there are parallels, especially relating to people whose great ambitions lead to their downfall.
Among them is the line in Shakespeare's play Macbeth that refers to the protagonist's fatal ambition to gain power at all costs:
To prick the sides of my intent, but only vaulting ambition, which o'erleaps itself and falls on th'other-- (Numerous explanations of this complicated metaphor are available online)
The dangers of overweening ambition are also drawn in another Shakespeare play, Julius Caesar, which points to the perils of lusting for power. One of Caesar's assassins, Brutus, tells the crowd that ambition's debt is paid.
Also (although rather vaguely) related to your expression is the tale of The Mountain in Labour in one of Aesop's Fables. Although the mountain's groans raise great expectations among the populace, it gives birth to just a mouse.
We use this expression to refer to occasions when excessive promotion and assurances lead to a disappointing result.
https://www.enotes.com/shakespeare-quotes/vaulting-ambition
https://english.stackexchange.com/questions/246031/whats-the-pun-in-this-julius-caesar-reference
https://en.wikipedia.org/wiki/The_Mountain_in_Labour


text:
Q: Pass additional props to a react component I would like to know how to pass additional props to an already defined React component, or if it is possible at all.
For instance, given,
const foo = (
  <Foo
    bar={bar}
  />
);

Having defined foo like above, Can I later expand the prop list of foo programmatically to include baz? i.e. as if I did the following to begin with?
const foo = (
  <Foo
    bar={bar}
    baz={baz}
  />
);

A: In that case you can do one this, instead of passing the values, pass some state object, latter if you want to pass more data just update the state value, automatically that value will get passed to child component.
data = {bar: bar};

const foo = (
  <Foo
    bar = {this.state.data}
  />
);

Latter change the data to:
data = {bar: bar, a: a};

Note: If you want to pass hug data then use some architecture like redux, don't store that data in state variable.
Check this example:

var Foo = (props) => {
   return(

         {props.data.a}

         {props.data.b ? props.data.b : null}

   )
}

class App extends React.Component{

   constructor(){
      super();
      this.state = {
          propsData: {a: 1}
      }
      this.click = this.click.bind(this);
   }

   click(){
      let propsData = Object.assign({},this.state.propsData);
      propsData.b = 2;
      this.setState({propsData});
   }

   render(){
      return(

            <Foo data={this.state.propsData}/>

                Click me pass more data to child

      )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))

A: You can do it programatically in the following manner
constructor() {
    super();
    this.state = {
         data: {bar: "bar"}
    }
}

And then pass it to you compoenent using spread operator like
const foo = (
  <Foo
    {...this.state.data}
  />
);

Later if you wan to add another prop you can just update the state data to have another property like
addData = () => {
    var data = {...this.state.data}
    data["baz"] = "baz"
    this.setState({data})
}

And now since you have passed the props ...this.state.data
you can access them in you child component like this.props.bar and this.props.baz


text:
Q: copying Queue and Stack into each other I want to use an empty stack S to check whether a Queue Q contaitns element x, thus my solution was to copy elements of Q into S and check if contain x, but I'm also asked to return S elements into Q again as it was originaly, this must be done using only a Q and S without any other arrays of SL, so I have written this algorithm:
Boolean found ← false
int element ←  0
While(Q is not empty)

  element ← Q.dequeue()
  if(element equal x)
           found ← true
  S.push(element)

While(S is not empty)
 ( elements back to Q) ?

stuck in last step, if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed

A:
if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed

That's right, it will be reversed. You can use it to your advantage by observing that once you run the same loop again, you would get the original order back.
You can avoid writing the same loop twice if you make a method that does the search, and leaves the queue in reversed state. You can call your search method twice, and ignore the second return value.

A: This feels like a HW question so I won't solve it for you, but I will give you a hint - what happens when you dequeue a queue into a stack and then dequeue the stack back to the queue?
How can you use that phenomena to restore the original queue?

A: Correct, the order will be reversed.
This means that if you repeat the algorithm yet again (all to S and back to Q) you will reverse it yet again, meaning you will get back to the original order of elements, which is what you want.

A: I am not sure how java default Queue work.

*

*Remove element from the end of the queue.

*Check if that element is x, if so return true.

*Else, push it into the stack

*Repeat until you find x or all the Queue is empty.

*When you are done, pop elements one by one from the stack and add them at the beginning of the queue everytime, the last element in the stack would become the first element in the queue. Thus you maintain the order.


text:
Q: Windows Store App XAML: Gridview doesn't show image on full screen A few days ago I started to develop a Windows Store App using C#/XAML. In my App I want to show GridView with images, but first image must be showed on full screen (for example, if user have screen 1920x1080px, first GridView item must be 1920x1080px).
I have the next trouble: When I add first item, GridView cuts image at the bottom.
To prove it, I prepared image 1920x1080px (http://i.imgur.com/pJM0Tdp.png) with Red line on border (it's 1.png in XAML). As you can see on screenshot of my app http://i.imgur.com/56kKYcY.png, red line there is at top, left and right, but at  the bottom line is missing and black background is visible.
It's my XAML code:
<Page.Resources>
    <Style x:Key="GridViewItemStyle1" TargetType="GridViewItem">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="Margin" Value="0,0,0,0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="GridViewItem">
                    <GridViewItemPresenter CheckHintBrush="{ThemeResource ListViewItemCheckHintThemeBrush}"
                                           CheckBrush="{ThemeResource ListViewItemCheckThemeBrush}"
                                           ContentMargin="0"
                                           ContentTransitions="{TemplateBinding ContentTransitions}"
                                           CheckSelectingBrush="{ThemeResource ListViewItemCheckSelectingThemeBrush}"
                                           DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}"
                                           DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
                                           DragBackground="{ThemeResource ListViewItemDragBackgroundThemeBrush}"
                                           DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
                                           FocusBorderBrush="{ThemeResource ListViewItemFocusBorderThemeBrush}"
                                           HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                           Padding="{TemplateBinding Padding}"
                                           PointerOverBackgroundMargin="0"
                                           PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"
                                           PointerOverBackground="{ThemeResource ListViewItemPointerOverBackgroundThemeBrush}"
                                           ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
                                           SelectedPointerOverBorderBrush="{ThemeResource ListViewItemSelectedPointerOverBorderThemeBrush}"
                                           SelectionCheckMarkVisualEnabled="True"
                                           SelectedForeground="{ThemeResource ListViewItemSelectedForegroundThemeBrush}"
                                           SelectedPointerOverBackground="{ThemeResource ListViewItemSelectedPointerOverBackgroundThemeBrush}"
                                           SelectedBorderThickness="{ThemeResource GridViewItemCompactSelectedBorderThemeThickness}"
                                           SelectedBackground="{ThemeResource ListViewItemSelectedBackgroundThemeBrush}"
                                           VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

<GridView ItemsSource="{Binding List}" ItemContainerStyle="{StaticResource GridViewItemStyle1}">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Image Source="Assets/1.png" Width="1920" Height="1080"/>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

Could somebody help me, please?

A: I found that when you change the bottom margin in your GridViewItemStyle1 to -12, then it works.
<Setter Property="Margin" Value="0,0,0,-12"/>

12 is probably the default space between items. Some time ago I was reading Windows Phone 7 design guidelines and there was mentioned that 12 is a magic number for margins and sizes.

A: I found a simple way to solve this problem. All what we need, it set Padding="0" in GridView.
This is the code which solved my problem:
<GridView Padding="0" ItemsSource="{Binding List}" ItemContainerStyle="{StaticResource GridViewItemStyle1}">
<GridView.ItemTemplate>
    <DataTemplate>
        <Image Source="Assets/1.png" Width="1920" Height="1080"/>
    </DataTemplate>
</GridView.ItemTemplate>


text:
Q: Plotting multiple series from JSON php import to Highcharts because I'm pretty new to JS, I can't understand how to implement multiple data series into my code
Here is my php page that I use as data grabber:
getTrendData-TIMEREQUESTED-hms.php
<?php
    //Define possible Argument request
    $format = $_GET['format'];

    if($format=='json')    {
        header("Content-type: text/json");
    }

    //Define database credential
    $servername = "localhost";
    $username   = "test";
    $password   = "test";
    $dbname     = "test";
    try {
        //Open connection to mysql_db from defined Database credentials
        $connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
        $sql   = "select TIMEREQUESTED,TS FROM TIMEREQUESTED ORDER BY TS;";
        $result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
        //create an array
        $data = array();
        while($row = mysqli_fetch_assoc($result))    {
            $TIMEREQUESTED = strtotime($row['TIMEREQUESTED'])*1000;
            $TS = strtotime($row['TS'])*1000;
            $data[] = array($TS, $TIMEREQUESTED);
        }

        echo json_encode($data);
        //close the db connection
        mysqli_close($connection);
    }

    catch(PDOException $e)  {
        echo $e->getMessage();
    }

    ?>

Than I include in HighCharts with an Ajax call, that call himselfs each 2500 miliseconds,
getTrendData-TIMEREQUESTED-hms.php
[[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0],[1461242303000,26.25,0],[1461242835000,-2.5,0],[1461242869000,-2.5,0],[1461242991000,1.5,0],[1461243034000,3.14,0],[1461243374000,-14.22,0],[1461243456000,-11.92,0],[1461244995000,0,0],[1461245036000,-3.6,140],[1461245208000,-3,140],[1461245260000,3.56,140],[1461245312000,2.1,140],[1461245346000,2.1,140],[1461245411000,3.5,140],[1461245442000,3.5,140],[1461245479000,-1,140],[1461245757000,-0.8,140],[1461245809000,-0.69,140]]

TIMEREQUESTED-hms.html
function buildTIMEREQUESTED() {
  var chart;
  var dataSource = 'getTrendData-TIMEREQUESTED-hms.php?format=json';
  var ChartHeight = window.innerHeight;

  function requestData() {
    $.ajax({
      url: dataSource,
      success: function(points) {
        chart.series[0].setData(points, true);
        setTimeout(requestData, 2500);
      },
      cache: false
    });
  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("

");
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-laptime',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          s = (this.y / 1000);
          m = Math.floor(s / 60);
          h = Math.floor(m / 60);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          return 'Time Zero - ' + [m, s].join(':');
        }
      },
      title: {
        text: 'TIMEREQUESTED'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {
          text: 'RACE TIME'
        }
      },
      yAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
          millisecond: '%H:%M:%S',
        },
        //dateFormat: {"%H:%M:%S.%L"}
        title: {
          text: 'TIMEREQUESTED'
        }
      },
      series: [{
        name: 'TIMEREQUESTED',
        showInLegend: false,
        //tooltip: {type: 'datetime',},
        data: [],
      }]
    }); //end chart
  }); //end document.ready
}

In that way I can get the single series proper displayed, but with the MySQL query I'm able to get more columns from the database, and parsing in each rows of the json file,(As is showed in the JSON file from php request, there is a third values for each array) but  I'm not able to understand how to display multiple data series, with on the xAxis always the first column of the JSON file, and on the yAxis each time a different columns.
Could you please give me some suggestions on how to display multi series on the same graph? It would be so much appreciated,
Best regards.

A: var dataForTwoSeries = [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]]; //your data, just took 3 elements. Should work for any number of elements.
var seriesOne = [];
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
   var seriesOneDataPoint = [dataPoints[0], dataPoints[1]];
   var seriesTwoDataPoint = [dataPoints[0], dataPoints[2]];

   seriesOne.push(seriesOneDataPoint);
   seriesTwo.push(seriesTwoDataPoint);
});

And then you'll have to create 2 series in your chart object like
series: [{
    name: 'seriesName1',
    showInLegend: false,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: false,
    data: [],
}]

And in your requestData method, set the data for both like
chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

EDIT : After your updated code, these are the changes you further need to make.
$.ajax({url: dataSource, success: function(dataForTwoSeries) //dataForTwoSeries is the data you get from the request
  {
  //var dataForTwoSeries = []; you don't need this.
  var seriesOne = []; //these two don't have to be global.
  var seriesTwo = [];
  $.each(dataForTwoSeries, function(index, dataPoints){

    var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
    var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];

    seriesOne.push(seriesOneDataPoint);
    seriesTwo.push(seriesTwoDataPoint);
  }); // draw chart after iteration and not during each interation
    chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
    chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

    setTimeout(requestData, 2500);

  },
  cache: false
  });

A: I've update the code and now is free from syntax error, but I have no data displayed. I'm going to put some windows.allert() tu understand where the data flow is broken.
Here's the updated code:
<!DOCTYPE html>

    <title>Strategy - Time Zero</title>

    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">


text:
Q: Problemas con load_file en mysql Hola gente les comento,
tengo una db en mysql con la siguiente tabla (entre otras):
create table documentos(
   id int primary key not null auto_increment,
   archivo blob not null,
   codigo varchar(55) not null,
   nombre varchar(55) not null,
   tipo_doc varchar(55) not null,
   subproceso varchar(55) not null,
   proceso varchar(55) not null,
   depto_unidad varchar(55) not null,
   division varchar(55) not null,
   fecha_aprobacion date not null,
  fecha_modificacion date not null
);

Es primera vez que trabajo con una columna BLOB y necesito cargar archivos a la db, para ello estoy haciendo un insert tal que:
insert into documentos values
(null, load_file('C:\allmyCode\src\sql\Files\doc1.txt'), 'DOC1', 'Documento N1', 'Tpdc1', 'Sbprcs1', 'Prcs1', 'Dptundd1', 'Dvsn1', '2020-11-23', '2020-11-23');

pero me arroja un Error Code: 1048. Column 'archivo' cannot be null.
El único dato null que hago es a la columna con el auto_increment, que me funciona bien en las demás tabla y al probar a quitarlo de esta no soluciona el problema.
Para asegurarme he probado con todos los tipos de barras tanto '/', '\', '//' y '\\'.
Acabo de leer un poco buscando soluciones y he ejecutado SHOW VARIABLES LIKE "secure_file_priv"; para ver el directorio predeterminado y he probado en colocar los documentos ahí y hacer el insert:
insert into documentos values
(null, load_file('\doc1.txt'), 'DOC1', 'Documento N1', 'Tpdc1', 'Sbprcs1', 'Prcs1', 'Dptundd1', 'Dvsn1', '2020-11-23', '2020-11-23');

Esta vez lo probé sin barras y con todos los tipos de barras nuevamente. Me sigue dando el mismo error.
A su vez leí que hay que hay que verificar los privilegios, con lo que usé un GRANT FILE ON . TO 'root'@'localhost'; y luego FLUSH PRIVILEGES; no me arrojó error pero no estoy seguro de si esta sea la forma ni la sintaxis correcta (me aseguré de hacer esto antes de hacer las pruebas con load_file('doc1.txt') y sus variantes barrísticas).
Mencionar por último que el archivo es de prueba, es un txt vacío (probé también con escribirle dos líneas de texto), por lo que no debería ser problema el tamaño del archivo.
Utilizo windows 10 y mysqlserver / workbench 8.0. Lo que intento hacer con crear una tabla para cargar documentos es mostrar sus datos y posiblemente descargar el archivo desde una página html desarrollada con node.js usando extensiones .ejs; cualquier consejo respecto a esto será de mucha ayuda.
¡Gracias por sus respuestas!


text:
Q: What do the color codes mean for file blocks? While using uTorrent 3.4 alpha I couldn't help but notice that file blocks have various colors, but what do they mean?
On the screenshot I painted some of the most often appearing colors, but there might be more.

A: The developers change these colors quite often throughout the various updates on the software. Here are the colors that you highlighted;

*

*Neutral Green: Downloaded and written to disk

*Light Green: Requested data from peers, about to be downloaded

*Dark green: ...No idea as of current moment

*Orange: Canceled Piece

*Purple: Downloaded but not written to disk

There you go :)

A: A more correct description of colors:

*

*Grey: To be downloaded

*Purple: Requested from peer, awaiting download

*Dark green: Requested from multiple peers

*Light Green: Downloaded, not flushed to disk

*Neutral Green: Downloaded and written to disk

*Orange: Canceled Piece


text:
Q: Two divs side by side, the right one's width decided by its content, the left one takes up all available space? In the right div I have an image and a link. The images that might load have a huge variety of aspect ratios (from 0.38 to 6.83) and I have no control over the source images but they need to have the proper aspect ratio. To do that, I've given it a max-width but all too often the image is thinner than that width.
I'm trying to get the first div (.owner-info-container) to take up all left over space in the parent that the second div (.primary-image-container) doesn't use. If the image doesn't take up the entire space allowed by max-width, I'd like the left container not leave that as white space.
I've messed with floating the second div right but if the first div's content gets too wide it won't break into a new line, it'll just push the second div down.
HTML

Address

      Owner Name

      Name goes here

    Send us an updated photo

A: You can accomplish this using flexbox.
If you assign display: flex; to your .owner-address class, and then give your .owner-info-container a flex-grow: 1;, it will take up the remaining space within the .owner-address.
CSS
.owner-address {
  display: flex;
}

.owner-info-container {
  flex-grow: 1;
}

JSFiddle


text:
Q: App is not listed in Google play store for tablet devices Have published the app on the google play store. Able to download and install on android phones.
But the app is not at all listed in Play store for tablet devices.
i suspect there is something wrong in my manifest file.
contents of the manifest file are
<supports-screens
    android:anyDensity="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:resizeable="true"
    android:xlargeScreens="true"
    android:smallScreens="true" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Please guide me with the changes which i have to make so that the app gets listed on Play Store for Tablet devices.
thanks in advance

A: There are two reason, I know, why my app doesn't be shown on Play Store.

*

*The device's OS version is lower than you specified using "minsdkversion" on Androidmanifest.xml.

*Permission things. If you declared permissions of Phone Call, Camera etc, and Tablet that not have those hardware, Users cannot find my app on Google Play Store for their device.

So, We should add some code to Androidmanifast.xml like below.
<uses-feature
    android:name="android.hardware.telephony"
    android:required="false" >
</uses-feature>

For more informations, check this Q/A.
,this document and this.

A: After @Lal's answer i did a simple test. I added the permissions below and upload a simple apk. Manifest is like below.
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="com.fingerprints.service.ACCESS_FINGERPRINT_MANAGER" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.USE_FINGERPRINT" />
    <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.telephony" android:required="false" />

I uploaded app to play store and i can install for tablet. Then i removed
<uses-feature android:name="android.hardware.telephony" android:required="false" />

and tried to update play store app and there was a warning that tablets cant download after this update. I took screenshot, may be some one can need this.

and this is details.

After published update, i could not install for tablet.


text:
Q: Hardware menu button not opening in Samsung galaxy tab 3 I have a samsung galaxy tab3 and I have the menu implemented in the usual manner - i.e.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

and for menu selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

In my xml ive used  android:showAsAction="never" for items that I want to see in overflow and  android:showAsAction="ifRoom" for items I want to see upfront. But in this tablet I see only the ones with ifRoom set and the others just disappear and the menu button does not show the overflow items. I've looked at all answers on SO and tried the popular ones like setting minimum and target sdk versions to less than 11 and so on. But the menu just wont come up. It works fine in devices that dont have the capacitive menu touch and an overflow button is shown in the action bar.

A: Well it ended up working when I programmatically called openOptionsMenu with onKeyDown
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

         if (keyCode == KeyEvent.KEYCODE_MENU) {
            openOptionsMenu();
        }
        return true;
    };

A: MAybe you have a theme (like full screen) that does not support an ActionBar?


text:
Q: set index for row grouping in data tables i have two tables one is em table another is branch table. by combining these tables i need to generate datatables
emp table          branch table
A                   1
B                   1
C                   1
D                   2
E                   2
F                   2
G                   3
H                   3

i need a output in data table below format
India
1   1   A
2   2   B
3   3   C
Singapore
4   1   D
5   2   E

serverprocessing code in php
<?php
include_once("../../../../php/includes/dbconnection.php");

//SESSION START
session_start();

if (!isset($_SESSION['username'])) {
    header("location:../../../index.php");
}

//MYSQL CONNECTION
$dbcon = GetDbcon();
$sql_details = GetDbconArray();
$table = 'vepl_employee';
$primaryKey = 'id';

$columns = array(
    array('db' => 'D.branchName', 'dt' => '', 'field' => 'branchName'),
    array('db' => 'A.engrCode', 'dt' => 1, 'field' => 'engrCode'),
    array('db' => 'A.engrName', 'dt' => 2, 'field' => 'engrName',
            'formatter' => function( $d, $row ) {
            $tooltip = $d;
                        if (strlen($d) > 15)
                            $d = substr($d, 0, 15) . '...';
                        else
                            $d = $d;
                            return ''.$d.'';
                    }
        ),
    array('db' => 'D.branchName', 'dt' => 3, 'field' => 'branchName'),
    array('db' => 'D.branchLocation', 'dt' => 4, 'field' => 'branchLocation'),
    array('db' => 'A.internationalMobile', 'dt' => 5, 'field' => 'internationalMobile',
            'formatter' => function( $d, $row ) {
            $tooltip = $d;
                        if (strlen($d) > 15)
                            $d = substr($d, 0, 15) . '...';
                        else
                            $d = $d;
                            return ''.$d.'';
                    }
        ),
    array('db' => 'A.domesticMobile', 'dt' => 6, 'field' => 'domesticMobile',
        'formatter' => function( $d, $row ) {
            $tooltip = $d;
                        if (strlen($d) > 15)
                            $d = substr($d, 0, 15) . '...';
                        else
                            $d = $d;
                            return ''.$d.'';
                    }
        ),
    array('db' => 'B.project_place', 'dt' => 7, 'field' => 'project_place'),
    array('db' => 'C.client_name', 'dt' => 8, 'field' => 'client_name',
            'formatter' => function( $d, $row ) {
            $tooltip = $d;
                        if (strlen($d) > 15)
                            $d = substr($d, 0, 15) . '...';
                        else
                            $d = $d;
                            return ''.$d.'';
                    }
        ),
    array('db' => 'A.employee_status', 'dt' => 9, 'field' => 'employee_status'),
    array('db' => 'A.id', 'dt' => 10, 'field' => 'id')

);

require( 'ssp.class1.php' );

$joinQuery='FROM vepl_employee AS A LEFT JOIN vepl_project AS B ON B.id=A.currentProject LEFT JOIN vepl_client AS C ON C.id=B.client_id LEFT JOIN vepl_branches AS D ON D.id=A.branchId';
$where="A.engrDesignation NOT IN('Accounts Executive','Country Manager') AND A.employee_status != 'Deputed' AND A.currentProject != 0 AND A.company=".$_SESSION['company'];
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,$joinQuery,$where);
$start = $_REQUEST['start'];
$start++;
foreach ($result['data'] as &$res) {
   $res[0] = (string) $start;
    $start++;
}
echo json_encode(
  $result
);
?>

In jquery function
$('#emptotTable').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": "includes/employeelistServer.php",
    "fnRowCallback": function (nRow, aData, iDisplayIndex) {
        $('td:eq(1)', nRow).html('' + aData[1] + '');
        return nRow;
    },
    "drawCallback": function () {
    var api = this.api();
    var rows = api.rows( {page:'current'} ).nodes();
    var last=null;

    api.column(4, {page:'current'} ).data().each( function ( group, i ) {
        if ( last !== group ) {
            $(rows).eq( i ).before(
                '
'+group+'
'
            );
             last = group;
        }

    } );
    }
});

actually i got output in that format. but i need a output above mentioned format.
India
1       A
2       B
3       C
Singapore
4       D
5       E

thanks in advance


text:
Q: 'lock' datastore access while cron task running I have an application that I am planning to deploy on Google App Engine. Access to the datastore is through JPA. I also have several cron tasks that run throughout the day. My question is, is there a way that I can essentially prevent certain datastore entries from being accessed while the cron task is running?
Let's say the datastore entries for a particular table were Orders, and there was a cron task that is 'processing' these orders. I don't want the users to be able to modify the order while that task is running.
My first thought was to have all of the entities implement a simple interface called locked, and the cron task would set the lock value to true for all of the entitites that it was going to be processing, and then unlock them at the end, but that would require a ton of database updates each time the cron runs, and I'm sure there has to be a more efficient way.
Any ideas?

A: Take a look at this transaction mechanism. Transactions provide a guarantee that any changes required to individual entities will be synchronized and therefore prevent a potential race condition.
Or you can add "state" property in your order model. Whose values could be "processing", "pending", "delivered", etc. Then your cron can change it and your login read it to ensure that anyone will be able to modify it.


text:
Q: Which one is correct? why? if they both are correct, what's the difference in terms of meaning?
1- Once you reach the top, perhaps no one seeing you, you'll be able to
  see top of the world. Occasionally, life means hardworking for a dream
  not seen by anyone other than you.

Or

2-Once you reach the top, perhaps no one sees you, you'll be able to see top of the world. Occasionally, life means hardworking for a dream not seen by anyone other than you.

P.S. Suppose that italic one is adverbial phrase. I consider the first one to be correct because of Absolute clause being used there. But I am not sure about its relevance.

A: I don't think either really work. You are adding a qualifying idea into the "reach the top ... you'll be able to see", but as currently expressed it's ambiguous. Do you mean that once you are at the top you may not be seen, or do you mean that no one sees you in the process of making it to the top.
Either expression could have either meaning but

no one seeing you

has more of the flavour of seeing the process of getting to the top

no one sees you

has more of the flavour of being seen once at the top.
I would want to phrase this in a way that makes the intent clear

Once you reach the top, even though now maybe no one can see you, you'll be able to see top of the world. Occasionally, life means hardworking for a dream not seen by anyone other than you.

explicitly saying what the observer can (or rather cannot) see

Once you reach the top, even though no one saw your climb, you'll be able to see top of the world. Occasionally, life means hardworking for a dream not seen by anyone other than you.


text:
Q: Inconsistent MSDN documentation for InterlockedExchange() type functions/intrinsics? First, we have InterlockedExchange64();
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683593%28v=vs.85%29.aspx
LONGLONG __cdecl InterlockedExchange64( __inout LONGLONG volatile *Target, __in LONGLONG Value );

Second, we have the compiler intrinsic, _InterlockedExchange64(), note the absence of volatile;
http://msdn.microsoft.com/en-us/library/1s26w950%28v=vs.80%29.aspx
__int64 _InterlockedExchange64( __int64 * Target, __int64 Value );

Next, we have InterlockedExchangePointer() which like InterlockedExchange64(), uses volatile.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683609%28v=vs.85%29.aspx
PVOID __cdecl InterlockedExchangePointer( __inout  PVOID volatile *Target, __in PVOID Value );

But now we come to the intrinsic for pointer exchange, _InterlockedExchangePointer() and here we see volatile used!
http://msdn.microsoft.com/en-us/library/853x471w.aspx
void * _InterlockedExchangePointer( void * volatile * Target, void * Value );

The underlying instruction is the same in all cases, so what gives?  documentation error?
The GCC instrincs don't mention volatile for exchange, but then they don't mention it for CAS either!  so that doesn't help.
My view is that a CAS target is volatile, because you can only know at run time if the exchange will occur; but atomic exchange should not be volatile, because the target is always updated (even if it's value doesn't change), so the compiler has no uncertainty.
I see also the function for InterlockedIncrement() are volatile, but the instrincs are not.  The intrinsics for CAS have volatile for their destinations.

A: MSDN is riddled with mostly minor documentation errors (for instance, __readfsdword was marked as kernel only under the VS 2005 docs), what you should really pay attention to is the definition the compiler uses, in this case, the definitions in intrin.h (taken from VS2010 Ultimate SP1):
__MACHINEI(long _InterlockedExchange(long volatile *, long))
__MACHINEIA64(__int64 _InterlockedExchange64(__int64 volatile *, __int64))

as we can see they are indeed volatile pointers that are required.
One final thing to note, all your links are the VS 2005 docs (default linked to by google for older intrinsics), so make sure you use the drop down at the top of the page to switch to the latest versions.

A: It's not that pointer to volatile is required by these function it is that it is allowed. That is, if the parameters were declared as long* instead of long volatile* then passing the address of a volatile variable would give this error:
cannot convert argument 1 from 'volatile LONGLONG *' to 'LONGLONG *'

This can be seen with this simple code:
LONGLONG a;
volatile LONGLONG b;

void DoSomething(LONGLONG* p) {}

int main() {
  DoSomething(&a);
  DoSomething(&c); // Error!
  return 0;
}

There is a long tradition in C/C++ of misusing volatile as a way to indicate that a variable may be modified by other threads. This is misguided because volatile doesn't not actually give meaningfully useful semantics for multi-threading, but when C++ didn't acknowledge multi-threading developers got desperate. The problem with using volatile is that it does not prevent compiler or CPU reordering so it it is wrong, say, 99% of the time in multi-threaded code.
Absent C++11 the safe thing to do is to only ever reference these thread-shared variables using Interlocked* functions. If you do this then volatile is unnecessary. Or, use locks like a sane person.
But, since lots of developers tag their thread-shared variables with atomic it is necessary for Interlocked* functions to accept those variables. And that is why they all take the type of pointer-to-volatile.


text:
Q: CRM 2013 field changes are not recognized in Custom Button JavaScript I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?

A: Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box.  Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?

function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();

var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;

callentity.Subject = "Call Activity";
callentity.Description = oDescription ;

XrmSvcToolkit.createRecord({....Some more functions here...

})
}

HTML Button code for calling above function

<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>

A: Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:

*

*document.getElementById('new_description_i')[0].value

*Removing focus from "new_description" on click of your button.


text:
Q: Why is my child form not showing a custom icon in the taskbar? I have a Windows Forms application that uses a custom form to display a progress bar during a long operation.  This form is currently set up to display on the taskbar along with the other windows in my program.  However, while the other windows of my application show the appropriate application icon, this custom form displays only the default icon:

I set the icon in the designer to the same icon file all of my other windows use, but only this particular form has this problem.  The icon shows up correctly in the form's caption as well.  Manually setting the icon with form.Icon = Resources.Sample_Icon; in the either the child form's constructor or in the using loop seems to have no effect.
Here's a code sample that reproduces the problem:
// Inside Form1.cs on a button click
using (var form = new SampleForm())
{
    form.Show();

    for (int i = 0; i < numberOfIterations; ++i)
    {
        // Do work here in a real program

        // This function just calls progressbar.PerformStep():
        form.UpdateProgress();
    }
}

Changing the Show() to ShowDialog() does show the correct icon, but a DialogResult doesn't really have meaning in this situation.
I suspect that there is some event or message which sets the Windows taskbar icon which never gets processed, but when I tossed in a form.Refresh() and an Application.DoEvents() (just to see if it made a difference), I still had the default icon.
What am I missing?  And, why does ShowDialog work properly?
I'm using C# 4.0.

A: Forms don't inherit their icon from the parent form, even if Show or ShowDialog is called. You should probably try changing the other form's icon explicitly. Either do it in the current code:
form.Icon = <your icon>;

Or, do it in the loading code of your other form, just refer to the form itself.


text:
Q: CSS nested elements ignored by Chrome/Firefox? This might be painfully easy, so my apologies in advance, but I'm on Hour 5 trying to figure this mess out.  Here's the UL I'm trying to present as a horizontal bar:

Search

Tips

Neighborhoods

Relocation

And here's the strange CSS that seems to malfunction:
#navbar {}
#navbar ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
#navbar li {display: inline;}
#navbar ul li a {text-decoration:line-through;}

The problem I'm having is that with this markup, the text wrapped in anchor tags in the HTML aren't receiving line-through (I'm using line-through as a placeholder because it's obvious when it's working or not; I don't actually want a line-through in the end).
Here's the strange bit.  If I replace the "#navbar ul li a" nest with the following, it works:
#navbar li a {text-decoration:line-through;}

Furthermore, if I change "#navbar li{display: inline;}" with the following, I lose the inline property:
#navbar ul li{display:inline;}

Is it because I'm duplicating with "#navbar" and "ul"?  It seems entirely too strange to me, and I feel as though I've been able to use this syntax in the past without error.
Thanks for the help in advance.

A: Your ul already have id of navbar. That's why #navbar ul doesn't match anything.
ul#navbar will match.

A: #navbar ul is wrong...#navbar is the ul itself.

A: Your selectors are not correct.
#navbar is the UL element itself, so the selector #navbar ul does not target anything.
The correct selectors are
#navbar {
  list-style-type: none;
  margin: 0px;
  padding: 0px;
}
#navbar li { display: inline; }
#navbar li a { text-decoration:line-through; }

A: Your
 has the ID #navbar, so with #navbar ul you are actually addressing an additional ul inside your ul.
Try
ul#navbar li a {text-decoration:line-through;}


text:
Q: Pandas dataframe.apply() misapplying values to dataframe columns My code calls a function using dataframe.apply(). The function returns several values using a pandas.Series. However, the dataframe.apply() applies the values to the wrong columns.
The code below attempts to return dte, mark and iv. These values are printed out before the return statement to validate the values.
import pandas as pd
from pandas import Timestamp
from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday
from datetime import datetime
from math import sqrt, pi, log, exp, isnan
from scipy.stats import norm

# dff = Daily Fed Funds Rate https://research.stlouisfed.org/fred2/data/DFF.csv
dff = pd.read_csv('https://research.stlouisfed.org/fred2/data/DFF.csv', parse_dates=[0], index_col='DATE')
rf = float('%.4f' % (dff['VALUE'][-1:][0] / 100))
tradingMinutesDay = 450                                 # 7.5 hours per day * 60 minutes per hour
tradingMinutesAnnum = 113400                            # trading minutes per day * 252 trading days per year
USFedCal = get_calendar('USFederalHolidayCalendar')     # Load US Federal holiday calendar
USFedCal.rules.pop(7)                                   # Remove Veteran's Day
USFedCal.rules.pop(6)                                   # Remove Columbus Day
tradingCal = HolidayCalendarFactory('TradingCalendar', USFedCal, GoodFriday)    # Add Good Friday
cal = tradingCal()

def newtonRap(row):
    # Initialize variables
    dte, mark, iv = 0.0, 0.0, 0.0
    if row['Bid'] == 0.0 or row['Ask'] == 0.0 or row['RootPrice'] == 0.0 or row['Strike'] == 0.0 or \
       row['TimeStamp'] == row['Expiry']:
        iv, vega = 0.0, 0.0         # Set iv and vega to zero if option contract is invalid or expired
    else:
        # dte (Days to expiration) uses pandas bdate_range method to determine the number of business days to expiration
        #   minus USFederalHolidays minus constant of 1 for the TimeStamp date
        dte = float(len(pd.bdate_range(row['TimeStamp'], row['Expiry'])) -
                    len(cal.holidays(row['TimeStamp'], row['Expiry']).to_pydatetime()) - 1)
        mark = (row['Bid'] + row['Ask']) / 2
        cp = 1 if row['OptType'] == 'C' else -1
        S = row['RootPrice']
        K = row['Strike']
        T = (dte * tradingMinutesDay) / tradingMinutesAnnum
        iv = sqrt(2 * pi / T) * mark / S        # Initialize IV (Brenner and Subrahmanyam 1988)
        vega = 0.0                              # Initialize vega
        for i in range(1, 100):
            d1 = (log(S / K) + T * (rf + iv ** 2 / 2)) / (iv * sqrt(T))
            d2 = d1 - iv * sqrt(T)
            vega = S * norm.pdf(d1) * sqrt(T)
            model = cp * S * norm.cdf(cp * d1) - cp * K * exp(-rf * T) * norm.cdf(cp * d2)
            iv -= (model - mark) / vega
            if abs(model - mark) < 1.0e-5:
                break
        if isnan(iv) or isnan(vega):
            iv, vega = 0.0, 0.0
    print 'DTE', dte, 'Mark', mark, 'newtRaphIV', iv
    return pd.Series({'DTE': dte, 'Mark': mark, 'IV': iv})

if __name__ == "__main__":
    # sample  data
    col_order = ['TimeStamp', 'OpraSymbol', 'RootSymbol', 'Expiry', 'Strike', 'OptType', 'RootPrice', 'Last', 'Bid', 'Ask', 'Volume', 'OpenInt', 'IV']
    df = pd.DataFrame({'Ask': {0: 3.7000000000000002, 1: 2.4199999999999999, 2: 3.0, 3: 2.7999999999999998, 4: 2.4500000000000002, 5: 3.25, 6: 5.9500000000000002, 7: 6.2999999999999998},
                       'Bid': {0: 3.6000000000000001, 1: 2.3399999999999999, 2: 2.8599999999999999, 3: 2.7400000000000002, 4: 2.4399999999999999, 5: 3.1000000000000001, 6: 5.7000000000000002, 7: 6.0999999999999996},
                       'Expiry': {0: Timestamp('2015-10-16 16:00:00'), 1: Timestamp('2015-10-16 16:00:00'), 2: Timestamp('2015-10-16 16:00:00'), 3: Timestamp('2015-10-16 16:00:00'), 4: Timestamp('2015-10-16 16:00:00'), 5: Timestamp('2015-10-16 16:00:00'), 6: Timestamp('2015-11-20 16:00:00'), 7: Timestamp('2015-11-20 16:00:00')},
                       'IV': {0: 0.3497, 1: 0.3146, 2: 0.3288, 3: 0.3029, 4: 0.3187, 5: 0.2926, 6: 0.3635, 7: 0.3842},
                       'Last': {0: 3.46, 1: 2.34, 2: 3.0, 3: 2.81, 4: 2.35, 5: 3.20, 6: 5.90, 7: 6.15},
                       'OpenInt': {0: 1290.0, 1: 3087.0, 2: 28850.0, 3: 44427.0, 4: 2318.0, 5: 3773.0, 6: 17112.0, 7: 15704.0},
                       'OpraSymbol': {0: 'AAPL151016C00109000', 1: 'AAPL151016P00109000', 2: 'AAPL151016C00110000', 3: 'AAPL151016P00110000', 4: 'AAPL151016C00111000', 5: 'AAPL151016P00111000', 6: 'AAPL151120C00110000', 7: 'AAPL151120P00110000'},
                       'OptType': {0: 'C', 1: 'P', 2: 'C', 3: 'P', 4: 'C', 5: 'P', 6: 'C', 7: 'P'},
                       'RootPrice': {0: 109.95, 1: 109.95, 2: 109.95, 3: 109.95, 4: 109.95, 5: 109.95, 6: 109.95, 7: 109.95},
                       'RootSymbol': {0: 'AAPL', 1: 'AAPL', 2: 'AAPL', 3: 'AAPL', 4: 'AAPL', 5: 'AAPL', 6: 'AAPL', 7: 'AAPL'},
                       'Strike': {0: 109.0, 1: 109.0, 2: 110.0, 3: 110.0, 4: 111.0, 5: 111.0, 6: 110.0, 7: 110.0},
                       'TimeStamp': {0: Timestamp('2015-09-30 16:00:00'), 1: Timestamp('2015-09-30 16:00:00'), 2: Timestamp('2015-09-30 16:00:00'), 3: Timestamp('2015-09-30 16:00:00'), 4: Timestamp('2015-09-30 16:00:00'), 5: Timestamp('2015-09-30 16:00:00'), 6: Timestamp('2015-09-30 16:00:00'), 7: Timestamp('2015-09-30 16:00:00')},
                       'Volume': {0: 1565.0, 1: 3790.0, 2: 10217.0, 3: 12113.0, 4: 6674.0, 5: 2031.0, 6: 5330.0, 7: 3724.0}})
    df = df[col_order]

    df[['DTE', 'Mark', 'newtRaphIV']] = df.apply(newtonRap, axis=1)
    print df[['DTE', 'Mark', 'newtRaphIV']]

When I print the dataframe columns for dte, mark and iv, the value of iv is applied to the mark column and the value of the mark is applied to the iv column.
See output below:
DTE 12.0 Mark 3.65 newtRaphIV 0.330446529117
DTE 12.0 Mark 2.38 newtRaphIV 0.297287843836
DTE 12.0 Mark 2.93 newtRaphIV 0.308354580411
DTE 12.0 Mark 2.77 newtRaphIV 0.287119199001
DTE 12.0 Mark 2.445 newtRaphIV 0.305461340472
DTE 12.0 Mark 3.175 newtRaphIV 0.272517270403
DTE 37.0 Mark 5.825 newtRaphIV 0.347642501561
DTE 37.0 Mark 6.2 newtRaphIV 0.368273860485
   DTE      Mark  newtRaphIV
0   12  0.330447       3.650
1   12  0.297288       2.380
2   12  0.308355       2.930
3   12  0.287119       2.770
4   12  0.305461       2.445
5   12  0.272517       3.175
6   37  0.347643       5.825
7   37  0.368274       6.200

This is not the behavior I expected. What's going on?

A: df.apply(newtonRap, axis=1)

is a DataFrame with columns ['DTE', 'Mark', 'IV'], but the order of the columns is not guaranteed (see below for the reason why). So to fix the order of the DataFrame columns, you could
fix the order of the Series index returned by newtonRap:
return pd.Series((dte, mark, iv), index=['DTE','Mark','IV'])

or fix the order of the columns after df.apply returns:
df[['DTE', 'Mark', 'newtRaphIV']] = df.apply(newtonRap, axis=1)[['DTE', 'Mark', 'IV']]

The first option is better since
df.apply(newtonRap, axis=1)[['DTE', 'Mark', 'IV']]

creates two intermediate DataFrames -- df.apply(newtonRap, axis=1) and
df.apply(newtonRap, axis=1)[['DTE', 'Mark', 'IV']], whereas the first option creates the correct DataFrame from the get-go.

DataFrame assignment aligns on index but not on columns:
Note that assignment of the form
df[['C','E','D']] = other_df

aligns based on index but not on column names. So it does not matter what the column names of df.apply(newtonRap, axis=1) are. For instance, it would not help to change
return pd.Series({'DTE': dte, 'Mark': mark, 'IV': iv})

to
return pd.Series({'DTE': dte, 'Mark': mark, 'newtRaphIV': iv})

to make the column names of df.apply(newtonRap, axis=1) match those of
df[['DTE', 'Mark', 'newtRaphIV']]. If it did, it would just be dumb luck
that the order of the columns returned by df.apply(newtonRap, axis=1) happened to match the desired order. To corroborate this claim, consider the example
df = pd.DataFrame(np.random.randint(10, size=(3,2)), columns=list('AB'))
new = pd.DataFrame(np.arange(9).reshape((3,3)), columns=list('CDE'), index=[2,1,0])
#    C  D  E
# 2  0  1  2
# 1  3  4  5
# 0  6  7  8

df[['C','E','D']] = new
#    A  B  C  E  D
# 0  7  9  6  7  8
# 1  4  9  3  4  5
# 2  8  2  0  1  2

Notice that the index of new and df get aligned, but there is no alignment based on column labels.

Fixing the order of the DataFrame columns returned by apply:
Note that dict keys are unordered. In other words, when iterated over, dict keys may appear in any order. In fact, in Python3, dict.keys() may return the same keys in a different order each time the same code is run.
Because dict keys have an indeterminate order,
pd.Series({'DTE': dte, 'Mark': mark, 'IV': iv})

is a Series whose index has an indeterminate order, and therefore df.apply(newtonRap, axis=1) is a DataFrame whose columns appear in an indeterminate order.
However, if you use
return pd.Series((dte, mark, iv), index=['DTE','Mark','IV'])

then the order of the Series index is fixed. And thus df.apply(newtonRap, axis=1) has a fixed column order, and then
df[['DTE', 'Mark', 'newtRaphIV']] = df.apply(newtonRap, axis=1)

will work as desired.


text:
Q: Cross-referencing in a single-file bookdown document One of the promises of the bookdown package is functions for automatic numbering of figure/table captions, and cross-referencing figures/tables/sections.
This is claimed to be enabled for single-Rmd bookdown, if we use bookdown::html_document2 in the YAML: https://bookdown.org/yihui/bookdown/a-single-document.html
Looking at the raw rmarkdown for that chapter of the bookdown manual, I've tried to follow the instructions to make a single Rmd file that can use those cross-referencing functions. But I can't get it to render as expected, with cross-references.
Here's a simple example Rmd:
---
output: bookdown::html_document2
---

Here's the cross-ref: \@ref(fig:cars-fig)

Here's the figure:

```{r cars-fig, fig.cap = 'Here is a plot about cars'}
plot(cars)
```

Here's the output I get when I click on the knit button in RStudio, the cross-references are not quite working as expected:

How can I get the cross-referencing to show figure numbers and be a live link to the figure? And how can I get the caption to be formatted as expected?
Here's my session info:
> devtools::session_info()
Session info -------------------------------------------------------
 setting  value
 version  R version 3.3.0 (2016-05-03)
 system   x86_64, mingw32
 ui       RStudio (0.99.846)
 language (EN)
 collate  English_Australia.1252
 tz       Australia/Sydney
 date     2016-07-02

Packages -----------------------------------------------------------
 package   * version date       source
 bookdown    0.0.74  2016-07-01 Github (rstudio/bookdown@8333bbb)
 devtools    1.12.0  2016-06-24 CRAN (R 3.3.1)
 digest      0.6.9   2016-01-08 CRAN (R 3.3.0)
 htmltools   0.3.5   2016-03-21 CRAN (R 3.2.4)
 httpuv      1.3.3   2015-08-04 CRAN (R 3.2.3)
 memoise     1.0.0   2016-01-29 CRAN (R 3.2.5)
 mime        0.4     2015-09-03 CRAN (R 3.2.2)
 miniUI      0.1.1   2016-01-15 CRAN (R 3.2.4)
 R6          2.1.2   2016-01-26 CRAN (R 3.2.5)
 Rcpp        0.12.5  2016-05-14 CRAN (R 3.3.0)
 rmarkdown   0.9.6   2016-05-01 CRAN (R 3.3.0)
 rsconnect   0.4.3   2016-05-02 CRAN (R 3.3.0)
 shiny       0.13.2  2016-03-28 CRAN (R 3.2.4)
 withr       1.0.2   2016-06-20 CRAN (R 3.3.0)
 xtable      1.8-2   2016-02-05 CRAN (R 3.2.5)
 yaml        2.1.13  2014-06-12 CRAN (R 3.2.2)

A: This was a bug in the bookdown package and I have fixed it. The figure number should be generated correctly if you use bookdown >= 0.0.75.