text:
Q: Select and Where on multiple (sequential range) of criteria I'm looking for an SQL solution for my sheet that looks exactly 28 columns deep into a row, and if it has any non-blank values in that range, retrieves it.
Currently I'm able to get exactly what i want using this horrible formula:
QUERY(SomeOtherSheet!A85:BA,"select A,B,C,O,P,Q,R,S,T,U,V,W,X,Y,Z where (O>=0 OR P>=0 OR Q>=0 OR R>=0 OR S>=0 OR T>=0 OR U>=0 OR V>=0 OR W>=0 OR X>=0 OR Y>=0 OR Z>=0) ",1)

suffice to say the range O-Z isn't exactly 28 long, but its enough to showcase what I'm looking for in this example.
Question) Is there a better way to achieve this kind of query on a sequential range of columns?
specifically in my case the range of O-AQ
I suppose i can dynamically string together in a different cell the cols required. But I'd rather not...

A: I know OP already answered. But submitting this as an alternative:
For the Select,
  =ARRAYFORMULA(JOIN(",",CHAR(ROW(65:90)),"A"&CHAR(ROW(65:90))))

For the where OR part:
    =ARRAYFORMULA(JOIN(">=0 OR ", CHAR(Row(65:90)),"A"&CHAR(ROW(65:90))))&">=0"

To change the start and end parts, change the ROW number start and end parts:
http://www.asciitable.com

A: Please try converting the range into array:
QUERY({SomeOtherSheet!A85:BA},"select Col1,Col2,Col3,...")
I always use this method and search for columns inside query by their index, e.g. look for column called "Name":
=match("Name", SomeOtherSheet!A85:BA85, 0)

Update. To combine OR part of query:
="where Col"&JOIN(" >= 0 or Col",ARRAYFORMULA(COLUMN(O1:Z1)))&" >= 0"
The result is:
"where Col15 >= 0 or Col16 >= 0 or Col17 >= 0 or Col18 >= 0 or Col19 >= 0 or Col20 >= 0 or Col21 >= 0 or Col22 >= 0 or Col23 >= 0 or Col24 >= 0 or Col25 >= 0 or Col26 >= 0"
If new columns will be pasted inside range O1:Z1 this formula will adjust. In real projects it's useful to find ranges by their points: start cell, last cell and then use indirect:
="where Col"&JOIN(" >= 0 or Col",ARRAYFORMULA(COLUMN(indirect(range))))&" >= 0"
where range is name of range with string "O1:Z1", "O1" and "Z1" are found by their column names or ids.

A: Well I've worked out how to dynamically concatenate a string with as few possible static magic numbers:
First, A cell that contains:
=ARRAY_CONSTRAIN(ArrayFormula((IF((COLUMN(Lifetime!N$8:$8)+64)>CODE("Z"),"A"&CHAR(MOD(COLUMN(Lifetime!N$8:$8),26)+64),""&CHAR(COLUMN(Lifetime!N$8:$8)+64)))),1,28)

which gives us the following array:
N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO

this array can be used for the Select part of the query easily.
I've allowed myself the freedom of not accounting for cells that will be B* since my personal sheet won't get there. The Array_constrain() column parameter allows for quick change to different size of arrays if ever needed in the future.
Secondly, a simple textjoin() + regexreplace() for the required where clause
=REGEXREPLACE(TEXTJOIN(",",FALSE,A119:AB119),",",">=0 OR ")&">=0"

which results in the required string for the where clause:
N>=0 OR O>=0 OR P>=0 OR Q>=0 OR R>=0 OR S>=0 OR T>=0 OR U>=0 OR V>=0 OR W>=0 OR X>=0 OR Y>=0 OR Z>=0 OR AA>=0 OR AB>=0 OR AC>=0 OR AD>=0 OR AE>=0 OR AF>=0 OR AG>=0 OR AH>=0 OR AI>=0 OR AJ>=0 OR AK>=0 OR AL>=0 OR AM>=0 OR AN>=0 OR AO>=0

And the final product:
=ARRAY_CONSTRAIN(QUERY(Lifetime!A85:BA,"select A,B,C,"&120&" where ("&A121&")",1),105,20)

or as a one-liner:
=REGEXREPLACE(TEXTJOIN(",",FALSE,ARRAY_CONSTRAIN(ArrayFormula((IF((COLUMN(Lifetime!N$8:$8)+64)>CODE("Z"),"A"&CHAR(MOD(COLUMN(Lifetime!N$8:$8),26)+64),""&CHAR(COLUMN(Lifetime!N$8:$8)+64)))),1,28)),",",">=0 OR ")&">=0"


text:
Q: Ruby on Rails user queue system? I would like to create a Ruby on Rails application that would allow users to control the serial port of the host server. To keep some order to the serial commands, I would like to have some sort of queue system that would only allow one user at a time to issue commands, with a time limit. When their time expires, the next user in the queue is given control.
Has anything similar been created? I am looking for advice as to pre-existing gems or plugins that can be modified to fit this need, or whether I should try and roll my own.
I will be using the ruby-serial library to connect to an Arduino. I would also like to authenticate users via Twitter/Facebook OAuth.

A: Async Observer is by far my favorite for asynchronous job queue execution.
If you built it with gearman you could synchronously manipulate such shared resources as well, even on a distributed system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using WPF Path Data in ASP.NET Is there any way to re-use Path data created in the mini-language for use with the WPF Path element in ASP.NET? Or is the Path mini-language exclusive to WPF?
I have a Win8 app that has a number of path geometry strings in the format "M10,110 L30,90 M50,110 L30,90", etc. I would really like to re-use these in a new ASP.NET website.

A: I dont think there is an easy way to reuse 'WPF' path in ASP.NET. What exactly are you trying to do? Perhaps, reuse the shape image would be the best way to go.

A: As I understand it, this is the SVG path syntax. e.g. https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths


text:
Q: sqlite3_prepare_v2 / sqlite3_exec Few questions about sqlite3:
1.When is necessary to use first approach one and when the other ? It is a difference between them?
sqlite3_prepare_v2(_contactDB, sql_stmt_getIdRecepteur, -1, &sqlStatement, NULL);

and
if(sqlite3_prepare_v2(_contactDB, sql_stmt_getIdRecepteur, -1, &sqlStatement, NULL) == SQLITE_OK) {}

2.When is most indicated to use 'sqlite3_exec' than 'sqlite3_prepare_v2' ?
3.When is necessary to use first one, the second or the third:
while(sqlite3_step(sqlStatement) == SQLITE_ROW){}
if(sqlite3_step(sqlStatement) == SQLITE_ROW){}
if(sqlite3_step(sqlStatement) == SQLITE_DONE){}

Thank you in advance

A: *

*One should always check the return values of SQLite functions, in order to make sure it succeeded, thus the use of the if statement is greatly preferred. And if it failed, one would call sqlite3_errmsg() to retrieve a C string description of the error.

*One would use sqlite3_prepare_v2 (instead of sqlite3_exec) in any situation in which either:

*

*one is returning data and therefore will call sqlite3_step followed by one or more sqlite3_column_xxx functions, repeating that process for each row of data; or

*one is binding values to the ? placeholders in the SQL with sqlite3_bind_xxx.
One can infer from the above that one would use sqlite3_exec only when (a) the SQL string has no parameters; and (b) the SQL does not return any data. The sqlite3_exec is simpler, but should only be used in these particular situations.
Please note: That point regarding the ? placeholders is very important: One should avoid building SQL statements manually (e.g., with stringWithFormat or Swift string interpolation), especially if the values being inserted include end-user input. For example, if you call sqlite3_exec with INSERT, UPDATE, or DELETE statement that was created using user input (e.g., inserting some value provided by user into the database), you inherently risk the very real possibility of problems arising from un-escaped quotation marks and escape symbols, etc. One is also exposed to SQL injection attacks.
For example, if commentString was provided as a result of user input, this would be inadvisable:
NSString *sql = [NSString stringWithFormat:@"INSERT INTO COMMENTS (COMMENT) VALUES ('%@')", commentString];
if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL) != SQLITE_OK) {
    NSLog(@"Insert failure: %s", sqlite3_errmsg(database));
}

