text:
Q: How to enable capability with Tuist iOS I use this tool "Tuist" (https://tuist.io) to generate Xcode project. With Tuist we can't edit any settings through Xcode directly. How to enable background mode/notification capability with Tuist

A: Using tuist means getting rid of the need of maintaining .xcodeproj manually. All relevant settings are defined in the tuist configuration, and by running tuist generate, the related .xcodeproj will be generated.
To apply Info.plist changes (the capabilities are defined there), you have to set up a InfoPlist dictionary of [String : InfoPlist.Value], and herein, you define whatever you want. For background modes, this is - as an example -  "UIBackgroundModes": ["fetch", "remote-notification", "remove-notification"].
Then, you take that InfoPlist definition and provide it to a Targetof a Project, that's it.
The tuist documentation shows the syntax of the available configuration options, as well as some examples. You may want to have a look on medium.com, there are some more articles about working with tuist in practice. (I've written one there about creating a workspace with a main app and various module frameworks.)


text:
Q: Invariant of time-order in lightlike interval I'm trying to prove that the time order is invariant in a lightlike interval, I have this
$$P_1=(X_1^0, X_1^1,0,0)$$
$$P_2=(X_2^0, X_2^1,0,0)$$
Two lightlike events in a inertial frame where $t_2>t_1$. Under Lorentz transformations from a $\Sigma '$ frame I have
$$\Delta t' = \gamma(v)(\Delta t-\frac{v}{c^2}\Delta x)$$
Since the events are lightlike $c^2\Delta t^2=\Delta x^2$, where $\Delta t>0$, previously I got that, since $\Delta t>0$, $\Delta x>0$ as well, but, back in the equation above, it doesn't guarantee $\Delta t'>0$, I realized that if $\Delta x<0$ then $\Delta t'>0$, should it be like that? How do I get $\Delta x<0$ knowing the events are lightlike?
EDIT: I did this
Since the events are likelight and $c^2\Delta t^2=\Delta x^2$, we can just get $\Delta x$ and substitute this into the Lorentz transform expression above, having
$$\Delta t' = \gamma(v)\left(\Delta t-\frac{v}{c^2}(c\Delta t)\right)$$
Then
$$\Delta t' = \gamma(v)\Delta t\left(1-\frac{v}{c}\right)$$
Now, from the velocity-addition formula, $v<c$, so $\frac{v}{c}<1$ and $\left(1-\frac{v}{c}\right)$ is always greater than zero, thus, since the Lorentz gamma factor is also grater than zero as well as the interval $\Delta t$ (from the problem)
$$\Delta t'>0$$
Finally, the time-order is invariant under Lorentz transformation, thus time-order is a relativistic invariant in lightlike events as well as timelike events

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using RGB and HSL color objects in Particles.js I am working with this library : https://github.com/VincentGarreau/particles.js/blob/master/particles.js
In first few lines (starting from line 15) the developer sets some default values like :
this.pJS = {
canvas: {
  el: canvas_el,
  w: canvas_el.offsetWidth,
  h: canvas_el.offsetHeight
},
particles: {
  number: {
    value: 400,
    density: {
      enable: true,
      value_area: 800
    }
  },
  color: {
    value: '#fff'
  },

Later, around the line 269, the developer checks for appropriate value of colors :
this.color = {};
if(typeof(color.value) == 'object'){

  if(color.value instanceof Array){
    var color_selected = color.value[Math.floor(Math.random() * pJS.particles.color.value.length)];
    this.color.rgb = hexToRgb(color_selected);
  }else{
    if(color.value.r != undefined && color.value.g != undefined && color.value.b != undefined){
      this.color.rgb = {
        r: color.value.r,
        g: color.value.g,
        b: color.value.b
      }
    }

Users of the library can set all these options in a JSON file like this (https://github.com/VincentGarreau/particles.js):
{
"particles": {
"number": {
  "value": 80,
  "density": {
    "enable": true,
    "value_area": 800
  }
},
"color": {
  "value": "#ffffff"
},

The color can be set in a variety of ways as shown in the image below:

If I set the color like this :
"color": {
  "value": "#f00" // It works
}

"color": {
  "value": ["#00f","#A69","#CA1"] // It works
}

"color": {
  "value": "random" // It works
}

"color": {
  "value": {r:182, g:25, b:36} // Does not work
}

"color": {
  "value": {h:356, s:76, l:41} // Does not work
}

How can I properly set the color in RGB and HSL format?
Update : alert(typeof(color.value)); returns string in last two cases.
Update 2 : I have created a fiddle : https://jsfiddle.net/85djnk85/5/ for reference.
Before downvoting , let me know if you need any additional information :)

A: This should work, it checks h vs r value etc.

var item = {
  prop: {
    "color": {
      "value": {
        h: 356, // or r: 356
        s: 76, // or: s: 76
        l: 41 // or b: 41
      }
    }
  }
}

colorresult = {};
var color = item.prop.color;
if ((color.value.h || color.value.b) && (color.value.s || color.value.g)&& (color.value.l || color.value.b)) {
  colorresult.rgb = {
    r: color.value.h || color.value.r,
    g: color.value.s || color.value.g,
    b: color.value.l || color.value.b
  }
}

console.log(colorresult)

A: Your code is fine, but there is a bug in the Particles.js code that applies your settings over top of the defaults.
If you use a non-minified version of Particles.js, you can add use your debugger to watch the values just before it applies your settings (lines 139-141):
/* params settings */
if(params){
  Object.deepExtend(pJS, params);
}

Object.deepExtend copies values from one object to another, recursively.
It is defined further down in the same file:
Object.deepExtend = function(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};

This works fine when the source and destination have the same shape, like these two:
var destination =
{
  old: "no change",
  shared: "default"
},
source =
{
   shared: "override",
   new: "added"
}
Object.deepExtend(destination, source);

/* `destination` will now look like this:
{
   old: "no change",
   shared: "override",
   new: "added"
}
*/

A string in the source, a string in the destination. Just like your {color: {value: "#f00"}} example overwrites the default {color: {value: "#fff"}}.
But when the source has an Object where the destination has a string (like your example where the source says {color: {value: {r:182, g:25, b:36} and the destination (default) has {color: {value: "#fff"}}, its logic breaks down.
In particular, control eventually reaches Line 1423:
destination[property] = source[property];

And by that time, destination is set to a plain string, so it does something quite weird:
"#fff"["r"] = 182;

That's right, it sets the r property on the string "#fff". That's clearly not the behaviour you want :-)
Importantly, it means that the library's documentation and the library's code disagree with each other... pretty much the definition of a bug. I'd recommend filing an issue and maybe trying to figure out another way to get your colours in there (one way is to use your own copy of Particles.js and remove the default color).

A: you need to see the below link
http://www.softarc.com/Resources/Tips/ExternalApps/Resources/TemplateDocs/lessons/Using_JSON_strings_to_store_data.html


text:
Q: FFMPEG : syntax error: 'T�4��4' unexpected using FfmpegController for createSlideshowFromImagesAndAudio I have used https://github.com/guardianproject/android-ffmpeg-java for create video with multiple images and audio file.
But I could not generate expected output and got an error.
I have used https://github.com/guardianproject/android-ffmpeg-java/blob/master/src/org/ffmpeg/android/FfmpegController.java for controller.
Below is my code:
File fileTmp = getCacheDir();
    try {
        mFfmpegController = new FfmpegController(this, fileTmp);
    } catch (IOException e) {
        e.printStackTrace();
    }

    File folder = Environment.getExternalStorageDirectory();
    String path = folder.getAbsolutePath() + "/MyFolder";
    final ArrayList<Clip> paths = new ArrayList<Clip>();

    File baseDir = new File(Environment.getExternalStorageDirectory() + File.separator + "MyFolder");
    File[] iFrameJpegs = baseDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            Log.e("FileName", dir.getAbsolutePath() + "/" + name);
            if (name.endsWith(".jpg"))
                paths.add(new Clip(dir.getAbsolutePath() + "/" + name));
            return name.endsWith(".jpg");
        }
    });

    Clip audio = new Clip(path + "/audio.mp3");
    Clip out = new Clip(path + "/ffmpeg.mp4");
    out.width = 480;
    out.height = 320;
    out.videoCodec = "libx264";
    out.audioCodec = "copy";

    try {
        mFfmpegController.createSlideshowFromImagesAndAudio(paths, audio, out, 2, new ShellUtils.ShellCallback() {
            @Override
            public void shellOut(String shellLine) {
                System.out.println("MIX> " + shellLine);
            }

            @Override
            public void processComplete(int exitValue) {

                if (exitValue != 0) {
                    System.err.println("concat non-zero exit: " + exitValue);
                    Log.d("ffmpeg","Compilation error. FFmpeg failed");
                    Toast.makeText(MainActivity.this, "result: ffmpeg failed", Toast.LENGTH_LONG).show();
                } else {
                    if(new File( "/ffmpeg.mp4").exists()) {
                        Log.d("ffmpeg","Success file:"+ "/ffmpeg.mp4");
                    }
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

Below is code of error which i have got:
 I/FFmpeg controller: /data/data/com.orafox.vidmaker/cache/image-%03d.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i /storage/emulated/0/MyFolder/effect_hue.jpg -s 480x320/data/data/com.orafox.vidmaker/cache/image-000.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i /storage/emulated/0/MyFolder/effect_hue.jpg -s 480x320/data/data/com.orafox.vidmaker/cache/image-001.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i /storage/emulated/0/MyFolder/effect_engrave.jpg -s 480x320/data/data/com.orafox.vidmaker/cache/image-002.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i /storage/emulated/0/MyFolder/effect_flea.jpg -s 480x320/data/data/com.orafox.vidmaker/cache/image-003.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
D/dalvikvm: GC_FOR_ALLOC freed 357K, 5% free 8941K/9328K, paused 2ms, total 6ms
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i /storage/emulated/0/MyFolder/effect_grayscale.jpg -s 480x320/data/data/com.orafox.vidmaker/cache/image-004.jpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -loop 0 -f image2 -r 1/2 -i /data/data/com.orafox.vidmaker/cache/image-%03d.jpg -strict -2/data/data/com.orafox.vidmaker/cache/tmp.mpg
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg -y -i/data/data/com.orafox.vidmaker/cache/tmp.mpg -i /storage/emulated/0/MyFolder/audio.mp3 -map 0:0 -map 1:0 -acodec aac -b:a 128k -strict -2 -vcodec libx264/storage/emulated/0/MyFolder/ffmpeg.mp4
I/System.out: MIX> /data/data/com.orafox.vidmaker/app_bin/ffmpeg[1]: syntax error: 'T�4��4' unexpected
W/System.err: concat non-zero exit: 1
D/ffmpeg: Compilation error. FFmpeg failed
D/libEGL: loaded /system/lib/egl/libEGL_genymotion.so


text:
Q: splitting a node in b+ tree I'm trying to figure out what exactly happens when there is a node overflow.
info:
in my b+ tree there are 4 pointers per block and 3 data sections .
problem:
I understood that when there is an overflow we split into 2 nodes in my case each with 2
keys,
and insert the parent node the mid value, without erasing from the son(unlike in b tree).
however I got into situation:
                                |21|30|50|

           |10|20|-|      |21|22|25|  |30|40|-| |50|60|80|

and I want to insert the key 23
first I split |21|22|25| into: |21|22|-| and |23|25|-|
now I need to insert the key 23 to the parent |21|30|50| witch causes another split.
|21|23|-| and |30|50|-|
but where does the pointer before 30 points to?
is it possible that both this pointer & the one after 23 point to |23|25|-|
?

A: When inserting 23:

*

*as you said, 21|22|-| and |23|25|-| are created

*the 2 nodes require a parent

*a parent is created in the the root node: |21|23|30|50|

*the root has too many elements now

*split the root in 2 nodes |21|23|- and |30|50|-

*add a new parent for the 2 new nodes (which happens to be the new root of the tree)

Basically, that insert will increase the depth of the tree by 1

A: Here are how pointers should be handled. this is your B+ tree before insertion. (some padding used to make pointers easier to see)
                [21             30           50]
               /   \              \            \
       [10|20|-] => [21|22|25] => [30|40|-] => [50|60|80]

After inserting 23 you will have 2 nodes. Its important to know that left split should be always same instance and right split should be a fresh node. this will make handling pointers somewhat easier.
So splits should look like this.
  old          fresh
[21|22|-] => [23|25|-]

since left node is same instance, key 21 at root has the correct right pointer.  Here is what nodes look like before splitting root and after splitting leaf. we are in middle of process.
                [21                             30           50]
               /   \                              \            \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

only a new item with key 23 should be added next to 21 in root. since root has no space it will also split. middle key is 23 (first item of right split).
                [21                          30]          [ 50 ]
               /   \                           \          *    \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

Because root is split, we must add our middle key to left or right splits and find a new middle key to promote. notice the null pointer at right split. because that node is fresh, it must be initialized soon!
(root was split from right meaning that less items lay in right node in case of having odd amount of items. but in general it doesn't matter which way you split.)
our middle key was 23. so lets add 23.
                [21            23             30]          [ 50 ]
               /   \             \              \          *    \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

Good! If there was no split here, our insertion would be finished by now. but since there is split at this level, we must find new middle key to promote. also don't forget null pointer for fresh node.
(In case of splitting leafs, you must keep key-values at leafs and promote copy of middle key, but in case of splitting internal nodes you can safely move and promote keys up.)
here new middle key is 30. lets pop it from left node.
 30
   \
[30|40|-]

(Its important how to choose middle key. Always a node that gets the middle key from bottom splits, should drop one item for a new middle key. if that node is left node, drop last item from it, otherwise drop first item.)
                [21            23]            30           [ 50 ]
               /   \             \              \          *    \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

Notice that 30 is not inside any of splits. that's our middle key we have to handle. Always give right node of middle key to left of fresh node.
                [21            23]       30            [50]
               /   \             \         *          /    \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

Then right pointer of middle key will point to fresh node on right split. finally middle key is promoted, new root with left of left split and right of right split and key of middle key is created.
                                   [       30        ]
                                  /                   \
                [21            23]                     [50]
               /   \             \                    /    \
       [10|20|-] => [21|22|-] => [23|25|-] => [30|40|-] => [50|60|80]

Congrats! you have done your insertion. it may look easy on paper, but I have to admit its a bit of challenge when coding it.

There are couple of ways to represent these key-node items in memory. my approach is each key-node item has right pointer with a key. so each internal node will have array of key-nodes. this way, keys and node pointers are always kept together. left most child is handled by a separate left pointer, this pointer is kept on each internal node and is never null (after complete operations).

A: In B+ tree, the leaf and non-leaf nodes have different structures. Due to this, their overflow mechanisms are also different. What you say is true for overflow of leaf nodes(It is done without erasing the parent key from the son). But when non-leaf nodes overflow and are split, the child node doesn't retain the parent key (parent key is erased from the son).

A: The problem you have to understand what happens is because of the bad representation model you are using. You should have one data value associated with a pointer and the invariant that the data value is the smallest value in the subtree referenced by the pointer.
So this is how you should represent the b-tree node prior of insertion.
                         10|21|30|50|                       <--- root node

         10|20|    21|22|25|     30|40|       50|60|80|     <--- leaf nodes

In this representation the pointer after the value 10 in the root node points to the leaf node with the first value 10, etc.
When you insert 23, it is inserted in the leaf node with first value of 21. This yields the following tree and no need to split.
                         10|21|30|50|                       <--- root node

         10|20|    21|22|23|25|     30|40|    50|60|80|     <--- leaf nodes

When inserting 24 which produces the effect you described, what you get is the following
                              10|30|                         <--- new root node

                        10|21|24|   30|50|                   <--- intermediate nodes

         10|20|   21|22|23|   24|25|   30|40|    50|60|80|   <--- leaf nodes

As you see there is no ambiguity anymore. The leaf node was split, and the key pointer pair 24| had to be inserted in the root node. Since it was full, it had to be split. Now that there are 5 values, you get one node with 3 values and one node with 2. You are free to choose if the left node or the right node get the three value. What is important is that the fundamental invariant is preserved. Each key value in a node is the smallest element in the subtree referenced by its associated pointer. A new root node had to be added and its key value pointer set should now be obvious. No ambiguity.
This also makes obvious that many optimization strategies are possible. Instead of splitting the root node, we could have moved the value 21 into the left leaf node which was not full. The one with the first value 10. This avoids the need to split the root node and keeps the b-tree hight unchanged and yields a better filling of the b-tree. So you minimize space and search time. But this implies one can efficiently check if sideway balancing is feasible. A change of key value in the root node is still needed. etc.
As you see, the value 10 in your b-tree is not really required in none leaf nodes and it is often omitted in b-tree representation (i.e. wikipedia) but this can make it confusing and was probably the reason you where. :)

A: From what I've been taught, it is ok for the last node to have one node less than n/2. So in your example, the top nodes will become:
             |23|
         /        \
    |21|22|-|       |25|-|-|

I think it kind of make sense. If you think about it, you have 5 leave nodes, so you need 5 pointers from the upper level. This arrangement is the only way such that you can have 5 pointers, all other combinations would either overflow the node or create extra pointers.
If the nodes were |21|22|-| and |23|25|-|, then the root node would be |23|-|-|. Then, it does not make sense to have 23 in the right node, because whatever that is in the right node must be equal or greater than 23 anyway!


text:
Q: Javadoc on CoffeeScript? I'm new to CoffeeScript and seems that I can't find any document generator for CoffeeScript using Javadoc syntax. The only one I could find is available as a patch to the CoffeeScript compiler.
So, what do you use to generate documentation from Javadoc comment on CoffeeScript or how do you document your function arguments and return values?

A: People looking forward to using javadoc style documentation in coffeescript can checkout codo ( http://netzpirat.github.com/codo/ ) which provides support for a subset of javadoc and automatically infers class names, function names and parameters from source code.

A: So, JavaDoc syntax has never really caught on with JavaScript developers. There are those who use something like it—notably Google—but it's kind of at odds with JS, which doesn't have static typing and allows any number of arguments to any function.
If you want to create beautiful documentation with CoffeeScript, the standard is Docco (its home page is an excellent example). If you want to create JavaDoc-style comments for every function... well, you'll have to create them by hand, and escape them with backticks.
Alternatively, you could work in CoffeeScript until your code is release-ready, then document the resulting JavaScript.

A: Docco is great for prozedural coding style. If you want to document an API, coffeedoc is for you.

A: I'm using YUIDoc. I can add comments using a syntax similar to Javadoc to my classes, methods and events. The documentation gets output as html/css files and you can even customize the page layout.
Check this documentation example: http://yui.github.com/yuidoc/api/
PS: It relies on Node.JS and you need to install the package yuidocjs
npm install yuidocjs -g


text:
Q: How to use html5 to develop a video and audio call social application without using webrtc so that it is supported on all browsers? How to use html5 to develop a video and audio call social application without using webrtc so that it is supported on all browsers?
I've tried webrtc however it doesn't work on IE or ios.
Thankyou

A: You want to

Use HTML5

(and presumably javascript) to

develop video and audio call application

and

without using webrtc

You can't. No such thing exists.


text:
Q: Indexing array/subobject in mongoDB causes duplicate key error I have a collection where I will have a _children attribute like this:
{
  _children: {
    videoTags: [ { id: '1', name: 'one'}, { id: '2', name: 'two'} ],
  },
  a: 10
}

Since I WILL search in videoTags, I create an index as such:
> db.test4.createIndex({ "_children.videosTags.id" : 1 }, { "unique" : true } );
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Trouble is, I can no longer add anything to that table since I get a duplicate index error. Here is how to reproduce it:

*

*Step 1: insert to a collection

    db.test4.insert({a:20})
    WriteResult({ "nInserted" : 1 })

*

*Step 2: make the index

    db.test4.createIndex({ "_children.videosTags.id" : 1 }, { "unique" : true } );
    {
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
    }

*

*Step 3: try to insert again

    db.test4.insert({a:30})
    WriteResult({
        "nInserted" : 0,
        "writeError" : {
            "code" : 11000,
            "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: wonder_1.test4.$_children.videosTags.id_1  dup key: { : null }"
        }
    })

I think the issue here is that there is already a record where _children.videoTags.id is not defined.
However, what I expected was a behaviour where if videoTags.id was specified, it needed to be unique. Instead, an empty one is considered a "taken" key.
What am I doing that is stupidly wrong?
This will work if you don't set unique as true, but I have the feeling I need to fix it for real...

A: There could be two reasons.

*

*There could be other documents exists in collection with same _children.videosTags.id

*It's quite possible that more than one document may have missing  _children.videosTags.id" or having null value.
As you are creating unique key, null or empty values are give you tough time. Solution is either create sparse index and if your MongoDB version is 3.2+, create partial index. See documentation for partial indexes.


text:
Q: NodeJS Express POST Request Having some slight difficulty with making a POST request to an API. The goal is to make a POST request and just print the response to console for now. This is basically what I have done, please let me know as to what I am doing wrong.
var express = require('express');
var request = require('request');
var router = express.Router();

router.get('/', function(req, res, next) {
    var data = JSON.parse('{ "user": "username", "password": "pass", "layout": "out" }');
    console.log(data);

    request({
        url : "https://url.com",
        method : "POST",
        json: true,
        body : data
    }, function(error, response, body){
        console.log(body);
    });

    res.render('index', { title: 'Express' });
});

module.exports = router;

The issue i am facing is that while doing the same request using Postman as shown in this  is providing a response while if i print the response or body in Node, its shown as undefined.


text:
Q: Setting dynamically created EditTexts bottom line color programatically? Pretty much I have an application where you press a button and it adds 2 separate editTexts to the current layout but I am stuck with using a dark background as the default theme has a white underline. I cannot change the color of the editTexts and am stuck with a theme color I don't want.

A: I suppose you're creating your EditTexts dynamically (as you said in your question).
You just have to mutate the background of your newly created EditText. This can be achieved as follows:
yourEditText.getBackground()
            .mutate()
            .setColorFilter(getColor(R.color.someColor), PorterDuff.Mode.SRC_ATOP);

Related question
Changing EditText bottom line color with appcompat v7


text:
Q: Why a shapefile of a geological data is not displaying the fault lines in QGIS? I am a new user of QGIS 2.4. and can not get a shapefile of geological data to display correctly. This shapefile contains polygons, fault lines, dips, volcanic structures, shoreline types, geological boundaries between other layers. Characters set: utf8. Reference systems: UTM WGS 84, Zone 17 North.
This layer was digitized from the geological map of Panama, 1:250,000.
When using ArcGIS the fault lines are displayed, but not when using QGIS. This shape contains the following extensions: .shp, .shx, .dbf, .prj, .qix., shp.xml.
What might be the issue?


text:
Q: clock.js, conditionally set eastern or central time I have a perfectly functioning clock.js widget that I'm using  to display date and time on multiple displays throughout our offices in several states.
The offices in the Eastern timezone have no issue, as this defaults to eastern time (our server running the screens for every display is eastern).
However, I want to add a conditional in here (say if $screenID == 3 {... so that on the screens in the Central time zone it shows the proper central time.
How should I go about adding a block in here for that condition to show central rather than eastern?
 function startTime() {
    var today = new Date();
    var hr = today.getHours();
    var min = today.getMinutes();
    // var sec = today.getSeconds();
    ap = (hr < 12) ? "AM" : "PM";
    hr = (hr == 0) ? 12 : hr;
    hr = (hr > 12) ? hr - 12 : hr;
    //Add a zero in front of numbers<10
    hr = checkTime(hr);
    min = checkTime(min);
    // sec = checkTime(sec);
    document.getElementById("clock").innerHTML = hr + ":" + min + " " + ap;

    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var curWeekDay = days[today.getDay()];
    var curDay = today.getDate();
    var curMonth = months[today.getMonth()];
    // var curYear = today.getFullYear();
    var date = curWeekDay+", "+curDay+" "+curMonth;
    document.getElementById("date").innerHTML = date;

    var time = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

A: Use timezones.

function startTime(screen, loc) {
  var timeZone = "America/Chicago";
  if (screen === 1)
    timeZone = "America/New_York";

  var dateOptions = { weekday: 'long', day: 'numeric', month: 'long', timeZone: timeZone };
  var timeOptions = { hour: 'numeric', minute: 'numeric', timeZone: timeZone };
  var dt = new Date();

  document.getElementById("myclock" + loc).innerHTML = dt.toLocaleString("en-US", timeOptions);
  document.getElementById("mydate" + loc).innerHTML = dt.toLocaleString("en-NZ", dateOptions);
}

startTime(0, 1);
startTime(1, 2);

asdf

asdf

asdf

asdf


text:
Q: User is being redirected by SSO during OAuth 2.0 authorization dance I'm building an app that requires users to authenticate with Salesforce.  This is done with using a connected app and sends users through the Oauth redirect dance, as described here: https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com.
The problem I'm encountering occurs with an SSO implementation that steps in to authenticate the user automatically.  The user is authenticated and redirected back to the authorization server, but once authorized, is redirected to the Salesforce home page, rather than the Oauth callback redirect as configured in the connected app (and passed as query param).
This is happening between steps 3 and 4 on this diagram: https://developer.salesforce.com/page/File:OAuthWebServerFlow.png
Question:
Is there a way I can force a request to:
https://login.salesforce.com/services/oauth2/authorize?...
which redirects to:
https://na[XX].salesforce.com/setup/secur/RemoteAccessAuthorizationPage.apexp?source=...
to load that page without triggering SSO to automatically authenticate the user?
Example: My app is trying to implement the same flow that one would see on Workbench or Dataloader.io.

A: Double check that you're using the login server URL rather than the Salesforce instance URL


text:
Q: Haskell - ambiguous class function I'm making console program where I will be heavily working with text menus. I wrote a class Menu with function choices which returns string of possible menu choices and function parseChoice which convert string entered by the user to menu item.
data MainMenu = FirstItem | SecondItem

class Menu a where
  choices :: String -- ERROR HERE
  parseChoice :: String -> Maybe a

instance Menu MainMenu where
  choices = "1) first choice\n2) second choice"
  parseChoice "1" = Just FirstItem
  parseChoice "2" = Just SecondItem
  parseChoice _ = Nothing

getMenuItem :: Menu a => IO a
getMenuItem = do
  putStrLn choices -- ERROR HERE
  choice <- getLine
  case parseChoice choice of
    Just item -> return item
    Nothing -> getMenuItem

main :: IO ()
main = (getMenuItem :: IO MainMenu) >> return ()

Unfortunatelly, I'm getting following error
• Could not deduce (Menu a0) arising from a use of 'choices'
  from the context: Menu a
    bound by the type signature for:
               getMenuItem :: Menu a => IO a
    at [removed].hs:15:1-29
  The type variable 'a0' is ambiguous
  These potential instance exist:
    instance Menu MainMenu
      -- Defined at [removed].hs:9:10
• In the first argument of 'putStrLn', namely 'choices'
  In a stmt of a 'do' block: putStrLn choices
  In the expression:
    do { putStrLn choices;
         choice <- getLine;
         case parseChoice choice of {
           Just item -> return item
           Nothing -> getMenuItem } }

I know the error occurs because Haskell don't know which choices function use. I tried something like putStrLn (choices :: Menu a) but without success.
Question are: Where is the problem (and how to fix it)? Should I use different approach (which)?
And please be polite, I'm Haskell newbie.
Thank you.

A: @porges is correct about why this happens, the compiler simply doesn't have enough information to know which instance of the typeclass choices would be coming from.  Instead, you can try tagging it with a phantom type:
data Choices a = Choices String

class Menu a where
    choices :: Choices a
    parseChoices :: String -> Maybe a

This alone won't quite be enough, you'll need to annotate the type where ever you use choices:
putStrLn (choices :: Choices a)

This isn't really ideal, though.  An alternative is to ditch the typeclass approach altogether and stick with a basic data type:
data Menu a = Menu
    { choices :: String
    , parseChoices :: String -> Maybe a
    }

Then you can do
data MainMenu = FirstItem | SecondItem

mainMenu :: Menu MainMenu
mainMenu = Menu _choices _parseChoices where
    _choices = "1) first choice\n2) second choice"
    _parseChoices "1" = Just FirstItem
    _parsechoices "2" = Just SecondItem
    _parseChoices _   = Nothing

And finally
getMenuItem :: Menu a -> IO a
getMenuItem menu@(Menu choices parseChoices) = do
    putStrLn choices
    choice <- getLine
    case parseChoice choice of
        Just item -> return item
        Nothing -> getMenuItem menu

main :: IO ()
main = (getMenuItem mainMenu) >> return ()

A: The problem is that the line putStrLn choices is inherently ambiguous. When multiple instances of the class Menu are available, it might mean to print any of them. You might intend, in your mind, to use the instance made available by the Menu a => constaint, but another programmer could want to avoid that and pick the Menu MainMenu instance, disregarding a.
One option would be to avoid typeclasses. This is probably the saner, simpler, and most effective way to go. Just make Menu a type like
data Menu = Menu { choices :: String , ... }

and pass a value of that type around, manually.
Assuming we want to stick with the typeclass for some reason, we can disambiguate the culprit line by changing the type of choices as follows:
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Proxy

class Menu a where
   choices :: proxy a -> String
   ...

getMenuItem :: forall a. Menu a => IO a
getMenuItem = do
  putStrLn (choices (Proxy :: Proxy a))
  ...

The additional proxy argument has a dummy value. At runtime it carries no information, but at compile time it allows the compiler to disambiguate.
Alternatively, with some other newer GHC extensions one can use some code which is closer to the original one
{-# LANGUAGE ScopedTypeVariables, AllowAmbiguousTypes, TypeApplications #-}

class Menu a where
   choices :: String
   ...

getMenuItem :: forall a. Menu a => IO a
getMenuItem = do
  putStrLn (choices @ a)
  ...

This quite a new style, but chances are that this will be used a lot in the future. This is because it is simpler than passing proxies around. Even type theorists should appreciate explicit type arguments, which are commonly found in many typed lambda calculi.


text:
Q: download CSV file from a URL based on inputs from a ticker_list? I am new to Python and I want to make a program that does the following:

*

*Use this list = [aapl,goog,jnj,msft] as input

*Go to the url "https://finance.google.com/finance/historical?q=goog&output=csv" and replace "goog" with tickers from list above

*Finally save the CSV file onto the file system.
The image contains the code i have been able to think of
from urllib import request
ticker_list = "aapl"
response = request.urlretrieve("https://finance.google.com/finance/historical?q="+ticker_list+"&output=csv",'D:/LatestStockFile.csv')
#[aapl,goog,xom,ge,msft,bp,c,pg,wmt,pfe,tm,jnj]
# I want tickers from this list to append instead of ticker_list

# also if possible a different file name to save for each iteration of ticker
# example : say ticker = "aaple" then this "aapl" should be appended to url and path: "D:/Apple.csv"

def download_csv(ticker,path):
    response = request.urlretrieve(ticker,path)

def user_input():
 choice = input("enter choice: 1/2/3\n")
 if choice == 1:
  download_csv("aapl","D:/Apple.csv")
 elif choice == 2:
  download_csv=("goog","D:/Google.csv")
 elif choice == 3:
  download_csv("jnj","D:/Johnson.csv")

user_input()

A: import requests
if __name__ == '__main__':
    list = ["aapl", "goog", "jnj", "msft"]
    for items in list:
        req = requests.get('https://finance.google.com/finance/historical?q=' + items + '&output=csv')
        with open(items+".csv","w") as file:
            file.write(req.text)

A: The answer by GarfieldCat is good for its use case, but doesn't directly address your request of having the stock name as the CSV file name.  It's just the ticker name.
What you can do is define a dictionary key-value data structure to hold the company name as well as the stock name. For example, adapt your existing list to something like:
stocks =  [
    {
        'ticker': 'aapl',
        'company: 'Apple'
    },
    {
        'ticker: 'goog',
        'company: 'Google'
    },
    ...
    ...
]

Then use the code from GarfieldCat, just adapted to extract data from the dict:
for item in stocks:
    url = 'https://finance.google.com/finance/historical?q={}&output=csv'.format(item.get('ticker'))
    req = requests.get(url)
    with open('{}.csv'.format(item.get('company')), 'wb') as f:
       f.write(req.text)

If you continue to have questions about this, I would suggest you look in to the request library documentation for how to get data from a request, and then read about Python writing to files.

A: How about doing it this way?
"""
"""
#in this file "C:/Users/rshuell001/Desktop/symbols/amex.txt"
#you have the following tickers
#ibm
#sbux
#msft
"""

import urllib
import re
import json

symbolslist = open("C:/Users/rshuell001/Desktop/symbols/amex.txt").read()
symbolslist = symbolslist.split("\n")

for symbol in symbolslist:
    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "w+")
    myfile.close()

    htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+ symbol+ ":US")
    data = json.load(htmltext)
    datapoints = data["data_values"]

    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "a")
    for point in datapoints:
        myfile.write(str(symbol+","+str(point[0])+","+str(point[1])+"\n"))
    myfile.close()

Here is an option that is similar, but different (you are reading from a tuple not a text file).
import urllib2

listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"]

urls = []

for company in listOfStocks:
    urls.append('http://real-chart.finance.yahoo.com/table.csv?s=' + company + '&d=6&e=28&f=2015&g=m&a=11&b=12&c=1980&ignore=.csv')

Output_File = open('C:/Users/rshuell001/Historical_Prices.csv','w')

New_Format_Data = ''

for counter in range(0, len(urls)):

    Original_Data = urllib2.urlopen(urls[counter]).read()

    if counter == 0:
        New_Format_Data = "Company," + urllib2.urlopen(urls[counter]).readline()

    rows = Original_Data.splitlines(1)

    for row in range(1, len(rows)):

        New_Format_Data = New_Format_Data + listOfStocks[counter] + ',' + rows[row]

Output_File.write(New_Format_Data)
Output_File.close()


text:
Q: URL specific encode I try to recreate a URL but can not find the encoding function
Edit:
background:
the string is for an API (with no documentation ofcourse), I tried to use rawurlencode but it seems that only the original  encode / decode functions work so I have to find what it is ...
$input = "2/3*( ((word*888) )>(word2 AND ((word3*888))/word4>888";

$encoded = "2/3*(%20((word*888)%20)%3E(word2%20AND%20((word3*888))/word4%3E2888";

Tried with urlendode, rawurlencode but they replace  the brackets and "*"..
The string is created for URL from  PHP (possibly Javascript).
Edit
base64_encode - destroys the string ..
htmlentities - is not making changes ..
Not looking for "best url encode function" .. just need to recreate the example without custom replace function.
Edit3
OK I did some more debugging and this is the most of the replace table:
% - %25
^ - %5E
+ - %2B
{ - %7B
[ - %5B
} - %7D
] - %5D
" - %22
| - %7C
\ - %5C
< - %3C
> - %3E
" " - %20
May be some sort of  escape for SQL, the string is later transformed to a query.

A: You're looking for a PHP implementation of JavaScript encodeURI() function. Here we go:
function encodeURI($uri)
{
    return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#]}i", function ($m) {
            return sprintf('%%%02X', ord($m[0]));
        }, $uri);
}

And now you have exactly what you want.
Demo: https://eval.in/65314


text:
Q: Программа не правильно считает символы В задании на решу егэ Тут В ответе 35, в моем решении на пайтон выходит 34, помогите найти ошибку в коде
f = open("24_demo.txt", "r");
c1=None
c2=None
k = 0
k_max = 0
while 1:
   c1=f.read(1)
   if c1 != c2:
        k+=1
        if k >= k_max:
            k_max = k
    elif c1 == c2:
        k = 0
    c2=c1
    if not c2:
        break
print(k_max)
f.close()


text:
Q: Excel VBA : How to access (Referenced) Ranges from Formula in a Cell I have a cell (such as B2 in 'Sheet-1') containing a formula like:
='Sheet-2'!B2+'Sheet-3'!B3-'Sheet-4'!B4
Now I want VBA code that can access the references contained in the formula entered in that cell (i.e. B2 in Sheet-1) and then go to those references and make a change in those referred cells.

A: Expanding on z's comment somewhat.
Range(<cell>).Precedents returns a VBA Range representing all cells referred to by <cell> e.g. if cell A1 had the formula =B1+D1 then Range("A1").Precedents = Range("B1,D1")
Expanding this to further fulfil the requirements of your question we can then iterate over the cells within this range using a For Each loop as shown in the example below:
Public Sub AmendPrecedents(fromCell As Range)
    Dim rngReferredTo As Range
    Dim cell As Range

    Set rngReferredTo = fromCell.Precedents

    For Each cell In rngReferredTo
        'Do something with this cell, in this case we're just coloring the background red
        cell.Interior.Color = RGB(255, 0, 0)
    Next cell
End Sub


text:
Q: How I can scroll up and down by Keyboard In VS2008 Is there any shortcut in VS2008 to scroll up and down by keyboard?
Although CTRL + UP and Down will move between the methods but this is not what I'm looking for.
Thanks in advance.

A: How about Page Up and Page Down.

A: Tools -> Options -> Environment -> Keyboard
Find the commands Edit.ScrollLineUp and Edit.ScrollLineDown.
You can see what it's set to, or set the keyboard shortcut yourself.

A: How about Ctrl + Home and Ctrl + End

A: The ctrl+up and ctrl+down key combinations will scroll up and down a single line.
At least in the editor modes that I use, like C#, aspx, css, html, xml. In some modes it might be taken over by the function that you describe, and in that case there is no key combination to scroll, unless you redefine the keyboard bindings.


text:
Q: Does array declaration mean consecutive memory allocation? int main() {
 char a[5];
 a[0] = 0;
 return a[0];
}

In this snippet, does char a[5];, which is an array declaration without any initialization, guarantee allocation of 5 bytes of consecutive memory?
Or since only 1 element gets initialized later, compiler is free to use a register for that 1 element?
I'm assuming that reading any other index of this array beside 0 is undefined behaviour.

A: It guarantees that the observable behaviour of the program will be the same as if it has allocated this memory.
The compiler is free to optimize out any objects as in your trivial example:
main:
        xor     eax, eax
        ret

https://godbolt.org/z/KE5PzvTKq


text:
Q: In ubuntu 22.04 custom kernels not booting up on dell Pc I have did kernel compilation and tried to bootup the system with customised kernel in Dell pc but it is not coming up.
Solutions tried

*

*Disable secure BIOS.

*Updated Grub parameters.

*Updated the BIOS.


text:
Q: R shiny table with dates I'm making an app to analyse some data with Shiny.
When I directly send query to database, I can see good rezults:

But when I try to put results from this query to shiny, column 'not_outlier_date' look different:

I want to have the same date format, as in the first picture.
I was trying, on table, that I get from database, add:
  not_outlier_dates[,2]<-as.Date(as.numeric(as.vector(unlist(not_outlier_dates[,2]))))

But it doesn't make any changes and works with warning:
 Warning in formatC(x = c(16065, 16137, 16064, 15707, 16063, 15775, 15782 :
 class of 'x' was discarded

How can I solve this date format problem?

A: Try using this:
not_outlier_dates[,2] <- as.character(not_outlier_dates[,2])

The problem lies in the xtable library that Shiny uses to display tables. It seems there are bugs related to date columns, as stated in this SO question and this (closed) Shiny issue. Not sure if that still applies or if it applies to your xtable version, though.


text:
Q: RevealingPrototypePattern : TypeError: .... is not a constructor I'm trying to convert some of my javascript old code into Revealing Prototype Pattern. I write the below code, But getting error

TypeError: AllShowing is not a constructor

$(document).ready(function () {

    var allShowing = new AllShowing();

    // Edit record
    $('#allShowingGrid').on('click', 'a.edit_showing', function (e) {

        e.preventDefault();

        $('html, body').animate({ scrollTop: 0 }, 'fast');

        var command = 'Edit';

        var tr = $(this).closest('tr');

        allShowing.mapGridDataToFormData(command, tr);
    });

});

var AllShowing = function () {

    this.gridContainer = "#allShowingGrid";

    this.showRequestData = function() {
        $("#requestData").show();
    };
};

AllShowing.prototype = function () {

    var mapGridDataToFormData = function(command, tr) {
        if (command == 'Edit') {

            showRequestData.call(this);

            var id = $.trim((tr).children("td.row_id").text());
            var propId = $.trim((tr).children("td.showing_PropertyId").text());
            var name = $.trim((tr).children("td.showing_FirstName").text());
            var email = $.trim((tr).children("td.showing_Email").text());
            var phone = $.trim((tr).children("td.showing_WorkPhone").text());
            var schedule = $.trim((tr).children("td.showing_PreferredDate").text());
            var reqDetails = $.trim((tr).children("td.showing_Comment").text());
            var startHour = $.trim((tr).children("td.showing_StartHour").text());

            $("#hdVisitorId").val(id);
            $("#FirstName").val(name);
            $("#Email").val(email);
            $("#Work_Phone").val(phone);
            $("#PreferredDate").val(schedule);
            $("#StartHour").val(startHour);

        }
    };

    return {
        mapGridDataToFormData: mapGridDataToFormData
    };
}();

I check some of similar post like Javascript: TypeError: … is not a constructor and Javascript "Not a Constructor" Exception while creating objects
But can't solve my error. Can any body help me where i made a mistake.

A: Change var AllShowing = function () {
to
function AllShowing() {

it should work


text:
Q: choosing return values from .Net MVC API I've been working with Infusionsoft's API system in .Net and I find the "selectedFields" functionality to make a lot of sense.
I'm currently making an API system and would like to build similar functionality in.
I'm sure it's got a name but for the life of me I can't figure out what to search for in order to get some working examples.
My only solution is something like below
Data.DataDataContext _db = new Data.DataDataContext();
[HttpGet]
public IHttpActionResult load(int id, [FromUri] string rtnValue)
{
    var property = _db.PROPERTies.Where(p => p.id == id);

    if (!property.Any())
        return NotFound();

    var returnProperty = new Dictionary<string, string>();
    var prop = property.FirstOrDefault();

    if (rtnValue.Contains("Id")) returnProperty.Add("Id", prop.id.ToString());
    if (rtnValue.Contains("Energy")) returnProperty.Add("Energy", prop.energy.ToString());

    return Ok(returnProperty);
}

Going to the url /api/property/load/1/"Id","Energy".... IS returning what I'd expect [{ "Id": "1", "Energy": "45" }] so it seems to be working in that regard. It's more an optimisation of my code. I'm sure that I can do this in a better way.
Ideally I want to add a List<string> to the passed rtnValue variable, but then I'm not sure how I can pass the values to the API then, instinct tells me the url would look like /api/property/load/1/["Id", "Energy"] but this comes back with an error.
Any help on how to better optimise this code would be awesome.

A: What about this...
API Format:
/api/property/load/1?rtnValue[0]=test1&rtnValue[1]=test2

Controller Method:
public IHttpActionResult load(int id, [FromUri] List<String> rtnValue)


text:
Q: 30 mins Idleness, watermark event timer does not trigger My use case is to fire an event timer if the 2nd event did not come within 30 mins. Hence, I'll have 30 mins idless in between of the 2 events. My event timer triggers only if I send consequent events every atleast 1 sec, but does NOT if in between it's 30 mins gap, the onTimer never triggers. (Using PeriodicWatermarkAssigner)
How can I trigger if 30 mins gap is needed?

A: Event time timers are triggered by watermarks, which are only created from events. So if there are no events, there are no watermarks, and the timer will never fire. You'll need to use a processing time timer if the sources are completely idle.


text:
Q: HTTParty and text/xml I'm trying to make a POST request using HTTParty, in which I need the content-type to be text/xml. How can I make that happen? Right now the API I'm calling is complaining I'm not sending any xml. If I call it using curl I get the same error, unless I specify content-type to text/xml.

A: HTTParty.post url, :body => xml, :headers => {'Content-type' => 'text/xml'}


text:
Q: Can't receive JSON string from PHP file in Android below I include some of my code:
Here is my code:
int responseCode = httpCon.getResponseCode();

if (responseCode==-1) { httpCon.connect(); }

InputStream is = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
   response.append(line);
}
rd.close();

try {

    OutputStream file = openFileOutput("configND", Context.MODE_PRIVATE);
    DataOutputStream wrf = new DataOutputStream(file);
    wrf.writeBytes(line);
    wrf.close();

    } catch (Exception e){
    e.printStackTrace();
}

I'm trying receive data (JSON string) from PHP file and then create a file with a content but something is wrong. I can't receive a JSON string and the file can not be created.
I use HttpURLconnection and I don't use apache library. I might add that sending JSON is working properly.
Help!

A: If you receive nothing from the server, the problem might be simply in your PHP script.
For the Android part of the "problem", if you don't want to use Volley and simply handle this with Android APIs, these two links should make your day :)
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
Personnally, when I learned Android some years ago, I followed AndroidHive ressources and it works pretty well.


text:
Q: Mail::factory Email Address Containing Latin Characters PHP All docs I have read only show the "From Name" containing latin chars but not how to encode the email correctly.  But all those examples don't show how to create a mailing form that will work when the user has a email address like "Español@latin.com".
Currently the below code will encode the name correctly.  But if the email address has a latin char in it.  It will not send.
$extraheaders['From'] =  $message->encodeHeader('From', "$name <$from>", "utf-8", "quoted-printable");


text:
Q: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token i am trying to upload a pdf to the real time database in first time.so storage enter image description here the uploaded pdf file is loaded .but i looking for the real time database it hasn't appearing the pdf url and other details.then check the logcat i found this error.

error

 2020-09-18 15:52:59.471 30861-30975/com.example.projectx E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.

.Assignment.java

package com.example.projectx.buddhika;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.projectx.R;
import com.example.projectx.kavishka.Pp;
import com.example.projectx.rasuni.Marks;
import com.example.projectx.yasasri.Project;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Logger;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

public class Assignment extends AppCompatActivity {

    private Button button;

    Button btn_upload1;
    EditText txt_year;
    EditText txt_semester;
    EditText txt_name1;
    EditText txt_subject;

    StorageReference storageReference;
    DatabaseReference databaseReference;

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

        btn_upload1 = (Button) findViewById(R.id.ass_upload_btn);
        txt_year = (EditText) findViewById(R.id.ass_txt_year);
        txt_semester = (EditText) findViewById(R.id.ass_txt_semester);
        txt_name1 = (EditText)findViewById(R.id.ass_txt_name11);
        txt_subject = (EditText) findViewById(R.id.ass_txt_subject);

        button = (Button) findViewById(R.id.view);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Assignment.this, Edit_assignment.class);
                startActivity(intent);
            }
        });

        //intialize and assign variable
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        //set home selected
        bottomNavigationView.setSelectedItemId(R.id.assignment);

        //perform itemselected list
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.marks:
                        startActivity(new Intent(getApplicationContext(), Marks.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.todo:
                        startActivity(new Intent(getApplicationContext(), MainActivity2.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.assignment:

                        return true;
                    case R.id.project:
                        startActivity(new Intent(getApplicationContext(), Project.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.pp:
                        startActivity(new Intent(getApplicationContext(), Pp.class));
                        overridePendingTransition(0, 0);
                        return true;
                }
                return false;
            }

        });

        storageReference = FirebaseStorage.getInstance().getReference();
        databaseReference = FirebaseDatabase.getInstance().getReference("uploads");

        btn_upload1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectPDFFile();
            }
        });

    }

    private void selectPDFFile() {

        Intent intent = new Intent();
        intent.setType("application/pdf");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select PDF File"),1);
    }

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

        if (requestCode == 1 && resultCode == RESULT_OK
                && data !=null && data.getData()!=null)
        {
            uploadPDFFile(data.getData());

        }

    }

    private void uploadPDFFile(Uri data) {

        final ProgressDialog processDialog = new ProgressDialog(this);
        processDialog.setTitle("Uploading...");
        processDialog.show();

        StorageReference reference = storageReference.child("uploads/"+System.currentTimeMillis()+".pdf");
        reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
                while (!uri.isComplete());
                Uri url = uri.getResult();

                Upload_pdf Upload_pdf = new Upload_pdf(txt_name1.getText().toString(),url.toString());

                databaseReference.child(databaseReference.push().getKey()).setValue(Upload_pdf);

                Toast.makeText(Assignment.this,"File Upload",Toast.LENGTH_SHORT);
                processDialog.dismiss();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                double progress = (100.0 * taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
                processDialog.setMessage("Uploaded:"+(int)progress+"%");

            }
        });

    }
}

realtime database

   {
      "rules": {
        ".read": true,
        ".write": true
      }
    }

storage

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

gradle

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.projectx"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'com.google.firebase:firebase-auth:16.0.4'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.android.support:cardview-v7:+'

}


text:
Q: How can i translate this UDF to Pandas UDF I face some performance issues with this function, which aims to return True if a string of the string array matches with the val parameter. I would like to translate this into a Pandas UDF.
def list_contains(val):
    # Perfom what ListContains generated
  def list_contains_udf(column_list):
    for element in column_list:
      if element.startswith(val):
        return True
    return False
  return udf(list_contains_udf, BooleanType())

How could I achieve this?

A: Inspired by @jxc comment, try to use the sql below in the cell of Databricks.
%sql
SELECT exists(column_list, element -> substr(element, 1, length(val)) == val)

The code element.startswith(val) I understand it using SQL is to take the head N (length(val)) length of the string element using substr and that whether be equals the val self.
Otherwise, please refer to the class pyspark.sql.UDFRegistration(sparkSession) of PySpark document to register the simiar functions as UDFs to combined use them.


text:
Q: Three JS Circle Line Geom Color for Negative Values I've been testing some ideas on how to get a circle to have a different color for the part of the circle that has positive Z values. I tried one approach, creating two separate line segments and using different materials. It works if the circle has segments that don't jump across Z=0. The problem I'm working on is more complicated as the line segments will jump across the Z=0 boundary so I end up with gaps if I try to do it in two segments. Is there a way to just use one line Geom and then change the color of the part of the line that falls into negative Z values? I'm not sure this is the right approach. Thanks!
Here is what I have so far for a test (using X,Y):
<html>
    <head>
        <title>Cirle Color</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
    <script src="three.min.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 500, window.innerWidth/window.innerHeight, 0.1, 100000 );

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

                var segmentCount = 100,
                    radius = 10,
                    geometry = new THREE.Geometry();
                    geometry2 = new THREE.Geometry();
                    material = new THREE.LineBasicMaterial({ color: "#5fd119" }); // light green
                    material2 = new THREE.LineBasicMaterial({ color: "#3d8710" }); // darker green

                    //PUSH THE ORIGIN VERTICY IN
                    geometry2.vertices.push(new THREE.Vector3(-10,0,0));

                for (var i = 0; i <= segmentCount; i++) {
                    var theta = (i / segmentCount) * Math.PI * 2;

                    x = Math.cos(theta) * radius;
                    y = Math.sin(theta) * radius;
                    z = 0;

                    if (y >=0 ){
                        geometry.vertices.push(new THREE.Vector3(x, y, z));
                    } else {
                        geometry2.vertices.push(new THREE.Vector3(x, y, z));
                    }
                }

                scene.add(new THREE.Line(geometry, material));
                scene.add(new THREE.Line(geometry2, material2));

            camera.position.z = 5;

            var render = function () {
                requestAnimationFrame( render );

                renderer.render(scene, camera);
            };

            render();
        </script>
    </body>
</html>

Update using the answer below. Works great:

A: I hope I get you correctly. You can set colours of vertices of a geometry and then use vertexColors parameter of a material.
  var radius = 5;
  var shape = new THREE.Shape();
  shape.moveTo(radius, 0);
  shape.absarc(0, 0, radius, 0, 2 * Math.PI, false);
  var spacedPoints = shape.createSpacedPointsGeometry(360);

  var vertexColors = []; // array for our vertex colours
  spacedPoints.vertices.forEach( function( vertex ){ // fill the array
    if( vertex.y < 0 )
      vertexColors.push( new THREE.Color( 0xff0000 ))
    else
      vertexColors.push( new THREE.Color( 0x0000ff ));
  });
  spacedPoints.colors = vertexColors; // assign the array

  var orbit = new THREE.Line(spacedPoints, new THREE.LineBasicMaterial({
    vertexColors: THREE.VertexColors // set this parameter like it shown here
  }));
  scene.add(orbit);

jsfiddle example


text:
Q: Liferay 6.2 Integration with Acegi security Need suggestion, we are using Liferay Portal 6.2 we would like to have spring security features integrated, was able find documents on Acegi security integration with Liferay portal 4.2 and 4.3 versions.
http://acegi-ext.sourceforge.net/acegi-portlet-liferay.html
When i started following same steps in Liferay 6.2, i am stuck in very first step of introducing Application context XML in web.xml inside (ROOT).Even if i set contextConfigLocation to applicationContext.xml , it is never recognised and picked.
I can see in web.xml instead of "org.springframework.web.context.ContextLoaderListener" in Liferay 6.2 web.xml find "com.liferay.portal.spring.context.PortalContextLoaderListener".
It will be great if can get some help on this
Awaiting your response


text:
Q: Правильный синтаксис where() Подскажите правильный синтаксис. Нужно по условию внутри функции where() заполнить новый столбец new.
df['new']  = df.where(df['first'] > df['second'], 'Первый')

Ошибка

ValueError: Expected a 1D array, got an array with shape (23699, 26)

A: Синтаксис pandas DataFrame.where предполагает замену существующих значений по условию. При этом замена происходит только, если условие НЕ выполняется. Это значит, что при выполнении метода where возвращаются только измененные значения, а те, которые не попали под условие - не возвращаются. Из-за этого размерность возвращаемого фрейма или серии не совпадает с начальной размерностью.
В вашем случае для решения задачи сначала надо задать новую колонку, чтобы ее размерность соответствовала исходной, а потом заполнять:
import pandas as pd
import numpy as np

df = pd.DataFrame({"a":[1,0,0,1]})

df:
   a
0  1
1  0
2  0
3  1

теперь:
df["new"]=pd.NA
df["new"] = df["new"].where(df["a"]!=0, "bar")

df:
   a   new
0  1  <NA>
1  0   bar
2  0   bar
3  1  <NA>

При использовании же numpy where можно обойтись без инициализации колонки заранее:
import numpy as np

df["new"] = np.where(df["a"]!=0, np.nan, "bar")

df:
   a  new
0  1  nan
1  0  bar
2  0  bar
3  1  nan


text:
Q: GestureDetector not working for Android PdfViewer lib GestureDetector working fine when i tap on empty activity screen but it's not working when I tap on Android pdfViewer(means pdf document)....Please help me how to do it.
GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            //------------------apply your logic here------------
            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return super.onSingleTapConfirmed(e);
        }
    });

@Override
public boolean onTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}

Document opened in Android PdfViewer
<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="200dp"
        android:layout_height="200dp" />

when i click outside of opened doc GestureDetector working fine but when i click on pdf document GestureDetector not wrok.

A: Got Answer from Abhay Koradiya,
issue was onTouchEvent that not called if pdfviewer attached => This hapen because pdfviewer already consumed touch event.
So you need to use

dispatchTouchEvent

instead of that. check here
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);
    return super.dispatchTouchEvent(event);
}


text:
Q: Why doesn't my NSOutputStream have space available after the first write? (hasSpaceAvailable becomes NO) With NSOutputStream I get to write perfectly just the first time.
Here is the method to send data:
- (NSInteger)sendVsCommand:(VsCommand *)command
{
    NSData *commandArray = [NSData dataWithData:[command getCommandArray]];
    NSLog(@"Space availiable: %d", [writeStream hasSpaceAvailable]);
    NSInteger result = [writeStream write:[commandArray bytes]
                                maxLength:[commandArray length]];
    NSLog(@"Writing result: %d", result);
    return result;
}

And here is the handling of the events:
case NSStreamEventHasSpaceAvailable:
            NSLog(@"%@ can accept bytes", aStream);
            if (aStream == writeStream) {
                NSLog(@"Can send data: %d", [writeStream hasSpaceAvailable]);
            }
            break;

Just the 'case' that matters anyway.
Here are the results in the console:
2013-08-16 18:07:12.769 hMonitor[5765:307] <__NSCFInputStream: 0x148650> is open
2013-08-16 18:07:12.776 hMonitor[5765:307] <__NSCFOutputStream: 0x148330> is open
2013-08-16 18:07:12.777 hMonitor[5765:307] <__NSCFOutputStream: 0x148330> can accept bytes
2013-08-16 18:07:12.779 hMonitor[5765:307] Can send data: 1
2013-08-16 18:07:13.107 hMonitor[5765:307] <__NSCFInputStream: 0x148650> has bytes
2013-08-16 18:07:13.112 hMonitor[5765:307] Space availiable: 1
2013-08-16 18:07:13.116 hMonitor[5765:307] Writing result: 41
2013-08-16 18:07:13.118 hMonitor[5765:307] <__NSCFOutputStream: 0x148330> can accept bytes
2013-08-16 18:07:13.119 hMonitor[5765:307] Can send data: 1
2013-08-16 18:07:13.687 hMonitor[5765:307] <__NSCFInputStream: 0x148650> has bytes
2013-08-16 18:07:15.343 hMonitor[5765:307] Space availiable: 0
2013-08-16 18:07:15.345 hMonitor[5765:307] Writing result: 0

*

*As you can see, when the streams open, I can write just fine (Can
send data: 1).

*Then I receive some data, and write a response immediately, Space
availiable: 1 and Writing result: 41.

*Almost immediately the OutputStream is free to write again, Can send
data: 1 (but I don't need to send anything, until the user makes
some selection). And I get a response very quickly.

*Finally, I try to write again (2 seconds later because that's when
the user has made a selection). However, now the Space available is
NO, and the Writing result is 0.
Any ideas? Where do you recommend I should look?
Thanks in advance.

A: My pointers were becoming nil, because I was not handling them the right way.
Just goes to show how green I am in Objective-C.


text:
Q: Rails: Multiple renders in a content_tag? I've got this hairy bit in a helper method:
template = content_tag(:div) do
  form_builder.fields_for(association, object) do |f|
    formats.each do |format|
      partial = "#{format}_fields"
      render(:partial => partial, :locals => { :f => f })
    end
  end
end

Unfortunately template doesn't seem to actually have any content if I do the each loop within the content_tag.
Any ideas how I could pull this off? I need to render multiple partials for this content_tag.
Note: I'm running Rails 3.0.3

A: This code looks a little suspect, what is it exactly you want to do? You might be better served using a partial with a layout than trying to do this in a helper.
I think render(:partial => ) will return the content and not concat it to the output stream, so maybe try writing your helper like this:
template = content_tag(:div) do
  fields = ''
  form_builder.fields_for(association, object) do |f|
    formats.each do |format|
      partial = "#{format}_fields"
      fields << render(:partial => partial, :locals => { :f => f })
    end
  end
  fields
end


text:
Q: Call method on click on generated html component I'm pretty new in Blazor and I'm trying to create an HTML piece using RenderTreeBuilder.
This block is basically a div that should call a method when clicked and store its value in a variable.
AutocompleteListRender = builder =>
{
    builder.OpenElement(0, "div");
    builder.AddAttribute(0, "id", "input-autocomplete-list");
    builder.AddAttribute(0, "class", "autocomplete-items");

        foreach (string entry in Entries)
        {
            if (entry.ToLower().Contains(Value))
            {
                builder.OpenElement(1, "div");
                builder.AddAttribute(1, "id", entry + "-autocomplete-list");
                builder.AddAttribute(1, "onclick", /* Method to call */);
                builder.AddAttribute(1, "value", @entry);

                builder.AddContent(1, entry);

                builder.CloseElement();
            }
        }

        builder.CloseElement();
    };

The problem here is how to attach the event, since I cannot use @onclick here.
I would like to know what options I have here, since I have seen that it is possible to call events but I cannot get it to work.

A: You need to use the EventCallbackFactory to invoke a method. Like this:
builder.AddAttribute(1, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.UIMouseEventArgs>(this, YourMethod));

and then define the method in the same class:
void YourMethod() {
    // Your code here
}


text:
Q: BroadcastDispatcher finish event only called once (discord.js) I'm trying to make a LoFi Radio for Discord. Whenever the bot goes online, it joins every channel named lofi on a server (this is very badly coded and won't work if there's more than two lofi channels in one server I know, will fix later.) The problem I'm having is the broadcast dispatcher's finish event is only called once. I want it to play a new random song every time the last one stops, but it only plays one when it goes online and one after that song, then the dispatcher is set to null which confuses me.
Code:
var fs = require('fs');
var client = new Client();
var files = fs.readdirSync("./mp3/");

var broadcast;
var curSong;
var dispatcher;

client.on("ready", () => {
    console.log(`------------${client.user.tag}------------\n`);

    curSong = `./mp3/${files[Math.floor(Math.random() * files.length)]}`;
    broadcast = client.voice.createBroadcast();
    broadcast.play(curSong);
    broadcast.dispatcher.on("finish", () => {
        curSong = `./mp3/${files[Math.floor(Math.random() * files.length)]}`;
        broadcast.play(curSong);
        client.user.setPresence({ activity: { name: curSong.split("/")[2].replace(".mp3", ""), type: "STREAMING", url: "https://twitch.tv/TwitchChannel" }, status: "Online" });
    });

    client.user.setPresence({ activity: { name: curSong.split("/")[2].replace(".mp3", ""), type: "STREAMING", url: "https://twitch.tv/TwitchChannel" }, status: "Online" });

    client.channels.cache.array().forEach((chnl) => {
        if(chnl.name.toLowerCase() == "lofi") {
            chnl.join().then(connection => {
                connection.play(broadcast);
            });
        }
    });
});

A: I fixed this by creating a function inside the ready event of the client.
This is the code for the entire bot (excluding login & message event)
var fs = require('fs');
var client = new Client();
var files = fs.readdirSync("./mp3/");

var broadcast;
var curSong;
var dispatcher;

client.on("ready", () => {
    console.log(`------------${client.user.tag}------------\n`);

    curSong = `./mp3/${files[Math.floor(Math.random() * files.length)]}`;
    broadcast = client.voice.createBroadcast();
    broadcast.play(curSong);
    dispatcherLol();

    client.user.setPresence({ activity: { name: curSong.split("/")[2].replace(".mp3", ""), type: "STREAMING", url: "https://twitch.tv/AtlasDevelopment" }, status: "Online" });

    client.channels.cache.array().forEach((chnl) => {
        if(chnl.name.toLowerCase() == "lofi") {
            chnl.join().then(connection => {
                connection.play(broadcast);
            });
        }
    });

    function dispatcherLol() {
        broadcast.dispatcher.on("finish", () => {
            curSong = `./mp3/${files[Math.floor(Math.random() * files.length)]}`;
            broadcast.play(curSong);
            client.user.setPresence({ activity: { name: curSong.split("/")[2].replace(".mp3", ""), type: "STREAMING", url: "https://twitch.tv/AtlasDevelopment" }, status: "Online" });
            dispatcherLol();
        });
        return;
    }
});


text:
Q: AngularJS: Get path to file from input tag Using this solution I'm able to retrieve files from the input tag in  base64 encoding via a directive:
.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                };
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}])

The readAsDataURL will read the file as base64.
How is it possible to get the path to the selected file from the input tag? e.g. file:///....


text:
Q: Calculate Number of Working Days without Holidays & Weekends How can I calculate the number of working days between two dates without counting Saturdays, Sundays and holidays.
I have a table with the following fields:
enter image description here
I have the following table and what I want is that in the column called expr1 calculate the difference of working days.
Enter the code into Visual Basic, and call workingdays to the module
enter image description here
Replace the variables with the names of each column.
Function WorkingDays(ByVal FECHA_DE_VALIDACION_FA As Date, ByVal FECHA_IMPRESIÓN As Date) As Long
    While FECHA_DE_VALIDACION_FA <= FECHA_IMPRESIÓN
        Select Case True
            Case Weekday(FECHA_DE_VALIDACION_FA, vbMonday) > 5
            Case DCount("*", "Holidays", "Holiday = #" & Format(fromDate, "mm/dd/yyyy") & "#") > 0
            Case Else: WorkingDays = WorkingDays + 1
        End Select
        FECHA_DE_VALIDACION_FA = FECHA_DE_VALIDACION_FA + 1
    Wend
End Function

Then they tell me that in the query with the generator call the function Workingdays, but it does not give me a result.
enter image description here
enter image description here
I accept and run the query but I get an error.

A: As Tony suggests in the comments, you will first need to construct a table containing dates of holidays, as these can vary from year-to-year.
Then, rather than using functions such as DateDiff, the easiest method is probably to incrementally count the number of days between the two dates, without incrementing the counter should the date be a Saturday or Sunday, or a member of your holidays table, e.g.:
Function WorkingDays(ByVal fromDate As Date, ByVal toDate As Date) As Long
    While fromDate <= toDate
        Select Case True
            Case Weekday(fromDate, vbMonday) > 5
            Case DCount("*", "Holidays", "Holiday = #" & Format(fromDate, "mm/dd/yyyy") & "#") > 0
            Case Else: WorkingDays = WorkingDays + 1
        End Select
        fromDate = fromDate + 1
    Wend
End Function

The above assumes that you have a table called Holidays containing a field called Holiday with all of the holiday dates to be excluded.
The above function counts the number of working days inclusive of the two supplied dates.
For example, assuming that your Holidays table contains the following dates:

Then the function would return the following:
?WorkingDays(#2018-12-24#, #2019-01-04#)
 7

To use the code, open the VBA IDE (Alt+F11), insert a new Module (Alt, I, M) and then paste the code into the module and save the module.
You can then call the function from anywhere where the Expression Builder is available.


text:
Q: C++ ( Without MFC ) Disabling/Graying a menu item I have been having trouble with my program trying to gray out ( and disable ) a sub menu item.
What I'm looking for is that the "run" item be disabled unless the required .ini entry is not empty.
My code
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HMENU hmenu = GetMenu(hWnd);
// Reading in ini
    if (0 == strcmp(webLocation, "")){
    EnableMenuItem(hmenu,ID_WEBSERVICES_RUN,MF_DISABLED | MF_GRAYED);
    WritePrivateProfileString(_T("WEBSERVICES"), _T("Location"), _T("Tool Not Found"), WpathStr);
}

I am unsure as to whether I am getting the HMENU correctly and why this  code is not working for the desired effect.
Any help with this would be greatly appreciated.

A: You can't just put this in the WndProc at the top level. WndProc process events, whether the window has been constructed or not. It'll be called many times for many different reasons.
Your WndProc will almost certainly look like a big switch on message. The one you want here is WM_INITDIALOG:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
         case WM_INITDIALOG:
             // jump to a new function that reads the .ini
             // and disables the control etc.
             return OnInitDialog(hWnd, wParam, lParam);

         default:
             return DefWindowProc(hWnd, message, wParam, lParam);
    }
}


text:
Q: Not able to open Spring MVC .jsp in JQuery Dialog I have developed a Spring MVC application along with JQGrid. Relevant part of my .js file is as below wherein I am opening a JQuery Dialog box, when user clicks the 'select' custom button from the ADD/Edit dialog of the JQGrid. Dialog box gets opened, but not the .jsp file whose path is given in the load method of the JQuery Dialog.
My .js file is as below:
          function JQDialog(title, contentUrl, params) {
                var dialog1 = $("
").dialog(
                {
                    autoOpen: false,
                    modal: true,
                    title: title,
                    close: function (e, ui) { (dialog1).remove(); },
                    buttons: { "Ok": function () { (dialog1).dialog("close"); } }
                });

                dialog1.load(contentUrl, function () {
                     dialog1.dialog('open');
                });

            }

 $("#list").jqGrid('navGrid','#pager',{edit:true,add:true,del:true,search:true,refresh:false},
         {
           recreateForm: true, dataheight: 375, width: 400, height: 450,
           beforeShowForm: function(form) {$('#trv_ccode',form).hide();

           $('Select')
            .click(function(rowid, iRow, iCol, cellValue, e) {
                    JQDialog('Test Dialog',"../acctmstmgmt/opendlg",'');

However, when I open window with following code my .jsp file gets opened.
window.open("../acctmstmgmt/opendlg", 'Dialog', 'width=700,height=300', top=500, left=500 );

What could be the reason? any solution?


text:
Q: Creating custom shadows with Robolectric 2.X I am running Robolectric 2.x(2.4) on my project. I have followed the example in the official doc to create a custom shadow of my own class but Robolectric is not using it.
The project is on GitHub(branch roboMockitoTutorial). Here is some pieces of the code:
The class which I try to create shadow(AppUtils):
package com.jiahaoliuliu.robolectricsample;

/**
 * Created by jiahao on 2/15/15.
 */
public class AppUtils {

    public AppUtils() {}

    public int generateNumberUsersRandomly() {
        // :)
        return 42;
    }
}

The Activity where the class is used:
package com.jiahaoliuliu.robolectricsample;

import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends ActionBarActivity {

    TextView my_hello_text_view;
    Button mClickMeBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppUtils appUtils = new AppUtils();
        System.out.println("The randomly generated number of users is " + appUtils.generateNumberUsersRandomly());
        setContentView(R.layout.activity_main);
        my_hello_text_view = (TextView) findViewById(R.id.my_hello_text_view);
        mClickMeBtn = (Button) findViewById(R.id.clickMeBtn);

        int w = 200, h = 200;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
        Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
        bmp.compress(Bitmap.CompressFormat.PNG, 200, new OutputStream() {
            @Override
            public void write(int oneByte) throws IOException {
                System.out.println("Writting in the outputStream " + oneByte);
            }
        });
    }

    public void clickMeBtnPressed(View view) {
        my_hello_text_view.setText(getString(R.string.ok_thanks));
    }
}

The shadow class(AppUtilsShadow):
package com.jiahaoliuliu.robolectricsample;

import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.shadows.ShadowView;

/**
 * Created by jiahao on 2/15/15.
 */
@Implements(AppUtils.class)
public class AppUtilsShadow {

    @RealObject
    private AppUtils appUtils;

    public AppUtilsShadow() {}

    // Trying to create the constructor for it.
    public void __constructor__() {}

    @Implementation
    public int generateNumberUsersRandomly() {
        System.out.println("Invoking the real object method");
        return appUtils.generateNumberUsersRandomly();
    }
}

The test class:
package com.jiahaoliuliu.robolectricsample;

import com.jiahaoliuliu.robolectricsample.MainActivity;
import com.jiahaoliuliu.robolectricsample.RobolectricGradleTestRunner;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.List;

import static org.assertj.android.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

@RunWith(RobolectricGradleTestRunner.class)
@Config(shadows = {AppUtilsShadow.class, MyShadowBitmap.class})
public class MyActivityTest {

  private MainActivity mActivity;

  @Before
  public void setup() {
    mActivity = Robolectric.buildActivity(MainActivity.class).create().get();
  }

  @Test
  public void testMyActivityAppearsAsExpectedInitially() {
    assertThat(mActivity.my_hello_text_view).isVisible();
    assertThat(mActivity.my_hello_text_view).hasText("Hello world!");
    assertThat(mActivity.mClickMeBtn).hasText("Click Me");
  }

}

A: The catch with Shadows is that they are meant for shadowing Android classes, not all classes. See documentation or even better, the code.
Since AppUtils is not from the Android SDK, your shadow does not get picked up.
This is not a flaw, as far as I can tell, it's an intentional decision by design. Since this is your own class, you have better ways accessible to you for loading up a test class and shouldn't need shadows.
That said, if you really want to use shadows for this, you can create a custom test runner where you override shouldInstrument to make it also instrument the classes or packages you're interested in. Then, the code you have above should work. I've never tried this, but you can check this out for some sample code.


text:
Q: Using structs in C++ I'm having trouble using structs to program. I want to accept input in the form of (integer, character) which can repeat several times. The program will then store the character in the array in the spot where the integer indicates. Currently, the issue is that Message is undefined and that location is undefined.
struct MessagePiece
{
    int location;
    char message;
};

void readMessage( istream& in, Message message[] )
{
    MessagePiece;
    message[256];
    Message message;

      while ( !in.fail() )
     {
             in >> location; //I'm not sure why this counts as undefined as it is defined in the struct

             if (location < 256, location >= 0)
                in >> message[location];
      }
return;
};

A: It is undefined because it the location exists only in the context of an object of type MessagePiece
MessagePiece mp;
in >> mp.location;

A: You should use && instead of ',' in your if statement for checking the condition.
Also, these lines:
MessagePiece;
message[256];
Message message;

should be written like this:
MessagePiece messages[256]; //declaring an array of struct MessagePiece
char message; // a char for storing input read from the user.

One more thing, either take message as an argument or declare it in the function itself.
Please consider reading a good book on programming in C++.


text:
Q: Without specifying a port number inside of a API request how server decided that this request is for port 80 or 443 I did not mention port number in my api end point, but how server decided to serve this request using port 80 or 443
const {data} = await axios.get('/api/users/currentuser');

A: Use something like this in NGINX:
server {
  root /var/www/html;

  server_name _;

# this is the react/angular fronted application endpoints
  location / {
    try_files $uri $uri/ /index.html;
  }

# this is the api endpoints
  location /api {
    proxy_pass http://127.0.0.1:8000;
  }
}

However you have not explicitely mentioned in the question that you are using NGINX or not but you have nginx in one of the 5 tags of this question, so I am supposing that you must be using NGINX and so, I am answering in that context.


text:
Q: How to Replace a string by another in a text file I would like to replace a given string in a text file into by another, but with one extra detail.
Example:
If the file content's is :
Library Hello1
===============
any text here
version: 0.1
--------------

Library Hello2
===============
any text here
version:0.1
--------------

Library Hello3
===============
any text here
version: 0.2
--------------

I would like to grep all lines containing the word Library and replace all "Library" by the other word, eg. "myStr". However this should only be done for those which version is, for example, 0.1. All the others should be ignored.
Please notice that the search/replace should be done inside each block of code. The blocks are delimited by ===== and -----.
Note: I can do search and replace, but I don't know how to simultaneously search for the version inside a block.

A: You can try this sed
sed '/^Library/!b;:A;N;/version/!bA;/0\.1$/s/^Library/myStr/' infile

Look first for Library.
If find get all the following line until version.
When find look for 0.1 and make change if it's ok.


text:
Q: Python: Reading from two array of tuples at a time and placing them side-by-side on CSV file So I have two arrays of tuples that are arranged with Restaurant Name and an Int:
("Restaurant Name", 0)

One is called ArrayForInitialSpots, and the other is called ArrayForChosenSpots. What I want to do is to write the tuples from both rows in side-by-side order in a csv file like this:
"First Restaurant in ArrayForInitialSPots",0,"First Restaurant in ArrayForChosenSpots", 1

"Second Restaurant in ArrayForInitialSpots",0,"Second Restaurant in ArrayForChosenSpots",0

So far i've tried doing this:
with open('data.csv','w') as out:
        csv_out=csv.writer(out)
        csv_out.writerow(['Restaurant Name','Change'])
        for x, y in zip(arrayForInitialSpots, arrayForChosenSpots):
            csv_out.writerow(x + y)
            #csv_out.writerow(y)

But I get:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-6: ordinal not in range(128)

If I remove the zip function, I get too many values to unpack. Any suggestions guys? Thank you very much in advance.

A: with mhawke help here is my solution
with open('data.csv','w') as out:
   csv_out=csv.writer(out)
   csv_out.writerow(['Restaurant Name','Change'])
   for x, y in zip(arrayForInitialSpots, arrayForChosenSpots):
      list_ = [str(word).decode("utf8") for word in (x+y)]
      counter = 0
      while counter < len(list_):
         s=""
         for i in range(counter,counter+4):
            s+=list_[i].encode('utf-8')
            s+=","
         counter = counter + 4
      csv_out.writerow(s[:-1])

A: There are two things that you could use to handle extended ascii characters while writing to files:

*

*Set default encoding to utf-8
import sys
reload(sys).setdefaultencoding("utf-8")

*Use unicodecsv writer to write data to files
import unicodecsv
unicodecsv

A: The problem is not due to your use of zip() - that looks OK, but instead it is an encoding issue. Probably the restaurant names are unicode strings or in some encoding other than ASCII or UTF8? ISO-8859-1 perhaps?
The csv module does not handle unicode; other encodings might work, but it depends. The module does handle 8-bit values OK (except ASCII NUL), so you should be able to encode them as UTF8 like this:
ENCODING = 'iso-8859-1'    # assume strings are encoded in this encoding

def to_utf8(item, from_encoding):
    if isinstance(item, str):
        # byte strings are first decoded to unicode
        item = unicode(item, from_encoding)
    return unicode(item).encode('utf8')

with open('data.csv', 'w') as out:
    csv_out = csv.writer(out)
    csv_out.writerow(['Restaurant Name', 'Change'] * 2)
    for x, y in zip(arrayForInitialSpots, arrayForChosenSpots):
        csv_out.writerow([to_utf8(item, ENCODING) for item in x+y])

This works by converting each element of the tuple formed by x+y into a UTF-8 string. This includes byte strings in other encodings, as well as other objects such as integers that can be converted to a unicode string via unicode(). If your strings are unicode, just set ENCODING to None.

A: I'd suggest using numpy:
import numpy as np
IniSpots=[("Restaurant Name0a", 0),("Restaurant Name1a", 1)]
ChoSpots=[("Restaurant Name0b", 0),("Restaurant Name1b", 0)]
c=np.hstack((IniSpots,ChoSpots))
np.savetxt("data.csv", c, fmt='%s',delimiter=",")


text:
Q: How to let Ruby-Gnuplot/Multiplot plot to file? The example
require 'gnuplot'
require 'gnuplot/multiplot'
def sample
    x = (0..50).collect { |v| v.to_f }
    mult2 = x.map {|v| v * 2 }
    squares = x.map {|v| v * 4 }

    Gnuplot.open do |gp|
        Gnuplot::Multiplot.new(gp, layout: [2,1]) do |mp|
            Gnuplot::Plot.new(mp) { |plot| plot.data << Gnuplot::DataSet.new( [x, mult2] ) }
            Gnuplot::Plot.new(mp) { |plot| plot.data << Gnuplot::DataSet.new( [x, squares] ) }
        end
    end
end

works pretty well. But how can I send this to a file instead of the screen? Where to put plot.terminal "png enhanced truecolor" and plot.output "data.png"?

A: Indeed, I don't even know where I should call #terminal and #output methods since the plot object are inside a multiplot block.
As a workaround, the following would work as expected.
Gnuplot.open do |gp|
   ...
end

The block parameter gp in this part is passed the IO object to send the command to gnuplot through the pipe. Thus, we can send commands ("set terminal", "set output") directly to gnuplot via gp.
    Gnuplot.open do |gp|
        gp << 'set terminal png enhanced truecolor' << "\n"
        gp << 'set output "data.png"' << "\n"
        Gnuplot::Multiplot.new(gp, layout: [2,1]) do |mp|
            Gnuplot::Plot.new(mp) { |plot| plot.data << Gnuplot::DataSet.new( [x, mult2] ) }
            Gnuplot::Plot.new(mp) { | plot| plot.data << Gnuplot::DataSet.new( [x, squares] ) }
        end
    end