text:
Q: Node.js 100% CPU - gettimeofday call I've got a long running node.js process that sometimes jumps to 100% CPU and stops responding to requests. The most recent time it did this I attached strace to the process, and here's what I saw:
Process 19523 attached - interrupt to quit
gettimeofday({1394558574, 234192}, NULL) = 0
gettimeofday({1394558574, 235381}, NULL) = 0
gettimeofday({1394558574, 306460}, NULL) = 0
mmap(0x3edab823a000, 2097152, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0) = 0x3edab823a000
munmap(0x3edab823a000, 811008)          = 0
munmap(0x3edab8400000, 237568)          = 0
mmap(0x3edab8300000, 1048576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x3edab8300000
gettimeofday({1394558574, 316435}, NULL) = 0
gettimeofday({1394558574, 316576}, NULL) = 0
gettimeofday({1394558574, 316677}, NULL) = 0
gettimeofday({1394558574, 316775}, NULL) = 0
gettimeofday({1394558574, 316879}, NULL) = 0
gettimeofday({1394558574, 316978}, NULL) = 0
gettimeofday({1394558574, 317439}, NULL) = 0
gettimeofday({1394558574, 317537}, NULL) = 0
gettimeofday({1394558574, 318139}, NULL) = 0
gettimeofday({1394558574, 318234}, NULL) = 0
gettimeofday({1394558574, 318343}, NULL) = 0
gettimeofday({1394558574, 318437}, NULL) = 0
gettimeofday({1394558574, 318530}, NULL) = 0
gettimeofday({1394558574, 318624}, NULL) = 0
gettimeofday({1394558574, 319135}, NULL) = 0
gettimeofday({1394558574, 319648}, NULL) = 0
gettimeofday({1394558574, 319769}, NULL) = 0
gettimeofday({1394558574, 319975}, NULL) = 0
futex(0x7f5b380008c8, FUTEX_WAKE_PRIVATE, 1) = 1
gettimeofday({1394558574, 322266}, NULL) = 0
gettimeofday({1394558574, 322426}, NULL) = 0
gettimeofday({1394558574, 322520}, NULL) = 0
gettimeofday({1394558574, 322759}, NULL) = 0
gettimeofday({1394558574, 322853}, NULL) = 0
gettimeofday({1394558574, 322995}, NULL) = 0
futex(0x7f5b380008c8, FUTEX_WAKE_PRIVATE, 1) = 1
gettimeofday({1394558574, 417614}, NULL) = 0
gettimeofday({1394558575, 386566}, NULL) = 0
gettimeofday({1394558575, 387704}, NULL) = 0
gettimeofday({1394558575, 463410}, NULL) = 0
mmap(0x24cfd260f000, 2097152, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0) = 0x24cfd260f000
munmap(0x24cfd260f000, 987136)          = 0
munmap(0x24cfd2800000, 61440)           = 0
mmap(0x24cfd2700000, 1048576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x24cfd2700000

That's a lot of gettimeofday calls, and not much else! What might cause node.js to get stuck like this?
UPDATE: I upgraded from an older version of node.js to 10.29 (I think) and this went away. I've just upgraded to 10.33 and the problem has come back. I've made a little more progress on debugging it this time out. First strace:
$ sudo strace -p 11812 -c
Process 11812 attached - interrupt to quit
Process 11812 detached
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.000192           0      2780           gettimeofday
  0.00    0.000000           0      1390           getrusage
  0.00    0.000000           0        31           futex
  0.00    0.000000           0      1390           clock_gettime
------ ----------- ----------- --------- --------- ----------------
100.00    0.000192                  5591           total

From Node.js: How to attach to a running process and to debug the server with a console? I found out about attaching the node debugger to a running process, and here's where I got with that:
$ sudo kill -s SIGUSR1 11812
$ sudo node debug -p 11812
connecting... ok
break in timers.js:79
  77 }
  78
  79 function listOnTimeout() {
  80   var msecs = this.msecs;
  81   var list = this;
debug> bt
#0 timers.js:79:23

So it looks like it is definitely related to a timer, but I don't know how to move further up the stack to find out where in my code the problem is getting triggered.

A: My guess is that someone manually implemented a blocking "setTimeout".  This could happen if someone doesn't want to release control of the main JS thread in an effort to prevent a potential race condition.
For obvious reasons this is a bad practice for production code, but I've used it on occasion in debugging to force asynchronous processes to execute in a specific order.
You could look for something silly like this:
var mockAsyncFunction = function (cb) {
    setTimeout(function () {
        cb(null, 'dummy_result')
    }, 5000);
};

var myResult = null;
mockAsyncFunction(function (err, result) {
    myResult = result;
});
var timeOut = 10000; // timeout in 10 sec.
var timeStart = new Date().getTime();

while (1) {
    if (new Date().getTime() - timeStart > 10000) {
        break;
    }
}
console.log('DONE');

or something more nefarious with nextTick recursion like:
var timeStart = new Date().getTime();

var recurseUntilDone = function () {
    if (new Date().getTime() - timeStart < 10000) {
        process.nextTick(recurseUntilDone);
    } else {
        console.log('Done recursing');
    }
};

recurseUntilDone();

A: Use node-inspector to be able to pause your code when the CPU is 100% - my bet is also on some badly implemented loop checking state until a certain time has passed, but they can be hard to find.
Attach the debugger with --debug when starting node (ie. node index.js --debug) and in a separate window run node-inspector. Use Chrome to connect to your debug session (the url is outputted from node-inspector command) and wait until the problem occurs and pause the execution and you should be able to find it.

A: We saw this too, in both production and development.  Also looking for an answer.
We started investigating the node run-time, but the problem is so infrequent it's not getting any priority.  Because it's completely cpu bound, no system calls, it's hard capture with an strace.
It won't be timed loop checking state, because a new Date().getTime() loop does not make any calls to gettimeofday (in node v0.10.29; it just does a long series of nanosleeps in one pid and just futex calls in the other.  Clever, actually).  Same for Date.now().

A: don't know if it's related, but here's a simple way to crush a node process:  use an array as a queue when it has data in it.  The symptoms are very very slow processing rate, and 100% cpu use.
//a = [];
a = new Array();

for (i=0; i<87370; i++) a.push({});

for (i=0; i<1000000; i++) {
    a.shift();
    a.push({});
    if (i%1000 === 0) {
    process.stdout.write(".");
    //global.gc();
    }
}

// node v0.10.29: 10k:  0.15 sec
//        80k:  0.17 sec
//        87369: 0.17 sec
//            87370: instant 41k, then .9k per second
//        87400: Array: instant 41k, then .9k per second
//        87400: []: instant 28k, then .9k per second
//        87400: Array, pushing 1 or 'x': .9k per second from the start
// node v0.11.13: 10k: 1.94 sec
//        16683: 3.87 sec
//        16884: uniform 237.16 sec

I ran perf record -F 997 -g node-v0.11.13 --perf-basic-prof script.js but pretty much all the time is ascribed to Builtin_ArrayShift (5-6 different hex locations called from ~)
Note that the behavior has a toggle point, below which it's fast, above it's slow.
The 0.10 and 0.11 behavior is different; 0.11 seems to have two toggle points (3 different speeds of dots).  The toggle points don't seem to stay the same between groups of runs.
Does not matter if global.gc() is invoked or not (with the --expose_gc switch).  Does not matter if the push/shift is in a continuable or in a blocking loop like above.
Edit: what's weird is that this is both data and loop count dependent.  Shorter loops run faster (even though they're chunked into 1k batches).
Also, when this condition exists, shift/push to other (empty) lists is also slowed to the same .9k ops/sec (node v0.10.29), but curiously they can be overlapped:  10 concurrent shift/append loops will each insert .9k items/sec, ie a total of 9k/sec.  (So there are resources for 10x more throughput -- an internal throttle then?)
Edit: not an internal throttle; the slow thread is using a solid chunk of 0.8 - 1.2 ms of cpu, and all other threads are blocked until it finishes.  Since concurrent threads must yield periodically (I used setImmediate), they keep getting blocked behind the cpu hog and make correspondingly slow progress.

A: explicit delete from larger hashes or arrays, like cleanup of an internal data container, could also cause symptoms like this.  The inherent node operation can be abysmally slow:
h = {}
for (i=0; i<200000; i++) h[i] = i;     // 25,000,000 / sec
for (i=0; i<1000; i++) delete h[i];    // 11,000 / sec
for (i=0; i<200000; i++) delete h[i];  // 7,700 / sec

a = new Array();
for (i=0; i<200000; i++) a[i] = i;     // 50,000,000 / sec
for (i=0; i<1000; i++) delete a[i];    // 10,000 / sec
for (i=0; i<200000; i++) delete a[i];  // 8,000 / sec
// and out of curiousity...
for (i=0; i<200000; i++) a[i];         // 250,000,000 / sec
for (i=1; i<200000; i++) a[i-1] = a[i]; // 180,000,000 / sec

deleting from back to front is 2x faster, but that's still very slow.  (note: assigning into a new Array is 50m/s, but into [] is only 25m/s)
The slowdown is O(n^2): doubling the array size to 400k quadruples the runtime.  Each delete operation is O(n) of the size of the hash/array.
The strace of a 400k run (100 seconds) shows no sytem calls to speak of, and does not match the gettimeofday() pattern seen above.
...
14:08:36.327886 munmap(0x44200000, 802816) = 0
14:08:36.328145 munmap(0xf7100000, 1183744) = 0
14:08:36.328483 clock_gettime(CLOCK_REALTIME, {1418584116, 328495018}) = 0
14:08:36.328540 clock_gettime(CLOCK_REALTIME, {1418584116, 328551680}) = 0
14:08:36.328581 clock_gettime(CLOCK_REALTIME, {1418584116, 328592628}) = 0
14:08:36.328633 futex(0x8e79a7c, FUTEX_WAKE_PRIVATE, 1) = 1
14:09:03.130336 clock_gettime(CLOCK_REALTIME, {1418584143, 130406483}) = 0
14:09:03.130479 clock_gettime(CLOCK_REALTIME, {1418584143, 130503357}) = 0
14:09:03.130560 futex(0x8e79a7c, FUTEX_WAKE_PRIVATE, 1) = 1
14:09:37.090127 clock_gettime(CLOCK_REALTIME, {1418584177, 90195108}) = 0
14:09:37.090271 clock_gettime(CLOCK_REALTIME, {1418584177, 90296760}) = 0
14:09:37.090355 futex(0x8e79a7c, FUTEX_WAKE_PRIVATE, 1) = 1
14:10:17.588552 mmap2(0x3f302000, 4231168, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0) = 0x3f302000
14:10:17.588694 munmap(0x3f302000, 1040384) = 0
14:10:17.588768 munmap(0x3f709000, 8192) = 0
...

A: If anyone is still in this issue, I encounter this issue also (to such a heavy state that my "repeat" node starts to drop instruction every second).
IN MY CASE this was caused by "serial" node - you can check it by launching htop command to monitor CPU usage and then redeploy all nodes after deleting "serial input" node.
CPU usage should immediately goes back down.


text:
Q: python write header to csv, all headers in one cell I am trying to write headers to a csv file, but all the headers are written in one cell. Can any one help me with that?
total_production_cost_w = open('Total_Production_Cost.csv','w')
headers = ['Company', 'Pool', 'Steam Cost', 'Nuclear Cost', 'Turbine Cost', 'Variable O & M', 'Emission Fee Tax', 'Hydro Cost', 'Hydro Maintenance Cost', 'Total Production Cost']
total_production_cost_w.write('\t'.join(headers) + '\n')
total_production_cost_w.close()

A: The problem with your code is you use TAB to separate the columns. For csv, replace \t with ,. But if you are dealing with csv, I highly recommend the csv module:
import csv

headers = ['Company', 'Pool', 'Steam Cost', 'Nuclear Cost', 'Turbine Cost', 'Variable O & M', 'Emission Fee Tax', 'Hydro Cost', 'Hydro Maintenance Cost', 'Total Production Cost']
with open('Total_Production_Cost.csv','w') as total_production_cost_w:
    writer = csv.writer(total_production_cost_w)
    writer.writerow(headers)

A: If it's a Comma-Separated Value file you want to write, then you should use a comma as separator instead of a tab, maybe ? :-)
Try:
total_production_cost_w.write(','.join(headers) + '\n')

instead of:
total_production_cost_w.write('\t'.join(headers) + '\n')

Or, better: use the csv module.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this code not writing anything to the file Why is this code not writing anything to the file?
It returns TRUE though, but nothing goes in the file.
No exception thrown either.
This is the method. I call it like this in main()
boolean b = AppendFile( f, " hello world" );

    public folder = "dir/";
    String f= "ttest"; // no file extension. A plain text file

    public boolean AppendFile( String f, String s ){
    try{
    int err=1;

    File file = new File( folder + f );
    if (!file.exists()) { return false;  }

    s= s.replace( "NULL", " " );
    s= s.replace( "null", " " );
    s= s.replace( "Null", " " );

    s= s.trim() +"\r\n";

    FileWriter fileWritter = new FileWriter( file.getName(),true);
    BufferedWriter br = new BufferedWriter( fileWritter );
    br.write( s );
    br.close();
    return true;

    }catch(Exception e){ return false; }

    }//end

A: Found the error. Thanks @Andreas
I should remove the .getName() from this line:
FileWriter fileWritter = new FileWriter( file.getName(),true);
Thanks :)