Instead, you should:
const char *sql = "INSERT INTO COMMENTS (COMMENT) VALUES (?)";
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK) {
    NSLog(@"Prepare failure: %s", sqlite3_errmsg(database));
    return;
}
if (sqlite3_bind_text(statement, 1, [commentString UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
    NSLog(@"Bind 1 failure: %s", sqlite3_errmsg(database));
    sqlite3_finalize(statement);
    return;
}
if (sqlite3_step(statement) != SQLITE_DONE) {
    NSLog(@"Step failure: %s", sqlite3_errmsg(database));
}
sqlite3_finalize(statement);

Note, if this proper implementation felt like it was too much work, you could use the FMDB library, which would simplify it to:
if (![db executeUpdate:@"INSERT INTO COMMENTS (COMMENT) VALUES (?)", commentString]) {
    NSLog(@"Insert failure: %@", [db lastErrorMessage]);
}

This provides the rigor of sqlite3_prepare_v2 approach, but the simplicity of the sqlite3_exec interface.

*When retrieving multiple rows of data, one would use:
while(sqlite3_step(sqlStatement) == SQLITE_ROW) { ... }

Or, better, if you wanted to do the proper error handling, you'd do:
int rc;
while ((rc = sqlite3_step(sqlStatement)) == SQLITE_ROW) {
    // process row here
}
if (rc != SQLITE_DONE) {
     NSLog(@"Step failure: %s", sqlite3_errmsg(database));
}

When retrieving a single row of data, one would:
if (sqlite3_step(sqlStatement) != SQLITE_ROW) {
    NSLog(@"Step failure: %s", sqlite3_errmsg(database));
}

When performing SQL that will not return any data, one would:
if (sqlite3_step(sqlStatement) != SQLITE_DONE) {
    NSLog(@"Step failure: %s", sqlite3_errmsg(database));
}

When using the SQLite C interface, you can see that it takes a little work to do it properly. There is a thin Objective-C wrapper around this interface called FMDB, which not only simplifies the interaction with the SQLite database and is a little more robust.

A: For question 1,in most cases, you need to verify that result is equal to SQLITE_OK to make sure your command ran successfully. (SQLITE_OK is int type**). Therefore, the second is preferred.
For question 2, the function sqlite3_exec is used to run any command that doesn't return data, including updates,inserts and deletes. Retrieving data from the database is little more involved. And the function sqlite3_prepare_v2 can used for SELECT (in SQL). In common, create table often use the first one.
For question 3, well, while is for loop, while if is for condition. Generally, if you retrieve dada from db, you need a loop to traverse the *return array**. If you insert a data to db (for instance), you can use SQLITE_DONE to check you operation.
By the way, core data is preferred in IOS for most cases.

A: A late answer to #2 that I just found: use sqlite3_exec (or use sqlite3_prepare_v2 in a loop) when sql_stmt_getIdRecepteur actually contains multiple SQL statements.  From the docs for sqlite3_prepare_v2:

These routines only compile the first statement in zSql, so *pzTail is left pointing to what remains uncompiled.

sqlite3_exec includes an internal loop that calls sqlite3_prepare_v2 multiple times until the entire input string is compiled.  If you don't use sqlite3_exec, and you have multiple SQL statements in a string, you need to check the pzTail return value from sqlite3_prepare_v2.


text:
Q: How do I extract color matrix from MP4 an x264 stream in Media Foundation I am playing a video (mp4 containing x264 encoded video stream) with a custom player using media foundation.
When I convert the YUV information into RGB I need to account for the color matrix and range used at encode time.
Some of my videos have this information, I can use MediaInfo.exe or FFMPEG to see that it is present.
However, for such videos if I look at the relevant Media Foundation properties (Extended Color Information) the properties are not present in the files.
So, somehow I need to find a way to access the information.
Media Foundation does provide access to MF_MT_MPEG4_SAMPLE_DESCRIPTION and MF_MT_MPEG_SEQUENCE_HEADER for the video stream but I can't find descriptions of what these contain.
I noticed that the MF_MT_MPEG_SEQUENCE_HEADER is much longer for the videos with the information present and this (MPEG Headers Quick Reference) seems to suggest headers might contain the information I need.
I'm looking for Color Range (limited/full), Color Primaries, Transfer Characteristics and Matrix Coefficients (BT.709 etc).
I'd greatly appreciate any help finding this information from a Media Foundation video stream.
Thanks
Jules

Update - Sequence Header
The sequence header appears to be a subset of MPEG4 sample description, though I can't find anything that indicates what either bits of data actually contains / doesn't contain specifically.
The sequence header appears to contain data structured as an MP4 byte stream as described in the H264 Standards Document and includes the VUI (Video Usability Information - Annex E of document) which may then include the colour information I'm interested in.
Given that it's a byte stream I need to know where it starts and whether there's some existing code I could use to decode it.
In FFMPEG in libavcodec/h264_ps.c there is a function called ff_h264_decode_seq_parameter_set which ends up calling decode_vui_parameters. It seems possible that seq_parameter_set maps to MF_MT_MPEG_SEQUENCE_HEADER and it may be possible to use that code to decode the data.
If anyone one has any direct experience with decoding this data it would be very useful.
Thanks again

Update - Related posts
I found this How to decode sprop-parameter-sets in a H264 SDP? and  Possible Locations for Sequence/Picture Parameter Set(s) for H.264 Stream which are fairly helpful.
The sequence header would appear to be Sequence or picture parameter set (pps) and the parameters I want are the VUI extension subset.
Plus this post H.264 stream structure gives the high level of how the stream data is structured, and the MF_MT_MPEG_SEQUENCE_HEADER appears to start with a NAL 0x00 0x00 0x01 so I'm guessing it is a NAL containing the PPS.

A: (a cross-post from MSDN Forums)
You can look up sample code parsing H.264 parameter sets in GraphStudioNext here in H264StructReader.cpp, as well as other projects with available code.
GraphStudioNext will also be able to provide this information (colour_primaries etc.) visually, where it's available:

Image above displays a GraphStudioNext window with visualization of H.264 media type (for a MP4 file with respective H.264 data), which embeds parameter sets, which in turn (for that specific file) contain a non-empty section with color primaries and matrix coefficients.
Indeed, even though the values are present in the parameter set, Media Foundation does not make them available in the media type (MPEG-4 File Source does not add respective attributes, initialized from the parameter sets).

A: Yes, the information is in the VUI extension subset.
So you need to check for vui_parameters_present_flag and video_signal_type_present_flag. If those flags are not set, i think there are default values for Color Range/Color Primaries/Transfer Characteristics/Matrix Coefficients in the h264 specifications.
Also you need to extract information from the SPS and what you have to care to do this, is to learn about Exponential-Golomb coding.
Check this link : The h.264 Sequence Parameter Set
EDIT
Also yes, MF_MT_MPEG_SEQUENCE_HEADER normaly contains SPS and PPS information, when file is h264 video format.


text:
Q: Drawing with turtle(python) using PyCharm I'm running the latest PyCharm Pro version and trying to run the below code from a scratch file but it doesn't seem to work
import turtle

wn = turtle.Screen()
alex = turtle.Turtle()
alex.forward(150)
alex.left(90)
alex.forward(75)

By not working I mean, no window is popping out however I do see in the output saying
Process finished with exit code 0

Any idea

*

*If it can be done via PyCharm

*What am I missing in terms of configuration

Cheers

A: I managed to find out a way of doing it by using the below code.
The only downside is that it does close the canvas once it finished.
def main():
    wn = turtle.Screen()  # creates a graphics window
    alex = turtle.Turtle()  # create a turtle named alex
    alex.forward(150)  # tell alex to move forward by 150 units
    alex.left(90)  # turn by 90 degrees
    alex.forward(75)  # complete the second side of a rectangle

if __name__ == "__main__":
    main()

If anyone has a different idea on how to not close the canvas that will be awesome.
Thanks,
Dani

A: I ran into the same problem. Turns out the solution is in the "turtle" module.
You want to end with
turtle.done()
or
turtle.exitonclick()
Enjoy!

A: As Allan Anderson says, easiest way I found (as I don't use main that often):
turtle.exitonclick()

As the last line of code forces the Graphics Window to stay open until it is clicked.

A: By "no window is popping out" means that the program is executing and then directly closing. To fix it you have to loop the program as follows:
import turtle

wn = turtle.Screen()
alex = turtle.Turtle()
alex.forward(150)
alex.left(90)
alex.forward(75)

wn.mainloop()

A: def main():
    import turtle
    wn = turtle.Screen()  # creates a graphics window
    alex = turtle.Turtle()  # create a turtle named alex
    alex.forward(150)  # tell alex to move forward by 150 units
    alex.left(90)  # turn by 90 degrees
    alex.forward(75)  # complete the second side of a rectangle

if __name__ == "__main__":
    main()

    input("Press RETURN to close.  ")

The last line will hold display till RETURN key is not pressed.

A: Use the below code. You are missing the function which keep the screen alive until it is closed by the user. exitonclick() Method helps to keep screen alive.
import turtle

wn = turtle.Screen()
alex = turtle.Turtle()
alex.forward(150)
alex.left(90)
alex.forward(75)
wn.exitonclick()


text:
Q: Angular JS $http undefined in $routeProvider I have the following code in my routeProvider but for some reason $http is coming back undefined. What am I missing?
config(['$routeProvider', function($routeProvider, $http) {
  var routes = ['partial1','partial2'];
  angular.forEach(routes, function(route, key) {
    var defaultUrl = 'partials/' + route + '.html',
        deviceUrl = 'partials/' + route + '.' + getDevice() + '.html';
    $http.get(deviceUrl).
      success(function() {
        $routeProvider.when('/' + route, {templateUrl: deviceUrl, controller: route + 'Ctrl'});
      }).
      error(function(){
        $routeProvider.when('/' + route, {templateUrl: defaultUrl, controller: route + 'Ctrl'});
      });
  });
  $routeProvider.otherwise({redirectTo: '/' + routes[0]});
}]);

A: You forgot to annotate $http to the dependency injector.
Besides, it's not possible to inject a service into a configuration.
To workaround this problem, you could also inject $http manually.
Here is a working example:
config(['$routeProvider', function($routeProvider) {
  var routes = ['partial1','partial2'];
  angular.forEach(routes, function(route, key) {
    var defaultUrl = 'partials/' + route + '.html',
        deviceUrl = 'partials/' + route + '.' + getDevice() + '.html';
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');
    $http.get(deviceUrl).
      success(function() {
        $routeProvider.when('/' + route, {templateUrl: deviceUrl, controller: route + 'Ctrl'});
      }).
      error(function(){
        $routeProvider.when('/' + route, {templateUrl: defaultUrl, controller: route + 'Ctrl'});
      });
  });
  $routeProvider.otherwise({redirectTo: '/' + routes[0]});
}]);

A: You cannot inject services in the module config.
But you can move your code into a provider in case you want to do it in config itself.


text:
Q: How do you display a string on Android? Edit: it turned out the XML Viewer wasn't the emulator, and does not actually run code.
So, I'm starting my first app in Android Studio 1.1.0, and I realized that I can't even manage to display a string (created in the java file).
I did all research I could, but no matter what snippets of code I copy/paste, it never works.
I tried copy/pasting the snippet of code from the first answer here: Android Eclipse: Change the text in the app to a string created withing the program and it doesn't work. The findViewById method is in red, and so is my_text_view :
String displaythisgoddammit = "display this goddammit";
    private TextView text = (TextView) findViewById(R.id.my_text_view);
    text.setText(displaythisgoddammit);

And my textview (in activity_main.xml) is:
 <TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/displaythisgoddammit"/>

It can't find the string, no matter what I do. Apparently I must put it in the strings.xml file, but then how do I edit it...? In the question I linked, the snippet of code apparently worked for a string in the java file.
Here is my main file (I'm not sure if it's really relevant though, it's just snippets of code I copy/pasted): http://pastebin.com/7uuHyJWP I put the string at line 144, should I put it elsewhere?
Some help please? I've been researching for 5 hours but none of the solutions I tried work...

A: The issue with your code is on the line when you use
TextView text = (TextView) findViewById(id.my_text_view);

It is occuring because when you define a TextView or any other object by it's Id you need to use R.id.my_text_view.
So, to fix it simply change it to
TextView text = (TextView) findViewById(R.id.my_text_view);

A: In your code please check the reference to the TextView that you are making.
It should be findViewById(R.id.my_text_view);

A: A few things you should check:

*

*Inside a method, you should not be using the word private, as you are not defining a class level variable.

*You need to use R. before the id, to signify you are retrieving a resource.

*You need to make sure that the Text View is inside activity_main.xml.

In addition to all of that, you have a lot of things wrong in your pastebin file, I highly recommend you avoid just copy and pasting code, because it is never that simple.
You need to remove all access modifiers that are not at the class level, and clean up snippets like this:
String contentAsString;
    public void onCreate;(Bundle savedInstanceState;) {
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    txtView=(TextView)findViewById(R.id.my_text_view);
    txtwidth = (TextView)findViewById(R.id.viewwidth);
    hello="This is my first project";

    mybtn.setOnClickListener(this);
    txtView.setText(hello);}

There are brackets and semi colons all over the place, and not to mention this code is written after a return statement, so you won't even hit this line of code.
NOTE
Other things that I've found that are wrong:

*

*You have an extra closing bracket after the DownloadWebpageTask which will cause some compilation errors.

*You override onCreate twice in HTTPExample

*It looks like the code you're having trouble with should be inside onCreate.

In other words, try something like this.

*

*Also, inside your XML where you have the line android:text="@string/displayThis, the @string is basically saying you want to get the string 'displayThis' from strings.xml. If you don't have, or don't want to put 'displayThis' in strings.xml, you need to remove that attribute and just set the text programatically.


text:
Q: Unhandled rejection SequelizeDatabaseError - stream csv to update database I have a few hundreds of csv files located in s3 bucket. I am building a server would fetch those csv files and update my database with Sequelize.
I am running this task as a scheduler, and I am seeing these error on occasions. It does not happen all the time, so I am suspecting it is related to Promises.
Here is the code:
FilesNames consist a list of filenames. I then use csvtojson to read these csv from stream, and insert those data with Sequlize
fileNames.forEach(file => {
      const csvFilePath = `${new_url}${file}`;
      csv({
        noheader: true,
      })
        .fromStream(request.get(csvFilePath))
        .on('csv', (csvRow, rowIndex) => {
          Hydrograph.create({
            data: csvRow,
            gaugeId: Number(file.slice(10, -4)),
            percentille: PERCENTILLE[rowIndex],
            type: 'GAUGE',
          });
        });
    });

These are the error I am getting. Again these errors only show up sometimes.

Unhandled rejection SequelizeDatabaseError: invalid input syntax for type numeric: ""
      at Query.formatError (/Users/leoqiu/apps/eflow-api/node_modules/sequelize/lib/dialects/postgres/query.js:363:16)
      at query.catch.err (/Users/leoqiu/apps/eflow-api/node_modules/sequelize/lib/dialects/postgres/query.js:86:18)
      at tryCatcher (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/util.js:16:23)
      at Promise._settlePromiseFromHandler (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/promise.js:512:31)
      at Promise._settlePromise (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/promise.js:569:18)
      at Promise._settlePromise0 (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/promise.js:614:10)
      at Promise._settlePromises (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/promise.js:689:18)
      at Async._drainQueue (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/async.js:133:16)
      at Async._drainQueues (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/async.js:143:10)
      at Immediate.Async.drainQueues (/Users/leoqiu/apps/eflow-api/node_modules/bluebird/js/release/async.js:17:14)
      at runCallback (timers.js:781:20)
      at tryOnImmediate (timers.js:743:5)
      at processImmediate [as _immediateCallback] (timers.js:714:5)


text:
Q: preserving colors in write command I'm using the write command to send messages to friends , I made a simple script that turns the text we give into ASCII art as follows:
ascii.py
import pyfiglet
from termcolor import cprint
import sys,random
f,t = '',''
fonts = list(pyfiglet.FigletFont.getFonts())
if sys.argv[-1] in fonts:
    f = sys.argv[-1]
    t = sys.argv[1:-1]
else:
    f = random.choice(fonts)
    t = sys.argv[1:]
cprint(pyfiglet.figlet_format(' '.join(t),str(f)),'red','on_blue',['bold'])
print(t)

Then I use the following command to send message:
python ascii.py hi graffiti | write neo

when I run the run the command without pipe i.e., python ascii.py hi graffiti, I get the following output:

But when I run python ascii.py hi graffiti | write neo , the colors are not being displayed instead some extra characters are being displayed as show below:

so how do I preserve colors so that they reach to the person at other end??

A: Python isn't removing the colours; they're there:
These start some formatting
^[[1m^[[44m^[[31m

And this ends formatting
^[[0m

for instance, try this on your command line
$ printf '\e[1;31mHello, World!\e[0m\n'

you'll get the text in red, but not the formatting characters. This is because your terminal has interpreted the characters.
If you then do this, you'll see the formatting characters are still there. This is because when the terminal gets the data from write, it doesn't interpret the escape sequences.
$ printf '\e[1;31mHello, World!\e[0m\n' | write neo

What's happening is that the escape sequences '\e[1;31m' and '\e[0m' are being converted to their related byte values. You can see this by doing a hexdump of the data
$ printf '\e[1;31mHello, World!\e[0m\n' | hexdump
0000000 5b1b 3b31 3133 486d 6c65 6f6c 202c 6f57
0000010 6c72 2164 5b1b 6d30 000a
0000019
$ printf '\\e[1;31mHello, World!\\e[0m\n' | hexdump
0000000 655c 315b 333b 6d31 6548 6c6c 2c6f 5720
0000010 726f 646c 5c21 5b65 6d30 000a
000001b

See the start and end bytes are different? Write is receiving the formatting bytes, but printing out their related escape sequences.
I don't know exactly why write doesn't interpret the escape characters on the client side, but it's likely due to security (these escape sequences can do more than just change the font).
If you want pretty colours, you won't be able to use write.

A: Ok I ran a small test, and it seems the problem is the write-command must do some shenannigans that don't seem to be parametrizable.
I wrote this small python-script which on my mac will write to another terminal (the same one picked by write), and it will color the output:
with open('/dev/ttys009', 'wb') as outf:
    outf.write('\x1b[35mfoobar\x1b[30m\n')

So I guess you'll have to re-create write yourself, by looking at /dev/tty* for the given user, and then just open that file and write.


text:
Q: Random Image for Launch Screen I have 3 different images I'd like to use Launch Screen.
I've added a UIImageView in the Launchscreen.storyboard
And I was thinking I could use a simple Switch statement with a randomizer to select the image:
var random = arc4random_uniform(3) //returns 0 to 2 randomly

  switch random {
    case 0:
        launchImageView.image = UIImage(named: "splash1.jpg")
    case 1:
        myImageView.image = UIImage(named: "splash2.jpg")
    default:
        /myImageView.image = UIImage(named: "splash3.jpg")      }

However I'm not really sure where to implement the code as the viewDidLoad will not work.

A: You can set the UILaunchImageFile by a relative path and then put an image at the path and use your random.
For example you change the launchscreen after launching by setting UILaunchImageFile property in the info.plist. You would then write a random image to the Documents folder.
<key>UILaunchImageFile</key>
<string>../Documents/image.png</string>


text:
Q: AssertThat with one parameter lib I was trying to execute a test from http://mapstruct.org/#get-started
And there they use the code
assertThat( carDto ).isNotNull();

Since in many tutorials they don't add the import clause for readability and i'm not master of testing tools, I added latest junit mvn dependency.
    <junit.version>4.12</junit.version>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>

And in Java, I added the import:
import static org.junit.Assert.assertThat;

Eclipse is complaining there is only one alternative for assertThat which is

assertThat(T, Matcher) in the type Assert is not applicable
  for the arguments (CarDto)

Am I doing something wrong? Is this a method from a different lib I am not aware of? I searched on the internet and found something but i'm not sure it is widely adopted, I would like to have that in mind because we're going to use this in a real project.
PS: Also tried org.hamcrest.MatcherAssert.assertThat; but it yields the same error, the signature is the same for their lib.

A: assertThat( carDto ).isNotNull(); looks like AssertJ, which is not distributed with JUnit. Have a look into this Quick Start.


text:
Q: Brownian motion as a rough path I'm reading through the Fritz and Hairer book on Rough Path Theory and naturally want to know that a Brownian rough path or enhanced Brownian motion yields a rough path.
By the classical Kolmogorov criterium I know that for almost every $\omega\in\Omega$ the path $t\mapsto B.(\omega)$ is $\alpha$-Hölder continuous for any $\alpha<1/2$.
If I now define the second order process/object $\mathbb{B}:[0,T]^2\rightarrow \mathbb{R}$ via Itô integration, that is define
$$\mathbb{B}^{Itô}_{s,t}:=\int_s^t B_rdB_r-B_sB_{s,t}$$ where the Integral is made sense of as Itô-integral. How do I know that I obtain an $\alpha$-Rough Path?
The Hölder condition on $\mathbb{B}^{Itô}_{s,t}$ can be verified via a Kolmogorov argument and thus one only needs to verify the algebraic condition, i.e. Chen's relation.
Chen's relation for $\mathbb{B}^{Itô}_{s,t}$ now clearly holds in $L^2(\Omega)$ due to the additive nature of the stochastic integral, but I need Chen's relation to hold almost surely. How can this we shown when the integrals aren't even defined in an almost sure sense but only in $L^2(\Omega)$? Or is it possible to show the additivity of the stochastic integral to hold almost surely even though the stochastic integral is only defined in $L^2(\Omega)$?

A: This is further mentioned in "3.2 Ito Brownian motion" in the "a course on rough paths":
The $\mathbb{B}_{s,t}:=\int_{s}^{t}B_{s,r}\otimes dB_{r}$ satisfies the Chen relation on an event of probability one. They basically do this by (re)defining the increment $\mathbb{B}_{s,t}$ in terms of $\mathbb{B}_{0,\cdot}$
$$\mathbb{B}_{s,t} =\mathbb{B}_{0,t} -\mathbb{B}_{0,s} − B_s \otimes B_{s,t}.$$
This variable is defined almost surely (as is any $L^2$-Cauchy limit) and as you mentioned it satisfies the Chen relation's by breaking the integral into $\int_{s}^t=\int_{s}^u+\int_{y}^t$.
In "Lecture 27. Approximation of the Brownian rough path", the author even obtains an almost sure convergence to the above rough path in the p-variation norm by using the interpolation of Brownian motion.
As mentioned here What is the explicit obstruction to almost sure convergence in stochastic integrals?
one can even have almost sure convergence in the Ito-integral.

If the meshes are chosen regularly with meshwidth $h_n\to 0$ such that
$$
 \sum_{n=1}^{\infty}\mathbb{E}\left[
 \int_{0}^{1}(f(\omega,x)-f(\omega,\lfloor x/h_n\rfloor h_n)^{2}\;dx\right]<\infty, $$ then the
Itô sums converge almost surely to the Itô integral (under usual conditions on the integrand)
This is proven, for example, in Remark 7.7 of the textbook Brownian motion by Mörters and Peres. It is an immediate consequence of Itô's isometry.
In particular, if $f$ is $1/2+\epsilon$ Hölder continuous, then $h_n=n^{-1}$ guarantees pathwise convergence.


text:
Q: Is it possible to export functions that have bindings to names that are variables? (Feel free to edit the confusing title)
Suppose I want to define three functions to point to the same function - I can achieve that with code like this
orig <- function() {
  match.call()[[1]]
}

one <- orig
two <- orig
three <- orig

If this is inside a package and I want to make the one, two, three functions "public", I can easily just add a roxygen @export above them:
orig <- function() {
  match.call()[[1]]
}

#' @export
one <- orig
#' @export
two <- orig
#' @export
three <- orig

But what if I want to store the function names in a vector such as c("one", "two", "three") and then define and export the functions based on that vector?
If I'm not in a package, I could use
methods <- c("one", "two", "three")
lapply(methods, function(x) assign(x, orig, envir = parent.env(environment())))

But as far as I can tell, I can't export functions that are created this way.
One potential usecase can be if I define a function and want to have many synonyms to it.  That's probably not a good idea, but for the sake of learning, I'd like to know if there's there a way to achieve this?


text:
Q: How can I convert an index column and add it back to the dataframe? My df looks like this:

Index1
Index2
cat
art

id
1
1293874
Vintage

name
1
Sam
old

id
2
2030039
Retired

name
2
Ben
lacklust

My goal is try to pivot index1 and add them as columns. Currently, my data is not structured and correctly formatted. The category column has a bucket of information of both name and id, but it is not a category.
Not only do I want to group by the index, but I also want to add the columns to the dataset without removing any of the original columns.
My desired output looks like this

Index2
cat
name
id_Art
name_Art

1
1293874
Sam
Vintage
old

2
2030039
Ben
Retired
lacklust

A: You can use melt:
out = (df.melt(['Index1', 'Index2'], var_name='Category', value_name='Value')
         .assign(Category=lambda x: x['Index1'] + '_' + x['Category'])
         .pivot('Index2', 'Category', 'Value')
         .rename_axis(columns=None).reset_index())
print(out)

# Output
   Index2   id_art   id_cat  name_art name_cat
0       1  Vintage  1293874       old      Sam
1       2  Retired  2030039  lacklust      Ben

A: You can use unstack on level=0 (in your case Index1):
df.set_index(['Index1', 'Index2'], inplace=True) #make sure your Index1 and Index2 are set are index
print(df.unstack(level=0))

Output:
            cat           art
Index1       id name       id      name
Index2
1       1293874  Sam  Vintage       old
2       2030039  Ben  Retired  lacklust

A: Another way to get to the same result as Tranbi's answer, since you mentioned pivoting:
df.pivot(index='Index2', columns='Index1')

gives
            cat           art
Index1       id name       id      name
Index2
1       1293874  Sam  Vintage       old
2       2030039  Ben  Retired  lacklust


text:
Q: What is the meaning of this command? What is the meaning of following command, especially this part </dev/console
exec >/dev/console 2>&1 </dev/console

A: <f sets the stdin for the given command:
echo abc >f; nl <f

is similar to (except for FIFO vs file differences):
echo abc >f; cat f | nl

With exec <f, all stdin from that point onwards will come from file f as explained here, and with exec >f all stdout from this point onwards will go to f.
About the /dev/console, doing:
sudo bash 'echo a > /dev/console'

outputs a to the current tty, independently of redirections. Therefore, to see this working you many need to be on a textual tty (Ctrl+Alt+F2 , F3, etc. on Ubuntu).
Using /dev/tty instead of /dev/console may or not be different according to this answer. On Ubuntu, they are different, and using /dev/tty is better since it also works on xterm windows. On Ubuntu also /dev/tty does not require sudo to use, so I will use it on the following examples.
To see this at work, create a script:
echo '
echo a
echo b >/dev/tty
' > s

and do:
sudo bash s >/dev/null

You will see b on the tty, because a went to the stdout and then to null.
The same goes for >/dev/null, but for the stdin of the script.
Therefore finally putting everything together this means that even if we call the program as:
echo a | ./a.sh >/dev/null

from that point onwards stdout and stderr will go to the tty and stdin will come from the tty, which would not happen without that command (stdin would come from a pipe, and stdout would go to /dev/null).
For portability reasons, I do not recommend that you rely on device files, since I think they are not specified by POSIX.


text:
Q: Hello, can a strategy.entry/exit be directly executed on a connected broker connection on Tradingview? can a strategy.entry/exit be directly executed on a connected broker connection?
The strategy.entry/exit does not open order/positions on connected broker instance


text:
Q: Multiple tooltips not showing correctly in react I am working with react D3 charts, and I have created charts and it is working fine.
What I have done

*

*I have several charts which are updating with in some time intervals, something like live data

*So here to achieve this I out use effect and updating my charts every second, and my data in charts updates correctly.

*I have given one tooltip on hover over the the bar, so that user can check the data for each bar or line.

Using below code to show the tooltip
.on("mousemove", function (event, d) {
    // this whole code is when I hover that perticular bar
    d3.select(this)
      .transition()
      .duration("50")
      .attr("opacity", 0.6)
      .attr("x", (a) => xScaleBars(a.timeline) - 3)
      .attr("width", xScaleBars.bandwidth() + 6)
      .style("filter", "url(#glow)");

    div.transition().duration(50).style("opacity", 1);
    div
      .html(
        `</text><text">
 value :  ${d.dataToShow}

        </text><text">
 Month :  ${d.month}
        `
      )

      .style("left", event.pageX - 58 + "px")
      .style("top", event.pageY - 140 + "px");
  })
  .on("mouseout", function (d, i) {
    // this is when I move cursor out of that bar
    d3.select(this)
      .transition()
      .duration("50")
      .attr("width", xScaleBars.bandwidth())
      .attr("x", (a) => xScaleBars(a.timeline))
      .style("filter", "none")
      .attr("opacity", "1");
    div.transition().duration("50").style("opacity", 0);
  })

Issue I am facing

*

*The issue is when I hover over one chart component it shows the tooltip, and than when I hover over the other both shows at the same time.

*What I am trying to do is to show the tooltip when I hover the one bar of any chart and than hide it,I tried below code
d3.select("svg").selectAll(".tooltipCHart").remove();
But it doesn't resolve my issue, I think I am missing some small part
here is my code sandbox which I tried

A: The problem is that you're creating a new tooltip div every time you re-render the chart.
A better approach is to have a hidden tooltip div in the beginning (in the render / return from your function component) and then just modify its contents and style (opacity: 1) on mouseover and mouseout. Keep track of the tooltip div using a ref.
See working codesandbox (I only modified chart1, you can make similar changes to chart2)


text:
Q: Google Org Chart Striations I am having problems with google charts displaying in Chrome. The issue is illustrated in the picture below.

The striations go across the entire chart area and I don't understand why. The striations do not show up in IE or Firefox. Does anyone has an idea about this issue?
Thanks in advance!


text:
Q: MongoDB Aggregation PHP, Group by Days I have the db with the following format
Array
(
[_id] => MongoId Object
    (
        [$id] => 53f4bf0e8db0d31b0ba802df
    )

[userSession] => 580929792589634763f964479eee8721
[pageEnteredDate] => 1408548587
[pageLeftDate] => 1408548622
[userName] => User 1
[userId] => 33657
[pageView] => monitoring patients
[pageActions] => []
[pageTag] => 1-3-16-131-315
[timeSpent] => 35
)
Array
(
[_id] => MongoId Object
    (
        [$id] => 53f3d7008db0d33e61cae841
    )

[userSession] => e04e5081c9482654030bacf3c8c90b21
[pageEnteredDate] => 1408488536
[pageLeftDate] => 1408489216
[userName] => user 2
[userId] => 4278
[pageView] => Surgery Staff
[pageActions] => [["BUTTON","Comment",1408488701],["A","Discussion",1408488712]]
[pageTag] => 1-3-5-148
[timeSpent] => 680
)
Array
(
[_id] => MongoId Object
    (
        [$id] => 53f3d7008db0d33gj1cae841
    )

[userSession] => e04e5081c9482654030bahjhc8c90b21
[pageEnteredDate] => 1408488536
[pageLeftDate] => 1408489216
[userName] => user 3
[userId] => 428
[pageView] => Surgery Staff
[pageActions] => [["BUTTON","Comment",1408488701],["A","Discussion",1408488712]]
[pageTag] => 1-3-5-148
[timeSpent] => 680
)

pageEnteredDate is the date that i want to use
I want to group the data by pagetag and day. I mean on one day i should get the same pageTag only once.
So, from those 3 arrays it should display only 2 because 2 have the same pageTag and are on the same day.
Thanks
***code used
$result = $this->collection->aggregate(
array(
    array(
        '$group' => array(
            '_id'=> array( 'pageTag' => '$pageTag','day' => array('$subtract' => array('$pageEnteredDate', 86400))),
            'timeSpent' => array( '$sum' => '$timeSpent' ),
            'lastView' => array( '$max' => '$pageEnteredDate' )
        )
    ),
    array('$skip' => 0),
    array('$limit' => 20)
)

);

A: Your "date" values appear just to be numbers derived from epoch timestamps ( without the milliseconds ). But all you really want to do here is apply $group via the aggregation framework, and a little date math to group by "day":
$result = $collection->aggregate(array(
    array(
        '$group' => array(
            '_id' => array(
                'pageTag' => 'pageTag',
                'day' => array(
                    '$subtract' => array(
                        '$pageEnteredDate',
                        array('$mod' => array(
                            '$pageEnteredDate',
                            60 * 60 * 24
                        ))
                    )
                )
            ),
            'timeSpent' => array( '$sum' => '$timeSpent' ),
            'lastView' => array( '$max' => '$pageEnteredDate' )
        )
    )
));

That basically says to group on both the "pageTag" values and using the "pageEnteredDate" to apply the math that essentially rounds the timestamp to the current day, so all values within the same day are the same.
You haven't said exactly what it is that you want to "group" here, so the examples are given of applying a $sum to the "timeSpent" value and using $max to identify the last timestamp value recorded on that day.
You can use any of the "grouping operators" in this way to suit your needs


text:
Q: Print name of the list while using KivyMDList I am developing an application that shows movie info. But a problem has arisen; how to find out which item of the mdlist has been clicked?
E.g: if I clicked a movie name in the list: joker, it should open a new screen with a name joker.
from kivymd.app import MDApp
from kivymd.uix.button import MDIconButton,MDFloatingActionButton
from kivymd.uix.screen import Screen
from kivy.lang import Builder
from kivymd.uix.list import OneLineListItem,OneLineIconListItem,IconLeftWidget,OneLineRightIconListItem
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivymd.uix.textfield import MDTextField
import imdb
from kivymd.uix.boxlayout import BoxLayout
from kivy.uix.image import AsyncImage
from kivymd.uix.label import MDLabel

Window.size=(300,500)

Builds ="""
ScreenManager:
    Search_screen:
    Show_screen:
    Movie_screen:

<Search_screen>:
    name:'searchs'
    MDIconButton:
        icon:'movie'
       pos_hint:{'center_x':.5,'center_y':.5}
       on_press:app.hlo()
    MDTextField:
        id:wow
        hint_text:'search movie'
        pos_hint:{'center_x':.5,'center_y':.9}
        color_mode: 'accent'
        width:300

<Show_screen>:
    name:'show'
    ScrollView:
        MDList:
            id:container
    MDFloatingActionButton:
        icon:'keyboard-return'
        pos_hint:{'center_x':.9,'center_y':.1}
        on_press:app.move()

<Movie_screen>:
    name:'movie'
    ScrollView:
        BoxLayout:
            MDCard:
    MDIconButton:
        icon:'android'
        on_press:root.manager.current='searchs'

"""

class Search_screen(Screen):
    pass

class Show_screen(Screen):
    pass

class Movie_screen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(Search_screen(name='search'))
sm.add_widget(Show_screen(name='show'))
sm.add_widget(Movie_screen(name='movie'))

class apps(MDApp):
    def build(self):
        screens = Screen()
        self.theme_cls.primary_pallete = "Orange"
        self.theme_cls.theme_style = 'Dark'
        self.helper = Builder.load_string(Builds)
        screens.add_widget(self.helper)
        return screens

def hlo(self):
    self.helper.current='show'
    ia = imdb.IMDb()
    name = self.helper.get_screen('searchs').ids.wow.text
    search = ia.search_movie(name)
    self.no=0
    self.j=0
    for self.i in search:

       self.helper.get_screen('show').ids.container.add_widget(OneLineListItem(text=str(self.i),#here on_presss it should print its name)

def wown(self,o):
    self.helper.current='movie'
    self.helper.get_screen('show').ids.container.clear_widgets()
def move(self):
    self.helper.current='searchs'
    self.helper.get_screen('show').ids.container.clear_widgets()

A: You just need to add an on_press or on_release to each OneLineListItem. Here is a modified hlo() method that does that:
def hlo(self):
    self.helper.current='show'
    ia = imdb.IMDb()
    name = self.helper.get_screen('searchs').ids.wow.text
    search = ia.search_movie(name)
    self.no=0
    self.j=0
    for self.i in search:
       self.helper.get_screen('show').ids.container.add_widget(OneLineListItem(text=str(self.i), on_release=self.item_pressed))

def item_pressed(self, item):
    print('item_pressed:', item.text)


text:
Q: Function calling messed event handling I trigger the event (focus the input element) only after the eventhandle() produces output after the body load. The comments are the output that are produced when eventhandle is called by the event Firing.
<input type="text" value="xyz" ></input>
<script>
    eventhandle();
    document.getElementsByTagName("input")[0].onclick=eventhandle
    function eventhandle()
    {
        alert(this.value);//works
        alert(event);    //works
        alert(event.type)//Error for all the properties of event object
    }
</script>

This problem gets resolved if I call eventhandle() after the DOM fires event on target ie.
<input type="text" value="xyz" ></input>
<script>
    document.getElementsByTagName("input")[0].onclick=eventhandle
    function eventhandle()
    {
        alert(this.value);
        alert(event.type); //works for all properties of event object
        alert(event)       //works
    }
    eventhandle();
</script>

I cant understand why the error occurs and how it gets resolved

A: Firstly, I don't know why you call the eventhandle like that, I mean eventhandle()? An event handle is not for calling directly, it will be called after an event is fired.
Secondly, you got the error because when the eventhandle function was called, your page was not completely loaded. You should use window.onload = your_handler first

A:
I cant understand why the error occurs

At the moment you are calling eventhandle() manually, no event was triggered, so the global event variable does not have a value.

and how it gets resolved

As you can see here, placing the call at the end of the code, doesn't actually resolve the error: http://jsfiddle.net/M7rXK/. The problem is still the same.

A: Okay, this is my code:
<input type="text" value="xyz" ></input>
<script>
    // eventhandle(); I hate this, verymuch =="
    document.getElementsByTagName("input")[0].onclick=eventhandle
    function eventhandle(event) // please parse a parameter represent the event here
    {
        alert(this.value);//works
        alert(event);    //works
        alert(event.type)// If works, plz tell me :D
    }
</script>

A: Event doesn't exits in Firefox. The following code should work in most browsers though:
document.getElementsByTagName("input")[0].onclick=eventhandle
function eventhandle(e)
{
    var event = e || window.event;
    console.log(this.value); // works
    console.log(event.type); //works for all properties of event object
    console.log(event)       //works
}
// trigger the click event without actually clicking on it
document.getElementsByTagName("input")[0].click();

In IE you have to press F12 to open the developer tools to see the console.log or it'll generate an error. In most other browsers you have to press F12 as well to open the console and see the console messages but it won't generate an error if it's not open.


text:
Q: how to put HashMap in BroadCast variable? I'm trying to put HashMap in BroadCast Variable, but getting below error
The method broadcast(T, ClassTag<T>) in the type SparkContext is not applicable for the arguments (Map<String,String>, ClassTag<HashMap>)

on below code snippet
Broadcast<HashMap<String, String>> br = ss.sparkContext().broadcast(mp, classTag(HashMap.class));

complete code
        private static <T> ClassTag<T> classTag(Class<T> clazz) {
                return scala.reflect.ClassManifestFactory.fromClass(clazz);
    }

        Dataset<Row> schema = ss.read().format("csv").option("delimeter", ",").option("header", "true")
                .option("quote", "").load("D:\\Data\\schema.csv");

        Map<String, String> mp = new HashMap<String, String>();

        schema.foreach((ForeachFunction<Row>) row -> {
            String[] names = row.schema().fieldNames();

            for (int i = 0; i< names.length; i++) {
                mp.put(names[i], row.getAs(names[i]));
            }

        });

        Broadcast<HashMap<String, String>> br = ss.sparkContext().broadcast(mp, classTag(HashMap.class));

Am literally stuck on this. Can anyone suggest what am doing wrong ?

A: You are using the Scala version of the SparkContext, you can get the Java version like this :
JavaSparkContext.fromSparkContext(sc).broadcast(new HashMap<String, String>());

No need for a class tag !


text:
Q: can i use variable in load data infile in mysql I've only got a 'working knowledge' of mysql.
Is it possible to use a variable in the LOAD DATA INFILE statement below. I'm getting a syntax error for the concat.
SET @DATA_DIR='/Documents/Projects/OCSCommerce/admin/src/main/testdata/csv';

-- import the roles
SELECT 'Importing roles' AS ' ';
LOAD DATA INFILE concat(@DATA_DIR, 'roles.csv') replace
INTO TABLE roles
FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"'
LINES TERMINATED BY '\r\n'
(id, created, lastUpdated, code, name, createUser_id, lastUpdateUser_id, visible, markForDelete);

Also if I could get the directory value from an environment variable, that's even better!


text:
Q: Как исправить ошибку: String types not allowed
Error:(182, 40) String types not allowed (at 'view_vertical_margin' with value 'm').

а вот и сам ФАЙЛ
 <dimen name="view_vertical_margin">m</dimen>

удаляю при чистке проекта все равно дает ошибку

A: Параметром данного значения должно быть число в одной из единиц измерения - px, dp, sp, in, pt, mm, а не символ (строка), о чем вам и сказано в ошибке, если бы вы ее прочитали.
<dimen name="view_vertical_margin">16dp</dimen>

PS: dimen - сокращение от dimenstion - размер, измерение и используется для указания меток к определенным значениям размеров на разметке.
Подробнее

A: Проблему решил так удалил xml файл затем вставил


text:
Q: How to show push notification at notification area iOS I have a Json Array Push Notification Arriving Like This,
 {
    "alert" : "You got your emails.",

    "badge" : 9
 }

I want to instantly display this array in notification tray of iphone | ipad

A: In your AppDelegate File.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSString *msg = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"MyTitle" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

This will show your message in your payload. Providing your application is in background,or foreground, NOT terminated.

A:
Use below Library to show notification in Navigation Bar

MPNotificationView
An in-app notification view that mimics the iOS 6 notification views which appear above the status bar.
Features:

Animation and layout similar to iOS 6 notifications
Provides two UILabels and an UIImageView
Simple API
Enqueues multiple notifications and shows them with a default
     duration of 2 seconds.

And if You want to get Notification, YOu have to do few code in Appdelegate.m File As given Below
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }

}

#pragma mark Notification tokan

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    deviceTokenForPushNotification  = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    deviceTokenForPushNotification = [deviceTokenForPushNotification stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSUserDefaults *objUserDefalut = [NSUserDefaults standardUserDefaults];
    [objUserDefalut setValue:deviceTokenForPushNotification forKey:@"DeviceToken"];
    [objUserDefalut synchronize];

    NSLog(@"My token is: %@", deviceToken);
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{

    NSUserDefaults *objUserDefalut = [NSUserDefaults standardUserDefaults];
    [objUserDefalut setValue:@"" forKey:@"DeviceToken"];
    [objUserDefalut synchronize];
}


text:
Q: How to subclass a UILabel in swift with letter spacing set to 1.5 using NSKernAttribute I am trying to subclass a UILabel so that it has a default kerning set to 1.5
then i am going to use that in my app with multiple labels. goal is to have default kern set out of the box so i can avoid repeated code all over the place also labels are set as mix of attributed and regular text
Example:
@IBoutlet weak var myLabel: CustomeLabelWithKern!
myLabel.attributedText = myAttributedText

@IBOutlet weak var myOtherLabelInADifferentViewController: CustomeLabelWithKern!
myOtherLabelInADifferentViewController.text "Foo Bar"

both of these label should have kern of 1.5
here is what i have so far
class CustomLabel: UILabel {
   var kerning: CGFloat = 1.5

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setKerning(kerning)
    }

    private func setKerning(kern: CGFloat) {
        guard let text = self.text else { return }
        let range = NSRange(location: 0, length: text.characters.count)
        let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
        mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
        attributedText = mutableString
    }
}

A: Here is what i have so far i think i will use this solution for now if anyone comes up with a better one i will be happy to try that as well
class CustomLabel: UILabel {
    static var kerning: CGFloat = 1.5

    override func awakeFromNib() {
       super.awakeFromNib()
       setKerning(CustomLabel.kerning)
    }

    func setKerning(kern: CGFloat) {
        let text = self.text ?? ""
        let range = NSRange(location: 0, length: text.characters.count)
        let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
        mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
        attributedText = mutableString
    }
}

I can use it like this in my viewController
mylabel.text = "Hello World!" // this should be set to 1.5 by default but what if i am setting my label dynamically?
mylabel.setKerning(1.5) // Here i am passing the value so if the label is set dynamically set it will have correct spacing

// This also works if some of my labels have attributed text
myAttibutedLabel.attributedText = myAttributedText
myAttributedLabel.setKerning(1.5)

I think a this can be reduce to just an extension on UILabel class
like so
extension UILabel {
    func setKerning(kern: CGFloat) {
        let text = self.text ?? ""
        let range = NSRange(location: 0, length: text.characters.count)
        let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
        mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
        attributedText = mutableString
   }
}

A: How about subclassing UILabel like this:
class TestKerningLabel: UILabel {
 func addKerning(kerningValue: Double) {
    let attributedString = self.attributedText as! NSMutableAttributedString
    attributedString.addAttribute(NSKernAttributeName, value: kerningValue, range: NSMakeRange(0, attributedString.length))
    self.attributedText = attributedString
 }
}

And then use this in your VC:
let testLabel = TestKerningLabel()
testLabel.attributedText = NSAttributedString(string: "test")
testLabel.addKerning(kerningValue: 1.5)
view.addSubview(testLabel)


text:
Q: Can't figure out geolocation So I'm trying to use geolocation in Javascript for the first time. I basically copied over the code from another stack overflow jsfiddle example, that worked, but I'm getting some weird errors. For awhile I was getting a "maximum callstack size exceeded jquery" error (and like 20 calls to getLocation() ) in the JS console, and now I'm getting nothing back - except for the little target icon in the address bar with an X over it saying location permission denied (even after automatically allowing all location requests). That's on chrome. Tried safari, it gave an alert asking for permission but then nothing happened. Still no errors. Any suggestions?
    $(window).load(function() {
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
        else {
            $('#test').write("Couldn't fetch location.");
        };
    };

    function showPosition(position) {
        $('#test').write("
Latitude: \"" + position.coords.latitude + "\"
");
        $('#test').write("
Longitude: \"" + position.coords.longitude + "\"
");
    };

    getLocation();
});,

A: There is no write() method in jQuery, and you have a comma at the end there.
Fix the syntax errors and it should work :
$(function() {
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
        else {
            $('#test').html("Couldn't fetch location.");
        }
    }

    function showPosition(position) {
        $('#test').html("
Latitude: \"" + position.coords.latitude + "\"
");
        $('#test').append("
Longitude: \"" + position.coords.longitude + "\"
");
    }

    getLocation();
});

FIDDLE

A:


text:
Q: Android - using webview from activity 2 in activity 1 i have WebView in activity WebViewActivity, and some imagebuttons in main_activity.
Can u help me? I need when i click imagebutton1, it will open WebViewActivity ane open in WebView etc google.com. When i Click imagebutton2, it will open etc yahoo.com . Im new in programming, and im not anglophone (my english is bad because im from czech rep). Thanks for any help!
MAIN ACTIVITY
package com.tona.arcig;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        ImageButton imgbutton1 = (ImageButton) findViewById(R.id.imageButton1);
        imgbutton1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "I like trains", Toast.LENGTH_LONG).show();
            }
        });
    }

}

WEBVIEWACTIVITY
package com.tona.arcig;

import android.app.Activity;
import android.os.Bundle;

public class WebviewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

    }

}

ACTIVITY MAIN XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/suplovani"
            android:src="@drawable/suplovani" />

        <ImageButton
            android:id="@+id/imageButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/rozvrh"
            android:src="@drawable/rozvrh" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageButton
            android:id="@+id/imageButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/prihlasovani"
            android:src="@drawable/prihlasovani" />

        <ImageButton
            android:id="@+id/imageButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/email"
            android:src="@drawable/email" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageButton
            android:id="@+id/imageButton5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/email"
            android:src="@drawable/moodle" />

        <ImageButton
            android:id="@+id/imageButton6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:contentDescription="@string/kdm"
            android:src="@drawable/jidelna" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/imageButton7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/o_aplikaci"
            android:src="@drawable/about" />

    </LinearLayout>

</LinearLayout>

ACTIVITY WEBVIEW XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>

MANIFEST
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>

STRINGS
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="suplovani">Suplování</string>
    <string name="rozvrh">Rozvrh hodin</string>
    <string name="prihlasovani">Přihlašování do systému</string>
    <string name="email">Email</string>
    <string name="moodle">Moodle</string>
    <string name="kdm">KDM</string>
    <string name="o_aplikaci">O Aplikaci</string>
    <string name="app_name">Arcig.CZ</string>
    <string name="title_webview">Arcig.CZ</string>

</resources>

Thank you.

A: Here is basic skeleton of what should you do.
First you should pass some data depending on what button have you clicked(for example url string).
Next you should retrieve data and open appropriate url.
Here is how you can achieve this.
Intent openWebViewActivity = new Intent(this, WebViewActivity.class); // this is current Activity
openWebViewActivity.putExtra("web_url", "google.com"); // openWebViewActivity.putExtra("web_url", "yahoo.com");
startActivity(openWebViewActivity);

Now new Activity will be opened with appropriate intent.
And you can get url from this.
package com.tona.arcig;
import android.app.Activity;
import android.os.Bundle;

public class WebviewActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    String urlToLoad = getIntent().getStringExtra("web_url");
    WebView webView = (WebView) findViewById(R.id.webview);
    webView.loadUrl(urlToLoad);
}
}


text: Q: How can I edit the default email template in wordpress? Well, I have a problem. I have set up that after registering a new user, an e-mail with a verification link is sent to him. And how could I edit the template of this e-mail, or at least translate elements into another language?


text:
Q: onDraw and ontouchEvent method public class AI extends AppCompatActivity {
    public static Game gameAI = new Game();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DrawGameAI view = new DrawGameAI(this);
        setContentView(view);
    }
}
class DrawGameAI extends View {

    public DrawGameAI(Context context){
        super(context);
    }

    protected void onDraw(Canvas canvas){
        ....
    }

    public boolean onTouchEvent(MotionEvent e){
            if(gameAI.getBlackTurn() == true) {
                gameAI.move((int) ((xPos - 7.0 / 1080.0 * width) / gridSize), (int) ((yPos - 7.0 / 1080.0 * width) / gridSize));
                invalidate();
                break;
            }

            else if(gameAI.getBlackTurn() == false){
                    gameAI.AI();
                    invalidate();
                    break;
                }
            }
            return true;
        }
    }
}

My idea is that I am the black and the AI is the white. Each time I click on on my board, it will paint a black piece on the position. Then I want my AI to automatically respond. (the gameAI.AI() will put a piece on the board when it is AI turn, gameAI.move() will switch the turn and put my black piece on the board)
My problem is that each time I have to click on the screen when it is the AI turn, which triggers the ontouchEvent to make it draw.
I tried to change else if(gameAI.getBlackTurn() == false) to if(gameAI.getBlackTurn() == false), so in this way, after the first if statement, my turn is completed and the program will execute the second if statement, which looks like
if(gameAI.getBlackTurn() == true) {
    gameAI.move((int) ((xPos - 7.0 / 1080.0 * width) / gridSize), (int)
    ((yPos - 7.0 / 1080.0 * width) / gridSize));

}

if(gameAI.getBlackTurn() == false){
    gameAI.AI();
}
invalidate();
break;

This time, after each ontouchEvent, two pieces are on the board, then onDraw will be called and draw the my piece and AI piece at the same time.
However, my AI is really slow. I have to wait for a while before the two pieces are drawn at the same time.
Therefore, what I want is after my turn, immediately paint the black piece on the board, then I do not have to touch the screen when it is the AI turn and after the AI moves, paint the AI piece on the board.
How can I do this? Thanks!


text:
Q: Obtner datos de promesa sin uso de la palabra then en javascript? Tengo una duda:se que para obtener el dato de una promesa se usa la palabra Then. Pero me gustaría saber si existe otra forma,ejemplo:
El siguiente código funciona bien ,el resultado se guarda en la variable resultado y con un then saco los datos de la promesa. Pero solo puede ser así? No existe otra manera en la que uno pueda obtener los datos sin usar then?
const resultado=(async function api(){

const peticion=await fetch('https://api.hacienda.go.cr/fe/ae?identificacion=112720566')
json=await peticion.json()

return json
})()

resultado.then(resultado=>console.log(resultado))

A: Tanto el uso de:

*

*then

*catch

*finally
Nos ayudan a obtener y manejar el eventual resultado de la promesa; entonces no veo modo de evitar manejar el estado de la promesa sin alguna de las funciones mencionadas.
Directamente lo que estás usando que es async & await lo pudieras administrar dentro de la propia función que se auto ejecuta por medio de una estructura de control try/catch que en conjunto con await van a terminar haciendo casi lo mismo que las promesas que tienes escritas de forma explícita.
Es decir pudiera quedar así:
const resultado=(async function api(){

const peticion=await fetch('https://api.hacienda.go.cr/fe/ae?identificacion=112720566')
try{
  json=await peticion.json()
    console.log(json)
}catch(error) {
  console.log(error.message)
}

})()

Ahora conviene aclarar que el que no se vean no quiere decir que las promesas y su manejo por medio de alguno de las funciones ya no existen, pues:

*

*Cuando hacemos uso de la palabra await indicamos que se pausará la ejecución para que se resuelva, esto sería en el try como obtener el estado de resolve

*en la sección de catch que pudiera equivaler a un reject donde la petición fallo y en concencuencia obtendremos el mensaje de ese estado.

Te invito a leer la documentación de Mozilla developer donde dice y cito 1

La finalidad de las funciones async/await es simplificar el comportamiento del uso síncrono de promesas y realizar algún comportamiento específico en un grupo de Promises. Del mismo modo que las Promises son semejantes a las devoluciones de llamadas estructuradas, async/await se asemejan a una combinación de generadores y promesas.

Referencias

*

*1 Mozilla Developer


text:
Q: Blacklist career-development Not only blacklist, but perhaps put up a message 'if you thought this tag was appropriate, your question is almost certainly off-topic'?
In any case, I burned up a stack of close votes starting the cleanup process, but I'm no Hercules and the stable is Augean. Could I get some help?

A: From our experience on Programmers, tags with questions in them do not get blacklisted. Editing the tag wiki to say "do not use this tag" is also not a very reliable deterrent.
Orchestrating a mass clean-up of the questions in the career-development tag is something we could do as a first step: vote to close and/or delete questions as appropriate. Some might be worth migrating to Programmers, but it'd have to be judged carefully and on a case-by-case basis.
It's pretty clear that these questions are off-topic on Stack Overflow now en masse, so it should be fairly easy to close and remove (where needed) these questions in preparation for removing the tag itself.

A: If you're going to special-case a tag, why not offer to move the already-entered content to the programmers.se "Ask a Question" form?
If we have a good idea where such questions are on-topic, we should at a minimum point users there, instead of dismissing them with "it's off-topic".  After all, that's why questions get migrated instead of simply closed.
But if we can save the user the effort of re-entering their question on the other site, why not?


text:
Q: Pandas обновить сводную таблицу (Pivot table) есть Pivot файл, Ссылка: TransFiles.ru/os4r7  в Sheet2 хранятся данные, которые переодически дополняются из других источников
В Sheet1 создана сводная таблица, на основе данных из Sheet2

проблема заключается в том, что перед тем, как исползовать данные, приходиться вручную обновлять таблицу в Sheet1

Вопрос: возможно ли обновить таблицу в Sheet1 посредством Pandas или Openpyxl?


text:
Q: Show class docstring in VSCode There are some classes written with the docstring at the class level, as opposed to under methods like the init method, for example PyTorch's CrossEntropy loss class.
How can I show the class docstring in VSCode with a shortcut, similar to this question?

A:

*

*Set these three key-bindings in the picture.

*Click or move the cursor to what you want to display the content

*Use the shortcuts to get.

You can also use the methods in the comments, hover over an instance of that class with your mouse.


text:
Q: Error "The name "soap" does not denote a namespace" if i try to parse XML in T-sql When i try to parse XML in T-sql I get error "The name "soap" does not denote a namespace"
This is my XML and query. Answer, please, how can I parse such XML. Thanks.
DECLARE @xml xml
SET @xml =
'<soap:Envelope xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/>
   <soap:Body>
      <GetWebLinkResponse xmlns=http://test.org/ xmlns:ns2=http://schemas.datacontract.org/2004/07/.Configuration xmlns:ns3=http://schemas.datacontract.org/2004/07/.Configuration.Results xmlns:ns4=http://schemas.microsoft.com/2003/10/Serialization/>
         <GetWebLinkResult>
            <ns3:Error>
               <ns2:Id>0</ns2:Id>
               <ns2:Text>Success.</ns2:Text>
            </ns3:Error>
            <ns3:Url>
                    https://example.com&content=true
                    </ns3:Url>
         </GetWebLinkResult>
      </GetWebLinkResponse>
   </soap:Body>
</soap:Envelope>'

SELECT
   -- n.value('(./Code/text())[1]','int') as CODE
--,
  n.value('ns3:Url','varchar(1000)')as NAME
FROM @xml.nodes('/soap:Envelope/soap:Body/GetWebLinkResponse/GetWebLinkResult') as a(n)

A: First of all - your XML is invalid - your namespace definitions must be in double quotes:
DECLARE @xml xml
SET @xml =
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <GetWebLinkResponse xmlns="http://test.org/" xmlns:ns2="http://schemas.datacontract.org/2004/07/.Configuration" xmlns:ns3="http://schemas.datacontract.org/2004/07/.Configuration.Results" xmlns:ns4="http://schemas.microsoft.com/2003/10/Serialization/">
         <GetWebLinkResult>
            <ns3:Error>
               <ns2:Id>0</ns2:Id>
               <ns2:Text>Success.</ns2:Text>
            </ns3:Error>
            <ns3:Url>
                    https://example.com&content=true
                    </ns3:Url>
         </GetWebLinkResult>
      </GetWebLinkResponse>
   </soap:Body>
</soap:Envelope>';

Once you've corrected that, you'll need to define all relevant XML namespaces for your T-SQL query. Relevant XML namespaces are all explicitly used namespaces (like soap: and ns3:), as well as default namespaces like the xmlns="http://test.org/" on your <GetWebLinkResponse> node.
When you declare them all - the T-SQL query should work:
WITH XMLNAMESPACES('http://schemas.xmlsoap.org/soap/envelope/' AS soap,
                   'http://schemas.datacontract.org/2004/07/.Configuration.Results' as ns3,
                   DEFAULT 'http://test.org/')
    SELECT
        n.value('(ns3:Url)[1]', 'varchar(1000)') AS NAME
    FROM
        @xml.nodes('/soap:Envelope/soap:Body/GetWebLinkResponse/GetWebLinkResult') as a(n)


text:
Q: Algotrading - store websocket data in database I'm trying with Algo-trading. so I have WebSocket which has market data, I'm trying to store in the database. other modules read this stored database and make the buy/sell decisions.

*

*what should be the best database option here considering it should be faster to insert the data and required concurrent reading.

*how do I handle the WebSocket data, it contains a lot of data to store, without losing the data.

?

A: To answer question 1:
You can use a memory based database such as redis.
For question 2:
you can use rabbitMQ or kafka.

A: To answer question 1:
Several people use Redis Timeseries to store market data for analysis/display.  Insert and retreival are fast.
For question 2:
You could run several consumers and use Redis for de-duplication so you don't update everything twice, but it will heavily depend on your stack


text:
Q: CSS transforms not pixel perfect I have the following example for an off-canvas menu: http://jsfiddle.net/pwghdvoh/
When you click the button in the top left of the blue header, it moves the main app view to reveal the hidden menu.

It does this using the following CSS:
.showSidebar .app
{
    -webkit-transform:  translateZ(-20px)
                        translateX(240px);
            transform:  translateZ(-20px)
                        translateX(240px);
}

However I'm finding that on various resolutions that the app is not moved 240px to the right and 20px offset from the the top and bottom... If you look at the screenshot, you can see that it's too close to the top and bottom of the screen, it should have 20px at the top and bottom.
Could this be caused by the perspective of the wrapper being incorrect?
I do this dynamically using jQuery:
$('.wrapper').css({
    'perspective': $(window).width(),
    '-webkit-perspective': $(window).width()
});

So it's always the perspective of the viewport width. But this doesn't seem to fix the issue.
Any ideas?

A: Instead of giving width: 100% and height: 100% to the .wrapper class, I added position absolute and stretched it to its parent container which is body element. and when the side bar is viewed, I gave the top and bottom properties as 20px which overrides the already provided 0px value.
.wrapper {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
}
.wrapper.showSidebar {
    top: 20px;
    bottom: 20px;
}

Working Fiddle


text:
Q: Vertically center div in a div with height auto Well, I got this structure:

    #parent{
       max-width: 800px;
       height: auto;
       margin: auto;
    }
    #child{
       position: absolute;
       width: 100%;
       height: 52px;
       display: none;
    }

The child div is hidden per default. It gets visible by using jQuery (.fadeIn). Now the question is, how can I vertically center the child element by using only css?

A: I have created a prototype... But I had to modify your HTML and CSS so it might not be the best solution: http://jsfiddle.net/TmCwB/
HTML

CSS
#outerDiv {
    margin: 0 auto;
    width: 200px;
}
#parent{
    background-color: red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 200px;
    height: 500px;
}
#child{
    width: 100%;
    height: 52px;
    display: inline-block;
    background-color: blue;
}

