text:
Q: Wagtail API - how to expose snippets Imagine I have a Snippet and a Page containing it:
@register_snippet
class MySnippet(models.Model):
    content = models.CharField(max_length=255)

class MyPage(Page):
    snippet = models.ForeignKey('MySnippet', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')

    api_fields = [
        APIFiled('snippet')
    ]

Now in the wagtail API page endpoint this page will look like this:
{
    "id": 1,
    "meta": { ... },
    "snippet": {
        "id": 1,
        "meta": {
            "type": "my_module.MySnippet"
        }
    }
}

What can I do to make this endpoint displaying snippet's content?
Also, how do I create a separate API endpoint only for snippets?

A: I'm not sure how to answer the main question, but I can help with creating separate API endpoints for snippets.
You have to create an endpoints.py file in your app root, using the existing Wagtail endpoint classes as a base, such as BaseAPIEndpoint
Then, register the new endpoint in your api.py file.
endpoints.py
from wagtail.api.v2.endpoints import BaseAPIEndpoint
from .models import MySnippetModel

class MySnippetModelAPIEndpoint(BaseAPIEndpoint):

    model = MySnippetModel

    body_fields = BaseAPIEndpoint.body_fields + [
        'field_1',
        'field_2',
        'field_3',
    ]

    listing_default_fields = BaseAPIEndpoint.listing_default_fields = [
        'field_1',
        'field_2',
        'field_3',
    ]

api.py
from .endpoints import MySnippetModelAPIEndpoint

...

sua_api_router.register_endpoint('snippets', MySnippetModelAPIEndpoint)

I would also look at the endpoints.py file in Wagtail core, so you can see what else you can extend or modify.
https://github.com/wagtail/wagtail/blob/master/wagtail/api/v2/endpoints.py

A: Here's how I did it, it was a simple enough representation though in my case
from rest_framework import serializers

class MyPage(Page):
    snippet = models.ForeignKey('MySnippet', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')

    api_fields = [
        APIField('snippet', serializer=serializers.StringRelatedField(many=True))
    ]

And you can add a 'str' method to your snippet
@register_snippet
class MySnippet(models.Model):
    content = models.CharField(max_length=255)

        def __str__(self):
            return self.content


text:
Q: Next button on questions pages requires lots of scrolling if you have many tags If you have a lot of Interesting Tags and Ignored Tags configured like I do, then on the 'Questions' page, or, say, /questions/tagged/java/ (java is a tag with lots of related tags, which makes the problem worse), the 1 2 3 ... [X] [Next] buttons may appear more than a full page below the last displayed question on the page, requiring a lot of scrolling just to click 'next'. This isn't browser specific from what i can tell.
Here's a screenshot
It would be really sweet if the buttons instead appeared directly below the last question in the list. Currently this only happens if the right sidebar tags occupy less vertical space than the default 10 questions per page.
Fortunately in searching for this question I found the rel=next request, which gives me a workaround to constantly scrolling just to hit 'next'.

A: A simple solution is to increase the questions shown to their maximum of 50 per page (option to do this is at the bottom right of the page).

redpajama_set_name: RedPajamaStackExchange


text:
Q: In python , How to find if a random string (AB122340) lies in between series of strings starting from AB120000 to AB125000 I will get a string from API looks like AB122340, AB122360 .... etc.
I want to return true if that string (AB122340) lies between AB120000 to AB125000
Ex:
for AB122340  --> true
for AB127999  ---> false as it was not in the above range(AB120000 to AB125000)

A: Assuming that your values are the same length, simple lexical comparison will do. You can use Python's comparison chaining here.
if "AB120000" <= the_code <= "AB125000":

Or if the range is exclusive (doesn't include its endpoints):
if "AB120000" < the_code < "AB125000":


text:
Q: XSD - Presence of element depending on presence of other element(s) I have three possible elements inside a parent element:
<parent>
    ...
    ...
    <c>...</c>
</parent>

Inside parent, element b is only allowed when element a is present. Also, element c is only allowed when element b (and therefore also a) is present. In other words, the following configurations are allowed:
<parent>
    ...
    ...
    <c>...</c>
</parent>

<parent>
    ...
    ...
</parent>

<parent>
    ...
</parent>

The following configurations are invalid:
<parent>
    ...
</parent>

<parent>
    <c>...</c>
</parent>

<parent>
    ...
    <c>...</c>
</parent>

Is this constraint expressable in XSD?

A: Sure, the grammar is
( a, (b, (c)?)?)

which translates to
<xs:sequence>
  <xs:element name="a"/>
  <xs:sequence minOccurs="0">
    <xs:element name="b"/>
    <xs:element name="c" minOccurs="0"/>
  </xs:sequence>
</xs:sequence>


text:
Q: How to fix MS Access EnumFields error in VBA I just started studying VBA for Access. I am therefore using some examples of site "https://learn.microsoft.com/en-us/office/client-developer/access/access-home".
When the code contains "EnumFiels" its execution generates the error "Sub or Function not defined".
I can't understand the reason for it and, above all, I don't know how to eliminate it.
For instance:
Sub WhereX()

    Dim dbs As Database, rst As Recordset
    Set dbs = OpenDatabase("Northwind.mdb")
    Set rst = dbs.OpenRecordset("SELECT LastName, " _
        & "FirstName FROM Employees " _
        & "WHERE LastName = 'King';")
    rst.MoveLast

    EnumFields rst, 12

    dbs.Close
End Sub


text:
Q: error after running a job in google cloud ML I tried running a word-RNN model from github on Google Cloud ML . After submitting the job,I am getting errors in log file.
This is what i submitted for training
gcloud ml-engine jobs submit training word_pred_7 \
    --package-path trainer \
    --module-name trainer.train \
    --runtime-version 1.0 \
    --job-dir $JOB_DIR \
    --region $REGION \
    -- \
    --data_dir gs://model-development/arpit/word-rnn-tensorflow-master/data/tinyshakespeare/real1.txt \
    --save_dir gs://model-development/arpit/word-rnn-tensorflow-master/save

This is what I get in the log file.

A: Finally, after submitting 77 jobs to cloud ML I am able to run the job and problem was not with the arguments while submitting the job. It was about the IO errors generated by files .npy which have to stores using file_io.FileIo and read as StringIO.
These IO Errors have not been mentioned anywhere and one should check for them if they find any errors where it says no such file or directory.

A: You will need to modify your train.py to accept a "--job-dir" command-line argument.
When you specify --job-dir in gcloud, the service passes it through to your program as an argument, so your argparser (or tf.flags, depending on which you're using), will need to be modified accordingly.

A: I had the same issue and it seems like google cloud somehow uses that --job-dir anyway when loading your own script (even if you place it before -- on the gcloud command)
The way I fixed it like the official gcloud census example on line 153 and line 183:
parser.add_argument(
  '--job-dir',
  help='GCS location to write checkpoints and export models',
  required=True
)
args = parser.parse_args()
arguments = args.__dict__
job_dir = arguments.pop('job_dir')

train_model(**arguments)

Basically it means to let your python main program take in this --job-dir parameter, even if you are not using it.

A: In addition to adding --job-dir as accepted argument, I think you should also move the flag after the --.
From the getting started:

Run the local train command using the --distribued option. Be sure to
  place the flag above the -- that separates the user arguments from the
  command-line arguments

where, in that case, --distribued was a command-line argument
EDIT:
--job-dir IS NOT a user argument, so it is correct to place it before the --


text:
Q: Why do we see multiple PID's related to same application/owner for http like this below. What does this mean? Why do we see multiple PID's related to same application/owner for http like this below. What does this mean?.
 $ ps -ef | grep httpd | grep -v grep
 apache    9619 20181  0 07:08 ?        00:00:03 /usr/sbin/httpd
 apache   10092 20181  0 Jan24 ?        00:00:07 /usr/sbin/httpd
 apache   13086 20181  0 06:09 ?        00:00:00 /usr/sbin/httpd
 apache   13717 20181  0 Jan25 ?        00:00:01 /usr/sbin/httpd
 apache   14730 20181  0 07:13 ?        00:00:01 /usr/sbin/httpd
 apache   16359 20181  0 09:54 ?        00:00:00 /usr/sbin/httpd
 root     20181     1  0  2011 ?        00:00:01 /usr/sbin/httpd
 apache   21450 20181  0 09:55 ?        00:00:00 /usr/sbin/httpd

A: Each httpd PID represent a server process which is running in order to handle the incoming request. The default NO of server process to be run in background can be controlled by the following directives in the httpd conf file (similarly in other applications).
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

A: This is the way the Apache web server works.  Basically, the master process starts as root, opens the appropriate ports based on the configuration file, and then duplicate/forks the number of listeners/servers as you configured them.  These servers run as the configured user (apache in this case) and basically handle one HTTP transaction.  So the larger the number of configured servers, the more requests that you can handle concurrently.
So the meaning to answer your question, is that it looks like you have an Apache website(s) running.

A: This is normal; Apache, like many other applications, will run multiple copies of itself. In this case, full processes (with their own PID's), though in other configurations it could be multiple threads.
StartServers,  MinSpareServers, MaxSpareServers, etc are the configuration directives of note.

A: The numbers in the second column are the PPIDS (parent PIDs) which indicate that most of your http processes are children (due to exec/fork/...) of the original process (in this case 20181 which was originally started as root).
As the other answers already point out this is one option to implement multi-processing to leverage multiple CPUs for parallel processing. This is influenced by the selection of the "mpm" worker model in your Apache configuration.


text:
Q: Backbone.js model.save() fire a "too much recursion" error in underscore I've got a problem trying to use backbone on saving my Model from a form. Here I want my my view to actually be an editing form:
    (function() {

    'use strict';

    var YachtEditor = {};
    window.YachtEditor = YachtEditor;

    var template = function(name) {
        return Mustache.compile($('#' + name + 'Template').html());
    };

    YachtEditor.Tank = Backbone.Model.extend({
        defaults : {
            dCapacity : "",
            sType : ""
        }
    });

    YachtEditor.Tanks = Backbone.Collection.extend({
    //      url: "/rest/tanks",
        localStorage: new Store("tanks"),
        model : YachtEditor.Tank
    });

    YachtEditor.TankView = Backbone.View.extend({
        template: template("tank"),
        events: {
            'click .save' : 'save',
            'click .remove' : 'remove'
        },
        initialize: function() {
            console.log("initialize tank View :");
            console.log(this.model.get("id"));
        },
        render: function() {
            this.$el.html(this.template(this));
            return this;
        },
        save: function() {
            console.log('change');

            var self = this;
            var values = {
                    sType:     self.$("#sType").val(),
                    dCapacity: self.$("#dCapacity").val()
                };

            console.log("dCapacity : " + values.dCapacity);
            console.log("sType : " + values.sType);

            this.model.save(values);
        },
        remove: function() {
            this.model.destroy();
        },
        dCapacity : function() {
            return this.model.get("dCapacity");
        },
        sType : function() {
            return this.model.get("sType");
        }
    });

    YachtEditor.TanksView = Backbone.View.extend({
        el: $("div.tankZone"),
        template: template("tanks"),
        events: {
            "click .add" : "addTank",
            "click .clear" : "clear"
        },
        initialize: function() {
            this.tanks = new YachtEditor.Tanks();
//          this.tanks.on('all', this.render, this);
            this.tanks.fetch();
            this.render();
        },
        render: function() {
            this.$el.html(this.template(this));
            this.tanks.each(this.renderTank, this);
            return this;
        },
        renderTank: function(tank) {
            var view = new YachtEditor.TankView({model: tank});
            $(".tanks").append(view.render().el);
            return this;
        },
        addTank: function() {
            this.tanks.create({});
            this.render();
        },
        clear: function() {
            this.tanks.each(function(tank) {
                tank.destroy();
            });
            this.render();
        }
    });
    ...
    })();

Here is the mustache template i use for each tank

My problem here is that this.model.save() triggers a 'too much recursion' in underscore. js. (chrome is displaying an error also.
Here is the call stack on error:
_.extend
_.clone
_.extend.toJSON
_.extend.save
_.extend.update
Backbone.sync
_.extend.sync
_.extend.save
YachtEditor.TankView.Backbone.View.extend.save
st.event.dispatch
y.handle

I suspect the save to recall the blur event but i cannot find a way to explicit it... Maybe I'm not using backbone as i should?

A: My problem, aside of some pointed out by Yurui Ray Zhang (thank you), was that I was using a backbone-localstorage.js from an example I found here : git://github.com/ngauthier/intro-to-backbone-js.git
The "too much recursion error" stopped to appear as soon a I replaced it with a storage I found here : https://github.com/jeromegn/Backbone.localStorage

A: a few things. you defined your tank model as
app.Tank = ...

but in your collection you are referencing it as:
model : YachtEditor.Tank

and in your view, you are trying to assign elements before they are rendered on the page:
this.input = {}
this.input.sType     = this.$("#sType");
this.input.dCapacity = this.$("#dCapacity");

I'm not sure how your view is rendered to the page, some people, like me, like to use render() to render the template directly to the page:
render: function() {
  this.$el.html(this.template(this));
   //done, you should be able to see the form on the page now.
},

some others, will use something else to insert the el, eg:
//in another view
tankView.render().$el.appendTo('body');

but either way, if you want to cache your elements, you need to do it after they are rendered to the page, not in initialize.
//this method is only called after render() is called!
cacheElements: function() {
    this.input = {}
    this.input.sType     = this.$("#sType");
    this.input.dCapacity = this.$("#dCapacity");
}

I'd suggest, first, try to fix this things, and then, try to add some console log or debuggers in your readForm method to see if the values are grabbed correctly:
readForm: function() {
    var input = this.input;
    console.log(input.sType.val());
    console.log(input.dCapacity.val());
    this.model.save({
        sType:     input.sType.val(),
        dCapacity: input.dCapacity.val()
    });
},


text:
Q: Why floats or doubles get written as integers? In the following program
#include <fstream>

int main(){

    std::ofstream fs_;
    fs_.open("test.txt");

   fs_<<1.f;
   fs_<<"   ";
   fs_<<1.0;

    fs_.flush();
    fs_.close();

return 0;
}

Why the resulting file has written
1   1

instead of 1.0 1.0 ? And is there a way to write them as floats or doubles?
I should have added that with floats with a lot of decimals I don't want them to be truncated.
So far with the suggested solution 1.034255 becomes 1.03 with precision of 2
Rather than the "duplicate" that this question was closed for, this question is more related to this one


text:
Q: how to explicitly use mv to rename a folder(Pen-drive)? I am trying to rename the my pen-drive by using mv command but it tries to move it and fails.
uman@uman-All-Series /media/uman$ sudo mv USB\ STICK/ Videos
mv: cannot move 'USB STICK/' to 'Videos': Device or resource busy

How can I explicitly use mv to rename a folder(it is Pen-drive in this case)?

A: When you connect a USB, the kernel will give it a name in the /dev folder, probably /dev/sdb or /dev/sdc.
The partition in your device gets mounted in the folder /media/yourusername/partition-label.
What you are trying to do is to move the folder where is mounted /media/uman/USB\ STICK, and this cannot be don whilst is mounted (busy).
If you want to rename the pendrive, you can change the label of the partition with the "disks" utility in Ubuntu. Next time it will mount in a /media/yourusername/newlabel.
You can also mount it manually in a different folder with any name you want. Have a look at man mount if this is what you want.

A: As long as I know moving a mounted folder is not possible still now.
If you want to really move to another folder then you must remount to the target location.
First unmount your device
$ umount /path/to/device device path is usually /dev/sdb1 for a pendrive (make sure especially if you have multiple drives connected).
Then make a folder in your taget folder
$ mkdir -p ~/Videos/Pendrive

Here -p indicates that the entire path will be created if not exists.
Then mount your drive here.
$ mount /dev/sdb1 /absolute/path/to/Videos/Pendrive

If anything is not permitted try as root or add sudo before every command.

A: When Ubuntu mounts external drives to /media/username/ it uses partition labels for the directory names. You can mount the partition manually to set the name of the folder as you want as Chitholian suggests or change the label of the partition on the pen drive.
You have e2label, mlabel,... programs to change the partition label. You can also to it with Disks application, which is part of Ubuntu distribution.


text:
Q: Smart contract ownership I have renounced ownership of smart contract and now it is a null address (0x00..). Is there a way for me to reclaim ownership? As currently if I call transferOwnership - it comes back with error that caller is not owner.
Thanks in advance.

A:
Is there a way for me to reclaim ownership?

Simple answer: No.

Unless... there's a function to specifically reclaim ownership from the zero address. Which would not make much sense to implement.
// holds the previous owner before renouncing their ownership.
address previousOwner;

function reclaimOwnership() external {
    require(msg.sender == previousOwner);
    owner = msg.sender;
}

Assuming there's no such function:

*

*Theoretically, you could reclaim the ownership by invoking the transferOwnership() function from the zero address, for which you'd need its private key. But it's practically impossible to guess its private key, and there's no record of anyone successfully guessing the zero address private key, ever.

*Or if your contract was deployed using the CREATE2 opcode and has a selfdestroy mechanism, you could destroy and redeploy it to the same address, which would effectively set the owner value to the deployer (depending on your implementation, but most contracts set the owner in the constructor). But it's not very common to have this combination in a contract if you're not specifically counting on this option beforehand.


text:
Q: How should I add multiple images from a folder(present locally on my PC) in a 9x9 grid in HTML

.card {
  width: 20rem;
  margin: 30px;
}

.image-grid-container {
  display: grid;
  width: auto;
  height: 310px;
  overflow: auto;
  /* For 3 columns */
  grid-template-columns: auto auto auto;
}

img {
  width: 100%;
}

          LR

          Low Resolution Images before applying Algorithm.

     LR FOLDER

          Loading Results...

          Developer Guy love to develop front-end and back-end

     ESRGAN

          HR

          High Resolution Images after applying Algorithm.

     HR FOLDER

I have made a 9x9 grid using HTML and CSS.
It contains 9 images which can be scrolled down/up using scroller.
Now I have around 100,000 images which I have to display in the grid.
Is there anything I can do... I am new to frontend.
This is the look of the grid:

I have to display images from the folder using some loops.


text:
Q: Printing a substring from an argument in C I need to make a program that prints a string with the first character on the first line, then the second two characters on the next line. i.e Hello
H
He
Hel
Hell
Hello
Here is what I have tried so far, but I only get one letter per line.
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    for(int i = 1; i < argc; i++)
    {
      int wordLength = strlen(argv[i]);
      for(int j = 0; j < wordLength; j++)
      {
        printf("%c\n", *argv + i);
      }
    }
    return 0;
}

A: By perform minor change on your code this is correct version to do that.
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{

    for(int i = 1; i < argc; i++)
        {
        int wordLength = strlen(argv[i]);

        for(int j = 0; j < wordLength; j++)
        {
            for (int k=0;k<=j;k++){
                printf("%c", argv[i][k]);
            }
                printf("\n");
        }
        }
    return 0;
}

Compile and Run
gcc -Wall file.c -o file
./file salam hello
Output
s
sa
sal
sala
salam
h
he
hel
hell
hello


text:
Q: Converting for loops on script that is called by another script into GNU parallel commands Currently I have the following script for using the HaploTypeCaller program on my Unix system on a repeatable environment I created:
#!/bin/bash
#parallel call SNPs with chromosomes by GATK
for i in 1 2 3 4 5 6 7
do
  for o in A B D
  do
    for u in _part1 _part2
    do
      (gatk HaplotypeCaller \
        -R /storage/ppl/wentao/GATK_R_index/genome.fa \
        -I GATK/MarkDuplicates/ApproachBsortedstettler.bam \
        -L chr$i$o$u \
        -O GATK/HaplotypeCaller/HaploSample.chr$i$o$u.raw.vcf &)
    done
  done
done

gatk HaplotypeCaller \
    -R /storage/ppl/wentao/GATK_R_index/genome.fa \
    -I GATK/MarkDuplicates/ApproachBsortedstettler.bam \
    -L chrUn \
    -O GATK/HaplotypeCaller/HaploSample.chrUn.raw.vcf&

How can I change this piece of code to parallel at least partially?
Is it worth to do I am trying to incorporate this whole script in a different script that you can see on a different question here
should I?
Will I get quite the boost on performance?

A: I don't have parallel,
and I don't really understand what the guts of your script is doing,
so I can't test this.
But I believe that this will work,
and may be in the style you were looking for.
Rewrite the script to remove the loops, and to take arguments:
#!/bin/bash
#parallel call SNPs with chromosomes by GATK
            (to be safe, verify that "$#" is 3)
i="$1"
o="$2"
u="$3"
            (if you want, verify that the arguments are valid)
gatk HaplotypeCaller \
          ︙       \
    -L "chr$i$o$u" \
    -O "GATK/HaplotypeCaller/HaploSample.chr$i$o$u.raw.vcf" &

gatk HaplotypeCaller \
          ︙       \
    -L chrUn -O GATK/HaplotypeCaller/HaploSample.chrUn.raw.vcf &

Then run it like this:
printf '%s\n' {1,2,3,4,5,6,7}' '{A,B,D}' '_part{1,2} | parallel -L1 (your_script)

Let me walk you through this:

*

*{1,2,3} expands as three words: 1, 2 and 3.

*{1,2,3} {A,B} expands as five words: 1, 2, 3, A and B.

*{1,2,3}{A,B} expands as six words:
1A, 1B, 2A, 2B, 3A and 3B.

*{1,2,3}' '{A,B} expands as six words:
1 A, 1 B, 2 A, 2 B, 3 A and 3 B.
Note that these "words" include spaces.

*{1,2,3,4,5,6,7}' '{A,B,D}' '_part{1,2} expands as 42 (7×3×2) words,
each of which includes two spaces.

*printf '%s\n' outputs each "word" on a separate line.
But remember, we're talking about "words" with spaces in them.
The effect is that it prints two or three regular (non-whitespace)
words per line.
For example,

$ printf '%s\n' {1,2,3}' '{A,B}
1 A
1 B
2 A
2 B
3 A
3 B

At this point, these are ordinary spaces; they are no longer quoted.

*-L1 tells parallel to run your program with the data from one line.
It will break the line apart at the spaces,
and get a set of three arguments.

A: parallel echo HaploSample.chr{1}{2}{3}.raw.vcf ::: 1 2 3 4 5 6 7 ::: A B D ::: _part1 _part2

A: #!/bin/bash
#parallel call SNPs with chromosomes by GATK

gatk_a_single() {
    i="$1"
    o="$2"
    u="$3"

    gatk HaplotypeCaller \
        -R /storage/ppl/wentao/GATK_R_index/genome.fa \
        -I GATK/MarkDuplicates/ApproachBsortedstettler.bam \
        -L chr$i$o$u \
        -O GATK/HaplotypeCaller/HaploSample.chr$i$o$u.raw.vcf
}
export -f gatk_a_single

# This call does not fit the pattern of the others, so just run that in the background
gatk_a_single Un "" "" &

# Use 3 input sources: All combinations between all input sources will be generated and run
parallel gatk_a_single ::: 1 2 3 4 5 6 7 ::: A B D ::: _part1 _part2

# The parallel tasks are now complete
# Wait for the earlier backgrounded task to complete
wait

A: At the first approximation, paralleling makes sense when the number of jobs is <= the number of cores.  Do you have 42 cores available?  If not, then paralleling all the jobs at once might not make sense.
Here's the "naive" way to parallel your jobs:
1) Don't RUN the commands, WRITE them:
for i in 1 2 3 4 5 6 7
do
  for o in A B D
  do
    for u in _part1 _part2
    do
      echo "gatk HaplotypeCaller \
        -R /storage/ppl/wentao/GATK_R_index/genome.fa \
        -I GATK/MarkDuplicates/ApproachBsortedstettler.bam \
        -L chr$i$o$u \
        -O GATK/HaplotypeCaller/HaploSample.chr$i$o$u.raw.vcf &"
    done
  done > file-$i.sh
done

Now you've got 7 text files of 6 commands each.  You can parallel your jobs in batches of 6 by running those 7 scripts one after the other.  If you've got enough cores (16?), you can run two batches of 6 at a time.
Lather, rinse, repeat.


text:
Q: GridBagConstraints weightx and weighty values In many books weightx and weighty values are expressed in different ways:
some says 0.0 to 1.0
other says 0 to 100
other say until 1000
I'm a lot confused.
In the API these variables are double types so I think the first is correct but what does it meaning a value of 0.4 or 0.7? are percentage values, point values? relative of what?

A: I would follow the examples used in the Swing tutorial on How to Use GridBagLayout.
In that context 1.0 means as the frame grows the components gets all the extra space. 0.0 means it gets no space.

A: Actually, these are weights. So what counts is that they are all on the same "scale".
It doesn't really matter then if percentage or not, in the end, they are evaluated regarding their total on a dimension. So just use what seems to be the most clear for you.


text:
Q: Im having trouble with the variable of a for loop in javascript in a django template what i am trying to do is make an animation by looping throught some images in my static file folder with javascript in django. but something keeps screwing their adress up
my code looks something like this
{% load static %}

<img id="image_1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Solid_red.svg/512px-Solid_red.svg.png?20150316143248">

<button onclick="animation()">Click me</button>

<script>
  function animation(){
    for(var i=0; i < 10; i++){
      changeImg(i);
    }
  }
  function changeImg(number){
    let text = number.toString();
    document.getElementById("image_1").src = "{static 'img" + text + ".png' %}";
  }
</script>

if the images in static look like this:
img1.png
img2.png
img3.png
and so forth...
and the adress of the image was this afterward
img%22%20%2B%20text%20%2B%20%22.png


text:
Q: Switching a solenoid between 2 different AC/DC adapters? I have build a circuit to turn a solenoid on and off with an Arduino (actually it's 10 solenoids, but that's not important right now), and now I would really like to make it possible to choose between 2 different AC/DC adapters because that would give me possibility to have 2 velocity levels that I can trigger from Max/msp. Of course I never want the positive side of the two different AC/DC adapters to connect, so I would have to make sure (in my Arduino code), that never happens.
Here's a rudely made schematic hopefully spreading some light on what I'm trying to achieve:

As the picture shows, I am unsure as where to connect the positive side of the solenoid. At first I thought this was easy to do, but I don't think connecting the positive side of the solenoid to each of the AC/DC adapters positive sides would work out, although I'm not sure.
NOTE: In the end I want to be able to control a minimum of 10 solenoids - each with the possibility to choose between 9 and 24V.

A: I'd consider doing it this way: -

There is a P channel FET used to switch either the 9V or the 24V. Note the extra 10k resistor (circled in red) in series with the FET gate - most FETs can have several volts on their gates but 24V is too much and so I've limited it to about 12V with the resistor.
Also circled in red are schottky diodes. These are protection but the one in series with the 24V output may not be needed and can be replaced with a short circuit. The one in series with the 9V is needed because when the 24V supply activates it doesn't want to be driving current into the 9V supply switch - the schottky diode prevents this by reverse biasing when 24V is present.
The "optional schottky" is to stop reverse currents into the top P channel FET should the 24V supply become disconnected whilst the 9V is activated. It is removable should you feel there are no circumstances that warrant this.
Controls are circled in blue (MCU #1 and #2) - the logic levels can be 3V3 or 5V. Also note the 1N4001 diode across the solenoid to prevent voltage spikes damaging the devices when the solenoid is switched off.
I've assumed that the max current thru the solenoid is 1A - if it is greater than this then maybe consider going for a more powerful diode than the 1N4001 but it should be OK providing you are not switching this circuit on and off rapidly and repeatedly.
I've not listed the P channels FET but use one that can handle the current of the load and is rated no-less than 30V. The schottky diodes also need to be rated with max reverse voltage greater than 30V and current rating should be as per the solenoid's requirements with a little headroom of course.
The down side of this circuit is that the 9V supply is realistically dropped to about 8.5V due to the lower schottky and should you decide the top schottky is required the 24V supply will be more like 23.5V
EDIT - here's a FET I'd consider using. It can easily switch the load and is rated at 30V and can even tolerate 25V on the gate (I'd still use the 10k resistor though): -


text:
Q: Subset raster stack in R by a vector of number sequences? I have a large raster stack that I need to subset by somewhat irregular time spans. I'd like to do something like this:
rstack[[c(1:3, 4:8, 9:15)]]

But there are 30 sequences like the ones above that I need to subset by, and I'd rather not type them all in manually.
I'm wondering if I can create a vector object, something like this:
vec <- c(1:3, 4:8, 9:15)
rstack[[vec]]

But based off of a data frame where I have the start, end values for the sequences to automate the process?:
df <- tibble(
start = c(1, 4, 9),
end = c(3, 8, 15)
)

# A tibble: 3 x 2
  start   end
  <dbl> <dbl>
1     1     3
2     4     8
3     9    15

A: With a data frame (not a tibble) like this:
> layers = data.frame(start=c(1,4,11),end=c(3,8,15))
> layers
  start end
1     1   3
2     4   8
3    11  15

Note I made it so that there's a gap in the total sequence so I can see it is doing something...
Do this to get the vector of merged sequences:
> unlist(apply(layers,1,function(s){s[1]:s[2]}))
 [1]  1  2  3  4  5  6  7  8 11 12 13 14 15

Assign that and use it to subset your stack:
> keep = unlist(apply(layers,1,function(s){s[1]:s[2]}))

s is my stack with 20 layers:
> dim(s)
[1]  3  4 20

subset to get 13 back:
> kept = s[[keep]]
> dim(kept)
[1]  3  4 13
>


text:
Q: How to extract whether the text is bold or italic using PDFBOX api? Actually I tried with text.getFont().getFontDescriptor().getFontWeight() for extracting the bold / italic of a text but it returns me 0.0
here text is a TextPosition object
Is there any way to determine whether the text is of bold or italics
Can you please share your views on it
Thanks in advance

A: text.getFont().getBaseFont().Contains("bold")

i do this in a proyect and works perfectly.


text:
Q: Plot Additional Quantiles on Seaborn Violin Plots Using the example on http://seaborn.pydata.org/generated/seaborn.violinplot.html:
import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.violinplot(x="day", y="total_bill", data=tips)

(source: pydata.org)
How can I draw two small horizontal lines on top of each violin (like the caps of error bars indicating the 2.5 percentile and the 97.5 percentile of the distribution?

A: Here is a rather hacky solution:
What about drawing another boxplot on top of your Violin plot? (And hiding the box in the box plot.)
Here is the output using 2.5 and 97.5:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")

sns.boxplot(x="day", y="total_bill", data=tips, showfliers=False, showbox=False, whis=[2.5,97.5])
sns.violinplot(x="day", y="total_bill", data=tips)

plt.show()


text:
Q: How to send attachment in chatterbot I am trying to build a bot using python. I am using chatterbot (
a python package), I am able to send and receive messages according the knowledge which i have built.
But I want to send attachment in the chat response. Attachment may be a pdf of excel file or image.
I've tried for by making custom class for message response and listTrainer also.
Please help to solve this.
Any help will be appreciated.
Thank you in advance.
bot chatting image

A: I think you are using django_chatterbot app.
currently chatterbot doesn't support this feature over Django. However you could make a work around in urls, views and app.html files to achieve this task.
In url.py
from django.conf.urls import url
from .views import ChatterBotView

urlpatterns = [
    url(
        r'^$',
        ChatterBotView.as_view(),
        name='chatterbot',
    ),
    url(r'^test/getFile', 'getFile')
]

In views.py
def getFile(request):
    fileContent = "Your name is %s" % request.GET['name']
    res = HttpResponse(fileContent)
    res['Content-Disposition'] = 'attachment; filename=yourname.txt'
    return res

In app.html
if (inputData.text.indexOf("please download this script and run it") !=-1) {
    <script type="text/javascript">
        var data = {name: 'Jon'};
        $(function(){
            $("body").append('<iframe src="/test/getFile?'+ $.param(data) + '" style="display: none;" ></iframe>');
        });
    </script>
}

I hope this information will help you solve your problem.


text:
Q: On the proof of Poincaré dual of transversal intersection I'm studying a proof of the following:
Let $M$ be an oriented manifold of finite type without boundary. Let $R,S$ be two transversal embedded submanifolds without boundary; if $\eta_{R}, \eta_{S}, \eta_{R \cap S}$ denote respectively the compact Poincarè duals of $R,S, R \cap S$ in $M$, then:
$$ \eta_{R \cap S} = \eta_{R} \wedge \eta_S  $$
By the tubolar neighborhood theorem, we can choose a tubolar neighborhood $T_R$ of $R$ such that the diffeomorphism between $T_R$ and $\mathcal{N}_{R|M}$ maps $T_R \cap S$ onto $(\mathcal{N}_{R|M})_{|R \cap S}$, the same holds for $S$. Set $T = T_R \cap T_S$. Let $\pi_R : T_R \mapsto R$ and $\pi_S : T_S \mapsto S$ be the bundle maps. By the transversality assumption, there is an isomorphism of vector bundles:
$$ \mathcal{N}_{R \cap S |M} \simeq (\mathcal{N}_{R|M})_{|R \cap S} \oplus (\mathcal{N}_{S|M})_{|R \cap S} \qquad (1) $$
Whence $T$ is a tubolar neighborhood of $R \cap S$ in $M$.
We can choose  representatives $\Phi_S, \Phi_R$ of the Thom classes of $\mathcal{N}_{S | M},\mathcal{N}_{R | M}$ such that:
$$ (\Phi_R)_{|T}=\pi^{*}_{S}(\Phi_R)_{|S \cap T} \qquad (\Phi_S)_{|T}=\pi^{*}_{R}(\Phi_S)_{|R \cap T} \qquad (2)$$
A representative of the Thom calss of $\mathcal{N}_{R \cap S | M}$ is then:
$$\Phi(\mathcal{N}_{R \cap S |M})=\Phi((\mathcal{N}_{R|M})_{|R \cap S} \oplus (\mathcal{N}_{S|M})_{|R \cap S})=\pi^{*}_{S}(\Phi_R)_{|S \cap T} \wedge \pi^{*}_{R}(\Phi_S)_{|R \cap T}=\Phi_R \wedge \Phi_S  $$
The conclusion now follows from the connection between the Poincarè dual of a submanifold and the Thom class of its normal bundle.
I basically have two problems: it is not clear, to me, why we are able to choose representatives of the Thom classes satisfying $(2)$; on the other hand, I cannot convince myself that such a choice is even necessary, can't we just consider isomorphism $(1)$ and "pass to Thom classes"? I'll be thankful for every suggestion or explanation.


text:
Q: Reuse consumer to fetch extra content from the same endpoint I have an Apache Camel route which purpose is to fetch xml-documents and files linked in the document.
<route id="route-ftp">
     <from uri="ftp://foo@server:21/data?password=xxx&include=.*.xml"/>
     <to uri="myBean"/>
 </route>

When it reaches myBean I want to parse the file and use the same ftp settings to fetch the files listed in the xml-file.
Or perhaps fetch them all at the same time using xpath.
<root>
    <article>
        <headline>Headline</headline>
        <image src="images/cat.jpg"/>
    </article>
</root>

The filenames is taken from the above xml image tag and src attribute.
I then want to deliver the original file together with my images in a package.
I can't find the right approach to my problem.

A: I would probably do it this way.

*

*Depending on how your file is structured, I would consume it as you have done. I would then split the body per row (assuming each row contains a filename). The split is done using the splitter EIP. Now each body contains the file name.

*I would then use Camel's dynamicTo to enrich the route with the file using the ftp parameters. You can save the ftp parameters are properties so that they are always the same.
In this way, you fetch the list, iterate over the list and fetch the file for every row in the list.


text:
Q: URL manipulation: http://example.com/foo.jpg -> http://example.com/foo.preview.png In rails I want to wrote some code to change this url string
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg
to
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.png
Should I use regular Expression to change it?
I'm new to Regexp, anyone can show me how to do this, and how to learn this stuff
thanks

A: If the extension is of fixed length, you're better off using string slicing.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
print url[0..-5] + ".preview" + url[-4..-1]

outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpg

Or if your extensions are of variable length you can use rindex() to find the start of the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
dot_index = url.rindex(".")-1
print url[0..dot_index] + ".preview" + url[dot_index+1..-1]

outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg

If you must use a regex then do it like this:
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
print url.gsub(/\.(\w{2,4})$/, ".preview.\\1")

outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg

A: If you're sure the file ends with .jpg, you can to
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
url.gsub(".jpg", ".preview.jpg")

Otherwise, you can get the filename, then append the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
ext = File.extname(url)
url.gsub(ext, ".preview{ext}")

A: A string replace seems to be enough.
 ".jpg" -> ".preview.png"
Unfortunately I do not know ruby.
In python it'll be
new_url = url.replace(".jpg",".preview.png",1)

I think that it'll be similar in ruby. It seems to be sub() instead.
new_url = url.sub(".jpg",".preview.png")


text:
Q: Windows 10 showing time on lock screen and alarms in 24H, but shows regular 12h on task bar clock? I recently finally upgraded to Windows 10. Like all my upgrades, I didn't actually upgrade, I used the license to do a clean install. It took me a couple weeks to notice, but I am now noticing that the time is being displayed on the lock screen and in the alarms app in the 24h format, But the time is in the regular 12h format on the clock on the taskbar, at the bottom right of the screen. Are there two separate time and date settings in Windows 10???

A: OK I literally just stumbled across the answer right after posting this. I found that the date and time on the lock screen and the alarms app is set to what is known as the "long time" while the conventional clock in the task bar is set to the "short time". Apparently Windows default settings are to use 24H as long time and 12h as short time. Kind of odd to mix those opposing formats if you ask me. You can change this either from the traditional Region settings in Control Panel, or from the new Settings "app" which I absolutely loath.
EDIT: That's interesting, the icon for the "Programs" entry on the root of my Control Panel menu has changed to a big solid black box. Oh wait, now it looks normal again. What the heck is happening to my computer???


text:
Q: where to find library dependencies for android studio I'm new to Android development and am currently looking at a library on github where the user can drag and swipe items.  The project is using an outside library from:
import co.paulburke.android.itemtouchhelperdemo.helper.OnStartDragListener;
I know that in Eclipse I could just import the jar file and this import would work, however in android studio I usually update the dependencies within the gradle file however i do not know where this library is located.  Is there an alternate way of using this library, or some way to find it? The link is the project I am currently working with
https://github.com/iPaulPro/Android-ItemTouchHelper-Demo

A: The class you're looking for is contained in the project itself:
https://github.com/iPaulPro/Android-ItemTouchHelper-Demo/tree/master/app/src/main/java/co/paulburke/android/itemtouchhelperdemo/helper
When libraries have (outside) dependencies, they do declare them themselves in their own gradle.build file (transitive dependencies) and you don't have to take care about that.
Library artifacts declared in build.gradle files are usually stored at Maven Central or jCenter.


text:
Q: Search iTunes Music Library for a search term via API All,
I'm trying to allow a user to search for a song. Say the user is searching for Jack Johnson and I want to display all of the songs on iTunes by Jack Johnson. I know I need to construct a URL like the following:
http://itunes.apple.com/search?term=jack+johnson&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song
From a programming persepective, how would I send this to Apple? If I copy that URL into my browser I get some results. Based on those results, how could I parse those results so that I can display them back to the user? Would I want to use JSON, cURL, a combination of the two? What would be the most efficient way to do this?
Any help here would be greatly appreciated!

A: If I understand correctly what you want, maybe something like this:
<?php
if(isset($_POST['term']))
{
    $term = urlencode($_POST['term']); // user input 'term' in a form
    $json =  file_get_contents('http://itunes.apple.com/search?term='.$term.'&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song');
    $array = json_decode($json, true);

    foreach($array['results'] as $value)
    {
        echo '
';
        echo $value['artistName'].'
';
        echo $value['artistLinkUrl'].'
';
        echo $value['primaryGenreName'];
        echo '
';
    }
}
?>

<form method="post">
    <input type="text" name="term" /><input type="submit" value="Go" />
</form>

For more $array value, try print_r($array);

A: You would use file_get_contents and parse the result with json_decode.
$js= json_decode(file_get_contents('http://itunes.apple.com/search?term=jack+johnson&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song'));

$js would now be an array with all the information apple returned.

A: The request must be performed over HTTP. JSON is only a format for the data it returns, not a method of retrieving it.
There are many ways you could fetch that data.
The simplest option is simply to use file_get_contents if your server has fopen wrappers enabled (it likely does).
$data = file_get_contents('http://itunes.apple.com/search?term=jack+johnson&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song');

cURL is also an option using something like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://itunes.apple.com/search?term=jack+johnson&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

Once you've retrieved the contents of that page, unserializing it is easy as long as you have the JSON extension installed. If you're using PHP 5.2.0+, then it's part of the core. Otherwise you need to install the PECL module. See the PHP manual page on the extension for more information.
$response = json_decode($data);
var_dump($response);

The unserialized data is an object. You could use it like so:
foreach ($response->results as $result)
{
    echo "Artist: ".$result->artistName."
".PHP_EOL;
}


text:
Q: If $X+Y = 10 $ ($X$ and $Y $ both are positive) then what is the maximum value of $(X^3)(Y^2)$? I can get to the result by trying different values of X and Y but that is of course time taking. I want to know if there is a better way to get to the result?

A: You can probably use the Arithmetic geometric mean equality. We have:
$$x+y=10$$
$$\frac{x}{3}+\frac{x}{3}+\frac{x}{3}+\frac{y}{2}+\frac{y}{2}=10$$
Since x and y are both positive,
 $$AM\ge GM$$
$$\frac{10}{5} \ge \left(\frac{x^3y^2}{3^32^2}\right)^\frac{1}{5}$$
$$\frac{x^3y^2}{3^32^2} \le 2^5$$
$$x^3y^2 \le 2^73^3$$

A: If, $y = 10 - x$ then the expression can be written as function of one variable:
$$f(x) = x^3(10-x)^2$$
Now all you have to do is to differentiate this function and find its critical points.

A: $Y = 10 - X$,and $X^3Y^2 = X^3(10-X)^2 = X^3(X^2 - 20X + 100) = X^5 - 20X^4 + 100X^3 = f(X)$.
$f'(X) = 5X^4 - 80X^3 + 300X^2 = 0 \iff 5X^2(X^2 - 16X + 60) = 5X^2(X-6)(X-10) = 0 \iff X = 0, 6, 10$. Since $0 < X < 10$, $X = 6$, and $Y = 10 - 6 = 4$. From this the max value of $X^3Y^2$ is $6^34^2 = 3,456$.

A: You have $y=x-10$, so you're looking for maximum value of
$$x^3y^2=x^3(10-x)^2=100x^3+x^5-20x^4$$
When $x \to \infty$ then $100x^3+x^5-20x^4 \to \infty$, so there isn't maximal value of $x^3y^3$.

A: We just have to find the stationary points of
$$ f(x) = x^3(10-x)^2 $$
whose derivative is:
$$ f'(x) = 5x^2(10-x)(6-x) $$
hence the maximum of $x^3 y^2$ when $x+y=10$ is attained at $x=6$.


text:
Q: How to return a value from a React Native functional component to the parent In the case of this functional component, how can I return a value to another component that calls the function?
/**
 * A custom fetch wrapper.
 */

import Config from '../config'

const _Fetch = (context: Object, endpoint: string, init: Object, key?: string) => {

  var k = (typeof key !== 'undefined') ? key : 'data';

  return fetch(Config.base+endpoint, init)
  .then(response => {

    if (response.ok) {
      response.text().then((text) => {

        var obj = tryParseJSON(text)

        if (obj) {
          // For jsonapi.
          if (obj.data) {
            obj = obj.data
          }

          var s = {
            data: Object
          }
          s[k] = obj

          context.setState(s)

          return s // This value exists here, but how can I return it to the _Fetch caller?
        }

      })
      .catch((error) => {
        console.error(error)
      })
    }
  })

  function tryParseJSON(jsonString) {
    try {
      var o = JSON.parse(jsonString)
      if (o && typeof o === "object") {
          return o
      }
    }
    catch (e) {
      console.log(e)
    }
    return false
  }

}

export default _Fetch

When I try to get the value in another function, it is undefined:
var myVar = _Fetch(context, end, init, key)
console.log(myVar); // undefined

Similar questions that don't quite help in my case:

*

*React - Can A Child Component Send Value Back To Parent Form

*How to return values from function - React native

A: The correct way to solve this problem would be to use Redux or some other store manager. If you are using redux then you can update store with new values and it will be available to all the components. This way, your parent can access it directly.
fetch operation is async and it can not directly return data to the invoking method.
If you don't want to use redux then a very standard javascript solution will be using callback.
You can pass a callback method to your fetch function. In your code, you can replace return s with a call to callback method.
e.g. replace return s with callback(s).


text:
Q: Symfony single FormType to input data for several Entity attributes? Let's say I have two distinct entities named DanceTeacher and DanceSchool:
class DanceTeacher
{
    $firstName;
    $lastName;
    $email;
    $phone;
    $street;
    $city;
}

class DanceSchool
{
    $name;
    $emailContact;
    $phoneContact;
    $street;
    $city;
}

I would like to build a FormType regrouping the 4 similar fields:
class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('email', EmailType::class) // serves both teacher email and school emailContact
            ->add('Phone', TextType::class)  // serves both teacher phone and school phoneContact
            ->add('Street', TextType::class) // serves both teacher and school street
            ->add('City', TextType::class)   // serves both teacher and school city
        ;
    }
}

Then, my teacher and school forms have some common fields, and I could build them like:
class DanceTeacherType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('firstName', TextType::class)
            ->add('lastName', TextType::class)
            ->add(SOMETHING_HERE, ContactType::class, SOME_OPTIONS)
            ->add('save', SubmitType::class);
    }
}

class DanceSchoolType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class)
            ->add(SOMETHING_HERE, ContactType::class, SOME_OPTIONS)
            ->add('save', SubmitType::class);
    }
}