text:
Q: JAXB-2 Maven Plugin and maxOccurs=5000 limitation I'm using the JAXB-2 Maven Plugin to generate classes from an XSD. One element has a maxOccurs of 50000 so the secure processing feature causes an exception for violating the 5000 limit.
Changing the XSD is not an option so as a workaround I added the "-nv" parameter to turn off strict validation. So I got my classes but it doesn't feel like a real solution.
Is there a way to set the MAX_OCCUR_NODE_LIMIT?


text:
Q: Necessity of using "had had" when a single "had" could have sufficed?
If Sir John had had the slightest idea what was going to be the devastating effect of his son's handsome looks upon a certain beautiful courtesan and the tragedy which would ensue, he might have had second thought about continuing his journey without him. (Source: Vengeful Ghosts by Vida Derry)

I am having problem with this use of "had" (BOLD). How I understand using had is that it is used if some action (action 1) precedes another action (action 2) and "had" accompanies the first action (A perfect Past Perfect scenario). For example:

I had done it, before you did that.

Now in the highlighted text, Sir John did not have the slightest idea, he did not take his son with him and the devastating effects of his son's looks did happen. So how can "had" here be used when the action i.e. having a slightest idea has never happened to Sir John?
In my opinion, a single "had" (simple past) would have sufficed.

A: You are confused here by the fact that a past form may be used in two ways: as a marker of past tense and as a marker of counterfactuality. In this case, it must serve both uses, and it is that which requires the past perfect form.
Let's consider this in the present tense, and then 'backshift' it to the past. There are two constructions:

*

*
Sir John is a judicious man. If he has the slightest idea of the result he may have second thoughts.

This employs the simple present of HAVE and MAY to express a condition regarded as possible or plausible. Backshift that into the past—as reported speech, for instance—and you get this:

Lord West told me that Sir John was a judicious man and if he had the slightest idea of the result he might have second thoughts.

*Note, however, that exactly the same constructions are used to express a present counterfactual:

Sir John is an idiot. If he had the slightest idea of the result he might have second thoughts. But he has no such idea.

The second sentence there has already used up all its available past forms to mark counterfactuality. To backshift it into the past you must add some sort of past marker. By convention, those markers are supplied by converting the past forms into past perfects:

Lord West told me that Sir John was an idiot; if he had had the slightest idea of the result he might have had second thoughts. But he had no such idea.


text:
Q: Debian server doesn't show in DHCP list on router I have a Raspberry Pi running Raspbian which is connected over ethernet to my router. The router has been running both with DCHP and Static IP addresses and over the local LAN I can connect fine over ssh, for example. However, the device never shows in the list of connected devices on the router so I cannot configure port forwarding for external access.
I would have said that this was a problem with the router but I have now tried with two different routers (BT Home Hub 2 and Edimax BR-6428) with the same results so I am thinking that it must be the OS.
Is there some setting that I need to make the device appear to the router?

A: If your Rpi is on the network with a static IP, it never talks to the router to 'advertise' itself.
A really simple solution is to use the upnpc program (in miniupnpc package) to set your port forwarding dynamically.  MUCH easier than tweaking the router all the time.
You'll need upnp enabled on your router, usual caveats apply here.
The following command will forward internet port 1337 to internal port 22 on the server:
upnpc -e "ssh server" -a $(hostname --all-ip-addresses) 22 1337 tcp

See the man page for upnpc of course for more details, but here you can see -e sets the name of the forward setting, -a lists the server's IP addresses, the last three items are inside port, outside port, type of connection (tcp/udp).
I use a similar command to forward port 80 from outside to my own web server too, don't have to set up a DMZ with all that that entails security-wise.  (and no, I didn't put my actual external ssh port number here... duh!)

Another method would be to set a static DHCP setting for your Rpi in the router, and shift your Rpi back to dynamic IP (DHCP) mode... but unless you're going to also set up some sort of name-server system, this gets hairy fast since your RPi address COULD change. (Yes, I know it's not supposed to... )
Letting it set up its own forwarding using its current IP address is the best way, as it adapts as needed.


text:
Q: Facebook Share button and comment plugin conflict In my blog I need to implement both a Facebook share button (with a counter) and comment plugin. I just used the code below.
FACEBOOK SHARE

    Share

FACEBOOK COMMENT PLUGIN

<div class="fb-comments" data-href="<?php the_permalink(); ?>" data-num-posts="2" data-width="524">

In the end, it returns the error

Uncaught TypeError: Object # has no method 'provide'

on line 4, and this error don't show the comment plugin. It shows instead the share button.
Is there any solution to this problem?

A: I had the exact same problem.  I ultimately had to switch which FB plugin I was using.
Here's the link to my site where I have the comments and the like button together:
http://www.jhousemedia.com/blog-articles/145/Building-A-Good-Website-For-Your-Business.html
I had to switch out the share button with the Like/Send plugin.  Fortunately, they have an option to make it fit a similar form as the share button.
Here's the plugin used
http://developers.facebook.com/docs/reference/plugins/like/

A: I'm not sure, but you can try to comment or delete this line:
js.src = "//connect.facebook.net/it_IT/all.js#xfbml=1";

Maybe share and comment scripts are duplicating code.

A: Solved this by replacing the comments script with just this line in the header


text:
Q: Exclude a configuration when @WebMvcTest in Spring Boot 1.4 I have a @SpringBootApplication class in java/ directory(same package) and another @SpringBootApplication class in test/ for mocking some auto-wired beans. There are several tests and which configuration is used varies from test to test.
And in a test class
@RunWith(SpringRunner.class)
@WebMvcTest(RecApiServerController.class)

throws
java.lang.IllegalStateException: Found multiple @SpringBootConfiguration annotated classes [Generic bean: class [com.xxx.MockedTestConfig]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/..direction.../target/test-classes/com/xxx/MockedTestConfig.class], Generic bean: class [com.xxx.MyApplication]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/...direction.../target/classes/com/xxx/MyApplication.class]]

I just want to test routing of a controller.
How could I set a specific application configuration?

A: You can't have two @SpringBootConfiguration (@SpringBootApplication) in the same package. @WebMvcTest searches automatically the source of configuration for you (see the doc). You can have a special @SpringBootConfiguration (or application) in a nested package of your test if you want to tune things but you can't have two in the same package.
I am not sure the doc is very explicit about that so we should probably clarify it.
Anyway, a custom @SpringBootApplication and slicing is a bit weird. @SpringMvcTest already takes care of only enabling what is necessary. If you want to mock some beans, you should not define that in a @SpringBootApplication. A regular @Configuration that you import is fine. We also have @MockBean to automatically mock things for you.