Hope this helps...

A: #child{
   position: absolute;
   width: 100%;
   height: 52px;
    /*display:none;*/
   display: block;
   background-color: blue;
   top:50%;
}

just add top:50% to your CSS code.
http://jsfiddle.net/nirus/dry2Q/

A: Ok guys. Thank you for your answers. Atrox11's answer was the right one but I found out that there was another issue that I had to deal with.
There's another wraper div. Since all my children divs are positioned absolute, the parent div had a height of 0px. This was the actual fault. After I fixed that, everything worked as expected.
Sorry for the question. I would appreciate it, if you won't rate it down, since everyone makes some mistakes when he is in a hurry.


text:
Q: Where is gradle tasks in Android Studio 4.1? I updated my android studio to 4.1. But I can't find Gradle tasks in the Gradle tab. Does anybody know where these Gradle tasks moved?

A: On the Gradle tab if you can see the project name but there isn't any task, right-click on the project name, and then in the opened dialog click on the "Reload Gradle Project".


text:
Q: CMSampleBufferRef to Audio Video for RTMP streaming I am using iOS libRTMP to connect to an RTMP server. Now my problem is, how can I send the audio and video to an RTMP server? I've seen that CMSampleBufferRef is used for processing and sent to the server. The data is being processed with some flash video like metadata.
I tried VideoCore but it fails with the server I am using(Evostream) but works with other servers. Medialibs works but I need an open source option.
How do we convert CMSampleBufferRef to a format that RTMP understands?