Is that possible? I can't find any doc about having a single FormType to write into several entity attributes. I thought I could find options to define some sort of "mapping" between FormType sub-fields and my underlying entities' attributes.
Anyway, put like this, I'm not sure I would win a lot in factorizing in such a way.
Thanks in advance
(oh yes I know, "don't use entities in forms" ;-)

A: I think that what you want to do is documented here :
https://symfony.com/doc/current/form/form_collections.html


text:
Q: Pointer casting with ARC ARC is giving me a hard time with following cast:
NSDictionary *attributes;
SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);

Error: Cast of an indirect pointer to an Objective-C pointer to 'CFTypeRef ' (aka 'const void *') is disallowed with ARC

A: As we were doing something similar things and using the example above, we were facing another problem:
CFDataRef resultRef;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary,
               (CFTypeRef *)&resultRef);
NSData* result = (__bridge_transfer NSData*)resultRef;

This will result in an EXEC_BAD_ACCESS, because resultRef is not set to any adress and points somewhere to the memory.
CFDataRef resultRef = nil;

This will fix the error.

A: The problem is that attributes shouldn't be a dictionary, it should be a SecKeyRef or CFDataRef. And then cast that back into NSData for the password data copied into it.
Like so:
CFDataRef attributes;
SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);
NSData *passDat = (__bridge_transfer NSData *)attributes;