text:
Q: why do we need $f$ bounded for uniform convergence? Theorem
If $f$ is a bounded measurable function, then there exists a sequence of simple functions $\{f_{n}\}$ which converge uniformly to $f$.
Proof
Define $f_{n}(x) = \frac{m}{n}$ whenever $\frac{m}{n} \leq f(x) < \frac{m+1}{n}$.  We clearly have that $f_{n}(x) \rightarrow f(x)$ (if this isn't clear, look at what value $f_{n}(x)$ is and in what range the $f(x)$ can be; $f(x)$ essentially gets "squished" between these two values, and $f_{n}(x)$ goes to this value as $n$ increases).  In addition, and here is the clever part, notice that for every $x$ it is the case that
$$|f(x) - f_{n}(x)| < \frac{1}{n}$$
which gives us convergence.  The fact that $f$ is bounded between, say, $[m,M]$, gives uniformity (why?).  $\Box$.

I don't understand why we need $f$ bounded for uniform convergence. Isn't it already enough that $|f(x) - f_{n}(x)| < \frac{1}{n}$ was independent of the $x$ value?

A: Every simple function $f_n$ is bounded, so if $f$ is unbounded, $f-f_n$ is unbounded, and you can't have uniform convergence.
As said in the other answer, your proposed function is, in fact, not a simple function for unbounded $f$

A: I will expand my comment just in case that you don't fully understand it. By definition, a simple function $s$ is a finite sum of scaled characteristic functions of measurable sets, i.e. $s$ is of the form
$$
s(x)=\sum_{i=1}^mc_i\chi_{A_i}(x)\ .
$$
Let us suppose that $f(x)=\frac 1x$ for concreteness. In your proposed example, $f_n$ would have to be an infinite sum of $c_i\chi_{A_i}$ since $f$ is unbounded. This is the reason why your constructed $f_n$ fails to be a simple function. The boundedness  of $f$ is indeed indispensable.


text:
Q: Providing SQL query access to visitors on a rails app I want to provide the ability to query the underlying mysql db on a rails-powered site to visitor on the web. The most transparent way seems to be able to take the text in a textbox and pass it to an sql connection.
However, I'd want to hide the user/password details and only make certain content tables available. Also, I only want to provide read access. Is there a convenient way to do this? It would be better if there were convenient view helpers too. Any gems like this? Perhaps something similar to PHP's MyAdmin?

A: The solution to this is more about configuring your database rather than finding special code.
You need to create a user in your MySQL database and grant read-only privilege to a subset of tables of your choice. Use this user in your connection string for queries from your "raw" SQL page. This is the only place you'll have to change code and all it involves is using a different connection string from your other code.
Here's an object-specific example of granting read-only permissions to a user.
To help manage this issue on the server you could make use of a schema.


text:
Q: Method show Exception when extract a substring from a string in android I tried to convert String of UTC date to String of Current Date using method attached below.
Method throws Index out of bound Exception in mentioned line.

A: There is no ( character in your utcDate so indexOf() will return -1. Then you substring() from 0 index to -1 index. But the minimum index of character array inside String is 0. So it caused IndexOutOfBoundsException
See: String#substring(). In the document it says throws
IndexOutOfBoundsException if beginIndex is larger than endIndex.


text:
Q: Dynamdb issue with recognizing courses I'm suppose to create a table named Courses to hold attribute including Subject (e.g. SDEV), CatalogNbr (e.g. 400), Title (e.g. Secure Programming in the Cloud), NumCredits (e.g. 3), and a CourseID (e.g. 001). The CourseID should represent the Hash Key for the Courses table. Then provide a command line simple interface that allows a user to search for a title given the Subject and CatalogNbr. The search program should continue to loop until the user requests to exit. Also, if both Subject and CatalogNbr are not entered, the program should request the data be re-entered. My code is not recognizing the courses when they clearly exist. Apparently its somewhere within my search_title() part of the code and I can't figure it out.I've tried editing and adding the search_title() but to no avail.
Screen shot of code not recognizing course
My full code is below:
from __future__ import print_function

from boto3.dynamodb.conditions import Key, And
import boto3
import sys

dynamodb = boto3.resource('dynamodb')
table= dynamodb.Table('Courses')

def create_table():

        dynamodb = boto3.resource('dynamodb')

        table = dynamodb.create_table(
        TableName='Courses',
        KeySchema=[
            {
                'AttributeName': 'subject',
                'KeyType': 'HASH'  #Partition key
            },
            {
                'AttributeName': 'catalognbr',
                'KeyType': 'RANGE'  #Sort key
            }
        ],
            AttributeDefinitions=[
            {
                'AttributeName': 'subject',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'catalognbr',
                'AttributeType': 'N'
            }enter image description here
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 10,
            'WriteCapacityUnits': 10,
        }
    )

        print("Table status:", table.table_status)

def load_data():
    dynamodb = boto3.resource('dynamodb')

    courses = [[1, 'CMIS', '102', 'Inroduction to Problem Solving and Algorithm Design', '3'],
    [2, 'CMIS', '141', 'Inroductory Programming', '3'],
    [3, 'WRTG', '393', 'Advanced Technical Writing', '3'],
    [4, 'CMIS', '242', 'Intermediate Programming', '3'],
    [5, 'CMIS', '320', 'Relational Database Concepts and Applications', '3'],
    [6, 'SDEV', '300', 'Building Secure Python Applications', '3'],
    [7, 'SDEV', '350', 'Database Security', '3'],
    [8, 'SDEV', '360', 'Secure Software Engineering', '3'],
    [9, 'SDEV', '325', 'Detecting Software Vulnerabilities', '3'],
    [10, 'WRTG', '394', 'Advanced Business Writing', '3']]

    for course in courses:
        courseid = course[0]
        subject = course[1]
        catalognbr = course[2]
        title = course[3]
        numcredits = course[4]

        table.put_item(
           Item={
               'CourseID': courseid,
               'Subject': subject,
               'CatalogNbr': catalognbr,
               'Title': title,
               'NumCredits': numcredits,
            }
        )
        return courses

def get_subject():
    dynamodb = boto3.resource('dynamodb')
    subject = ['SDEV', 'WRTG', 'CMIS']

    while True:
      if subject == 'SDEV' or subject == 'WRTG' or subject == 'CMIS':
          return subject

def get_catalognbr():
    dynamodb = boto3.resource('dynamodb')
    catalognbr = ''

    while True:
       if catalognbr == '':
           return catalognbr

def search_title(subject, catalognbr):

        subject = subject.upper()
        catalognbr = catalognbr.upper()

        filters = {
            'Subject': subject,
            'CatalogNbr': catalognbr
        }
        response = table.scan(
        FilterExpression=And(*[(Key('CatalogNbr').eq(catalognbr)) or And('Subject').eq(subject) for key, value in filters.items()]))

        if not response['Count']:
            print('No course found with the given Subject and Catalog Number')
            return None
        else:
            return response['Items'][0]['title']

def run_search():

    subject = input('Enter the Subject: ')
    catalognbr = input('Enter the CatalogNbr: ')

    if not subject or not catalognbr:
        print('Both Subject and CatalogNbr are required')
        return False

    title = search_title(subject, catalognbr)

    if title:
        print(f'The title of {subject} {catalognbr} is {title}')
    return True

def main():
    while True:
        if not run_search():
            break
        if input('Would you like to search for another title? (Y or N)').upper() != 'Y':
            break
    print('Thanks for using the Catalog Search program.')

if __name__ == '__main__':
    main()

A: Your partition key is: subject.
Your sort key is: catalognbr.
Your function parameters are therefore containing the items keys: search_title(subject, catalognbr), which means you should do a get_item not a Scan with a filter:
def search_title(subject, catalognbr):
    res = table.get_item(
        Key={
            'subject': subject,
            'catalognbr': catalognbr
        }
    )
    return(res)

res = search_title('WRTG', '393')

If you do change your use case to non-key attributes then your FilterExpression should look like this:
FilterExpression= reduce(And,([Key(key).eq(value) for key, value in filters.items()]))


text:
Q: PHP - sort multidimensional grouped arrays I'm trying to sort following array:
$myArray = array(
    "ID"    =>  array(
                    0,
                    5,
                    8,
                    12,
                    15
                ),
    "date"  =>  array(
                    1484391600,
                    1483910300,
                    1484920000,
                    1482393630,
                    1484391600
                ),
    "name"  =>  array(
                    "Pete",
                    "Max",
                    "Tom",
                    "June",
                    "Arend"
                ),
);

I want to be able to choose which subarray is sorted and in which way (numeric / string) and order (DESC / ASC). All the other subarrays should be sorted accordingly.
Here is some code that worked at first, but when the subarray to sort contained an empty string, it failed: All subarrays where sorted differently.
$sortCatArray = $myArray['name'];

foreach($myArray as $category => $value){
    $keepOrigin = $sortCatArray;
    array_multisort($keepOrigin, SORT_DESC, SORT_STRING, $myArray[$category]);
}

var_dump($myArray);

Can someone point out what I'm doing wrong.
Also I don't want to rearrange the arrays to match the other sorting solutions as I need the values in the given format.


text:
Q: Variável com ponteiro é declarada nula, porém função membro executa normalmente Abaixo segue um exemplo do código que eu estou tentando executar.
//main.cpp

#include <iostream>

using namespace std;

class A{
public:
    A(){}
    ~A(){}
    void teste(){
        cout << "Teste" << endl;
    }
};

int main(){
    A *pA = NULL;

    pA->teste();
    return 0;
}

//end main.cpp

Uma vez que declaro o ponteiro *pA como nulo, esperava que o programa desse erro. Porém, o mesmo executa o normalmente e exibe a mensagem "Teste".
Por que o programa executa normalmente em vez de lançar um erro to tipo null pointer exception?
Estou utilizando a plataforma Qt5 no Linux.

A: Por que você acha que deveria dar uma exceção?
O ponteiro é necessário para referenciar-se para uma estrutura de dados, ou seja, para um estado, para dados na memória. Para acessar o comportamento da classe, ou seja, os seus métodos. o ponteiro não precisa referenciando para nenhuma posição da memória. Pelo tipo o compilador sabe onde está o código dos métodos que são independentes da instância.
O código fica em uma área estática (fixa) na memória e o progressivamente o compilador, com o linkador, e depois a carga do executável pelo sistema operacional determinarão o endereço do código. Os métodos estão disponíveis sempre na aplicação, mesmo que você não tenha criado uma instância válida.
Ainda assim poderia gerar uma exceção dentro do método se ele estivesse tentando acessar algum estado da classe. Mas neste caso não está, então não tem porque dar erro.
O que você está mandando fazer é chamar o método teste() do tipo A que por acaso está sendo referenciado pela variável pA mas como a classe não tem dados, nada precisa ser armazenado na memória para sua execução. Se nada precisa ser armazenado, não precisa ter nenhum endereço de memória para referenciar-se, então um NULL cai bem. E como durante a execução do método você apenas faz acesso a um stream enviando um literal string e o fim de linha, não acessa dado algum da instância (e nem poderia, já que não existe), não precisa acessar nada na memória, não precisa de um endereço válido na variável.
Então o ocorrido é o lógico. Seria estranho que uma exceção fosse lançada. Experimente criar um campo com estado na classe e acessá-lo no teste() ou diretamente no main() e veja o que acontece.
Em C++ não há necessidade e não é recomendado criar classes sem estado, prefira utilizar funções simples e se precisar organizar funções relacionadas em uma única unidade lógica use namespace. C++ não é Java.
Não esqueça de ler o complemento no comentário do Guilherme Bernal abaixo sobre comportamento indefinido que é altamente indesejável (o comportamento, não o comentário do Guilherme :) ). Ele é muito importante.


text:
Q: How do you set the text of a label to an array value? I would like to set a value of my array to a label.
Array declaration:
//
//  ViewController.h
//  Cornell Notes
//
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

    NSString *details[8][8];
    NSString *subtitles[8];
}