text:
Q: Checking if a number is a Simber A simber is defined as a positive integer in which any odd digit, if present, occurs an odd number of times, 1414414 is a simber. 4 is even and it appears four time and 1 is odd and it appears 3 times.
Here are my variables:
int is_simber(int n)
{
    int numberOfTimes = 0, length = 1, x = n;
    bool answer;
    vector <int> nmbrs = vector <int>();

    //get how many digits are in the integer

    do
    {
       x /= 10;
       length++;
    }
    while(x != 0)

    //get the digits in the integer

    for(int i = 0; i<length; i++)
    {
      nmbrs.push_back(((n/10^i) % 10);
    }

    //checking how many times a digit occurs and also testing to see if the digits
    //meet the requirements

    for(int i = 0; i<length; i++)
    {
        for(int j = 0; j<length; j++)
        {
            if (nmbrs.at(i) == nmbrs.at(j))
            {
                numberOfTimes++;
            }
        }

        if (nmbrs.at(i) % 2 == 0 && numberOfTimes % 2 == 0)
        {
          answer = true;
        }

        else if(nmbrs.at(i) % 2 == 1 && numberOfTimes % 2 == 1)
        {
            answer = true;
        }

        else if(nmbrs.at(i) % 2 == 0 && numberOfTimes % 2 == 1)
        {
            answer = false;
            break;
        }

        else if(nmbrs.at(i) % 2 == 1 && numberOfTimes % 2 == 0)
        {
            answer = false;
            break;
        }
    }

    return answer;
}

A: *

*Your code has compilation errors.

*^ is Binary XOR Operator. You can't expect it to produce pow(10,i). So replace nmbrs.push_back(((n/10^i) % 10); with nmbrs.push_back(((n/pow(10,i)) % 10);

*When I was able to remove the compilation errors, i realized your code has logical errors too. As your given definition of simber, int is_simber(int n) should be fair and simple.
bool is_simber( int n )
{
    if ( n<0 ) return false; // simber is a positive integer

    int digitCount[10] = {}; // initializing all with 0;
    // digitCount array holds the number of occurance of a digit
    // so d[1] holds the number of times 1 occurred
    // d[2] holds the number of times 2 occurred and so on ...

    while( n ){
        int d = n%10;
        n /= 10;
        digitCount[d]++;
    }

    // we just have to check
    // any odd digit, if present, occurs an odd number of times

    for( int i=1; i<=9; i= i+2) // Attention i=i+2, to iterate over just odd numbers
    {
        if( digitCount[i] != 0 && digitCount[i]%2 == 0 ) return false;
    }
    return true;
}

A: My definition of is_simber
inline bool is_even(int n) { return n % 2 == 0; }

bool is_simber(int n) {
    if (n < 0) return false;
    int digits[10] = {0};
    for (; n; n /= 10) ++digits[n % 10];
    for (int i = 0; i < 10; i += 2)
        if (!is_even(digits[i]) && is_even(digits[i + 1])) return false;
    return true;
}

LIVE DEMO


text:
Q: Proxy_pass 127.0.0.1 in nginx does not work I install nginx as a reverse proxy. If I use:
proxy_pass http://127.0.0.1:81

it does not work. But if I use:
proxy_pass http://domain.com:81

it works. And I can use browser to access to http://domain.com:81 and http://ip:81
Could anyone explain for me?

A: The telnet command I gave shouldn't have a colon. It should be "telnet 127.0.0.1 8080". It it doesn't work then I would guess whatever web server you're using isn't being bound to 127.0.0.1 and/or port 8080.

A: I couldn't find reason why it doesn't work, but what if you try like this:
proxy_pass http://localhost:81


text:
Q: Sum of features from one layer to another I have two different shapefiles and I work in Arcmap. This is what I have:

The areas in picture 1 are smaller areas and the areas in picture 2 are in an aggregated form. File 1 contains number of residents in the years 2000, 2005, 2010 and 2015. What I need is to sum the number of residents by year to know how many people are living in the larger areas. So, lets say 4 of the smaller areas make out for 1 of the bigger ones. I need to sum the number of residents from the 4 areas to know the number of residents in the 1 large one. The strange thing is; I know I've done this with the dissolve-tool before but I simply cannot remember what I'm doing wrong right now.

A: You can right click on the aggregated file Join and Spatial Relates> Join.
Then click 'Join Data from another layer based on spatial location. You can choose the option to sum the values at point 2.


text:
Q: How to show tooltip on a point click in swift I am drawing the lines using the following code. The line edges have dots and i want to show the tooltip when user click on the end dots.
The code snippet is below,
 override func drawRect(rect: CGRect) {
        // Drawing code
      UIColor.brownColor().set()
    let context = UIGraphicsGetCurrentContext()
    //CGContextSetLineWidth(context, 5)
    CGContextMoveToPoint(context, 50, 50)
    CGContextAddLineToPoint(context,100, 200)
    CGContextStrokePath(context)

    // now add the circle on at the line edges

        var point = CGPoint(x:50 , y:50)
        point.x -= 5.0/2
        point.y -= 5.0/2
        var circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0,height: 5.0)))
        circle.fill()

        point = CGPoint(x:100 , y:200)
        point.x -= 5.0/2
        point.y -= 5.0/2
        circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0,height: 5.0)))
        circle.fill()

    }