A: Need to change attributes to &attributes
CFDataRef attributes;
SecItemCopyMatching((__bridge CFDictionaryRef) keychainItemQuery,  ( CFTypeRef*) &attributes);
NSData* passDat=(__bridge_transfer NSData*) attributes;


text:
Q: Javascript function returning undefined instead of number I have the following JavaScript function that's part of a larger script:
const sub = 'L';

export function getFeedData (sub) {
    var feedId;
    switch (sub) {
        case '1': case '2': case '3': case '4': case '5': case '6': case 'S':
            feedId = 1;
            break;
        case 'A': case 'C': case 'E':
            feedId = 26;
            break;
        case 'N': case 'Q': case 'R': case 'W':
            feedId = 16;
            break;
        case 'B': case 'D': case 'F': case 'M':
            feedId = 21;
            break;
        case 'L':
            feedId = 2;
            break;
        case 'G':
            feedId = 31;
            break;
    }
    if (feedId === 2) {
        var feed = require('./MockData');
    }
    return {
        feed: feed,
        feedId: feedId
    };
}

I've tested every other function in this script, and they're working properly. For this function, here's my test (I'm using Jest because this is part of a larger React app).
import React from 'react';
import {getFeedData} from '../mocks/apiMock';

it('returns 2 as the feedId when L is sub parameter for getFeedData', () => {
    expect(getFeedData.feedId).toBe(2);
});