I am not allowed to do:
self.label.text = subtitles[0];

How can I do this?

A: This:
@interface ViewController : UIViewController{

    NSString *details[8][8];
    NSString *subtitles[8];
}

Should Be:
@interface ViewController : UIViewController

@property (strong, nonatomic) NSMutableArray *details;
@property (strong, nonatomic) NSMutableArray *subtitles;

You could declare it similar to the way you had it, but I believe this is the preferred current syntax.  Others may correct me on this.  Most important is that we declare NSMutableArray's as opposed to NSString's.  You are doing C-style declarations, which will be a bit different with these.  I chose NSMutableArray as opposed to NSArray because it looks like you want to be able to add objects at runtime.
And this:
self.label.text = subtitles[0];

should be:
if (!_subtitles) _subtitles = [NSMutableArray new];
[_subtitles insertObject:self.label.text atIndex:0];

This line:
if (!_subtitles) _subtitles = [NSMutableArray new];

Is just to make sure that our _subtitles dictionary exists, and if it does, we make sure that it isn't overwritten.  the [NSMutableArray new] syntax is something that I personally like because it looks clean; however, many prefer [[NSMutableArray alloc]init].  Just so you're aware.


text:
Q: Discord Python Rewrite - Custom Server Prefixes Error I tried these code
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
    prefixes = json.load(float)

    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix)

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(float)

    prefixes[str(guild.id)] = ','

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, float, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes.json', 'w') as float:
        json.dump(prefixes, float, indent=4)