It is currently displaying the following image,

and i want to show the tooltip like below,

Does anybody have an idea how will i recognise that this particular dot is clicked and also how will i show the tooltip.
I am looking for a solution in swift.

A: Define a struct to hold points you have to touch, and the text to show:
struct TouchPoint {
    var point: CGPoint // touch near here to show a tooltip
    var tip: String // show this text when touched
}

then in the UIView subclass where you define drawRect, make somewhere to keep them:
var touchPoints: [TouchPoint] = [] // where we have to touch and what tooltip to show

drawRect can be called many times, so start fresh each time:
override func drawRect(rect: CGRect) {
    touchPoints = []
    // ...
    // add a touchPoint for every place to touch
    touchPoints.append(TouchPoint(point: point, tip: "point 1"))
}

You need to detect taps on the UIView, so add a gesture recognizer by changing its initialisation:
required init?(coder aDecoder: NSCoder) {
    // standard init for a UIView wiht an added gesture recognizer
    super.init(coder: aDecoder)
    addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("touched:")))
}

then you need a method to see whether touches are near touchpoints, and to show the right tooltip:
func touched(sender:AnyObject) {
    let tapTolerance = CGFloat(20) // how close to the point to touch to see tooltip
    let tipOffset = CGVector(dx: 10, dy: -10) // tooltip offset from point
    let myTag = 1234 // random number not used elsewhere
    guard let tap:CGPoint = (sender as? UITapGestureRecognizer)?.locationInView(self) else { print("touched: failed to find tap"); return }
    for v in subviews where v.tag == myTag { v.removeFromSuperview() } // remove existing tooltips
    let hitPoints:[TouchPoint] = touchPoints.filter({CGPointDistance($0.point, to: tap) < tapTolerance}) // list of tooltips near to tap
    for h in hitPoints { // for each tooltip to show
        let f = CGRect(origin: h.point+tipOffset, size: CGSize(width: 100, height: 20)) // fixed size label :-(
        let l = UILabel(frame: f)
        l.tag = myTag // just to be able to remove the tooltip later
        l.text = h.tip // draw the text
        addSubview(l) // add the label to the view
    }
}