it('outputs feed from getFeedData', () => {
    expect(getFeedData.feed).toBeDefined;
});

The latter of those tests is passing - not sure why that's happening.
The first one is what I'm more concerned about. It's returning undefined as getFeedData.feedId and therefore failing. I'm self-taught with JavaScript, and I'm sure that I'm making a silly mistake in that function, and that's why getFeedData.feedId is undefined. If someone could point out that silly mistake, I'd greatly appreciate it.

A: The tests are not calling the function, but attempting to access feedId property of the function object itself.
The second test passes, because indeed getFeedData.feed is undefined. But that doesn't mean this test case is correct. The intention is probably to call the function, with a parameter that has no mapping in the switch,
and then verify that its value is undefined.
it('returns 2 as the feedId when L is sub parameter for getFeedData', () => {
    expect(getFeedData("L").feedId).toBe(2);
});

it('outputs feed from getFeedData', () => {
    expect(getFeedData("?").feed).toBeDefined;
});


text:
Q: SubscriptionTransferFailed hook not working as expected in Eclipse Milo I'm trying to manage reconnection to OPC server when it was down for some time and gets started again. My milo client is not able to automatically reconnect because server does not support Subscription transfer, so I added a SusbcriptionListener in order to catch the onSubscriptionTransferFailed event, so I can manually reconnect to the server. The problem seems to be my code is not catching the onSubscriptionTransferFailed event, so I'm not able to know that the server is up again and try to manually reconnect. I tried also with a SessionActivityListener but none event received neither.
This is the log file of milo trying to reconnect:
2022-05-19 16:26:59,512 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler [milo-netty-event-loop-2] Received Acknowledge message on channel=[id: 0x8dc57c76, L:/134.145.242.91:49555 - R:/134.145.242.30:4840].
2022-05-19 16:26:59,513 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-2] OpenSecureChannel timeout scheduled for +5000ms
2022-05-19 16:26:59,513 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler$1 [milo-shared-thread-pool-5] Sent OpenSecureChannelRequest (Issue, id=0, currentToken=-1, previousToken=-1).
2022-05-19 16:26:59,515 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-2] OpenSecureChannel timeout canceled
2022-05-19 16:26:59,515 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-shared-thread-pool-5] Received OpenSecureChannelResponse.
2022-05-19 16:26:59,516 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-shared-thread-pool-5] SecureChannel id=17, currentTokenId=1, previousTokenId=-1, lifetime=3600000ms, createdAt=DateTime{utcTime=116444737603600000, javaDate=Thu Jan 01 01:02:40 CET 1970}
2022-05-19 16:26:59,516 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-2] 0 message(s) queued before handshake completed; sending now.
2022-05-19 16:26:59,516 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-0] [2] S(Reconnecting)          x E(ConnectSuccess)        = S'(Connected)
2022-05-19 16:26:59,564 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-5] [3] S(ReconnectWait)         x E(ReconnectDelayElapsed) = S'(Reconnecting)
2022-05-19 16:26:59,567 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler [milo-netty-event-loop-3] Sent Hello message on channel=[id: 0x311aec0a, L:/134.145.242.91:49556 - R:/134.145.242.30:4840].
2022-05-19 16:26:59,572 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler [milo-netty-event-loop-3] Received Acknowledge message on channel=[id: 0x311aec0a, L:/134.145.242.91:49556 - R:/134.145.242.30:4840].
2022-05-19 16:26:59,573 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-3] OpenSecureChannel timeout scheduled for +5000ms
2022-05-19 16:26:59,574 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler$1 [milo-shared-thread-pool-0] Sent OpenSecureChannelRequest (Issue, id=0, currentToken=-1, previousToken=-1).
2022-05-19 16:26:59,579 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-3] OpenSecureChannel timeout canceled
2022-05-19 16:26:59,580 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-shared-thread-pool-0] Received OpenSecureChannelResponse.
2022-05-19 16:26:59,580 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-shared-thread-pool-0] SecureChannel id=18, currentTokenId=1, previousTokenId=-1, lifetime=3600000ms, createdAt=DateTime{utcTime=116444737604250000, javaDate=Thu Jan 01 01:02:40 CET 1970}
2022-05-19 16:26:59,581 DEBUG org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-3] 0 message(s) queued before handshake completed; sending now.
2022-05-19 16:26:59,581 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-5] [3] S(Reconnecting)          x E(ConnectSuccess)        = S'(Connected)
2022-05-19 16:27:14,504 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-0] [5] S(CreatingWait)          x E(CreatingWaitExpired)   = S'(Creating)
2022-05-19 16:27:14,505 DEBUG org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory [milo-shared-thread-pool-0] [5] Sending CreateSessionRequest...
2022-05-19 16:27:14,512 DEBUG org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory [milo-shared-thread-pool-5] [5] CreateSession succeeded: NodeId{ns=1, id=100016}
2022-05-19 16:27:14,512 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-0] [5] S(Creating)              x E(CreateSessionSuccess)  = S'(Activating)
2022-05-19 16:27:14,513 DEBUG org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory [milo-shared-thread-pool-0] [5] Sending ActivateSessionRequest...
2022-05-19 16:27:14,516 DEBUG org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory [milo-shared-thread-pool-5] [5] Session activated: OpcUaSession{sessionId=NodeId{ns=1, id=100016}, sessionName=UaSession:Data Capture Automation:1652970434516}
2022-05-19 16:27:14,516 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-0] [5] S(Activating)            x E(ActivateSessionSuccess) = S'(Transferring)
2022-05-19 16:27:14,517 DEBUG org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory [milo-shared-thread-pool-0] [5] Sending TransferSubscriptionsRequest...
2022-05-19 16:27:14,520 ERROR org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler [milo-netty-event-loop-2] [remote=/134.145.242.30:4840] errorMessage=ErrorMessage{error=StatusCode{name=Bad_ServiceUnsupported, value=0x800B0000, quality=bad}, reason=null}
2022-05-19 16:27:14,522 DEBUG com.digitalpetri.netty.fsm.ChannelFsmFactory$1 [milo-netty-event-loop-2] [2] channelInactive() local=/134.145.242.91:49555, remote=/134.145.242.30:4840
2022-05-19 16:27:14,523 DEBUG com.digitalpetri.strictmachine.StrictMachine$PollAndEvaluate [milo-shared-thread-pool-5] [2] S(Connected)             x E(ChannelInactive)       = S'(ReconnectWait)
2022-05-19 16:27:14,523 DEBUG org.eclipse.milo.opcua.stack.client.UaStackClient [milo-shared-thread-pool-0] sendRequest() failed, request=TransferSubscriptionsRequest, requestHandle=305
java.util.concurrent.CompletionException: UaException: status=Bad_ConnectionClosed, message=connection closed
    at java.util.concurrent.CompletableFuture.encodeRelay(CompletableFuture.java:326)
    at java.util.concurrent.CompletableFuture.completeRelay(CompletableFuture.java:338)
    at java.util.concurrent.CompletableFuture.uniRelay(CompletableFuture.java:925)
    at java.util.concurrent.CompletableFuture$UniRelay.tryFire(CompletableFuture.java:913)