@client.command()
@commands.has_permissions(manage_channels=True)
async def prefix(ctx, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

    await ctx.send(f'Prefix changed succesfully, now my prefix for this server is: "{prefix}"')

and i got these erors

Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", >line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 943, in on_message
await self.process_commands(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in process_commands
ctx = await self.get_context(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 853, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 798, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line >331, in maybe_coroutine
value = f(*args, **kwargs)
File "C:\Users\PC\Desktop\Code\Project 01\index.py", line 20, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '744103149471662152'

Please help, it was working a few weeks ago.

A: The server ID is not in the JSON File
Add it manually OR Kick the bot from that server and re-invite it again

A: Ok. First, you are running json.loads(float). Float is a function, not the file. I edited the code you posted, try using this:
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)

    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix)

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = ','

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.command()
@commands.has_permissions(manage_channels=True)
async def prefix(ctx, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

    await ctx.send(f'Prefix changed successfully, now my prefix for this server is: "{prefix}"')

(I also fixed some spelling errors in your messages)
If that still gives you the error, kick the bot and re-invite. Should work then.

A: def get_prefix(client, message):
    with open('./database/prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

you did right load float instead of writing f
and check if the server id in the json file
try edit it manual or kick the bot and invite it again

A: Uhh your code may be right but just use f instead of float
But IG the problem is that you have not put {} in your JSON file so it is not taking that input.


text:
Q: Add onclick event on treeview Nodes and Child Node using Jquery i have an ASP tree view having a Node

so now, i have to add a click event on NODE (i.e Accomodations) that is different from the click event on Child Node(i.e Blue Parrot INN etc.)
How i achieve this??
any help will greatly appreciated...
NOTE: I want to achieve this using jquery

A: I add CSSclass on Root, Parent and Leaf Node like
    RootNodeStyle-CssClass="RootNodeStyle"
    ParentNodeStyle-CssClass="ParentNodeStyle"
    LeafNodeStyle-CssClass="LeafNodeStyle"

and then in js i write jquery as follow
   $("RootNodeStyle").click(function(){
        alert("Root Node is click");
   });

   $("ParentNodeStyle").click(function(){
        alert("Parent Node is click");
   });

   $("LeafNodeStyle").click(function(){
        alert("Leaf Node is click");
   });

This way i achieved what i want to get.... :)

A: ASP.NET assigns some predictable client id's to the nodes. Using these client id's, you can assign click event with jquery.
$(document).ready(function () {
    $("#id_of_your_node_in_html_page").click(function () {
        //do something
    });
});

More to say:
So how to get the client id of the node? Let's say your tree view has server id as my_tree. Then client id of the nodes will be like the following:
Accomodations     my_treet0
    PIER HOUSE... my_treet1
    BLUE PARROT.. my_treet2
    ISLAND CITY.. my_treet3
Hotels            my_treet4
    COUNTRY...... my_treet5

Note the t and the increasing number. However this method is not reliable. Once you add or remove one child node, client id of subsequent nodes will change.
Alternative:
Here is a more reliable method for getting client id. Instead of Accomodations, write Accomodations for the text property of the node. Then you can use nodeAccomodations as client id.


text:
Q: Crystal Report weird error (Unknown Query Engine Error) I have a Windows application that uses Crystal Reports 2008 as a reporting tool. It was working fine for a very long period, but yesterday, when I tried to load any report, I got this error:
CrystalDecisions.CrystalReports.Engine.DataSourceException: Unknown Query Engine Error
Error in File C:\Users\Magdy\AppData\Local\Temp\rpt_Stock_Cost {DC276D4F-79F4-43B9-8168-24E6B7BF490A}.rpt:
Unknown Query Engine Error ---> System.Runtime.InteropServices.COMException: Unknown Query Engine Error
Error in File C:\Users\Magdy\AppData\Local\Temp\rpt_Stock_Cost {DC276D4F-79F4-43B9-8168-24E6B7BF490A}.rpt:
Unknown Query Engine Error
   at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
   at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
   --- End of inner exception stack trace ---
   at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet dataSet)
   at Diamonds.UIL.Forms.frm_ReportViewer.Load_Report(String File_FullPath, DataSet DS) in E:\Development\Bitco\Diamond\Project\Diamond 2.0.1\Diamonds\UIL\Reports\Forms\Viewer\frm_ReportViewer.cs:line 256

Here's the code I used to load and assign data source for the report:
DataSet ds = new DataSet();
reportDocument_.Load(File_FullPath);
reportDocument_.SetDataSource(ds);

Where ds could be a typed dataset.
After some googling, I found some results that say I should have Network Services, user to temp folder in windows. Although I think this is for web applications, not for windows. I tried it for both temp folder, and the above folder in the exception, but neither helped.
I'm using Visual Studio 2010, C# 4.0, Windows Application
Any ideas what could be wrong?

A: If you compile in VS2010 (or VS2012) on a Win7 machine, try adding the following to the app.config:
<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

If that doesn't work (like on my machine), try compiling in VS2010 on WinXP machine.


text:
Q: Models for Long-Term Time-Series Forecasting and Pattern Recognition I'm trying to find a solution for long-term electricity hourly prices forecasting. Explaining simply, I have some data from 2018 - 2021 containing Demand, Renewable Generation, Hydropower Generation, System Losses, Energy Exchange, and Electricity Prices for each Energy Submarket (all this in hourly format). What I want to answer is: is possible to create a model to predict the prices for long-term or mid-term forecasting that identify the correlation on the Data?
For example, if I increase the Renewable Generation over the next ten years and maintain the other input variables as it is, what's the electricity hourly price?
Is there any model that can identify, learn, and understand the data pattern and achieve this prediction? I had looked into LSTM and RNNs but sounds like that they are used in short-term forecasting.


text:
Q: Mongo query keys order Mongo query parse: sorting key based on alphabetical order is there any solution to consider based on user input?
Example :
db.user.explain().find({name: 'test user', active: true})

In the above query, mongo will parse the query to
"$and" : [
    {
        "active" : {
            "$eq" : true
        }
    },
    {
        "name" : {
            "$eq" : "test user"
        }
    }
]

while parsing mongo considering "active" key first and "name"
I want the query should look for "name" key first and "active" like
"$and" : [
    {
        "name" : {
            "$eq" : "test user"
        }
    },
    {
        "active" : {
            "$eq" : true
        }
    },
]

is there any setting/config?

A: As you have noticed parsedQuery in explain() will show you the fields in alphabetical order , but this order is not important in case there is no suitable index to be used since all documents will be loaded from the storage to memory and evaluated , so even you rename the fields to "aname" and "nactive" the execution times will be same if you dont have index  , this is why it is important to create index and the order of your searched fields to coincide with the fields order in your index , for better performance in your case you may create index on:
      {name:1}

or
     {name:1, active:1}

But since the field "active" looks like a boolean value with very low selectivity it may not add too much difference during the search unless it is a "covered query" e.g. db.test.find({name:"Test",active:true},{name:1,_id:0})
and search happen only in memory.
Remember:
Reading from disk to memory is much more expensive then searching in memory so even your keys are intentionally renamed to satisfy the alphabetical order there will be no benefit if you dont create index and the mongod process perform COLLSCAN on the full collection.


text:
Q: JavaFX and Spring - Reusable FXML component I am building a GUI with Scene Builder in JavaFX and Spring Boot. Several of my scenes have one element in common, which is a simple KPI indicator, called PerformanceBeacon. Depending on the configuration, done by the controller class, the beacon can be used e.g. for project parameters like budget, time and so one. Ideally, even a single scene may have multiple of this elements.
The issue is, having multiple KPI beacons in a single scene does somehow not work, since all embedded controllers are pointing to the same memory and hence, I can only manipulate one - which is the last - KPI beacon.
The snipped from the fxml file looks like this:
...
<VBox layoutX="301.0" layoutY="325.0" spacing="6.0" AnchorPane.leftAnchor="2.0" AnchorPane.topAnchor="24.0">
      <children>
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedTimeKPI" />
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedBudgetKPI"/>
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedResourcesKPI"/>
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedScopeKPI"/>
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedEffortKPI"/>
               <fx:include source="PerformanceBeacon.fxml" fx:id="embeddedQualityKPI"/>
      </children>
</VBox>
...

The embedded controllers are defined in the controller class of the enclosing UI and the code should "only" set the label of each of the Hyperlinks in each PerformanceBeacon.
@Controller
public class ProductManagerCtrl implements Initializable {
 ...
 @FXML protected PerformanceBeaconCtrl embeddedTimeKPIController;
 @FXML protected PerformanceBeaconCtrl embeddedBudgetKPIController;
 @FXML protected PerformanceBeaconCtrl embeddedResourcesKPIController;
 @FXML protected PerformanceBeaconCtrl embeddedScopeKPIController;
 @FXML protected PerformanceBeaconCtrl embeddedEffortKPIController;
 @FXML protected PerformanceBeaconCtrl embeddedQualityKPIController;

 ...

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {

        ...
        initializePerformanceIndicator();
        ...
     }

    protected void initializePerformanceIndicator() {
        embeddedBudgetKPIController.setHyperlink("Budget", null);
        embeddedScopeKPIController.setHyperlink("Scope", null);
        embeddedTimeKPIController.setHyperlink("Time", null);
        embeddedQualityKPIController.setHyperlink("Quality", null);
        embeddedResourcesKPIController.setHyperlink("Resources", null);
        embeddedEffortKPIController.setHyperlink("Effort estimates", null);
    }

When I debug the code, each of these embedded controllers points to the same memory. So effectively I have one controller and can only manipulate the last element. In the end the last beacon has the "Effort estimates" label and all others are unchanged.
The PerformanceBeacon.fxml is rather simple. I copy it, in case you want to try yourself
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.Double?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Hyperlink?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.shape.Circle?>
<?import javafx.scene.shape.Polygon?>

<GridPane styleClass="pane" stylesheets="@../stylesheets/PerformanceBeacon.css" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.agiletunes.productmanager.controllers.PerformanceBeaconCtrl">
   <children>
      <Circle fx:id="beacon" fill="#1fff4d" radius="10.0" stroke="BLACK" strokeType="INSIDE" GridPane.columnIndex="1" GridPane.valignment="CENTER">
         <GridPane.margin>
            <Insets bottom="12.0" left="12.0" right="6.0" top="12.0" />
         </GridPane.margin>
      </Circle>
      <Polygon fx:id="trendArrow" fill="#11ff1c" rotate="45.0" stroke="#2e229a" strokeType="INSIDE" GridPane.columnIndex="2" GridPane.valignment="CENTER">
        <points>
          <Double fx:value="-10.0" />
          <Double fx:value="10.0" />
          <Double fx:value="-5.0" />
          <Double fx:value="10.0" />
          <Double fx:value="-5.0" />
          <Double fx:value="15.0" />
          <Double fx:value="5.0" />
          <Double fx:value="15.0" />
          <Double fx:value="5.0" />
          <Double fx:value="10.0" />
          <Double fx:value="10.0" />
          <Double fx:value="10.0" />
          <Double fx:value="0.0" />
          <Double fx:value="-10.0" />
        </points>
         <GridPane.margin>
            <Insets bottom="12.0" left="12.0" right="12.0" top="12.0" />
         </GridPane.margin>
      </Polygon>
      <Hyperlink fx:id="hyperlink" onAction="#showDetails" text="Subject">
         <GridPane.margin>
            <Insets left="24.0" />
         </GridPane.margin>
      </Hyperlink>
   </children>
   <columnConstraints>
      <ColumnConstraints hgrow="ALWAYS" maxWidth="1.7976931348623157E308" minWidth="170.0" />
      <ColumnConstraints minWidth="10.0" />
      <ColumnConstraints minWidth="10.0" />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints />
   </rowConstraints>
</GridPane>

And last but not least the Controller of the PerformanceBeacon
@Controller
public class PerformanceBeaconCtrl {

    @FXML   protected Circle beacon;
    @FXML   private Polygon trendArrow;
    @FXML   private Hyperlink hyperlink;

    @FXML
    public void showDetails(ActionEvent event) {
        // TODO
    }

    public void setHyperlink(String label, URL url) {
        Platform.runLater(() -> {
            hyperlink.setText(label);
        });
    }

    public void setBeaconColor(Color color) {
        Platform.runLater(() -> {
            beacon.setFill(color);
        });
    }

    public void setTrend(Double angle) {
        Platform.runLater(() -> {
            trendArrow.rotateProperty().set(angle);
        });
    }

}

I am successfully using embedded UI elements / controller also elsewhere in my code. But never the same element multiple times.
I am not sure whether this is a Spring side effect?
What am I doing wrong? Thank you in advance.

A: The described observation suggests that the issue was related to a singleton somewhere in the design. My suspicion regarding the Spring influence was right. The ProductManagerCtrl controller class gets created using
fxmlLoader.setControllerFactory(c -> ProdMgrApp.springContext.getBean(c));

and as it turns out, this approach creates singletons by default. Therefore all embedded controller are also singletons. The way to fix it is to annotate the PerformanceBeaconCtrl controller class also with
@Scope("prototype")


text:
Q: Get Tweets from Angularjs I'am trying to get tweets from a twitter acount but only using angularjs, whitout php or another language.
I have tried but I couldn't. and also I have to use the 1.1 twitter api

A:
1.We don't support or recommend performing OAuth directly through
Javascript -- it's insecure and puts your application at risk. The
only acceptable way to perform it is if you kept all keys and secrets
server-side, computed the OAuth signatures and parameters server side,
then issued the request client-side from the server-generated OAuth
values.
2.The OAuth access token will need to be part of the call and
the oauth_token_secret will need to be used to compute the signature
3.No

from Twitter Dev site


text:
Q: Why the images doesn't show on my website? I dont know why django doesn't find my images
When I go to my home page list images i want to see the images for user thumnbails and original
But the html can't find this
And maybe someone will know how can i show only fields what the user create not all users but the one user
views.py
def image_list(request):
images = Image.objects.all()
context = {'images': images}
return render(request, 'imagelist.html', context)

@login_required
def add_image(request):

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            profile = request.user.profile
            image = form.save(commit=False)
            image.user = profile
            image.save()
            return redirect('images')

    else:
        form = ImageForm()
    return render(request, 'add_image.html', {'form': form})

models.py
class Profile(models.Model):
    TIERS = (
        ('basic', 'Basic'),
        ('premium', 'Premium'),
        ('enterprise', 'Enterprise'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    tier = models.CharField(max_length=10, choices=TIERS,
                            default='basic', blank=True,
                            null=True)

class Image(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='images/', null=True, blank=True)
    thumbnail_200 = models.ImageField(upload_to='images/thumbnails/200/', null=True, blank=True)
    thumbnail_400 = models.ImageField(upload_to='images/thumbnails/400/', null=True, blank=True)

    def save(self, *args, **kwargs):
        # Create appropriate thumbnails for the user's tier
        if self.image and not self.thumbnail_200:
            self.create_thumbnail_200()
        if self.image and not self.thumbnail_400 and self.user.tier in ['premium', 'enterprise']:
            self.create_thumbnail_400()
        super().save(*args, **kwargs)

    def create_thumbnail_200(self):
        im = PILImage.open(self.image)
        output_size = (200, 200)
        im.thumbnail(output_size)
        thumbnail_io = BytesIO()
        im.save(thumbnail_io, 'JPEG', quality=85)
        thumbnail_io.seek(0)
        self.thumbnail_200.save(self.image.name, ContentFile(thumbnail_io.read()), save=False)

    def create_thumbnail_400(self):
        im = PILImage.open(self.image)
        output_size = (400, 400)
        im.thumbnail(output_size)
        thumbnail_io = BytesIO()
        im.save(thumbnail_io, 'JPEG', quality=85)
        thumbnail_io.seek(0)
        self.thumbnail_400.save(self.image.name, ContentFile(thumbnail_io.read()), save=False)

    def __str__(self):
        return self.image.name

urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.image_list, name='images'),
    path('addimage/', views.add_image, name='add_image'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                        document_root=settings.MEDIA_ROOT)

html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Image List</title>

Image List

        {% for image in images %}

        {% endfor%}

If you want something more i can show more


text:
Q: Is there another instruction similar to MOVZX, but supported on the 8086? Im trying to find an instruction that will replace MOVZX, since I'm using EMU8086 (which emulates an 8086 that does not support MOVZX).
The closest instruction I found was CBW, which puts the value in the register AX, but it's for signed values only. I need something that will work for unsigned values.
What are my options? Is it possible to do it with a single instruction?

A: The movzx instruction zero-extends a value with a smaller width to fit into a larger-width register. For example, movzx would be used to move a 16-bit value into a 32-bit register. (It is contrast to movsx, which does the same thing except with sign extension. You would use movzx when the value is unsigned, and movsx when the value is signed.)
As you point out, these instructions were not introduced until the 386, so if you're targeting an earlier generation of processor, then you'll need to find an alternative.

The basic strategy is, as others pointed out in the comments, to zero the destination register first, and then move the smaller value in. This will accomplish exactly the same thing as movzx. The obvious way to zero a register is with mov  reg, 0, but it is smaller and faster to do it using xor  reg, reg. Therefore, code like:
movzx  edx, WORD PTR [bx]

can be replaced with:
xor    edx, edx
mov    dx,  WORD PTR [bx]

On modern processors, this is slower than movzx, but it will actually be faster on the 386 and 486, where movzx is relatively slow. And of course, on processors where movzx doesn't exist, you have no choice. You can further minimize the cost by issuing the xor instruction earlier, interspersing it amongst other code.

One significant disadvantage of this approach is that you cannot do an in-place zero-extension on a value stored in a register. That is, there is no way to use this trick when you have code like:
movzx  edx, dx

Instead, you would have to use a temporary register:
xor  eax, eax
mov  ax,  dx
mov  dx,  ax    ; optional, if you really needed the result to be in DX

Or, if you were zero-extending an 8-bit value, you could take advantage of the fact that the upper and lower 8-bit halves of a 16-bit register can be accessed independently on x86, and simply zero the upper 8 bits. For example:
mov    al, BYTE PTR [bx]
xor    ah, ah
; now read from value in AX

Note that this works for in-place zero-extension—just zero the high 8 bits. However, this technique cannot be used to zero-extend a 16-bit value, since there is no way to access just the upper 16 bits of a 32-bit register.

Fortunately, the need for zero-extension on these older architectures is much less than it is on modern architectures, since you don't have to guard as vigorously against partial-register stalls and false dependencies.

In comments, the concern was raised that all of the alternatives to movzx require more than one instruction. Of course, that is true. If there were a way to do it in a single instruction, there wouldn't have been a need for the 386 to introduce movzx. If you're worried about execution speed, consider what I said above that xor+mov will be equally as fast as movzx would have been if it were available, if not faster.

If you're worried about number of instructions, then rest assured that less code does not necessarily mean faster code. In fact, in many cases, adding additional instructions can make your program execute faster. If you are trying to optimize a particular chunk of code, I encourage you to ask a question about it either here or on Code Review (we need more assembly language questions there!).


text:
Q: DNS resolving is slow only when using cURL to fetch data I have domain 'engine02.prod.qc.offercal.com' in my local bind9.
I don't think it's DNS server or TTL issue, because the benchmark is almost always look like this (I tried for 2 minutes using each method) :
curl -o /dev/null http://engine02.prod.qc.offercal.com:49157/void

        time_namelookup:  0.150
           time_connect:  0.151
     time_starttransfer:  0.152
                        ----------
             time_total:  0.152

curl -o /dev/null http://192.168.100.10:49157/void # use IP directly

                  time_namelookup:  0.000
           time_connect:  0.002
     time_starttransfer:  0.003
                        ----------
             time_total:  0.003

time dig @192.168.100.4 engine02.prod.qc.offercal.com

        real 0m0.009s
        user 0m0.004s
        sys  0m0.004s

time host engine02.prod.qc.offercal.com

        engine02.prod.qc.offercal.com has address 192.168.100.10
        real    0m0.011s
        user    0m0.006s
        sys     0m0.004s

My resolv.conf file:
[root@gateway01 ~]# cat /etc/resolv.conf
nameserver 192.168.100.4

I have been struggled with this issue for sometime, please help :D

A: I just hit this issue recently while building updown.io and investigated it a bit (thanks @Dan for the strace command). Here is what I found:
Condition
In my case curl was sometimes taking 65ms to resolve and sometimes <5ms.
It seemed to take 65ms after short time of inactivity (couple minutes) and <5ms after repeated calls. Definitely sounds like a cache and TTL issue obviously.
But my record has a 86400s TTL (1day) and it was already cached on my local resolver and dig always took 1ms.
Measures
So I tried running curl with strace to see where the time was spend, and this is what I found (stripped some details for clarity):
05:57:52.303 connect(3) = 0
05:57:52.303 sendmmsg(3, ["1\26\1\0\0\1\0\0\0\0\0\0\22jarthon-architecte\3"..., "\0253\1\0\0\1\0\0\0\0\0\0\22jarthon-architecte\3"...] , 2) = 2
05:57:52.303 poll([{fd=3, events=POLLIN}], 1, 5000) = 1
05:57:52.303 ioctl(3, FIONREAD, [56]) = 0
05:57:52.303 recvfrom(3, "1\26\201\200\0\1\0\1\0\0\0\0\22jarthon-architecte\3"...) = 56
05:57:52.304 poll([{fd=3, events=POLLIN}], 1, 4999) = 1
05:57:52.373 ioctl(3, FIONREAD, [96]) = 0
05:57:52.373 recvfrom(3, "\0253\201\200\0\1\0\0\0\1\0\0\22jarthon-architecte\3"...) = 96
05:57:52.373 close(3) = 0

This is DNS resolution part, what we can clearly see here is that 2 messages a sent, one response is received pretty quickly, and another one is received after a 69ms delay. I thought this second response is probably the IPv6 query (AAAA) so I tried it in dig:
$ dig AAAA jarthon-architecte.com

;; AUTHORITY SECTION:
jarthon-architecte.com. 180 IN  SOA ns0.dnsmadeeasy.com. dns.dnsmadeeasy.com. 2008010120 43200 3600 1209600 180

;; Query time: 86 msec
;; SERVER: ::1#53(::1)

Ok there's no answer obviously, but this SOA record has a 180s TTL, this looks very like the time it took to go from 5ms to 65ms in my curl tests.
Explanation
The SOA record is returned by your DNS server when there's no answer and contains among other things the negative TTL (last number on the line you can see 180) which is the time any resolver is allowed to cache negative responses (absence of record). So this means that when you query for the AAAA record, you have to hit the DNS server at least every 3 minutes just to make sure it's still not there.
Fix

*

*Add an IPv6 ☺

*If you're managing the DNS the easiest fix is to increase this value, in my case I'm using DNSMadeEasy, I can create a custom SOA record with a higher TTL value and assign it to my domains: http://help.dnsmadeeasy.com/managed-dns/records/soa-start-authority-record/. This will make curl resolve faster most of the time, back to the level of performance we have on our properly cached A record.

*If you're the one making the curls but don't manage the DNS, there are probably ways to optimize this at the DNS resolver level by serving stale negative response while fetching the real values or things like that, but I haven't looked into that yet.

*If you're don't care about IPv6 you can also disable it using curl command line flag -4

A: If this is a newer version of debian (namely ubuntu 13+) you need to have your dns-nameservers appended to the end of /etc/network/interfaces after your static ip config.  Editing resolv.conf will only bring you grief on these flavors of linux.
ie.
after gateway line
dns-nameservers local.dns.ip.here outside.back.ip.here


text:
Q: How to generate the certificate and key for HTTP/2 in Node.js I have a node.js application. I'm using http and it works. But I want to use http2 for my application. I have installed the module from npm:
npm install http2

And I use it like this: ( app variable is defined, my application works with HTTP perfectly.)
var http2 =require('http2') ;
var server=http2.createServer(app);

But this does not work and  I get "could not get any response" error from POSTMAN.
When I write var http2= require('http') , this is working without any problem.
I looked at Http/2 documentation here: https://nodejs.org/api/http2.html#http2_server_side_example
And There is something written here that i dont understand:
To generate the certificate and key for this example, run:

 openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
  -keyout localhost-privkey.pem -out localhost-cert.pem

Where will I write these codes and run? I could not find.

A: you'll need to run this command in a Terminal, so on Windows that could be powershell, Konsole or Terminal on Linux or MacOS. You might have to install openssl with your operating systems package manager. I would suggest googling:
"Install openssl $your_os_here"
and then it will generate some files you can use from within your node code


text:
Q: Calling list() empties my iterable object? a = range(1, 3)
a = iter(a)
list(a)
a = list(a)

a evaluates to [ ].
a = range(1, 3)
a = iter(a)
a = list(a)

a evaluates to [1, 2].
The first result is unexpected to me. What semantics are going on here?

A: Let's examine what happens:
>>> a = range(1, 3)
>>> a is iter(a)
False

as you can see, iter gives a new iterator object, which is not a itself
>>>> a = iter(a)

the name a now corresponds to the distinct iterator object iter gave us (just as if iter(a) had returned itself, e.g. as it happens with zip and with files)
>>> list(a)
[1, 2]

exhausts the iterator, therefore
>>> list(a)
[]

gives nothing as the iterator has been used (iterated on) already
Here are a few more experiments you can try to fully grasp what happens:
>>> a = range(1, 3)
>>> a
range(1, 3)
>>> type(a)
<class 'range'>
>>> b = iter(a)
>>> b
<range_iterator object at 0x7f331a6d96c0>
>>> type(b)
<class 'range_iterator'>
>>> a is b
False
>>> list(b)
[1, 2]
>>> list(b)
[]
>>> list(a)
[1, 2]
>>> list(a)
[1, 2]
>>> a
range(1, 3)
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'range' object is not an iterator
>>> b=iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> z=zip(a,b)
>>> iter(z) is z
True
>>> with open('words.txt') as f:
...  iter(f) is f
...
True

Note: on Python 2 quite a few functions return lists instead of iterators (e.g. zip)

A: a = iter(a)
list(a)
^^^^^^^

Means convert an iterator to a list, and don't save the output. However, a  iterator can only produce the output once. After you read it it'll become empty.
And if you try next() here, you can also see what's happening:
>>> next(a)
1

>>> next(a)
2

>>> next(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

>>> list(a)
[]

From the document:

An object representing a stream of data. Repeated calls to the iterator's __next__() method (or passing it to the built-in function next()) return successive items in the stream.
When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again.

A: The issue is not list() but iter() which as documented returns a single-use iterator.  Once something has accessed the iterator's elements, the iterator is permanently empty. The more commonly used iterable type is (normally) reusable, and the two types shouldn't be confused.
Note that you don't need iter() in order to turn a range into a list, because list() takes an iterable as an argument:
>>> a = range(1, 3)
>>> list(a)
[1, 2]
>>> list(a)
[1, 2]

And it is only the iterator returned by iter() that is single-use:
>>> b = iter(a)
>>> list(b)
[1, 2]
>>> list(b)
[]
>>> list(a)
[1, 2]

A: Creating a list from an iterator consumes the iterator. Simply spoken, its elements are created when needed and the content of the iterator is empty after you iterated over it. If you ever want another copy of an iterator, for example for creating a list, you can use itertools.tee.
>>> from itertools import tee
>>> it1, it2 = tee(range(1,3))
>>> lst = list(it1)
>>> lst
[1, 2]
>>> for x in it2:
...     print(x)
...
1
2
>>> list(it2) # it2 is now exhausted
[]

A: list(thing) means iterate all the items from thing (as for item in thing would do), and save all of the items in a new list.
iter(thing) means get an "iterator" for thing; an iterator is basically a marker in a stream of data items remembering where you're up to, than can be used to get the next item from the stream (advancing the "marker" as a side effect). It explicitly does not have any way of resetting the marker back to the start to repeat the iteration; this is so that it can support iteration of things that inherently cannot be iterated multiple times.
Iterating all the items from thing (as for item in thing) gets an iterator for thing, and then uses the iterator to retrieve all of the items from the thing. So if you do this:
a = range(1, 3)
for x in a:
    print x
for x in a:
    print x

The for loop creates a new iterator for a (which starts with the marker at the start of the range), then pulls items from the iterator until it runs off the end of the range. The range object itself is untouched, so the second for loop can create a new iterator (starting at the start again) and iterate it again.
But here:
a = range(1, 3)
a = iter(a)
for x in a:
    print x
for x in a:
    print x

You're not letting the for loop create an iterator for the range, instead you're doing it explicitly, and only once. When the for loop goes to create an iterator from a the iterator it gets is just a itself (iter(i) when i is an iterator is always required to return i). So the for loop pulls items from a, advancing the marker each time, until the marker is "off the end" of the range object.
Then the second for loop makes an iterator from the iterator a, and again gets a itself. It then pulls items from that iterator until it runs out; which it can do zero times because a is already "off the end".
So it's actually nothing to do with your list calls directly, it's just how iterator objects that you get with iter behave. Ordinarily you don't use iter very much, because the things you use to iterate collections (for loops, list(), etc) already handle the creation of iterators for you. You would only use iter when you're doing something complicated involving partially consuming an iterator, and then consuming more items starting from where the first partial iteration left off.

A: iter() returns an iterator, and calling list() a second time on it returns an empty sequence.
>>> a = iter(range(1,3))
>>> list(a)
[1, 2]
>>> list(a)
[]

Docs about iterable:

When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values.

Docs about iterator:

A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.


text:
Q: How to fix random erroneous behaviour of application windows when using compiz? I am not sure whether you have faced this. Since we have switched to compiz as the window manager, the application windows show the following erratic behaviour at irregular basis  for both of my machines (different brands, different monitors, both running regularly upgraded versions of Ubuntu),

*

*The windows once minimized and then maximized, move from one workspace to another.

*Sometimes I loose a window, it can not be found in any of the workspaces. I have searched each and everyone of them.

*Some application windows, once minimized and them maximized, change in size, mostly becoming larger.

*Sometimes, when I try to move one window from one workspace to another using built-in workspace switcher, by click and drag, the window will go to all the workspaces except one random one.

At first I thought that the workspace switcher (not built-in) was to blame. Previously, I used docky, now I use Avant Window Navigator, without any appreciable improvement in this regard.
The problem is, the problem is regenerateable, but only on a random basis.
I use 2 X 4 (R X C) workspaces.
Hope somebody can suggest me something.

A: You can use the Compiz Config Settings Manager (CCSM) and try to fix this behavior.
If you haven't installed , install it from Ubuntu-Software-Center. Search for: compizconfig.
You can call it from Dash writing : compizconfig
Although this program is dangerous and needs to be careful when you use it , will allow you to fix such behaviors.
Following is an example that may fix your problem.

Change the algorithm to smart (or any other that meet your needs)

Thanks


text:
Q: Understanding metaclasses in Python I am trying to get my head around metaclass but i still can't really get the concept of it.
For all i know:
Any class is itself an instance of type "type" - therefore "calling" a class just calls the method __call__ on its class - which happens to be type's __call__. The effect of type.__call__ is exactly: on code like:
class A:
    pass
b = A()
The sequence of steps i know here is:
1.type.__call__ receives the class A itself as its first parameter.

*It calls the A.__new__ - in pseudocode we could write instance = A.__new__(cls) as what runs.

3.That returns an instance of the "A" class
4.Then it calls __init__ on the instance(instance.__init__())
...and returns that instance return instance
But now consider the below code:
class MetaOne(type):
    def __new__(meta, classname, supers, classdict):
        print('In MetaOne.new:', meta, classname, supers, classdict, sep='\n...')
        return type.__new__(meta, classname, supers, classdict)

class Eggs:
    pass

print('making class')

class Spam(Eggs, metaclass=MetaOne):
    data = 1
    def meth(self, arg):
        return self.data + arg

print('making instance')
X = Spam()
print('data:', X.data, X.meth(2))

The output from this script is as follows:
making class
In MetaOne.new:
...<class '__main__.MetaOne'>
...Spam
...(<class '__main__.Eggs'>,)
...{'__qualname__': 'Spam', '__module__': '__main__', 'meth': <function Spam.met
h at 0x00000000010C1D08>, 'data': 1}
making instance
data: 1 3

So as per my understanding this is the sequence of steps:

*

*Since Spam is an instance of MetaOne, calling X = Spam() would try to call the __call__ method of MetaOne class which is not there .

*Since MetaOne inherits from type it would call the __call__ method of type class with Spam as the first argument.
After that the call lands up in the __new__ method of MetaOne class but it should contain Spam as the first param.
From where does meta argument of MetaOne class come into picture.
Please help me in my understanding.

A:
Since Spam is an instance of MetaOne, calling X = Spam() would try to
  call the __call__ method of MetaOne class which is not there .

That is the soruce of your confusion - the __call__ (or __new__ and __init__) of the metaclass is not called when you create ordinary instances of the class.
Also, since there is no __call__ method for MetaOne, the usual inheritance rules apply: the __call__ method on MetaOne's superclass is used (and it is type.__call__)
The metaclass' __new__ and __init__ methods are invoked when the class body itself is executed (as you can see in your example, the "print" in the metaclass' __new__ shows up before the "making instance" text).
When creating an instance of Span itself, the metaclass methods __new__  and __init__ are not called - the metaclass  __call__ is called - and it is that that executes the class's(Span's) __new__ and __init__. In other words: the metaclass __call__ is responsible for calling the "ordinary" class's __new__ and __init__.

Since MetaOne inherits from type it would call the call method of
  type class with Spam as the first argument.

And it does, but you made no print statements to "view" this happening:
class MyMeta(type):
    def __new__(metacls, name, bases, namespace):
        print("At meta __new__")
        return super().__new__(metacls, name, bases, namespace)
    def __call__(cls, *args, **kwd):
        print ("at meta __call__")
        return super().__call__(*args, **kwd)

def Egg(metaclass=MyMeta):
    def __new__(cls):
        print("at class __new__")

If I paste this at the ineractive console, at this point it prints:
At meta __new__

Then, going on the interactive session:
In [4]: fried = Egg()
at meta __call__
at class __new__

And the extra mind-twisting thing is that: "type is type's own metaclass": meaning that type's __call__ is also responsible for running the __new__ and __init__  methods on the metaclass itself, when a new (non-meta) class body is executed.


text:
Q: Node.js ffmpeg download M3U8 URL as MP4 I've installed ffmpeg.js using Node.js.
I want to be able to give an URL as an argument (where the resource located at the URL is an M3U8 file), and download it as an MP4.
With regular command line ffmpeg (not JavaScript ported), the command would be the following:
ffmpeg -i http://example.com/file.m3u8 -c copy out.mp4

I've tried the following, but it doesn't work.
var ffmpeg = require("ffmpeg.js");
var fs = require("fs");

var result = ffmpeg({
  arguments: ["-i", "http://example.com/file.m3u8", "-c", "copy", "out.mp4"],
});

fs.writeFileSync("out.mp4", Buffer(result));


text:
Q: How can I `cat` a file as an attachment on a new Thunderbird email message from the command line? As it says on the tin really. I would like to send some of my etc files to a colleague and it would be handy to cat them to a new Thunderbird email message.
Is this possible? If so how?

A: I googled «thunderbird command-line», and this first hit seems to be what you want: http://kb.mozillazine.org/Command_line_arguments_(Thunderbird)

A: Give this a try, it's working fine for me:
cat /etc/[file1] /etc/[file2] /etc/[file3] > ~/configs.txt && thunderbird -compose "subject='test',attachment='~/configs.txt'"
or (a revised command which will also print each filename):
for file in /etc/[file1] /etc/[file2] ; do echo -e '\n ****' $file '**** \n'  >> ~/configs.txt ; cat $file >> ~/configs.txt ; done && thunderbird -compose "subject='test',attachment='~/configs.txt'"

Just replace the [fileX] names with the ones you're interested.
The above command will create a new file named configs.txt with all of the config files you want and add it as an attachment to a new 'compose mail' window in TB.


text:
Q: C# - Conversion -Clarification This could be a very basic question for prodigies.But I have a doubt to handle it.

During Conversion we are using :

int.Parse(someThing)

Convert.ToInt32 or Convert.ToString()....

  (Int32)(someValue)

even we use  "as"

What are the restrictions for using each?

A: int.Parse assumes a string as a parameter and as such is only suitable for converting raw string representations to integers
Convert.ToInt32() will attempt to convert pretty much any object to an integer representation. Where the representation isn't a valid int (i.e. using a float with the value 55.3 or a string containing a word) this will raise a FormatException. If the integer is too large to fit in an int then an OverflowException will occur.
(int) is a direct cast. It's basically saying "I know that this object is really an integer, treat it as such". If the object actually isnt an integer you'll get an invalid cast exception.
Finally, as behaves the same as a direct cast except where the object is not of the correct type it will assign null. Not sure how this applies to int with it being a non-nullable type but certainly usable with
int? myInt = someVar as int?;

A: Convert.ToNnnn has the restrictions stipulated by its overloads; for instance, you cannot call Convert.ToMyCustomType (since that method does not exist). You can pass pretty much anything into Convert.ToString (or Convert.ToInt32 or any other of the Convert.ToNnnn methods) but the result may not always make sense. Also, if the method fails to perform the conversion it may throw an InvalidCastException.
The regular type case ((int)someValue) can be used in all cases where there is an explicit conversion available. If you try to perform an illegal cast you will get an exception thrown at you.
The as keyword can be used to cast type to another (reference) type (and it will return null if it's not possible). The as keyword cannot be used with value types (such as Int32, Point or DateTime).
In my own code I typically use a mixture of them, but in general I follow the following scheme:

*

*If I want to convert a string to a numeric type, I usually use the TryParse provided by that numeric type.

*If I want to cast a class instance to a base class or interface, I usually use the as keyword.

*In other cases I use regular type casting within try/catch blocks.

A: Convert.ToInt32 can convert from various types (DateTime, Decimal, etc) back to an integer, while int.Parse() only converts from a string.
If you're only parsing strings back to integers, Convert.ToInt32 is just an alias for int.Parse, so you might as well use int.Parse instead.
Regarding casting, you cannot cast a string to an integer, you have to convert it like mentioned above.
Consider that you are working with a database, and you have a column that is inefficiently declared as varchar while it stores integer data. You cannot do (int)dr["column"] when using a SqlDataReader for instance, you would have to use int.Parse(dr["column"].ToString()) instead. If the column was of the int column type in the database, you could then have used the cast: (int)dr["column"].


text:
Q: Fatal error: Call to undefined method wSpider::fetchPage() The error is :
Fatal error: Call to undefined method wSpider::fetchPage()

Firstly, what I'm trying to do is build a spider to get data from a webpage. I'm not exactly sure why I'm getting this error, but I'm fairly new to php so it could be something fairly obvious that I'm missing. Code:
<?php
class wSpider
{
var $ch; /// going to used to hold our cURL instance
var $html; /// used to hold resultant html data
var $binary; /// used for binary transfers
var $url; /// used to hold the url to be downloaded

function wSpider()
{
$this->html = "";
$this->binary = 0;
$this->url = "";
}
}

function fetchPage($url)
{
$this->url = $url;
if (isset($this->url)) {
$this->ch = curl_init (); /// open a cURL instance
curl_setopt ($this->ch, CURLOPT_RETURNTRANSFER, 1); // tell cURL to return the data
curl_setopt ($this->ch, CURLOPT_URL, $this->url); /// set the URL to download
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); /// Follow any redirects
curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, $this->binary); /// tells cURL if the data is binary data or not
$this->html = curl_exec($this->ch); // pulls the webpage from the internet
curl_close ($this->ch); /// closes the connection
}
}

$mySpider = new wSpider(); //// creates a new instance of the wSpider
$mySpider->fetchPage("http://www.msn.com"); /// fetches the home page of msn.com
echo $mySpider->html; /// prints out the html to the screen

?>

The specific line in question is
$mySpider->fetchPage("http://www.msn.com"); /// fetches the home page of msn.com

I'd be very grateful for any help to resolve this issue!

A: There is no fetchPage method in your class, that's why it isn't working. That's why you should indent your code.  Try
<?php
class wSpider
{
    var $ch; /// going to used to hold our cURL instance
    var $html; /// used to hold resultant html data
    var $binary; /// used for binary transfers
    var $url; /// used to hold the url to be downloaded

    function wSpider()
    {
        $this->html   = "";
        $this->binary = 0;
        $this->url    = "";
    }
    function fetchPage($url)
    {
        $this->url = $url;
        if (isset($this->url)) {
            $this->ch = curl_init(); /// open a cURL instance
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); // tell cURL to return the data
            curl_setopt($this->ch, CURLOPT_URL, $this->url); /// set the URL to download
            curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); /// Follow any redirects
            curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, $this->binary); /// tells cURL if the data is binary data or not
            $this->html = curl_exec($this->ch); // pulls the webpage from the internet
            curl_close($this->ch); /// closes the connection
        }
    }
}