func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat { return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y) }

func CGPointDistance(from: CGPoint, to: CGPoint) -> CGFloat { return sqrt(CGPointDistanceSquared(from, to: to)) }

and that incidentally uses a new version of the + operator to perform vector addition on CGPoint:
func +(left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x+right.dx, y: left.y+right.dy) }

and that works OK for me. Extra tweaks would be to compute the UILabel size from the text string, and move the UILabel so it didn't run off the side of the UIView at the edges. Good Luck!


text:
Q: How to create AdDuplex control using c#? I have AdDuplex control xaml code like below:
<adduplex:AdControl Name="adduplexControl" xmlns:adduplex="clr-namespace:AdDuplex;assembly=AdDuplex.AdControl.Silverlight" AppId="myid" Margin="0,68,0,0" Background="Black" />

How can I create this control using c#?
I tried like this:
AdDuplex.AdControl a = new AdDuplex.AdControl();
a.AppId = "myid";

But I don't know how to create xmlns:adduplex property.

A: That property is an XML namespace definition.  It is used by the xaml serializer to identify particular types during deserialization.
The namespace follows a specific format, containing the namespace of the type (AdDuplex), and the name of the assembly where its definition can be found (AdDuplex.AdControl.Silverlight.dll).  The name of the XML namespace is adduplex (xmlns:adduplex).  With this information, the xaml serializer can locate the AdControl type (adduplex:AdControl).
This attribute is added during serialization, and does not affect the state of any instance of AdControl.
tl;dr: You don't have to.