And this is my code to try to catch the onSubscriptionTransferFailed event:

            @Override
            public void onStatusChanged(UaSubscription subscription,
                                        StatusCode status)
            {
                logger.warn("onStatusChanged event for {}, status = {}. Trying to setup new subscription", subscription.toString(), status.toString());
            }

            @Override
            public void onSubscriptionTransferFailed(UaSubscription subscription, StatusCode statusCode) {
                logger.warn("onStatusChanged event for {}, status = {}. Trying to setup new subscription", subscription.toString(), statusCode.toString());
                Stack.sharedExecutor().execute(() -> {
                    try {
                        if(!isConnected()){
                            disconnect();
                            init(endpointUrl, securityPolicy.toString(), "AnonymousProvider");
                        }
                        subscribe(nodesToSubscribe);
                        logger.info("New subscription created");
                    } catch (Exception e) {
                        logger.error("Error creating Subscription: {}", e.getMessage(), e);
                    }
                });
            }
        });

And the SessionActivityListener:
this.client.addSessionActivityListener(new SessionActivityListener() {
            @Override
            public void onSessionInactive(UaSession session) {
                logger.warn("onSessionInactive event for {}. Trying to setup new subscription", session.toString());
            }

            @Override
            public void onSessionActive(UaSession session) {
            }
        });