$mySpider = new wSpider(); //// creates a new instance of the wSpider
$mySpider->fetchPage("http://www.msn.com"); /// fetches the home page of msn.com
echo $mySpider->html; /// prints out the html to the screen

?>

Your class ends right here
$this->url = "";
}
} // right here

and function is defined AFTER that bracket.

A: You 've got a brace issue that causes fetchPage to not be a member of your class:
function wSpider()
{
$this->html = "";
$this->binary = 0;
$this->url = "";
}
} // This brace ends your class declaration! Move it!

You might also want to rename the constructor to __construct, as is recommended.


text:
Q: Install emacs and ruby I'm a new user of ubuntu and I tried to install emacs and ruby but there is an error and I don't know how to resolve. The emacs error is this:
  E: Could not open lock file /var/lib/dokg/lock - open (13: Permission denied)
  E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

The ruby error is

Thaks for your help
Nayeli

A: Since you don't provide exact command that lead to this state, I can only think of a few possibilities:

*

*You did not run this with root privileges (you need special privileges to access mentioned path /var/lib/dpkg and /var/lib/dokg/lock) - you can fix this by adding sudo before your command (like sudo any commands you wish and entering your accounts password when prompted.

*Another program is currently accessing aforementioned directory (like opened package manager). You can just close it and thus unlock it.
Next time, please provide command that led to your behavior and Ubuntu version for good measure.


text:
Q: How to read HttpRequest data in json sent from client on Apache server in PHP? Let say client is sending json data to the local server (in my case it is apache). I need to read the data (in json format ) which is sent by client to server and access the data on server side for coding further in PHP.
Kindly let me know by using Apache how to fetch the client data using PHP on the server side.
I have tried the below code
 <?php
  $clientmessage= $_SERVER['QUERY_STRING'];  // "e.g, this is client message"
  echo "this is a message sent to client which server recieved",  urldecode($clientmessage);
    ?>

but with that i am able to send the response from server to client (the same message back to client) but when i debug it using Xdebug or print it then the output of client message is wrong it is "XDEBUG_SESSION_START=ECLIPSE_DBGP&KEY=143445995265345" instead i should read "e.g, this is client message"
Why i am getting this output ? Kindly let me know by using Apache how to fetch the data (request) from the client on server side ?


text:
Q: Is this the rule for a function to be holomorphic? I made up this rule and I think it should work:
$$\lim_{h\rightarrow 0}\frac{f(z+h(\cos\theta+i\sin\theta))-f(z)}{h(\cos\theta+i\sin\theta)}$$
If the limit exists and is independent of $\theta$, then the function is holomorphic or differentiable at $z$.
Clearly, fixing a particular value of $\theta$ means approaching $z$ from one particular direction. So, if this limit is independent of $\theta$, then the function has the same derivative from whatever direction we approach it. Is this rule correct?

A: Consider the function $f(x) = 0$ for $x\in \mathbb{R}$ and $f(re^{i\theta'}) = \frac{1}{\theta'}r^2$, where $r > 0, \theta' \in (0,2\pi)$.
Check: Your limit for $z=0$ is 0 regardless of the choice of $\theta$, but $f$ is not even continuous at $0$, as $f$ takes arbitrarily large values in any neighbourhood of $0$.


text:
Q: How to extract only one element type in JQ from output of CURL in BASH script.? I am working in simple bash script to get JSON value using CURL and Parse using JQ. Script i am using:
 var=$(curl -X GET -k -H "SEC: xxxxxx" 'https://localhost/api/reference_data/sets/malopid?fields=data(value)' | jq '.[]')
 echo $var;

Output of curl is:
[
  {
    "value": "11.945403842773683082"
  },
  {
    "value": "11.-4947520229339316351"
  },
  {
    "value": "11.-5919145046027777143"
  }
]

But i am expecting OP like below:
11.945403842773683082
11.945403842773683082
11.945403842773683082

Is it possible to do this.? Using this nos i will query another API. Please help me with logic? Please help me on this.

A: I'm expecting your dummy output is wrong, and you actually want what is listed below:
jq '.[].value' -r <<< '[
  {
    "value": "11.945403842773683082"
  },
  {
    "value": "11.-4947520229339316351"
  },
  {
    "value": "11.-5919145046027777143"
  }
]'

Output is:
11.945403842773683082
11.-4947520229339316351
11.-5919145046027777143

--raw-output/-r:
  With this option, if the filter's result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.


text:
Q: Possible to automate ios bundling process? Everytim before trying to achive, I have to run the following command in terminal

react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios

Is there by any chance I can automate it like says it gets rebundle on command react-native run-ios?
Not sure if it's related but I found the following code in my package.json
"scripts": {
  "start": "node node_modules/react-native/local-cli/cli.js start",
  "test": "jest",
  "android-linux": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"
},

Wondering if the above android-linux will be triggered automatically when we run react-native run-android?
Also, for iOS, I understand the need to bundle it and we change the AppDelegate.m to point to main bundle as below
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

But I don't understand how Android will point the bundle created from scripts, all this time we only run command ./gradlew assembleRelease to generate the APK

A: With your script you can run yarn android-linux for android.
For iOS, add react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios
to package.json > scripts, like:
"iOS-build": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios"
then you can run yarn iOS-build


text:
Q: Troubles with CSS defined in CssResource I am having some problem displaying the CSS using UiBinder and CssResource:
public interface Resources extends ClientBundle {

    @NotStrict
    @Source("style.css")
    Style style();

    @Source("logo.png")
    ImageResource logo();
}

public interface Style extends CssResource {
    @ClassName("orange")
    public String orange();
}

If I apply the CSS like this with UiBinder:
styleName="{res.style.orange}"

It doen't work, although the CSS ".orange" rule here is fully tested to be rendered properly.
I have defined the resouce in the UiBinder like this:
<ui:with field='res' type='com.mygwtapp.client.Resources'/>

And if I place this for example:
<g:Image resource='{res.logo}'/>

It works, the logo image is displayed but the CSS won't work. Is there any other procedure or method that I have missed that is causing the CSS not to be rendered?

A: You have to call ensureInjected() on your CssResources.
UiBinder does it automatically for a ui:style, but not for CssResources you provide via an ui:with.


text:
Q: Picking random from an assoctive array Im making a blackjack game in PHP. So i made an Assoctive array with all the cardnames and values. That looks like this:
$cards = array("Schoppen 2"=>"2", "Schoppen 3"=>"3", "Schoppen 4"=>"4", "Schoppen 5"=>"5", "Schoppen 6"=>"6", "Schoppen 7"=>"7", "Schoppen 8"=>"8", "Schoppen 9"=>"9", "Schoppen 10"=>"10"
            , "Schoppen boer"=>"10", "Schoppen vrouw"=>"10", "Schoppen heer"=>"10", "Schoppen aas"=>"11", "Harten 2"=>"2", "Harten 3"=>"3", "Harten 4"=>"4", "Harten 5"=>"5", "Harten 6"=>"6", "Harten 7"=>"7", "Harten 8"=>"8", "Harten 9"=>"9", "Harten 10"=>"10"
            , "Harten boer"=>"10", "Harten vrouw"=>"10", "Harten heer"=>"10", "Harten aas"=>"11", "Klaveren 2"=>"2", "Klaveren 3"=>"3", "Klaveren 4"=>"4", "Klaveren 5"=>"5", "Klaveren 6"=>"6", "Klaveren 7"=>"7", "Klaveren 8"=>"8", "Klaveren 9"=>"9", "Klaveren 10"=>"10"
            , "Klaveren boer"=>"10", "Klaveren vrouw"=>"10", "Klaveren heer"=>"10", "Klaveren aas"=>"11", "Ruiten 2"=>"2", "Ruiten 3"=>"3", "Ruiten 4"=>"4", "Ruiten 5"=>"5", "Ruiten 6"=>"6", "Ruiten 7"=>"7", "Ruiten 8"=>"8", "Ruiten 9"=>"9", "Ruiten 10"=>"10"
            , "Ruiten boer"=>"10", "Ruiten vrouw"=>"10", "Ruiten heer"=>"10", "Ruiten aas"=>"11");

Now i want to pick 2 cards for the player and 2 cards for the dealer, so im using this:
$playercards = array_rand($cards, 2);
$dealercards = array_rand($cards, 2);
But now if i echo $playercards its empty. Someone sees the problem? Since i dont worked before with array_rand.
Also the cards may not be the same. So once one is picked he cant be picked again by array_rand, is there an opportunity to fix that too?
Thanks !

A: Since you're playing cards, why don't you use the shuffle function?
shuffle( $cards );
$card_player_1 = array_shift( $cards );
$card_player_2 = array_shift( $cards );
$card_dealer_1 = array_shift( $cards );
$card_dealer_2 = array_shift( $cards );

Those cards will be out of the array thanks to array_shift
Update
if you want to keep the keys, there's a post in the documentation that explains how to achieve it:

Shuffle associative and non-associative array while preserving key,
  value pairs. Also returns the shuffled array instead of shuffling it
  in place.

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key) {
    $random[$key] = $list[$key];
  }
  return $random;
}

Then your code:
$cards_shuffled = shuffle_assoc( $cards );
$card_player_1 = array_shift( $cards_shuffled);
$card_player_2 = array_shift( $cards_shuffled );
$card_dealer_1 = array_shift( $cards_shuffled );
$card_dealer_2 = array_shift( $cards_shuffled );

If you want to store key and value in different variables, you can use this approach:
$cards_shuffled = shuffle_assoc($cards);
list($card_player_1_key, $card_player_1_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_player_2_key, $card_player_2_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_dealer_1_key, $card_dealer_1_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_dealer_2_key, $card_dealer_2_value) = each($cards_shuffled);
array_shift($cards_shuffled);

echo $card_player_1_key;// Print key of player 1 card.
echo $card_player_1_value;// Print value of player 1 card.
echo $card_dealer_2_key;// Print key of dealer second card.