A: Here is an example of creating an AdDuplex.AdControl in code:
AdDuplex.AdControl adduplex = new AdDuplex.AdControl();
adduplex.AppId = "YOUR_AD_UNIT_HERE";
adduplex.Width = 480;
adduplex.Height = 80;
adduplex.VerticalAlignment = VerticalAlignment.Top;
adduplex.HorizontalAlignment = HorizontalAlignment.Center;
adduplex.Margin = new Thickness(0, 0, 0, 0);

That's will create a AdDuplex banner dynamically.
On AppId don't use your app ID, use the adUnit to avoid the "Configuration Error".


text:
Q: How to compare convergence of two equations for the arctangent function? I want to compare two equations for the arctangent function:
$$\tag{1}\arctan\left(x\right)=\sum\limits_{n=0}^{\infty}{\frac{{2^{2n}}{\left(n! \right)}^{2}}{\left(2n+1\right)!}\frac{x^{2n+1}}{{\left(1+x^2\right)}^{n+1}}}$$ and $$\tag{2}\arctan\left(x\right)=i\sum\limits_{n=1}^{\infty}{\frac{1}{2n-1}}\left(\frac{1}{\left(1+2i/x\right)^{2n-1}}-\frac{1}{\left(1-2i/x\right)^{2n-1}}\right).$$
Which of them is faster in convergence?