Could someone tell me if there is something wrong in my code or any clue why I'm not catching the events with those listeners?
Many thanks in advance.

A:
I'm using milo 0.4.3

Due to an implementation defect in this server combined with this issue in Milo's Session FSM pre-0.5.3  you'll need to upgrade the version of Milo your client uses to at least 0.5.3.
I'd recommend just going all the way to 0.6.6, which was just released today. There's no point in moving to an older version.


text:
Q: Spring MVC application not accepting JSON I cannot figure out why I cannot post updates to my controller. I am trying to submit json data via a chrome addon. Eventually I will be using angular for the requests. I checked against other stackoverflow articles and it seems I have everything that they suggest.
For what its worth I have a GET request to the same controller that is working without issue.
HTTP Status 415 -  The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

My server log shows the following
INFO - Mapped "{[/service/products/addProduct],methods=[POST],params=[],headers=[],consumes=[application/json],produces=[],custom=[]}" onto public void com.cr.controllers.ProductsController.addProduct(com.cr.entity.Products)

Post to address
http://localhost:8082/service/products/addProduct

Data being posted
{
    "productId": 2,
    "productModel": "Product Model 2",
    "productName": "Product Name 2",
    "dateAdded": 1361880001000,
    "productWeight": 2,
    "productStatus": "Hidden",
    "productTaxClass": {
        "taxId": 2,
        "taxClassTitle": "High Tax Class",
        "taxClassDescription": "This is a high tax class",
        "lastModified": 1361880001000,
        "dateAdded": 1361880001000
    },
    "productImages": {
        "imageId": 2,
        "imageDescription": "Product Image 2",
        "imageTitle": "Image 2",
        "imagePath": "prd_02.jpg",
        "imageRelation": 1
    },
    "productManufacturer": {
        "manufacturerId": 2,
        "manufacturerName": "Factory 2",
        "manufacturerImage": null
    },
    "quantityAvailable": 4,
    "quantityInWarehouse": 4,
    "stockAlert": 1,
    "productCost": 1,
    "productRetail": 1,
    "productPrice": 1,
    "productSalePrice": 1,
    "saleInd": null,
    "productSku": null,
    "backOrderMessage": null,
    "inStockMessage": null,
    "outOfStockMessage": null,
    "manufacturerproductsku": null,
    "productDescriptionId": {
        "productTextId": 2,
        "productTextData": "Este es en espanol",
        "lastModified": 1361793601000
    }
}

Controller mapping
@RequestMapping(value = "/service/products/addProduct",
        consumes = "application/json",
        method= RequestMethod.POST)
public @ResponseBody void addProduct(@RequestBody Products products){
    productsDao.createProduct(products);
}

web.xml
   <servlet-mapping>
        <servlet-name>cr</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <servlet-name>cr</servlet-name>
    </filter-mapping>

_ UPDATE __
I started using amplify to do my requests because I wanted to be sure that it was not the chrome addon.  I am getting a 400 now.  Below is the error showing on my server.
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.cr.entity.Products out of START_ARRAY token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@28d528d5; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.cr.entity.Products out of START_ARRAY token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@28d528d5; line: 1, column: 1

Here is the amplify definition and request.
 amplify.request.define("addRequest", "ajax", {
            url: "service/products/addProduct",
            type: "POST",
            dataType: 'json',
            contentType: 'application/json'
        });
        amplify.request({
            resourceId: "addRequest",
            data: JSON.stringify(jsonData),
            success: function () {
                alert("success")
            },
            error: function () {
                alert("fail")
            }
        });

Data:
var jsonData = [{
    "productId": 4,
    "productModel": "Product Model 2",
    "productName": "Product Name 2",
    "dateAdded": 1361880001000,
    "productWeight": 2,
    "productStatus": "Hidden",
    "productTaxClass": {
        "taxId": 2,
        "taxClassTitle": "High Tax Class",
        "taxClassDescription": "This is a high tax class",
        "lastModified": 1361880001000,
        "dateAdded": 1361880001000
    }
}];

A: I needed to add the following to the jsonConverter bean.
<property name="prefixJson" value="false"/>

Final Bean was as follows
 <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="prefixJson" value="false"/>
        <property name="supportedMediaTypes" value="application/json"/>
    </bean>

Another Stack Overflow Article


text:
Q: How to extract the value of a given cell? I want to get the value of a given cell, but my code gives me following error:
AttributeError: 'str' object has no attribute 'value'.
How can I modify it to get the value and not the position of the cell?
data = xl_rowcol_to_cell(row+2,col+3)
datavalue = data.value
print datavalue

A: To access the value for a specific cell you would use:
value = worksheet.cell(row, column)


text:
Q: AS3 Graph Api -> Popup Blocked we developed an as3 facebook application (http://www.encuentratugemelo.cl), but unfortunately the authenification popup is blocked in all major browsers (ie, ff, chrome), which leads to a high rejection rate for our campaign.
If I have a look here ... http://www.newxv.cl/setomatumuro/
These fellows used the same api (http://code.google.com/p/facebook-actionscript-api/), I checked it with a decompiler and their popup is never blocked!
Can anybody point me into a direcction what we can do that the popup is not blocked?
Gracias y cheers,
Dennis

A: First you need to download the updated Facebook actionscript api frm here

http://code.google.com/p/facebook-actionscript-api/downloads/detail?name=GraphAPI_Web_1_8_1.swc&can=2&q=

Then in your code, where you have written this code :
Facebook.login(loginHandler,{scope:"user_birthday,user_photos,read_stream, publish_stream"});

Earlier we had this line in our code:
Facebook.login(loginHandler,{perms:"user_birthday,user_photos,read_stream, publish_stream"});

Note : Please change perms to scope
and finally, in the html pr php page, where you'll embed this swf:

This will be helpful i guess, please do this, after making these changes, we had a running Fb api in our project.
Have a gr8 time, take care


text:
Q: How can I get Primary Key in Yii 2 crud generator template I use gii code generator and I want to get primary key in
C:\wamp\www\yii2\vendor\yiisoft\yii2-gii\generators\model/default/views/index.php

Yii use this code
$count = 0;
if (($tableSchema = $generator->getTableSchema()) === false) {
    foreach ($generator->getColumnNames() as $name) {
        if (++$count < 6) {
            echo "            '" . $name . "',\n";
        } else {
            echo "            // '" . $name . "',\n";
        }
    }
} else {
    foreach ($tableSchema->columns as $column) {
        $format = $generator->generateColumnFormat($column);
        if (++$count < 6) {
            echo "            '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
        } else {
            echo "            // '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
        }
    }
}

And I want to get primaryKey before belowing code.

$generator->getTableSchema()->primaryKey();

but is not working.

A: That function does not return what you want. It will return the name attribute that may be the primary key or it may not be. If you add a column called "name" in your DB the name of that column will get returned and NOT the primary key.
Furthermore the purpose of that function is to return the name of 1 column. That 1 column may not be the full primary key, it may be part of it, if you have a primary key composed of multiple columns again that function will fail you.
The correct way to get it is
$class = $this->modelClass;
$pk = $class::primaryKey();

and $pk is an array.
Your answer may solve your problem (and I have used similar things myself in my code), but it does not really answer your question (how to get the primary key).

A: I find a function from

C:\wamp\www\yii2\vendor\yiisoft\yii2-gii\generators\crud\Generator.php

function is getNameAttribute()
 public function getNameAttribute()
{
    foreach ($this->getColumnNames() as $name) {
        if (!strcasecmp($name, 'name') || !strcasecmp($name, 'title')) {
            return $name;
        }
    }
    /* @var $class \yii\db\ActiveRecord */
    $class = $this->modelClass;
    $pk = $class::primaryKey();

    return $pk[0];
}

And I call following code successfully in file:

C:\wamp\www\yii2\vendor\yiisoft\yii2-gii\generators\model/default/views/index.php

such as
<?= $generator->getNameAttribute(); ?>//id

OR shortly
<?= $nameAttribute; ?>

A: $generator->getTableSchema()->primaryKey();

is not a method, is a property then would be:
$generator->getTableSchema()->primaryKey;

this return an array, for get the column name you must access to the first element of array, like
$generator->getTableSchema()->primaryKey[0];

For other hand, you can make:
  foreach ($generator->getTableSchema()->columns as $column) {
    if ($column->isPrimaryKey) {
      // your code
    }


text:
Q: Elasticsearch "_cat/indices" api update delayed until search? Elasticsearch (v7.9.2) got an api _cat/indices to show index status, the last change made to docs.count seems not visiable, until a search or another update is made.
Is this behaior for the purpose of performance improvement?
And, is there any way to make it always up to date?

@Update - How I obverse this?
I'm using logstash to import data into es.
In the browser I have opened http://localhost:9200/_cat/indices?v.
After each import, I refresh the browser page, usually it changes.
After the logstash finish, and I terminate it, the count in the page is less than the count from source db (e.g mysql).
Then I refresh the page again and again, it won't change.
But, as I send a query request in postman to query the es index, then refresh again, the docs.count changed, the total count become the same as in the source db.
So, I'm summarizing following behavior:

*

*At first, the docs.count do update after each import (aka. insert).

*But, as importing continues for a while, without querying on the index, the page's docs.count stopped updating.

*Then, a query on index will force docs.count update to the correct number.

*After that, the above steps will repeat. It does look like some kind of delay until necessary optimization.

And, the index setting from http://localhost:9200/xxx/_settings:
(as requested from comment):
{
  "xxx" : {
    "settings" : {
      "index" : {
        "number_of_shards" : "1",
        "provided_name" : "xxx",
        "creation_date" : "1602844600812",
        "analysis" : {
          "analyzer" : {
            "default_search" : {
              "type" : "ik_max_word"
            },
            "default" : {
              "type" : "ik_max_word"
            }
          }
        },
        "number_of_replicas" : "0",
        "uuid" : "qLFMHhyBQNOOs1u_EcJbBg",
        "version" : {
          "created" : "7090299"
        }
      }
    }
  }
}

A: same issue on the ES version v7.9.3
from ES official docs:

To get an accurate count of Elasticsearch documents, use the cat count
or count APIs

the cat count API is accurate on my ES cluster.
GET _cat/count/log-uwsgi-2021?v

epoch
timestamp
count

1638855942
05:45:42
500

A: last doc.count will be shown when a  refresh occurred.
it will refresh periodic base on refresh.interval setting.
from documention: Elasticsearch periodically refreshes indices every second, but only on indices that have received one search request or more in the last 30 seconds.


text:
Q: $\lim_{x \to \infty} f(x) = x -\sqrt{x^2 - x} $ I have to find the limit of $\lim_{x \to \infty} f(x) = x -\sqrt{x^2 - x} $
= $x(1-(1-\frac{1}{x})^{1/2})$
The part I don't understand is how $ (1 - \frac{1}x)^{1/2}$ = $1 - \frac{1}{2x} - \frac{1}{8x^2} -...$

A: $(1+y)^{n}= 1+ ny +  \frac{n(n-1)}{2!} y^2 + \frac{n(n-1)(n-2)}{3!} y^3 + \cdot\cdot\cdot\cdot $
Now , take $y=-\frac{1}{x}$ and $n=\frac{1}{2}$.
Edit : $x-\sqrt{x^{2}-x}$
$=x(1-(1-\frac{1}{x})^{\frac{1}{2}})$
$=x(1-(1-\frac{1}{2x}-\frac{1}{8x^2}-\frac{1}{16x^3}-\cdot\cdot\cdot\cdot))$
$=\frac{1}{2}+O(\frac{1}{x})$
So, $\lim_{x\to\infty} (x-\sqrt{x^{2}-x}) = \frac{1}{2} $


text: Q: in Hibernate how to produce mix of mysqlmyisam and innodb tables? I want to have some of my tables as innodb(which I have currently) and only 2-3 specific tables to be mysqlmyisam.Is there some annotation that we can use for an specific entity to become mysqlmyisam?on internet there is not much info I could find.


text:
Q: Filter for rows in pandas dataframe where values in a column are greater than x or NaN I'm trying to figure out how to filter a pandas dataframe so that that the values in a certain column are either greater than a certain value, or are NaN. Lets say my dataframe looks like this:
df = pd.DataFrame({"col1":[1, 2, 3, 4], "col2": [4, 5, np.nan, 7]})

I've tried:
df = df[df["col2"] >= 5 | df["col2"] == np.nan]

and:
df = df[df["col2"] >= 5 | np.isnan(df["col2"])]

But the first causes an error, and the second excludes rows where the value is NaN. How can I get the result to be this:
pd.DataFrame({"col1":[2, 3, 4], "col2":[5, np.nan, 7]})

A: Please Try
df[df.col2.isna()|df.col2.gt(4)]

  col1  col2
1     2   5.0
2     3   NaN
3     4   7.0

A: Also, you can fill nan with the threshold:
df[df.fillna(5)>=5]


text:
Q: C# WinForms How to add Panels with 100% width to FlowLayoutPanel? I'm currently adding dynamically panels inside a flowlayoutpanel. The size of the panel is defined by the flowlayoutpanel width (flowlayoutpanel.clientsize.width). But as soon as I resize the GUI and the flowlayoutpanel gets bigger, the panel stays the same size. I tried to solve the problem with anchors but it didn't work out for me.
How can I keep the panel size same as the flowlayoutpanel size?
Picture of what I'm trying to achieve after resizing the window:


text:
Q: Fast Multiplication of matrix and vector Multiplication of the DFT matrix and any vector can be implemented by FFT.
I'm interesting about other fast Multiplication.
Suppose there are three matrix of size $N\times N$, $F$ , $Q$ and $P$, where  $P=QFQ^T$.
$F$ is the DFT matrix and $Q$ is any orthogonal matrix.
$w$ and $x$ are two vectors of size $N\times 1$ .
If $w=Px$ (i.e., $w=[QFQ^T]x$), matrix computation need complexity of $\mathcal O(N^2)$ to obtain $w$.
Is there any way to fast implement the multiplication like FFT by complexity of $\mathcal O(N\log N)$ or other fast way?
Thanks for your answers.


text:
Q: Record type of nested prop of type I had the following type in one of my interfaces:
export interface CardProps {
  component?:
    |  'BatteryHealth'
    |  'DriveHealth'
    |  'SSDTrim'
    |  'ThermalDashboard'
    |  'MainFeature'
    |  'DiskSpace'
    |  'Benchmark'
    |  'Scanning'
    |  'Uninstaller'

  // other props of the interface
}

I was using that interface to create a type for another object related to this:
const components: Record<CardProps['component'], React.ComponentType> {
  // and here it gives me keys for that new components object
  // that match the possible values of the component property, like so:
  BatteryHealth: BatteryHealthComponent,
  DriveHealth: DriveHealthComponent,
  // ...
  // which is exactly what I want.
}

Now thigs have changed a bit and I had to rework that interface, and it now looks like this:
export interface CardProps {
  component?:
    | { type: 'BatteryHealth'; props: BatteryHealthCardProps }
    | { type: 'DriveHealth'; props: DriveHealthCardProps }
    | { type: 'SSDTrim'; props: SSDTrimCardProps }
    | { type: 'ThermalDashboard'; props: ThermalDashboardCardProps }
    | { type: 'MainFeature'; props: MainFeatureCardProps }
    | { type: 'DiskSpace'; props: DiskSpaceCardProps }
    | { type: 'Benchmark'; props: BenchmarkCardProps }
    | { type: 'Scanning'; props: ScanningCardProps }
    | { type: 'Uninstaller'; props: UninstallerCardProps }
}

Component is no longer a string, its an object with 2 properties type which is a string and props which is another interface corresponding that must be attached to that string value.
The problem is that now my Record type is no longer working, and that of course is normal, because component is no longer a string, its an object, so I have tried to do the following:
const components: Record<CardProps['component']['type'], React.ComponentType> {
  BatteryHealth: BatteryHealthComponent,
  DriveHealth: DriveHealthComponent,
  // ...
}

My keys are still there and errorless, but now the place where I use these components gives me an error:
Type '{ img: ImageContainerProps; icon: ImageContainerProps; } |
      { img: ImageContainerProps; } |
      { iconImg?: ImageContainerProps; description?: string; } |
       ... 5 more ... |
      { ...; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Type '{ img: ImageContainerProps; icon: ImageContainerProps; }' has no properties in common with type 'IntrinsicAttributes & { children?: ReactNode; }'.

And when it was just a plain string name of the component, it was all working just fine and there were no errors.
Screenshot: http://prntscr.com/1zb2yif

A: Playground
// define your props as a javascript array - don't forget "as const"
const props = [
{ type: 'BatteryHealth', props: 'some-props' },
{ type: 'DriveHealth', props: 'some-props' },
{ type: 'SSDTrim', props: 'some-props' },
{ type: 'ThermalDashboard', props: 'some-props' },
{ type: 'MainFeature', props: 'some-props' },
{ type: 'DiskSpace', props: 'some-props' },
{ type: 'Benchmark', props: 'some-props' },
{ type: 'Scanning', props: 'some-props' },
{ type: 'Uninstaller', props: 'some-props' },
] as const

// extract the props as a type
type CardProps = typeof props[number]

const components: Record<CardProps['type'], string> = {
  BatteryHealth: "foo",
  DriveHealth: "bar",
  InvalidComponent: "oh no" // error, as expected
}


text:
Q: Trim Youtube videos into part(s) and download that trimmed video to local machine I have a lot of videos in our channels, average length is around 45 minutes. I would like to trim each video to single or multiple short clips (e.g 15 second introduction clips). Youtube allows to cut the video into another new video, so is it possible to just download that trimmed clip without creating a new one on Youtube? Or is there any possible way to do that (e.g APIs, applications,...)?
It would be appreciated to receive any answer.


text:
Q: How can I make a master page for all of my pages like default page in Zebble for Xamarin? I created a new blank page as I read on Zebble documentation website like below code, but I need to use this for all of my pages and I do not want to repeat that design on all of my pages. And when I try to build my project an error occurs like below:
<z-Component z-type="Page1" z-base="Page" z-namespace="UI.Pages"
z-partial="true" Title="Page 1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./../.zebble-schema.xml">

  <Stack Id="Header" Direction="Horizontal">
     <Button  Text="MyToogleMenuBtn" />
     <TextView Text="MyPageTitle" />
     <Button Text="AddBtn" />
  </Stack>
  <Stack Id="Body">

  </Stack>
  <Stack Id="Footer">
     <Button Id="ConfirmBtn"  />
  </Stack>

/z-Component>

And the error is:
error screen shot
But I do not know where should I add the title property.

A: For using this page as template for your other pages you just need to specify it as the z-base:
<z-Component z-type="MyChildPage" z-base="MyTemplate" ...

As for the error you should remove the Title="Page 1" because there is no Title property in your current page


text:
Q: Impedir que a página só seja mostrada quando todos os elementos da mesma forem carregados Tenho uma página em html, em que listo dados, essa parte está assim:

                    Item 1
                    item 2
                    item 3
                    item 4

                {% for item in itens %}

                    {{ item.att2 }}
                    {{ item.att3 }}
                    {{ item.att4 }}

                {% endfor %}

Estou usando Django na minha aplicação.
O problema é o seguinte: os dados que estão sendo listados, são capturados no back-end e vem de um servidor externo, que muitas vezes atrasa muito o carregamento da página.
O que eu queria fazer era carregar toda a página (exceto a tabela), e enquanto isso poderia colocar uma mensagem qualquer para o usuário. E só depois quando todos os itens fossem carregados, a tabela seria exibida.
Andei pesquisando mas não encontrei nada relacionado. Alguém poderia me ajudar?

A: Então Naldson, pra você fazer isso a solução é você carregar essa tabela com uma chamada assíncrona via JavaScript, ou seja, quando a página é carregada o seu JavaScript faz uma requisição Ajax ao servidor, seu ou externo, isso vai da sua arquitetura, e quando você obtiver essa resposta do server você monta a tabela adicionando as linhas e colunas dele com JavaScript também.
Aí caso você ache esse trabalho massante, procure estudar alguma lib JavaScript que facilite esse trabalho como jQuery, frameworks de componentes como React ou Vue.js, outros frameworks bem interessantes como AngularJS e Aurelia.


text:
Q: Display image in an collectionview based on string selected I have following arrays of strings and images in kindsViewController.swift
How can I display all the images of animals if "Any" is selected from animals array and images of birds if "Any" is selected from birds array in a collection view
This is what I have done so far
class kindsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var titleDisplayed: UINavigationItem!

var kind = [String]()
var kindImages = [UIImage]()

let animals = ["Dog","Cat","Rabbit", "Any"]

let birds = ["Hen","Kiwi","Parrot", "Any"]

let animalImages: [UIImage] = [UIImage(named: "imageDog")!, UIImage(named: "imageCat")!,UIImage(named: "imageRabbit")!]

let birdImages: [UIImage]  = [UIImage(named: "imageHen")!,UIImage(named: "imageKiwi")!,UIImage(named: "imageParrot")!]

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showOptions"
        {
                let indexPaths = self.collectionView!.indexPathsForSelectedItems!
                let indexPath = indexPaths[0] as IndexPath
                let AVC = segue.destination as! DisplayViewController
                 AVC.labelSelected = self.kind [(indexPath as NSIndexPath).row]

// AVC.imageSelected =  animalImages
        }
    }

The following is DisplayViewController.swift
class DisplayViewController: UIViewController,  UICollectionViewDelegate, UICollectionViewDataSource{

    var labelSelected = String()
    var imageSelected = [UIImage]()

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 3

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
            as! DisplayCollectionViewCell

        cell.imageView?.image =  imageSelected[(indexPath as NSIndexPath).row]
        return cell
    }

A: Well is quite easy doing this programmatically, you will only have to adjust the anchors of the images in the collection view cell, depending the the selection, you will call the function that sets 1 image or the one that sets all of them.
setting the image anchors :
class collectionViewCell : UICollectionViewCell {

let image = UIImageView()
let image2 = UIImageView()
let image3 = UIImageView()

func setupImage () {

view.addSubview( image )

image.translatesAutoResizingMaskIntoConstraints = false

image.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
image.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
image.widthAnchor.constraintEqualToAnchor(view.widthAnchor).active = true
image.heightAnchor.constraintEqualToAnchor(view.heightAnchor).active = true

}

func setupThreeImages () {

view.addSubview( image )
view.addSubview( image2 )
view.addSubview( image3 )

image.translatesAutoResizingMaskIntoConstraints = false

image.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
image.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
image.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier : 0.5).active = true
image.heightAnchor.constraintEqualToAnchor(view.heightAnchor).active = true

image2.translatesAutoResizingMaskIntoConstraints = false

image2.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
image2.leftAnchor.constraintEqualToAnchor(image.rightAnchor).active = true
image2.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier : 0.5).active = true
image2.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier : 0.5).active = true

image3.translatesAutoResizingMaskIntoConstraints = false

image3.topAnchor.constraintEqualToAnchor(image2.bottomAnchor).active = true
image3.leftAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
image3.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier : 0.5).active = true
image3.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier : 0.5).active = true
}

}