A: If $x > 0$, let $r = 1/|1 + 2 i/x| = 1/\sqrt{1 + 4/x^2}$ and the $n$'th term on the right of the second sum is dominated  by $2/((2n-1)r^{2n-1})$.
On the other hand, for large $n$ the $n$'th term in the first sum is approximately $\sqrt{\pi/(4n)} (x/(1+x^2)) (x^2/(1+x^2))^n$.
Since $$ \frac{x^2}{1+x^2} > \frac{1}{1+4/x^2} = \frac{x^2}{4 + x^2}$$
for all $x > 0$ we find that the $n$'th term in the second sum will go to $0$ asymptotically faster.
Here is an animation showing the absolute values of the errors in the $N$'th partial sums for $N$ from $1$ to $50$ and $x$ from $0$ to $3$.  The red curve is for the first series and the blue curve is for the second.


text:
Q: How to return a value from a recursive asynchronous callback? I'm using the facebook js sdk, I'm trying to get a list of all groups, the response is pageinated.  So recursion seems like a an obvious solution for this
function handlePaging(response) {
  if (response && !response.error) {
    if (response.paging.next) {
      return response.data.concat(FB.api(response.paging.next, handlePaging));
    } else {
      return response.data;
    }
  }
}

console.log(FB.api("/me/groups", handlePaging));

But because its asynchronous I'm getting undefined returned.  I've had a look at other returning values from asynchronous requests, but none of them were recursive, and the answer was use a callback, which I have.
I'm not even sure if this is even possible.

A: The call to FB.api is asynchronous so it returns immediately usually before the call to the server is made and the handlePaging callback is invoked. Try something like this
    var data = [];

    function handlePaging(response) {

      if (response && !response.error) {

        data = data.concat(response.data);

        if (response.paging.next) {
          FB.api(response.paging.next, handlePaging);
        } else {
          console.log(data);
        }

      }

    }

    FB.api("/me/groups", handlePaging);


text:
Q: Automatically ssh into remote host depending on the folder you're in Is there a solution (or plugin for zsh) that will allow me to remote ssh depending on the folder in local OS? Similar to PyENV.
So if I develop a project and do
cd /home/projects/ERP
ssh production
ssh development

so that with easy to remember commands I jump right into desired remote host?
I understand I can do aliases and load them from a local folder when I switch dirs, but is there a better way?
Thanks,
Dmitry

A: Apparently I don't have enough reputation to comment to ask for clarification, so I'll just guess here, and edit my answer as necessary if it's incomplete.
I don't know of any such plugin, but writing one would not be too difficult. Your use case is not a common one, so that's probably the way to go. There are like 5 different ways to do this.
First, though, I should mention that it is entirely possible to have "host aliases" in your /etc/ssh/ssh_config or ~/.ssh/config, which makes it easy to assign a specific host alias to a set of configuration options for SSH.
Below is an example.
Host router
    Hostname 10.0.0.1
    Port 222
    User root

This would make typing ssh router equivalent to typing ssh root@10.0.0.1 -p 222.
This probably covers a significant amount of your use case. Sorry if you already knew this -- I'm just trying to cover all the bases, here.
If you really need SSH to interpret a fixed SSH command in different ways, you would most likely need a wrapper around the SSH command which looks at the input arguments, recognizes key ones (e.g., production or development), interprets those, then picks one of the possible hosts (possibly pre-configured in the SSH config) depending on the value of $PWD.
Let me know if this helps! ^.^

Update: thanks a bunch to @fra-san, who pointed out a much more elegant option! :D (At the very least, much more elegant if you have relatively few special cases...)
You can simply do:
Match host production, exec ssh_match_dir
    Port 5555
    Hostname foodev.biz

Where ssh_match_dir is a script in your PATH that exits with status 0 when it detects that the condition should apply, like so:
#!/usr/bin/env bash
if test "$PWD" = "/home/a/git"; then
    exit 0
else
    exit 1
fi

Be sure to look at man ssh_config and pay especial attention to the TOKENS section -- which includes info on arguments you can tell ssh to pass to the script to add extra conditions. I believe you could have a single script handle each host with different arbitrary conditions if you use exec ssh_match_dir %h and add some argument parsing to the script -- depending on what your use case is.


text:
Q: Manual Approval option via Executable shell in Jenkins FreeStyle job I want to ask for manual approval (Approve or Reject) in Jenkins pipeline console whenever the pipeline job execution starts. I want to achieve this with FreeStyle job and write manual approval code in Execute shell window.
Can someone Please help with your suggestions on this.