Then in your display view controller add conditionals so that when the selected = any , then the cell needs to call the setupThreeImages instead of calling the setupImage. you will also need to set every image by calling cell.image = ....


text:
Q: Endofunctors of $\mathbf{Set}$ that don't preserve monomorphisms Every functor $\mathbf{Set} \rightarrow \mathbf{Set}$ I can think of preserves monomorphisms (i.e. injective functions), including:

*

*$\mathrm{Hom}(X,-)$,

*$X \times -$,

*$X \sqcup -$,

*and the constant functors.

The monads I can think of all have this property, too.
What are some natural examples that don't?

A: Not a real answer on your question, but it might be enlightening.
Every functor preserves sections (i.e. split monomorphims) and in Set almost all monomorphisms are sections.
The only exceptions are the functions $\varnothing\to Y$ where $Y\neq\varnothing$.
These are the only functions that are monic, but do not have a left-inverse.
So it is not so strange that endofunctors in Set that do not preserve monomorphisms are hard to find.
In order to find a counterexample (or maybe a proof that all monomorphisms are preserved by endofunctors in Set) you will have to focus on the mentioned functions.


text:
Q: How to console my ember models as json values? I would like to console all my model's current satus before i proceed to next router. for that, I am trying to check the status of my model. I tried like this  form the suggession of this quesiton:Ember model to json
import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        proceed: function() {
            this.set('clickCancel',false);
        },

        formValidateBeforeNext:function(){
            console.log("i am called", this.getProperties(ret) );
        }
    }
});

But not works!!
UPDATE:
I tried to console models as this way still not works.
import Ember from 'ember';
export default Ember.Controller.extend({
    actions: {
        proceed: function() {
            this.set('clickCancel',false);
        },

        formValidateBeforeNext:function(){
            var rect = {};
            var propertyNames = arguments;
            if (arguments.length === 1 && Ember.typeOf(arguments[0]) === 'array') {
                propertyNames = arguments[0];
            }

             for(var i = 0; i < propertyNames.length; i++) {
                ret[propertyNames[i]] = get(this, propertyNames[i]);
            }

            console.log( "rect is",  rect );
        }
    }
});

A: I see a typo in your example...
ret[propertyNames[i]] = get(this, propertyNames[i]);
should be ...
rect[propertyNames[i]] = get(this, propertyNames[i]);


text:
Q: Highcharts: Deselect all points within a series Alright, so I have a selection event that selects wanted points.
The problem I have is that it just adds on to the previously selected points. I was curious if there is an easy way to have all the points deselected with a function/library call without making a custom function that iterates through all the points?
UPDATE:
This is how I select my points. It is performed within the selection event.
for (var i = 0; i < this.series.length; i++)    //Iterate through all the series on the chart
{
    if(this.series[i].selected)                 //If the series is selected in the legend
    {
        var points = this.series[i].points;   //Retrieve all points within this certain series that are visible
        var xs = event.xAxis[0];    //Get the xAxis size
        $.each(points, function (i,p) { //For all the points visible in the series
            if (p.x >= xs.min && p.x <= xs.max) {   //Boundary check the selected points
                p.select(true, true);   //Set the selected points to selected
            }
        });
    }
}

A: This is the solution to my problem. I added an else statement to the if that deselected any points that are not within the selected range. I plan to make the else into an else if (ctrl key is NOT pressed) for better functionality.
for (var i = 0; i < this.series.length; i++)    //Iterate through all the series on the chart
{
    if(this.series[i].selected)                 //If the series is selected in the legend
    {
        var points = this.series[i].points;   //Retrieve all points within this certain series that are visible
        var xs = event.xAxis[0];    //Get the xAxis size
        $.each(points, function (i,p) { //For all the points visible in the series
            if (p.x >= xs.min && p.x <= xs.max) {   //Boundary check the selected points
                p.select(true, true);   //Set the selected points to selected
            }
            else
                p.select(false, true);  //Set points outside of boundary to deselected
        });
    }
}

A: So, there is a function called getSelectedPoints(), then you have a array with all selected points. The next step is to deselect all these points with select()
Here the highcharts api: getSelectedPoints()
And the jsfiddle: jsfiddle

A: you should iterate over each serie of the chart and call hide or show function depending on what you want to do
i = 0;

while (i < chart.series.length) {
  if (chart.series[i].visible === false) {
    chart.series[i].select();
    chart.series[i].show();
    i++;
    return;
  }
}

A: Per the API docs on the select method you are explicitly telly it to accumulate all the points selected to the new point you want selected. So, set your second param to false.
$.each(points, function (i,p) { //For all the points visible in the series
    if (p.x >= xs.min && p.x <= xs.max) {   //Boundary check the selected points
        p.select(true, false);   //Set the selected points to selected
    }
});

A: TypeScript:
  /**
   * Deselect all the points on all series
   */
  private deselectAllPoints() {
    const series = chart.series;
    series.forEach(s => {
      s.data.forEach((point: Point) => {
        point.select(false);
      });
    });
  }

Or just plain JavaScript:
    chart.series.forEach(s => {
      s.data.forEach((point) => {
        point.select(false);
      });
    });