text:
Q: Can we save C structure in Redis by hiredis ? I can save it but can not get it I want to know if I could save a C structure in redis. But I do not know how to get it because the example.c in hiredis do not mentioned that.
I save a structure to Redis using binary-safe string. And I got a +OK which means I save that correctly.
The save code is here
...
reply = redisCommand(c, "HMSET %s stat %b", rcvgetattr.pathname, sndgetattr.stbuf, sizeof(struct stat));
printf("Save status %s\n", reply->str);//that shows +OK
freeReplyObject(reply);

And then When I try to get my data back, I use
...
reply = redisCommand(c, "HMGET %s stat", rcvgetattr.pathname);
printf("status %s\n", reply->str);
freeReplyObject(reply);

Because I do not know which part contains my structure, so I use gdb and try to find it out. I use commands like disp (struct stat)reply->str or disp (struct stat)reply->element->str to see if the data is equal to the one I just saved. But I failed.
Does anyone know where it stores its data?

A: I think the problem you are having is that HMGET returns an array, not a string. Try using reply->element[0]->str.
This sample code may also help
typedef struct mytest {
    int myInt;
    long myLong;
} mytest;

// ...
mytest t;
t.myInt = 5; t.myLong = 123451;
reply = redisCommand(c, "HMSET %s stat %b", "mykey", &t, sizeof(mytest));
printf("Save status %s\n", reply->str);//that shows +OK
freeReplyObject(reply);

reply = redisCommand(c, "HMGET %s stat", "mykey");
mytest* response = reply->element[0]->str;
printf("status %d %ld\n", response->myInt, response->myLong);
freeReplyObject(reply);


text:
Q: CUDA: allocation of an array of structs inside a struct I've these structs:
typedef struct neuron
{
float*  weights;
int n_weights;
}Neuron;

typedef struct neurallayer
{
Neuron *neurons;
int    n_neurons;
int    act_function;
}NLayer;

"NLayer" struct can contain an arbitrary number of "Neuron"
I've tried to allocate a 'NLayer' struct with 5 'Neurons' from the host in this way:
NLayer* nL;
int i;
int tmp=9;
cudaMalloc((void**)&nL,sizeof(NLayer));
cudaMalloc((void**)&nL->neurons,6*sizeof(Neuron));
for(i=0;i<5;i++)
    cudaMemcpy(&nL->neurons[i].n_weights,&tmp,sizeof(int),cudaMemcpyHostToDevice);

...then I've tried to modify the "nL->neurons[0].n_weights" variable with that kernel:
__global__ void test(NLayer* n)
           {
              n->neurons[0].n_weights=121;
           }

but at compiling time nvcc returns that "warning" related to the only line of the kernel:
Warning: Cannot tell what pointer points to, assuming global memory space

and when the kernel finish its work the struct begin unreachable.
It's very probably that I'm doing something wrong during the allocation....can someone helps me??
Thanks very much, and sorry for my english! :)
UPDATE:
Thanks to aland I've modified my code creating this function that should allocate an instance of the struct "NLayer":
NLayer* setNLayer(int numNeurons,int weightsPerNeuron,int act_fun)
{
    int i;
    NLayer  h_layer;
    NLayer* d_layer;
    float*  d_weights;

    //SET THE LAYER VARIABLE OF THE HOST NLAYER
    h_layer.act_function=act_fun;
    h_layer.n_neurons=numNeurons;
    //ALLOCATING THE DEVICE NLAYER
    if(cudaMalloc((void**)&d_layer,sizeof(NLayer))!=cudaSuccess)
        puts("ERROR: Unable to allocate the Layer");
    //ALLOCATING THE NEURONS ON THE DEVICE
    if(cudaMalloc((void**)&h_layer.neurons,numNeurons*sizeof(Neuron))!=cudaSuccess)
        puts("ERROR: Unable to allocate the Neurons of the Layer");
    //COPING THE HOST NLAYER ON THE DEVICE
    if(cudaMemcpy(d_layer,&h_layer,sizeof(NLayer),cudaMemcpyHostToDevice)!=cudaSuccess)
                puts("ERROR: Unable to copy the data layer onto the device");

    for(i=0;i<numNeurons;i++)
    {
        //ALLOCATING THE WEIGHTS' ARRAY ON THE DEVICE
        cudaMalloc((void**)&d_weights,weightsPerNeuron*sizeof(float));
        //COPING ITS POINTER AS PART OF THE i-TH NEURONS STRUCT
        if(cudaMemcpy(&d_layer->neurons[i].weights,&d_weights,sizeof(float*),cudaMemcpyHostToDevice)!=cudaSuccess)
                puts("Error: unable to copy weights' pointer to the device");
    }

    //RETURN THE DEVICE POINTER
    return d_layer;
}

and i call that function from the main in that way (the kernel "test" is previously declared):
int main()
{
    NLayer* nL;
    int h_tmp1;
    float h_tmp2;

    nL=setNLayer(10,12,13);
    test<<<1,1>>>(nL);
    if(cudaMemcpy(&h_tmp1,&nL->neurons[0].n_weights,sizeof(float),cudaMemcpyDeviceToHost)!=cudaSuccess);
        puts("ERROR!!");
    printf("RESULT:%d",h_tmp1);

}

When I compile that code the compiler show me the Warning, and when I execute the program it print on screen:
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
Error: unable to copy weights' pointer to the device
ERROR!!
RESULT:1

The last error doesn't not compare if I comment the kernel call.
Where I'm wrong?
I do not know how to do
Thanks for your help!

A: The problem is here:
cudaMalloc((void**)&nL,sizeof(NLayer));
cudaMalloc((void**)&nL->neurons,6*sizeof(Neuron));

In first line, nL is pointing to structure in global memory on device.
Therefore, in second line the first argument to cudaMalloc is address residing on GPU, which is undefined behaviour (on my test system, it causes segfault; in your case, though, there is something more subtle).
The correct way to do what you want is first to create structure in host memory, fill it with data, and then copy it to device, like this:
NLayer* nL;
NLayer h_nL;
int i;
int tmp=9;
// Allocate data on device
cudaMalloc((void**)&nL, sizeof(NLayer));
cudaMalloc((void**)&h_nL.neurons, 6*sizeof(Neuron));
// Copy nlayer with pointers to device
cudaMemcpy(nL, &h_nL, sizeof(NLayer), cudaMemcpyHostToDevice);

Also, don't forget to always check for any errors from CUDA routines.
UPDATE
In second version of your code:
cudaMemcpy(&d_layer->neurons[i].weights,&d_weights,...) --- again, you are dereferencing device pointer (d_layer) on host. Instead, you should use
cudaMemcpy(&h_layer.neurons[i].weights,&d_weights,sizeof(float*),cudaMemcpyHostToDevice

Here you take h_layer (host structure), read its element (h_layer.neurons), which is pointer to device memory. Then you do some pointer arithmetics on it (&h_layer.neurons[i].weights). No access to device memory is needed to compute this address.

A: It all depends on the GPU card your using. The Fermi card uses uniform addressing of shared and global memory space, while pre-Fermi cards don't.
For the pre-Fermi case, you don't know if the address should be shared or global. The compiler can usually figure this out, but there are cases where it can't. When a pointer to shared memory is required, you usually take an address of a shared variable and the compiler can recognise this. The message "assuming global" will appear when this is not explicitly defined.
If you are using a GPU that has compute capabiilty of 2.x or higher, it should work with the -arch=sm_20 compiler flag

redpajama_set_name: RedPajamaStackExchange


text:
Q: rails gem prawn, image and anchor Can you tell me how to insert image which will be a link to for example page 20? I know how to make with normal text:
text "<link anchor='page20'>Go to page 20</link>", :inline_format=>true

and then on page 20 I have
add_dest('page20', dest_fit(page.dictionary))

but how to do this with image ?

A: Partly thanks to lightswitch05 for some prodding in the right direction, I've found a way to get the effect I want through this inelegant way:

*

*Insert an image in a bounding_box (the page cursor is at this point at the bottom of the image)

*Move the cursor back up to the top of the image

*Insert a text link over the image (in my case I just used however many vertical bars '|' were needed to cover the image)

*Confirm visually that the clickable link area is about the same as the boundaries of the image

*Make the text link transparent, and voilà, it looks like you're clicking the image.

Here's some example code (measurements not exact; there was a lot of tweaking involved):

bounding_box([0, cursor], width: 35) do
  image open("http://mysite.com/remote_image.jpg"),
        fit: [35, 35],
        align: :center
  move_up 35
  transparent(0) do
    formatted_text([{
      text: "|||", # placeholder
      size: 40,
      link: "http://example.com/"
    }], align: :center)
  end
  # stroke_bounds
end

Needless to say, this experience has got me looking a bit more at Wicked PDF in order to do what I think I want to do with PDFs.
I'm sure a better/more elegant solution exists, so I'm not planning on considering this my final answer.

A: Prawn does not support this functionality. In fact, even if you placed a formatted_text_box over an image and fill it with white space, it still will not work. An anchor has to include text to work. If you don't mind having text over your image, then that might be a solution.
Prawn's own readme states:

One thing Prawn is not, and will never be, is an HTML to PDF generator.

After dealing with many of Prawn's shortcomings, I've switched to using wicked_pdf for my Ruby on Rails PDF generation and have been very happy with it. If you can do it in html & css, it can be done with wicked_pdf.


text:
Q: MPMoviePlayerController controls - remove fullscreen and aspect buttons? The documentation shows 3 control styles:
MPMovieControlStyleNone,
MPMovieControlStyleEmbedded,
MPMovieControlStyleFullscreen,
MPMovieControlStyleDefault = MPMovieControlStyleFullscreen

I want the controls to mimic the kind found in Apple's "Videos" app, which do not have a fullscreen button or an aspect ratio button. None of the above do this. How do we achieve that?

A: Just looked for a similar solution (following up on a client request saying: "I want the same behavior than in Apple's app Videos").
Result of my research:  It is not possible.
In fullscreen mode, you either:

*

*show no control (and the user can't control the playing of the video)

*show the controls when starting to play the video (and they automatically disappear after 5 seconds).

Apple has likely used a private API for this.

A: By iterating all MPMoviePlayerController subviews, then hide the full screen button stackoverflow.com/a/27482687/928599

A: Yes you can hide the full screen button. Use MPMovieControlStyleFullscreen with MPMovieScalingModeFill property. My example code is as under:
mpplayerObject.controlStyle = MPMovieControlStyleFullscreen;
[mpplayerObject setScalingMode:MPMovieScalingModeFill];


text:
Q: VS Code: Snippet selection escaping of "no character" I try to create a snippet where the NOCHAR inserts is empty. When the user selects this entry there should be NO character (not even a space).
--> just to define|,a,b,c| is not really working.
"Library.Internal":
{
    "prefix": "SYSTEM.Library.Internal",
    "description": "Insert command for label/value from internal library.\r",
    "body":
    [
        "# ------------------------------------------------------------------------------------------------------",
        "«LIB(${1|*NOCHAR*,a,b,c|)»",
        ""
    ]
},

Is there a way to do that?
Thanks in advance!

A: The closest I think you might get is to try:
    "«LIB${1|(,(a,(b,(c|})»",

It isn't that pretty but the first choice merely adds the left parenthesis with no argument as you wish.


text:
Q: fadeIn vs fadeOut vs fadeTo What is the difference between fadeIn vs fadeOut vs fadeTo ?

A: FadeIn.. Shows an element gradually
FadeOut .. Hides an element gradually
FadeTo .. Changes the opacity of an element to a given value

A: fadeIn fades from an elements current opacity to 1.
fadeOut fades from an elements current opacity to 0.
fadeTo fades from an elements current opacity to a given opacity.
$('#myObject').fadeTo('fast', 0.5, function() {
    $('#myObject').fadeTo('fast', 0.8);
});

The above fades myObject from whatever opacity it has, to 0.5, which is 50% transparency, and after that, it fades up again to 20% transparency.

A: Short Answer:

*

*fadeIn() and fadeOut() control the display property, while animating fade.

*fadeTo() controls the opacity property, while animating fade.

Long Answer:
fadeIn() and fadeOut() are both designed to control the display property, just like show() and hide(), but animating only a fade in between.
Process of fadeIn()

*

*Prep: Set to opacity:0.

*Process: Set to display:block.

*Process: Gradually change to opacity:1.

Process of fadeOut()

*

*Process: Gradually change to opacity:0.

*Process: Set to display:none.

fadeTo() is meant to set the opacity property, while animating a fade in between.
Process of fadeTo()

*

*Prep: Set to display: block.

*Process: Set to opacity: [$].

See the breakdown of formulas, which make up fadeIn() and fadeTo() on JsFiddle.
Update:
Closer relatives of fadeIn() and fadeOut() are rather show() and hide().
show() and hide() are also meant to control the display property, just like fadeIn()and fadeOut(), but in addition, animate width and height in between.
Process of show()

*

*Prep: Set to opacity:0, width:0, height:0

*Process: Set to display:block

*Process: Gradually change to opacity:1, width:[auto], height:[auto]
Process of hide()

*

*Process: Gradually change to opacity:0, width:0, height:0

*Process: Set to display:none.

Example:
Compare behavior of fadeIn(), fadeOut(), fadeTo(), show() and hide() on JsFiddle.

A: I see only linguistic redundance here, since fadeTo fits all the use cases regardless.


text:
Q: Aligning button below text view no matter length of text with swift I have a text view that displays data from a database. Typically the text is no more than a few sentences but there is a possibility a user will add multiple paragraphs.
I'm trying to align a button below this text view no matter how much text is displayed.
Is there a way to do this with swift? I tried re adjusting elements in the storyboard with no luck.

Thanks!!

A: Set button's Top Space constraint to your text view and add this in the scrollview.It will automatically scroll if your text is lengthy and the button will be shown at bottom of textview.

A: give your button vertical spacing to textView (make sure you have scroll View so then if textView size is long then you can scroll down to see that button)

A: You've not set contraints for the items in your storyboard. This is a classic Auto Layout issue.
A simple solution for this could be to embed it all in a stack.
First select all the items in your storyboard, form the document outline pane:
 1. UIImageView
 2. Title
 3. UIScrollView
 4. 'Share Updates' and 'Discussion' button.
Now, click on the Embed In Stack button

Now try running the simulator and check the outcome.
On the other hand, you can also specify individual constraints. For this purpose, I believe that embedding in stack is all that is necessary.
And here is the official link for Auto Layouts, which is a must know for developing:
Auto Layouts
Tips:
1. Use 'spacing' attribute of the stack
2. Try learning and embedding stacks into stacks, if in case you want custom spacing of the two buttons. (For example, the two buttons could be inside a stack with a larger spacing, and that stack will be co-existing with other elements of the parent stack, with lesser spacing.)


text:
Q: How to pass a List from JSP to Controller class in Java How to pass a List from JSP to Controller class with Spring mvc in Java?
Regards
Sony K Koshy

A: You need to use @ModelAttribute for your bean to be used in the form. Please check below demo code.
public class MusicianRequest {
    private List<Musican> musicians = new ArrayList<Musician>();
}

Use List or array for your data so you are able to access them by index with jstl.
Then in your JSP have:
<form:form modelAttribute="musicianRequest" method="PUT" action="" >
    <c:forEach items="${musicianRequest.musicians}" var="musician" varStatus="loop">

            <form:checkboxes items="${musician.instruments}" path="musicians[${loop.index}].instruments" />

    </c:forEach>
</form:form>


text:
Q: How to fix: No suitable driver found for jdbc:sqlserver I am trying to connect to a MS SQL Server database running on the same machine as the application but I keep getting the error:

No suitable driver found for
  jdbc:sqlserver://localhost:1433;database=SQLTEST;user=TEST;password=1234567890;encrypt=true;trustServerCertificate=false;loginTimeout=30;

I am running MS SQL Server 2017 and JDK1.8.x.
The first thing I did was creating a user in the following way in SSMS using T-SQL:
USE SQLTEST
CREATE ROLE TEST
GRANT SELECT, INSERT ON SCHEMA :: [dbo] TO TEST
CREATE LOGIN TEST_LOGIN WITH PASSWORD = '1234567890'
CREATE USER USER_TEST FROM LOGIN TEST_LOGIN
ALTER ROLE TEST ADD MEMBER USER_TEST

I then used Maven to add the driver to my project in the pom.xml file:
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
     <groupId>com.microsoft.sqlserver</groupId>
     <artifactId>mssql-jdbc</artifactId>
     <version>7.2.2.jre8</version>
</dependency>

Followed by adding and altering the example code given by Microsoft (note that this should become a JAX-RS REST-API, that is why the annotations are there):
@Path("t2")
public class T2 {
    @GET
    public String show() {
        String r = "";
        String connectionUrl =
                "jdbc:sqlserver://localhost:1433;"
                        + "database=SQLTEST;"
                        + "user=TEST;"
                        + "password=1234567890;"
                        + "encrypt=true;"
                        + "trustServerCertificate=false;"
                        + "loginTimeout=30;";

        try (Connection connection = DriverManager.getConnection(connectionUrl);) {
            // Code here.
        }
        // Handle any errors that may have occurred.
        catch (SQLException e) {
            e.printStackTrace();
            r = e.getMessage();
        }
        return r;
    }
}

Running this results in the error as given in the start of this post. Did I forget something or did I do something wrong?

A: Looks similar to this issue:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver
Doesnt look like you've got Class.forName("xxxx"); before your DriverManager.getConnection section in the try statement.


text:
Q: gitlab kubernetes runner cannot connect to the docker daemon I have configured gitlab runner within kubernetes , which is not able to connect to docker daemon . Showing below error .

$ docker build --cache-from "${DOCKER_IMAGE_TAG}" -t
  "${DOCKER_IMAGE_TAG}" .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is
  the docker daemon running? ERROR: Job failed: command terminated with
  exit code 1

stages:
  - push_to_docker

docker_image:
 image: 'docker:latest'
 services:
  - docker:dind
 stage: push_to_docker
 variables:
    DOCKER_IMAGE_TAG: 'gcr.io/abcd-project/test'
 script:
   - docker build --cache-from "${DOCKER_IMAGE_TAG}" -t "${DOCKER_IMAGE_TAG}" .
   - echo "$SERVICE_ACCOUNT_KEY" > key.json
   - docker login -u _json_key --password-stdin https://gcr.io < key.json
   - docker push ${DOCKER_IMAGE_TAG}
 only:
   - master
 tags:
   - abcd

My config.toml file is as below
listen_address = "[::]:9252"
concurrent = 4
check_interval = 3
log_level = "info"

[session_server]
  session_timeout = 1800

[[runners]]
  name = "runner-gitlab-runner-78c7db94bc-lzv76"
  request_concurrency = 1
  url = "https://gitlab.com/"
  token = "*********"
  executor = "kubernetes"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
  [runners.kubernetes]
    host = ""
    bearer_token_overwrite_allowed = false
    image = "ubuntu:16.04"
    namespace = "gitlab-managed-apps"
    namespace_overwrite_allowed = ""
    privileged = true
    service_account_overwrite_allowed = ""
    pod_annotations_overwrite_allowed = ""
    [runners.kubernetes.pod_security_context]
    [runners.kubernetes.volumes]

Checked with configuration as below
    image: docker:19.03.1
    services:
    - docker:19.03.1-dind
    variables:
      DOCKER_HOST: tcp://docker:2375

And my .gitlab-ci.yml file after changing the configuration is as below:
stages:
  - push_to_docker
  - deploy_into_kubernetes
variables:
  DOCKER_IMAGE_TAG: 'gcr.io/abcd-project/test:$CI_COMMIT_SHORT_SHA'
  DOCKER_HOST: tcp://docker:2375

docker_image_creation:
 image: docker:19.03.1
 services:
  - docker:19.03.1-dind

 stage: push_to_docker

 script:
   - docker build -t "${DOCKER_IMAGE_TAG}" .
   - echo "$SERVICE_ACCOUNT_KEY" > key.json
   - docker login -u _json_key --password-stdin https://gcr.io < key.json
   - docker push ${DOCKER_IMAGE_TAG}
 tags:
   - cluster
   - kubernetes

but getting bellow error :

Skipping Git submodules setup $ docker build -t "${DOCKER_IMAGE_TAG}"
  . time="2019-11-04T08:07:37Z" level=error msg="failed to dial gRPC:
  cannot connect to the Docker daemon. Is 'docker daemon' running on
  this host?: dial tcp: lookup docker on 10.0.0.10:53: no such host"
  error during connect: Post
  http://docker:2375/v1.40/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&session=l1ce41pzm1p9a4jdhs31z9p64&shmsize=0&t=gcr.io%2Fupbeat-flame-247110%2Fgitlab-runner-poc%3A25b1faa0&target=&ulimits=null&version=1: context canceled

A: use docker19, which automatically configures its host for you:
image: docker:19.03.1
services:
- docker:19.03.1-dind
variables:
  DOCKER_HOST: tcp://docker:2375

https://docs.gitlab.com/ee/ci/docker/using_docker_build.html


text:
Q: Cube Calculation median age (MDX) I need to create cube calculation for median Age in a HR cube.
Measures: head count and FTE
Dimension:  Age (Age, Age_Group, ...), Duty_type, Staff (Staff_ID, ...), Date, etc
I tried to use the following MDX script:
Median([Month Date].[Staff Profile Month Date - Hierarchy].[Month Date Calendar Year].currentmember.Children ,IIF([Age].[Age].currentmember.name ='All' ,0,StrToValue([Age].[Age].currentmember.name)))

I used the following help: http://msdn.microsoft.com/en-us/library/ms145570.aspx
How can this be solved?

A: Create base measure called Sum Age(make it invisible) and use this to create median calculated measure.
Median([Staff].[Staff ID].currentmember.children,[Measures].[Sum Age])


text:
Q: How to create an array in firebase database in iOS swift How to create an Array in Firebase realtime database in iOS using swift
note : I want to be able to append new elements without getting array value first an add element locally then setting it to database .

A: use childByAutoId()
Database.database().reference().child("arrayKey").childByAutoId().setValue("Value") }

A: This should be achieved easily:
let ref = storageRef.child("your_child")
let array = ["First", "Second", "Third", "Fourth"]
ref.setValue(array)


text:
Q: Flip a coin whilst counting attempts until you get 5 tails in a row What I am trying to do:
I want to loop infinitely until I get 5 tails in a row. I also want to show the number of attempts it took to be able to achieve 5 tails in a row
Here is what I have:
Dim number = rand.Next(1, 3)

If number = 1 Then
    RichTextBox1.Text += "Tails" & vbNewLine
ElseIf number = 2 Then
    RichTextBox1.Text += "Heads" & vbNewLine
End If

number = rand.Next(1, 3)

I haven't been able to figure it out. Thanks in advance for any help.

A: You need a counter variable that stores how often you already had tails. While tailCount < 5 will break this loop if you have found 5. Another counter will count the total attempts:
Dim rand As New Random()
Dim maxTailCount = 5
Dim attempts = 0
Dim tailCount = 0

While tailCount < maxTailCount
    attempts += 1
    Dim number = rand.Next(1, 3)
    If number = 1 Then
        tailCount += 1
    Else
        tailCount = 0 ' because they must be "in a row"
    End If
End While
Console.WriteLine("Found {0} tails, total attempts: {1}", maxTailCount, attempts)


text:
Q: How can I make individual people append text/strings to a .txt file I have on my server using php? Let's say user1 writes "Hello" in a textbox and submits it, and user2 writes later that day " World" and submits it. How can i code it so their inputs get sent to my .txt file? So the .txt file should look like this: "Hello World". This might be a bit complicated to answer. If so, could anyone point me in the right direction or give me any good links / tutorials? And second question: Do I need to learn MySQL for this?

A: It might help...

*

*index.php

    <?php
    if (!isset($_SESSION)) {
        session_start();
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    <?php
    if (!empty($_SESSION)) {
        echo $_SESSION['msg'];
        session_unset();
    }
    ?>
    <form action="store.php" method="POST">
        <input type="text" name="inputText">
        <input type="submit">
    </form>
    </body>
    </html>

*

*store.php
    <?php
    include_once 'TextStoreIntoFile.php';
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $addText = new TextStoreIntoFile();
        $addText->addTextIntoFile($_REQUEST['inputText']);
    }

*

*TextStoreIntoFile.php
    <?php
    declare(strict_types=1);

    class TextStoreIntoFile
    {
        public function addTextIntoFile(string $data)
        {
            if (!isset($_SESSION)) {
                session_start();
            }
            $data = $data . ' ';
            $textAdded = file_put_contents('text.txt', $data, FILE_APPEND | LOCK_EX);
            if ($textAdded) {
                $_SESSION['msg'] = 'Text added into the file';
                header('Location: index.php');
            } else {
                $_SESSION['msg'] = 'Text not added!';
                header('Location: index.php');
            }
        }
    }


text:
Q: Get list of parent sub-type with all sub-type in LINQ Using many Sub-Type tables with zero-one relation in C# code first!
 public class MemberContractRelation
{
    [Key]
    public long Id { get; set; }
    public long ContractId { get; set; }
    public long MemberId { get; set; }
    public long ListPrice { get; set; }
    public decimal TaxCountryToPay { get; set; }
    public decimal TaxProvinceToPay { get; set; }
    public long InsuredCode { get; set; }

}

 public class FamilyMemberContractSubtype : MemberContractRelation
{
    public long CalculatedCheckupPrice { get; set; }

}

i want to getting list of my parent table (MemberContractRelation) with sub-type related record (like Left join) via this code :
 var familyMemberContractSubtype = _rep.FamilyMemberContractSubtype.Where(a => a.Id == ContractId).Select(x => new
          FamilyMemberInformationsBag
        {
            BirthDate = x.Member.BirthDate,
            FirstName = x.Member.FirstName,
            LastName = x.Member.LastName,
            NationalID = x.Member.NationalCode,
            PhoneNumber = x.Member.IranPhoneNumber,
            Price = x.ListPrice,
            ChekUpPrice = x.CalculatedCheckupPrice,
            TotalPrice = x.ListPrice + x.CalculatedCheckupPrice + x.TaxProvinceToPay + x.TaxCountryToPay,
            TaxProvinceToPay = x.TaxProvinceToPay,
            TaxCountryToPay = x.TaxCountryToPay

        }).ToList();

But it returns only records that have sub-Type and don`t return other records in MemberContractRelation!
I want to get a list of MemberContractRelation with sub-type and if it has not recorded in sub-type return Null value of property in sub-type!
remember I cant use any other solution for my project except above solution!

A: Assuming this is using EF TPT inheritance strategy (as it seems), first you should start the query from the parent (base) table:
// instead of _rep.FamilyMemberContractSubtype
// assuming _rep is DbContext
_rep.Set<MemberContractRelation>()

and then use operator as (important: not cast!) to access subtypes members, promoting non nullable types to nullable. In your sample:
ChekUpPrice = (long?)(x as FamilyMemberContractSubtype).CalculatedCheckupPrice

and
TotalPrice = x.ListPrice + x.TaxProvinceToPay + x.TaxCountryToPay +
    ((long?)(x as FamilyMemberContractSubtype).CalculatedCheckupPrice ?? 0)


text:
Q: Why is a question about the pronunciation of an algorithm name off topic? I'm trying to get some insight into why this question about the pronunciation of Kruskal's algorithm is off topic.
Are pronunciation questions not welcome on SO?

A: "Pronunciation (phonetics and phonology, dialectology)" is generally specified as on-topic question in The English Language and Usage Stack Exchange FAQ.
You may check if your specific case fits there:

What kind of questions can I ask here?
The English Language and Usage Stack Exchange is for linguists, etymologists, and (serious) English language enthusiasts. Questions on the following topics are welcomed here:

*

*Usage, word choice, and grammar

*Etymology (history of words' development)

*Dialect differences

*Pronunciation (phonetics and phonology, dialectology)

*Spelling and punctuation

*Problems encountered by people learning English

But please, don't ask any questions about these topics. They are out of scope for this site.

*

*Please proofread my document ("are there any mistakes in this text?")

*Languages other than English (including translation)

*How to improve my English

*How to name this function/variable in my program

*Criticism, discussion, and analysis of English literature

*Peeving about grammar disguised as a question

*"Explain this joke to me", except in the case where the crux of the joke relies on an aspect of English covered by one of the welcomed topics above.

...

A: In addition to what MДΓΓ БДLL said, most potential questions about pronunciation would seem to either be "general reference" (e.g. "Java") or controversial (e.g. "SQL"), with little in between.
Controversial questions just end up as "Not Constructive" with a bunch of IMHOs.
General reference questions would just clutter the site. If a question about one algorithm name / initialism / programming language is on topic, almost all would be on topic by precedent, and that'd just lead to ridiculousness. "How do you pronounce A#?",  "How do you pronounce ActionScript?", "How do you pronounce Ada?" ...

A:
Are pronunciation questions not welcome on SO?

That question seems to have answered itself, don't you think? To reiterate: no, pronounciation questions are not remotely on-topic on SO. To quote the FAQ:

What kind of questions can I ask here?
Stack Overflow is for professional and enthusiast programmers, people
who write code because they love it. We feel the best Stack Overflow
questions have a bit of source code in them, but if your question
generally covers...

*

*a specific programming problem

*a software algorithm

*software tools commonly used by programmers

*practical, answerable problems that are unique to the programming profession ...then you're in the right place to ask your question!

The pronunciation of any word — regardless of the word's relevance to programming — does not fall into this category.
To quote the FAQ just a little bit more:

What kind of questions should I not ask here?
You should only ask practical, answerable questions based on actual
problems that you face.

'Nuff said.

OP question:

Guys, I understand your point that this is not a question about solving a programming problem. But do you really not think that pronunciation questions are useful for programmers?

My response:

not on Stack Overflow. SO has evolved to be, first and foremost, about solving programming problems, not about "being useful to programmers."


text:
Q: Using loop functions to calculate row means with specific columns Suppose I have the below data frame
a <- data.frame(A = 1:10, B = 26:35, C = 101:110, D = 1001:1010)
a[c(2,4,7),"A"] <- NA
a

    A  B   C    D
1   1 26 101 1001
2  NA 27 102 1002
3   3 28 103 1003
4  NA 29 104 1004
5   5 30 105 1005
6   6 31 106 1006
7  NA 32 107 1007
8   8 33 108 1008
9   9 34 109 1009
10 10 35 110 1010

I want to know if we can use any of the loop functions to fill the missing values in column A with the mean of corresponding values from columns B,C and D, i.e. NA at row 2 should be replaced by 377 (mean of 27,102 and 1002).
I can get this to work using a for loop, but am just curious if the same can be done with apply functions or not.
Edit: what if I don't want to take mean of all the columns, but only of few. Lets say suppose I need mean of only B and D. I guess rowMeans wouldn't work then.

A: First, a data.frame is not the right way to store entirely numeric data:
m = as.matrix(a)

From here, we can find the positions of NA values in the matrix
idx = which(is.na(m), arr.ind=TRUE)

     row col
[1,]   2   1
[2,]   4   1
[3,]   7   1

and fill them in
m[idx] <- rowMeans(m[idx[,1], ], na.rm=TRUE)

        A  B   C    D
 [1,]   1 26 101 1001
 [2,] 377 27 102 1002
 [3,]   3 28 103 1003
 [4,] 379 29 104 1004
 [5,]   5 30 105 1005
 [6,]   6 31 106 1006
 [7,] 382 32 107 1007
 [8,]   8 33 108 1008
 [9,]   9 34 109 1009
[10,]  10 35 110 1010

This will work for NAs in all columns, not just A.
If you have more NAs than rows, it should be faster to use rowMeans(m, na.rm=TRUE)[ idx[,1] ].

With zoo As @akrun mentioned, this also works:
library(zoo)
t(na.aggregate(t(m)))


text:
Q: Mapping non-ascii, long column names in SQLAlchemy fails with NoSuchColumnError Could it be that RowProxy objects' keys are truncated to some length?
I've a legacy MSSQL database that has some column names with accented letters.
I'm mapping it's columns to python properties with the following code:
@event.listens_for(Table, "column_reflect")
def column_reflect(inspector, table, column_info):
    if table.name == 'D_Allomanylista_Komplex_V':
        # set column.key = "attr_<lower_case_name>"
        columns_to_change = {
            'Allapot': 'allapot',
            'BIZTNEVE': 'biztosito_neve',
            u'Levelez\xe9siC\xedmUtca': 'LevelezesiCimUtca',
            u'Szerz\u0151d\xe9sSorsz\xe1m': 'SzerzodesSzam',
        }
        column_info['key'] = columns_to_change.get(column_info['name'], column_info['name'])

komplex_table = inspect_komplex_table()

class BiztositasokModel(Base):
    __table__ = komplex_table
    __mapper_args__ = {
        'primary_key': [
            komplex_table.c[u'KTVSZAM'],
            komplex_table.c[u'NyugtaSzam'],
            komplex_table.c[u'ajanlatszam'],
            komplex_table.c['SzerzodesSzam'],
            ],
        'include_properties': [
            'biztosito_neve',
            komplex_table.c['allapot'],
            komplex_table.c['LevelezesiCimUtca'],
            komplex_table.c['SzerzodesSzam'],
            'KTVSZAM', 'NyugtaSzam', 'ajanlatszam'],
    }

Unfortunately, this code gives an error when I try to query, stating that the SzerzodesSzam column does not exist.
/Users/viktornagy/.virtualenvs/dosszie/lib/python2.7/site-packages/sqlalchemy/orm/loading.pyc in _instance(row, result)
    361             identitykey = (
    362                 identity_class,
--> 363                 tuple([row[column] for column in pk_cols])
    364             )
    365

/Users/viktornagy/.virtualenvs/dosszie/lib/python2.7/site-packages/sqlalchemy/engine/result.pyc in _key_fallback(self, key, raiseerr)
    329                 raise exc.NoSuchColumnError(
    330                     "Could not locate column in row for column '%s'" %
--> 331                     expression._string_or_unprintable(key))
    332             else:
    333                 return None

NoSuchColumnError: "Could not locate column in row for column 'D_Allomanylista_Komplex_V.Szerz\\u0151d\\xe9sSorsz\\xe1m'"

I went into debugging mode to find out the root of the issue, and found that at line 363 above the column is Column('Szerz\u0151d\xe9sSorsz\xe1m', INTEGER(), table=<D_Allomanylista_Komplex_V>, key='SzerzodesSzam', nullable=False) while the corresponding row.key() is u'D_Allomanylista_Komplex_V_Szerz\u0151d\xe9sSorsz'. As if the key would be truncated (u'Szerz\u0151d\xe9sSorsz' once and u'Szerz\u0151d\xe9sSorsz\xe1m' at another point).
Querying row[u'D_Allomanylista_Komplex_V_Szerz\u0151d\xe9sSorsz'] indeed works, and gives the expected result.
Is there a way to avoid this truncation?

A: The above seems to be a limitation of the pyodbc driver. Switching to pymssql solved the issue.

A: works for me (even on OSX with freetds 0.86, typically this is where unicode DDL falls over badly):
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Foo(Base):
    __tablename__ = 'D_Allomanylista_Komplex_V'

    bar = Column(u'Szerz\u0151d\xe9sSorsz\xe1m', INTEGER(), autoincrement=False, primary_key=True)

e = create_engine("mssql+pyodbc://scott:tiger@ms_2008", echo=True)

c = e.connect()
t = c.begin()

Base.metadata.create_all(c)

s = Session(c)
s.add(Foo(bar=5))
s.commit()

row = s.query(Foo).first()

assert row.bar == 5

output:
CREATE TABLE [D_Allomanylista_Komplex_V] (
    [SzerződésSorszám] INTEGER NOT NULL,
    PRIMARY KEY ([SzerződésSorszám])
)

2014-07-24 19:15:22,504 INFO sqlalchemy.engine.base.Engine ()
2014-07-24 19:15:22,507 INFO sqlalchemy.engine.base.Engine INSERT INTO [D_Allomanylista_Komplex_V] ([SzerződésSorszám]) VALUES (?)
2014-07-24 19:15:22,507 INFO sqlalchemy.engine.base.Engine (5,)
2014-07-24 19:15:22,510 INFO sqlalchemy.engine.base.Engine SELECT TOP 1 [D_Allomanylista_Komplex_V].[SzerződésSorszám] AS [D_Allomanylista_Komplex_V_SzerződésSorszám]
FROM [D_Allomanylista_Komplex_V]


text:
Q: Solve $5^{x/2}-2^x=1$ I tried to think of it a lot but didn't get any breakthrough. I was trying with substitution method, but things were not fitting in.
Actual answer is 2

A: Let $x=2u$, then the equation becomes:
$$5^u-2^{2u}=1\Rightarrow 5^u=4^u+1^u$$
Divide both sides by $5^u$,
$$1=\left(\dfrac{4}{5}\right)^u+\left(\dfrac{1}{5}\right)^u$$
Easily observe that $u=1$ is one of the answer. However, as $\left(\dfrac{4}{5}\right)^u+\left(\dfrac{1}{5}\right)^u$ is strictly decreasing, so there must only have at most one answer. Therefore the answer is $u=1$, which means that $x=2$

A: Rewrite,
$$5^{x/2}-2^x=1$$
as
$$5^{x/2}=4^{x/2} + 1^{x/2}$$
Since $5=4+1$ and they all have the same exponential, the exponential must be 1,
$$\frac x2=1$$
which yields
$$x=2$$


text:
Q: Could not cast value of type NSSingleObjectArray to NSMutableArray Since iOS10, i am facing to this issue :

Could not cast value of type '__NSSingleObjectArrayI' to
  'NSMutableArray' .

There is my code :
manage.POST( url, parameters: params,
                     constructingBodyWithBlock: { (data: AFMultipartFormData!) in
                        //Some stuff here
            },
                     success: { (operation: NSURLSessionDataTask?, responseObject: AnyObject?) in

                         var array : NSMutableArray!

                        if AppConfig.sharedInstance().OCR == "2"{
                            let dictionnary = responseObject as! NSDictionary
                            array = dictionnary["data"]! as! NSMutableArray
                        }else{
                            //!!!!CRASH HERE!!!!!
                            array  = responseObject as! NSMutableArray
                        }
                        //Some stuff after
}

When i look for responseObject value, i have this in my console :
Printing description of responseObject:
▿ Optional<AnyObject>
  ▿ Some : 1 elements
    - [0] : Test

How can i extract value "Test" from responseObject ?
Many thanks

A: When we deal with response from web server then we can't sure about objects and types. So it is better to check and use objects as per our need. See for your reference related to your question.
if let dictionnary : NSDictionary = responseObject as? NSDictionary {

     if let newArr : NSArray = dictionnary.objectForKey("data") as? NSArray {

             yourArray = NSMutableArray(array: newArr)
      }

}

By this your app will never crashed as it is pure conditional for your needed objects with checking of types. If your "data" key is array then only it will proceed for your array. Thanks.

A: The crash happens because you assume that the object you receive is NSMutableArray, even though the object has been created outside your code.
In this case, an array that your code gets is an instance of an array optimized for handling a single element; that is why the cast is unsuccessful.
When this happens, you can make a mutable copy of the object:
array = (dictionnary["data"]! as! NSArray).mutableCopy() as! NSMutableArray

and
array = (responseObject as! NSArray).mutableCopy() as! NSMutableArray


text:
Q: How to enable/disable SelectManyCheck based on method returned value? Can anyone help in getting the returned value from a method in a bean to enable/disable components through ajax ex(SelectManyCheckbox, textbox ..etc) in a jsf page based on the selected radio button. First the SelectManyCheckbox component should disabled and based on the selection it should be enabled. The method is checking whether the value is "A" or "B" and it will return the value. Here is the method code:
private String firstToggle="True";
public String firstToggle(AjaxBehaviorEvent e){

        firstToggle=requestType;
        System.out.print("Value "+firstToggle);

        return firstToggle;
    }

Here it will return A or B.
However, When I am trying to disable/enable the SelectManyCheckbox component, the SelectManyCheckbox component won't pickup the value in the disabled attribute when the Value is B.
 <p:selectManyCheckbox id="Cars" value="#{user.xyz}" layout="pageDirection" disabled="#{user.firstToggle}=='B')">
<f:selectItems value="#{user.xyz}" var="xyz" itemLabel="#{xyz}" itemValue="#{xyz}"/>
</p:selectManyCheckbox>

So please help

A: The reason why you don't want to use firstToggle as a Boolean/boolean as suggested per Tiny's comment is really not clear! However, if you have your reasons to do that or you are handling the firstToggle in another place and you want to use it's value 'A' or 'B' in two different p:selectManyCheckbox ("where one should be enabled and the other should be disabled" as you said), then you could implement the first one with disabled="#{user.firstToggle eq 'B'}" and the second one with disabled="#{user.firstToggle eq 'A'}" or disabled="#{user.firstToggle ne 'B'}".
In case, you want to work with Boolean/boolean following Tiny's suggestion, then just use the first one with disabled="#{user.firstToggle}" and the second one with disabled="#{not user.firstToggle}"
NB: Also private String firstToggle="True"; even if it's correct, it doesn't make any sense, either use Boolean/boolean and assigne true to it, or assign 'A' which seems to mean false regarding your context.


text:
Q: Prevent wxPython from swallowing context manager exits on SIGINT It seems wxPython is intercepting any SIGINT in a way that prevents context manager __exit__ calls from happening. Is there any way to fix this behavior?
Here is a small test program that demonstrates the issue:
import wx
import time

class Printer(object):
    def __enter__(self):
        return self
    def __exit__(self, x, y, z):
        print('### Context manager called!')

with Printer() as p:
    app = wx.App()
    frame = wx.Frame(None)
    frame.Show()
    app.MainLoop()
    #time.sleep(1000)

If you run it like this and press Ctrl+C, no output is generated. If you change the wx code to the sleep statement and press Ctrl+C, the context manager does what it is expected to do.


text:
Q: How to correctly configure Datadog with Slack? I am currently using this link for writing a program in Python that will send out curl commands for POST , PUT, and DELETE requests using the Datadog API. So far, the request seems to be firing as I'd like it to, but it won't take my credentials. I'm not entirely sure what a service hook url is, but I believe it may be the culprit. Could anyone tell me how to find the following Slack specific elements for this?

*

*Account (is this your Slack name or your Slack handle? Say my Slack name is "John Doe", but my handle "J.D.")

*Slack Service Hook URL (no idea what this is or where to find it)

This is my test script in Python:
os.system("curl -v -X POST -H \"Content-type: application/json\" \
-d '{\
    \"service_hooks\": [\
        {\
            \"account\": \"[???]\",\
            \"url\": \"[???]\"\
        }\
    ],\
    \"channels\": [\
        {\
            \"channel_name\": \"[#???]\",\
            \"transfer_all_user_comments\": \"false\",\
            \"account\": \"[???]\"\
        }\
    ]\
}' \
\"https://api.datadoghq.com/api/v1/integration/slack?api_key=$"+[???]+"&application_key=$"+[???]+"\"");

The results were:
M-C02TW43FHV2Q:python foobar$ python main.py

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 00.000.000.00...
* TCP_NODELAY set
* Connected to api.datadoghq.com (00.000.000.00) port 000 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_000_GCM_SH00000
* Server certificate: *.datadoghq.com
* Server certificate: COMODO RSA Domain Validation Secure Server CA
* Server certificate: COMODO RSA Certification Authority
> POST /api/v1/integration/slack?api_key=00000000000000000000000000000&application_key=00000000000000000000000000000000 HTTP/1.1
> Host: api.datadoghq.com
> User-Agent: curl/0.00.0
> Accept: */*
> Content-type: application/json
> Content-Length: 292
>
* upload completely sent off: 292 out of 292 bytes
< HTTP/1.1 403 Forbidden
< Date: Tue, 26 Jun 2018 01:42:25 GMT
< Content-Type: application/json
< Content-Length: 31
< Connection: keep-alive
< Vary: Accept-Encoding
< Pragma: no-cache
< Cache-Control: no-cache
< X-DD-VERSION: 00.000000
< DD-POOL: dogweb_sameorig
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=100000000;
<
* Connection #0 to host api.datadoghq.com left intact
{"errors": ["Invalid API key"]}M-000000000000:python foobar$

I would really appreciate any help in finding this information!

A: It looks to me that these are Datadog specific configuration parameters. So you first need to install the Datadog app to your Slack workspace, which you find on the Slack App Directory.
Here is how the process is described in the official documentation:

Installation
The Slack integration is installed via its integration tile in the
  Datadog application.
Configuration

*

*In your Slack account go to the Applications page and search for
  Datadog.

*Click Install, followed by Add Integration.

*Copy the Slack Service Hook and paste in the service hook field for
  Slack in Datadog.

*Add the channels you want to be able to post to.

*If you would like to be notified for every comment on a graph, tick
  the check box "Transfer all user comments" by each channel. If left
  unchecked (default) you will need to use the @slack-channel_name
  syntax for comments to be posted to slack.

Source: official documentation from Datadog


text:
Q: If the circle (x-h)²+(y-k)²=r² touches the curve y=x²+1 at (1,2). Then show that h+2k=5. If the circle
$$(x-h)^2+(y-k)^2=r^2\quad\quad\text{(a)}$$  touches the curve
$$y=x^2+1\quad\quad\text{(b)}$$ at $(1,2)$. Then show that $h+2k=5$.
As Circle in equation (a) touches curve in equation (b), I tried to substitute $y=x^2+1$ in (a) and then putting $x=1$, I got
$$h^2+k^2-2h-4k+5-r^2=0$$
which is apparently the general equation of circle. Then its center is $(1,2)$. And it satisfies $h+2k=5$. Please correct me.

A: I'm assuming by "touches" you mean "is tangent to," otherwise the relation is not necessary. Namely, we require the tangent line to each curve at $(1, 2)$ to be the same. For this, their slopes must be equal.
We find for the circle, using implicit differentiation,
\begin{align}
2(x - h) + 2(y_1 - k) \frac{dy_1}{dx} &= 0 \\
\frac{dy_1}{dx} &= -\frac{x - h}{y_1 - k}.
\end{align}
For the parabola,
$$
\frac{dy_2}{dx} = 2x.
$$
We require
$$
\frac{dy_1}{dx} \bigg|_{(1,2)} = \frac{dy_2}{dx} \bigg|_{(1,2)}.
$$
Can you take it from here?

A: Show: $h + 2k = 5$.
The tangent to $y = x^2 + 1$ at $(1,2)$ is :
$y - 2 = 2 (x - 1)$ since $y'(1) = 2$.
The normal to this line passing through the same point $(1,2)$ is:
$y - 2 = -(1/2) (x -1)$ .
This line passes through the center $(h,k)$ of the given circle.
Hence:
$k - 2 = - (1/2) ( h - 1)$;
$- 2k +4 = h - 1$;
$h + 2k = 5$.
$\\$
P.S. Used:
1) Tangent to $y = x^2 + 1$ at $(1,2)$
has slope  $m = y'(1)  = 2$.
2) Line through $(1,2)$ with slope $m= 2$ is of the form:
$y - 2 = 2 ( x -1)$.
3)The normal to this line has slope$ -(1/m) = - (1/2)$.


text:
Q: amCharts wrong Zoom startDates and endDates I am using amCharts for displaying stock data. I have 7 zoom levels: 1H, 1D, 1W, 1M, 3M, 1Y, MAX. For 1H, 1D, I am using a dataset which contains minute wise data. For 1W, 1M, I use a different dataset which has hour wise data. And for rest 3 levels, I have another dataset with day wise data. Now here is my problem:
When initially, I load minute wise data at default zoom level 1D, and add a listener "changed" to chart.periodSelector, after clicking on 1W button or any further zoom level button, the difference in minutes between startDate and endDate of generated event: var minsDiff = (event.endDate.getTime() - event.startDate.getTime()) / 60000 is always equal to number of minutes in 1 day (1440) instead of 7 days.
I suppose this may be because the current dataset loaded is minutes dataset with 1440 max number of datapoints. So it may be setting date range for 1 Week equal to that of 1 Day because only that much data is available. But what I want is actual date range of 1 week if I click 1W button because I want to load a different chart with different dataset (hour wise data for 1W).
I tried using listener "zoomed" of chart. But same problem persisted.

A: Normally out of scope periods are not visible unless you set hideOutOfScopePeriods to false. As you noticed, if a period is greater than the amount of data available then the chart will truncate the zoom to fit the data you have.  Checking the predifinedPeriod property in the changed event is a surefire way to see which button was clicked, which will help in this scenario where the data doesn't necessarily encompass the entire period:
listeners: [
  {
    event: "changed",
    method: function(eventObj) {
      console.log("clicked " + eventObj.predefinedPeriod);
    }
  }
]


text:
Q: Reason: CORS header 'Access-Control-Allow-Origin' missing I'm getting Cross-Origin Request Blocked:

The Same Origin Policy disallows reading the remote resource at
http://localhost:8092/authenticate. (Reason: CORS header
'Access-Control-Allow-Origin' missing).

This error occurs while executing an Angular 8 project when I click the login button.

A: You need to add the Access-Control-Allow-Origin: * header to the server endpoint (Note: this allows access from anywhere if used in production)


text:
Q: How do you produce a .d.ts "typings" definition file from an existing JavaScript library? I'm using a lot of libraries both my own and 3rd party.  I see the "typings" directory contains some for Jquery and WinRT... but how are they created?

A: as described in http://channel9.msdn.com/posts/Anders-Hejlsberg-Steve-Lucco-and-Luke-Hoban-Inside-TypeScript at 00:33:52 they had built a tool to convert WebIDL and WinRT metadata into TypeScript d.ts

A: You can either use tsc --declaration fileName.ts like Ryan describes, or you can specify declaration: true under compilerOptionsin your tsconfig.json assuming you've already had a tsconfig.json under your project.

A: Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js files with modern JavaScript.
First, change all the extensions to .ts.
Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }

Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.
Get-ChildItem | foreach { tsc $_.Name  }

Finally, combine all the *.d.ts files into one index.d.ts, removing the import statements and removing the default from each export statement.
Remove-Item index.d.ts;

Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
  foreach { Get-Content $_ } | `
  where { !$_.ToString().StartsWith("import") } | `
  foreach { $_.Replace("export default", "export") } | `
  foreach { Add-Content index.d.ts $_ }

This ends with a single, usable index.d.ts file that includes many of the definitions.

A: There are a few options available for you depending on the library in question, how it's written, and what level of accuracy you're looking for. Let's review the options, in roughly descending order of desirability.
Maybe It Exists Already
Always check DefinitelyTyped (https://github.com/DefinitelyTyped/DefinitelyTyped) first. This is a community repo full of literally thousands of .d.ts files and it's very likely the thing you're using is already there.
You should also check TypeSearch (https://microsoft.github.io/TypeSearch/) which is a search engine for NPM-published .d.ts files; this will have slightly more definitions than DefinitelyTyped.
A few modules are also shipping their own definitions as part of their NPM distribution, so also see if that's the case before trying to write your own.
Maybe You Don't Need One
TypeScript now supports the --allowJs flag and will make more JS-based inferences in .js files. You can try including the .js file in your compilation along with the --allowJs setting to see if this gives you good enough type information. TypeScript will recognize things like ES5-style classes and JSDoc comments in these files, but may get tripped up if the library initializes itself in a weird way.
Get Started With --allowJs
If --allowJs gave you decent results and you want to write a better definition file yourself, you can combine --allowJs with --declaration to see TypeScript's "best guess" at the types of the library. This will give you a decent starting point, and may be as good as a hand-authored file if the JSDoc comments are well-written and the compiler was able to find them.
Get Started with dts-gen
If --allowJs didn't work, you might want to use dts-gen (https://github.com/Microsoft/dts-gen) to get a starting point. This tool uses the runtime shape of the object to accurately enumerate all available properties. On the plus side this tends to be very accurate, but the tool does not yet support scraping the JSDoc comments to populate additional types. You run this like so:
npm install -g dts-gen
dts-gen -m <your-module>

This will generate your-module.d.ts in the current folder.
Hit the Snooze Button
If you just want to do it all later and go without types for a while, in TypeScript 2.0 you can now write
declare module "foo";

which will let you import the "foo" module with type any. If you have a global you want to deal with later, just write
declare const foo: any;

which will give you a foo variable.

A: I would look for an existing mapping of your 3rd party JS libraries that support Script# or SharpKit. Users of these C# to .js cross compilers will have faced the problem you now face and might have published an open source program to scan your 3rd party lib and convert into skeleton C# classes. If so hack the scanner program to generate TypeScript in place of C#.
Failing that, translating a C# public interface for your 3rd party lib into TypeScript definitions might be simpler than doing the same by reading the source JavaScript.
My special interest is Sencha's ExtJS RIA framework and I know there have been projects published to generate a C# interpretation for Script# or SharpKit

A: This answer shows how to do it in a stand alone function using the typescript compiler API:
import ts from 'typescript';
function createDTsTextsFromJsFilePaths(
  jsFileNames: string[]
): Record<string, string> {
  const options = {
    allowJs: true,
    declaration: true,
    emitDeclarationOnly: true,
  };
  // Create a Program with an in-memory emit
  const createdFiles: Record<string, string> = {};
  const host = ts.createCompilerHost(options);
  host.writeFile = (fileName: string, contents: string): void => {
    const dtsName = fileName.replace('.js', '.d.ts');
    createdFiles[dtsName] = contents;
  };
  // Prepare and emit the d.ts files
  const program = ts.createProgram(jsFileNames, options, host);
  program.emit();
  return createdFiles;
}
////////////// test code below here ///////////////////////////////////
import fs from 'fs'
const jsTest =
`
"use strict"
function x(){
  return {
    a: 1,
    b: ()=>'hello'
  }
}
`;
const jsPath = '/tmp/jstest.js';
fs.writeFileSync(jsPath, jsTest);
const createdFiles = createDTsTextsFromJsFilePaths([jsPath]);
for (const dtsName in createdFiles) {
  console.log('================');
  console.log(dtsName);
  console.log('----------------');
  console.log(createdFiles[dtsName]);
}

Execution of the test gives the result
================
/tmp/jstest.d.ts
----------------
declare function x(): {
    a: number;
    b: () => string;
};

The function is derived from documentation in the type script compiler API guide

A: As Ryan says, the tsc compiler has a switch --declaration which generates a .d.ts file from a .ts file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.

A: The best way to deal with this (if a declaration file is not available on DefinitelyTyped) is to write declarations only for the things you use rather than the entire library. This reduces the work a lot - and additionally the compiler is there to help out by complaining about missing methods.

A: When creating your own library, you can can create *.d.ts files by using the  tsc (TypeScript Compiler) command like so:
(assuming you're building your library to the dist/lib folder)
tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly

*

*-d (--declaration): generates the *.d.ts files

*--declarationDir dist/lib: Output directory for generated declaration files.

*--declarationMap: Generates a sourcemap for each corresponding '.d.ts' file.

*--emitDeclarationOnly: Only emit '.d.ts' declaration files. (no compiled JS)

(see the docs for all command line compiler options)
Or for instance in your package.json:
"scripts": {
    "build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}

and then run: yarn build:types (or npm run build:types)


text:
Q: Styling navbar of bootstrap I've got a problem for styling my bootstrap navbar.
So in my navbar I have :

But I want this in only one line, just :

Essai actuel : kjvfged

My code for my navbar is :

                     AMG

And I give a content by this way :
$('.essaiActuel').text('Essai actuel : ');

Can someone tell me how I can increase the width of an element in a navbar please ?

A:
should do it
Span will keep everything inline.

A:

CodePen example
Looks like changing the div to span works.


text:
Q: Pass data and trigger modal on Angular2 form submit I have a modal with a form inside:

        <form (ngSubmit)="onSubmit(f)" #f="ngForm">

                Full Name
                <input type="name" class="form-control" id="fullname" placeholder="Enter full name" name="fullname" ngModel required>

             <button [disabled]="!f.valid" type="submit" class="btn btn-success" data-toggle="modal" data-target="#anotherModal" data-dismiss="modal">
            Confirm
          </button>
        </form>

When Button is clicked, a success modal is triggered:

Registration successful!

I'm trying to send the data collected in the form to parent component via my onSubmit method:
  onSubmit(){
    this.details = this.submittedForm.value;
    this.messageEvent.emit(this.details);
  }

But due to the first modal/form triggering the second modal, the onSubmit method isn't taking effect. If I remove the second modal trigger, the onSubmit works just fine. How can I get around this?


text:
Q: how to expand and collapse the UItable view cell on button click Has anyone seen a script like this or would be willing to help out with one?

Collapse/Expand Button
The uitableview cell to be expanded partially open (giving a preview in essence)

After the button is pressed then the cell of table would expand to show the entire contents (with a nice fade effect). If you chose to collapse the cell then it would return to the original offset (preview) height.
Has anyone seen anything like this? I've found a plethora of these scripts that fully expand or collapse, but not like this
Thank you for any help!!

A: you have to make custom cell class. While creating cell give the height of the cell as maximum you want (i.e when it expands) and when creating the custom cell drag a UIView and put all the contents in this view and hides this view. Then when button is being Tapped just you have to make it unhidden.


text:
Q: Does html5 link prefetch affect Google Analytics? Does the html5 link prefetch attribute cause a visit to be counted on the prefetched page in Google Analytics?
<link rel="prefetch" href="http://someurl.com/page.htm" />
This SO question about tracking prefetched AJAX content is similar but the <link> tag is a browser interpretation without any Javascript and it is implemented per browser.
I am developing sites with logical previous and next page content. The application is browsing sequentially through a website, training course or online brochure.

A: The prefetch only downloads the resources, but does not execute the code, or fire DOM events or so.
Given Google Analytics depends on running JS, I don't expect it to be affected.
Any server side analytics that track requests to the given resources will be affected though.


text:
Q: Angular show div based on URL parameter Is there a way I can display content based on a URL parameter being present, in Angular?
For example, myfile.php?id=123

    Show content

A: Inside of your controller/directive you can inject $location and use it to check for query params
 angular
    .module('locationExample', [])
    .controller('ExampleController',
     ['$scope', '$location', function($scope, $location) {
         $scope.search = $location.search();
     }]);

    Show content


text:
Q: How to defind __eq__ func for a custom object which need to compare the the same class I would like to implement an __eq__() method for an custom class Vertex.
However, when I carefully think about the problem, I find it is quite weird.
For example
class Vertex():
    def __init__(self,node):
        self.id = node
        self.adjacent = {}

However for the adjacent dict, it store the data like this:
 {neighbour_vertex1 : edge, neighbour_vertex2 : edge, ....}

If I want to implement the __eq__() method, it should look like:
def __eq__(self,other):
    return self.id == other and self.adjacent == other.adjacent

but the self.adjacent == other.adjacent requires to compare the dicts
 {neighbour_vertex1 : edge, neighbour_vertex2 : edge, ....}
 {neighbour_vertex1 : edge, neighbour_vertex2 : edge, ....}

In order to compare them, I have to define the comparison function for neighbout_vertex which indeed is an instance of class Vertex.
I think it is like a chicken or egg question, any suggestion is appreciated.
Edit: example
 class Vertex(object):
    def __init__(self,id):
        self.id = id
        self.adjacent ={}

    def add_vertex(self,obj):
        self.adjacent.update(obj)

    def __eq__(self,other):
        return self.id == other.id and self.adjacent == other.adjacent

    def __hash__(self):
        return hash(id(self))

obj1 = Vertex("one")
obj2 = Vertex("two")
temp = {obj2:"connect 1-2"}
obj1.add_vertex(temp)

obj1s = Vertex("one")
obj2s = Vertex("two")
temp2 = {obj2s:"connect 1-2"}
obj1s.add_vertex(temp2)

if obj1 == obj1s:
    print("True")

else:
    print("False")

I came out with a simple example, first I do not want to modify the hash function, how can I modify the __eq__function to make the above code output
True instead of False

A: I don't think you need an __eq__ override here at all. With the design you've chosen, it doesn't make sense for two different instances of Vertex to represent "the same vertex", and two Vertex instances should only compare equal if they are actually the same object. The default __eq__ implementation already gives you that behavior.
If you do want different instances of Vertex to compare equal, then you need to think about your design first. For example, your definition of __hash__ as hash(id(self)) only makes sense if equality works by identity, so your __hash__ will need to be changed. You'll also need to think about things like, what if vertices a and b both have self.id = 1 and self.adjacent = {c: 'asdf'}, but c has self.adjacent = {b: 'asdf'}? Are a and b equal? You're going to have to come up with a precise definition of the concept of equality you want to use.
One possible redesign would be to move adjacency tracking out of the vertex objects. If vertex objects only have self.id, and edges are tracked externally by some sort of Graph object, then it could make sense to compare Vertex objects "by value". At that point, it might make more sense to eliminate the Vertex class entirely, though.

A: @Ralf suggested comparing only the id attribute. This is probably the best solution, and you should absolutely go with that if possible.
If not, what is the structure of your vertices? Is it like a tree where adjacency only goes one way? Then writing it like that is fine; eventually you'll run out of nodes.
If the vertices can loop back, we'll have to do something more complicated. The basic trick is to maintain a stack of vertices you haven't visited, and a list of nodes you've already compared. With each loop, pop the top element off the stack. If you see anything that would make the elements compare false, you can return. Otherwise, put the adjacent nodes on the stack if you haven't visited them before, update the visited nodes, and keep going.
(I won't be making the effort to provide a code sample.)


text:
Q: phonegap app loads first page upon screen orientation change i am developing an android app using phonegap. i have multiple pages in the app and a single activity. whenever i change the orientation of the device, no matter which page i am on, the app loads the first page which is shown when the app is launched. i assumed it was because i had not overriden the onResume() method in the activity, but even that failed to solve the problem.
EDIT: This issue does not arise if the app is paused and the resumed.
My activity:
public class MainScreen extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/landing.html");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }
}

EDIT: Added Manifest file
My Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.me.code"
    android:versionCode="5"
    android:versionName="1.4" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.miniorange.authenticator.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.miniorange.authenticator.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.miniorange.authenticator.MainActivity"
            android:label="@string/app_name" >

        </activity>
        <activity android:name="com.miniorange.authenticator.MainScreen">
             <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.plugin.gcm.PushHandlerActivity"/>
            <receiver android:name="com.plugin.gcm.CordovaGCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                    <category android:name="com.me.code" />
                </intent-filter>
            </receiver>
            <service android:name="com.plugin.gcm.GCMIntentService" />

    </application>

</manifest>

what may be the solution to this problem?

A: sorry ... ( answering it late :D )
I had this problem with my app :
When I change the orientation, activity reloads ...
And I found this solution :
add this attribute to your <activity> tags :
android:configChanges="orientation"

suggestion ... use this insted (better) :
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"

==========================================
information about solution :
what is the reason .. (?)
It'll say to application that you want to handle this changes (orientation, keyboardHidden, keyboard, screenSize, locale, etc.) yourself.


text:
Q: Difference between array_map, array_walk and array_filter What exactly is the difference between array_map, array_walk and array_filter. What I could see from documentation is that you could pass a callback function to perform an action on the supplied array. But I don't seem to find any particular difference between them.
Do they perform the same thing?
Can they be used interchangeably?
I would appreciate your help with illustrative example if they are different at all.

A: The idea of mapping an function to array of data comes from functional programming. You shouldn't think about array_map as a foreach loop that calls a function on each element of the array (even though that's how it's implemented). It should be thought of as applying the function to each element in the array independently.
In theory such things as function mapping can be done in parallel since the function being applied to the data should ONLY affect the data and NOT the global state. This is because an array_map could choose any order in which to apply the function to the items in (even though in PHP it doesn't).
array_walk on the other hand it the exact opposite approach to handling arrays of data. Instead of handling each item separately, it uses a state (&$userdata) and can edit the item in place (much like a foreach loop). Since each time an item has the $funcname applied to it, it could change the global state of the program and therefor requires a single correct way of processing the items.
Back in PHP land, array_map and array_walk are almost identical except array_walk gives you more control over the iteration of data and is normally used to "change" the data in-place vs returning a new "changed" array.
array_filter is really an application of array_walk (or array_reduce) and it more-or-less just provided for convenience.

A: *

*Changing Values:

*

*array_map cannot change the values inside input array(s) while array_walk can; in particular, array_map never changes its arguments.

*Array Keys Access:

*

*array_map cannot operate with the array keys, array_walk can.

*Return Value:

*

*array_map returns a new array, array_walk only returns true. Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk.

*Iterating Multiple Arrays:

*

*array_map also can receive an arbitrary number of arrays and it can iterate over them in parallel, while array_walk operates only on one.

*Passing Arbitrary Data to Callback:

*

*array_walk can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced).

*Length of Returned Array:

*

*The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function. It does preserve the keys.

Example:
<pre>
<?php

$origarray1 = array(2.4, 2.6, 3.5);
$origarray2 = array(2.4, 2.6, 3.5);

print_r(array_map('floor', $origarray1)); // $origarray1 stays the same

// changes $origarray2
array_walk($origarray2, function (&$v, $k) { $v = floor($v); });
print_r($origarray2);

// this is a more proper use of array_walk
array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; });

// array_map accepts several arrays
print_r(
    array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2)
);

// select only elements that are > 2.5
print_r(
    array_filter($origarray1, function ($a) { return $a > 2.5; })
);

?>
</pre>

Result:
Array
(
    [0] => 2
    [1] => 2
    [2] => 3
)
Array
(
    [0] => 2
    [1] => 2
    [2] => 3
)
0 => 2.4
1 => 2.6
2 => 3.5
Array
(
    [0] => 4.8
    [1] => 5.2
    [2] => 10.5
)
Array
(
    [1] => 2.6
    [2] => 3.5
)

A: From the documentation,

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool

array_walk takes an array and a function F and modifies it by replacing every element x with F(x).

array array_map ( callback $callback ,
  array $arr1 [, array $... ] )<-return array

array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.

array array_filter ( array $input [,
  callback $callback ] )<-return array

array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

A: The other answers demonstrate the difference between array_walk (in-place modification) and array_map (return modified copy) quite well. However, they don't really mention array_reduce, which is an illuminating way to understand array_map and array_filter.
The array_reduce function takes an array, a two-argument function and an 'accumulator', like this:
array_reduce(array('a', 'b', 'c', 'd'),
             'my_function',
             $accumulator)

The array's elements are combined with the accumulator one at a time, using the given function. The result of the above call is the same as doing this:
my_function(
  my_function(
    my_function(
      my_function(
        $accumulator,
        'a'),
      'b'),
    'c'),
  'd')

If you prefer to think in terms of loops, it's like doing the following (I've actually used this as a fallback when array_reduce wasn't available):
function array_reduce($array, $function, $accumulator) {
  foreach ($array as $element) {
    $accumulator = $function($accumulator, $element);
  }
  return $accumulator;
}

This looping version makes it clear why I've called the third argument an 'accumulator': we can use it to accumulate results through each iteration.
So what does this have to do with array_map and array_filter? It turns out that they're both a particular kind of array_reduce. We can implement them like this:
array_map($function, $array)    === array_reduce($array, $MAP,    array())
array_filter($array, $function) === array_reduce($array, $FILTER, array())

Ignore the fact that array_map and array_filter take their arguments in a different order; that's just another quirk of PHP. The important point is that the right-hand-side is identical except for the functions I've called $MAP and $FILTER. So, what do they look like?
$MAP = function($accumulator, $element) {
  $accumulator[] = $function($element);
  return $accumulator;
};

$FILTER = function($accumulator, $element) {
  if ($function($element)) $accumulator[] = $element;
  return $accumulator;
};

As you can see, both functions take in the $accumulator and return it again. There are two differences in these functions:

*

*$MAP will always append to $accumulator, but $FILTER will only do so if $function($element) is TRUE.

*$FILTER appends the original element, but $MAP appends $function($element).

Note that this is far from useless trivia; we can use it to make our algorithms more efficient!
We can often see code like these two examples:
// Transform the valid inputs
array_map('transform', array_filter($inputs, 'valid'))

// Get all numeric IDs
array_filter(array_map('get_id', $inputs), 'is_numeric')

Using array_map and array_filter instead of loops makes these examples look quite nice. However, it can be very inefficient if $inputs is large, since the first call (map or filter) will traverse $inputs and build an intermediate array. This intermediate array is passed straight into the second call, which will traverse the whole thing again, then the intermediate array will need to be garbage collected.
We can get rid of this intermediate array by exploiting the fact that array_map and array_filter are both examples of array_reduce. By combining them, we only have to traverse $inputs once in each example:
// Transform valid inputs
array_reduce($inputs,
             function($accumulator, $element) {
               if (valid($element)) $accumulator[] = transform($element);
               return $accumulator;
             },
             array())

// Get all numeric IDs
array_reduce($inputs,
             function($accumulator, $element) {
               $id = get_id($element);
               if (is_numeric($id)) $accumulator[] = $id;
               return $accumulator;
             },
             array())

NOTE: My implementations of array_map and array_filter above won't behave exactly like PHP's, since my array_map can only handle one array at a time and my array_filter won't use "empty" as its default $function. Also, neither will preserve keys.
It's not difficult to make them behave like PHP's, but I felt that these complications would make the core idea harder to spot.

A: The following revision seeks to more clearly delineate PHP's array_filer(), array_map(), and array_walk(), all of which originate from functional programming:
array_filter() filters out data, producing as a result a new array holding only the desired items of the former array, as follows:
<?php
$array = array(1, "apples",2, "oranges",3, "plums");

$filtered = array_filter( $array, "ctype_alpha");
var_dump($filtered);
?>

live code here
All numeric values are filtered out of $array, leaving $filtered with only types of fruit.
array_map() also creates a new array but unlike array_filter() the resulting  array contains every element of the input $filtered but with altered values, owing to applying a callback to each element, as follows:
<?php

$nu = array_map( "strtoupper", $filtered);
var_dump($nu);
?>

live code here
The code in this case applies a callback using the built-in strtoupper() but a user-defined function is another viable option, too.  The callback applies to every item of $filtered and thereby engenders $nu whose elements contain uppercase values.
In the next snippet, array walk() traverses $nu and makes changes to each element vis a vis the reference operator '&'. The changes occur without creating an additional array. Every element's value changes in place into a more informative string specifying its key, category and value.
<?php

$f = function(&$item,$key,$prefix) {
    $item = "$key: $prefix: $item";
};
array_walk($nu, $f,"fruit");
var_dump($nu);
?>

See demo
Note: the callback function with respect to array_walk() takes two parameters which will automatically acquire an element's value and its key and in that order, too when invoked by array_walk(). (See more here).


text:
Q: How to write a common generic function for different classes? func setPostcommentData(postmodel:model1,index: IndexPath) {
     btnReply.tag = index.section
     lblName.text = postmodel.getFullName()
     btnReply.setTitle("Reply", for: UIControlState.normal)
     btnCount.setTitle("0", for: UIControlState.normal)
     TxtViewComment.text = postmodel.description
     lblTime.text = ChatDates.commentTimeData(postmodel.createdDate).dateString
}

Usage:
cellComment.setPostcommentData(postmodel: model1,index:indexPath)
cellComment.setPostcommentData(postmodel: model2,index:indexPath)
cellComment.setPostcommentData(postmodel: model3,index:indexPath)

How to write generic function so that it accepts different models and sets data?

A: If I got the idea right, here is a solution
protocol PostComment {
    var value1: String {get}
    var value2: String {get}
    var value3: String {get}
}

class PostCommentParent: PostComment {
    var value1: String {
        return self.myValue1
    }

    var value2: String {
        return self.myValue2
    }

    var value3: String {
        return self.myValue3
    }

    var myValue1 = "1"
    var myValue2 = "2"
    var myValue3 = "3"
}

class PostCommentChild: PostCommentParent {
    override var value3: String {
        return self.myValue4
    }

    var myValue4 = "4"
}

let myParent = PostCommentParent()
let myChild = PostCommentChild()

func parse(comment: PostComment) {
    print(comment.value3)
}

parse(comment: myChild)
parse(comment: myParent)


text:
Q: Get a 403 error code when I trying to get a token from Auth0 I trying implement Auth0 authentication/authorization in web api. But get 403 error code (No such host is known. (https:443))
Simple code for get token is below
        var client = new AuthenticationApiClient(new Uri($"https://{ _config.GetValue<string>("auth0:Authority")}"));

        var authenticationResponse = await client.GetTokenAsync(new RefreshTokenRequest
        {
            Audience = "https://dev-rignosgw.us.auth0.com/api/v2/",
            ClientSecret = _config.GetValue<string>("auth0:ClientSecret"),
            ClientId = _config.GetValue<string>("auth0:ClientId")
        });

But if execute analogous query in postman it is work correctly and i get auth token in response. Query is below

curl --request POST \   --url
'https://dev-rignosgw.us.auth0.com/oauth/token' \   --header
'content-type: application/x-www-form-urlencoded' \   --data
grant_type=client_credentials \   --data client_id=CLIENT_ID \
--data client_secret=CLIENT_SECRET \   --data audience=https://dev-rignosgw.us.auth0.com/api/v2/

Question is folowing. What url must using in AuthenticationApiClient constructor? As I understand in my case it must beeen ttps://dev-rignosgw.us.auth0.com/oauth/token. Or I'm wrong?
I have never used Auth0 before. What i'm doing wrong? Thanks.


text:
Q: Kohana image upload validation I'm having problems with image validation, documentation as always doesn't help, so there is my simple validation to check if image was uploaded
    $validate = Validation::factory($_FILES)
                ->rule('file', array('Upload::not_empty'));

But this gives me error
ErrorException [ Warning ]: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members
What could be causing this error?

A: The 2nd argument for rule is a PHP callback. So this would suffice because the not_empty method in the upload class is static:
rule('file', 'Upload::not_empty');

You only really need to do the array syntax when the method is not static:
rule('file', array($class, 'method'));


text:
Q: How to auto-brighten an SVG node using SVG only? I would like to be able to specify some kind of transformation that would, given an arbitrary SVG node remap all of its pixel values to cover the full (0-100% or 0-255) range of intensities while avoiding clipping.
The feComponentTransfer filter with feFuncX linear mapping functions almost offers what I want but seems to lack the ability to refer to the global maximum intensity of the input node, is there some clever way around it ?

A: There is no "auto-brighten" feature that will do what you want.
You would have have to do it yourself by reading all the colours yourself with javascript and work out the appropriate brighten/saturate value.
But as a good-enough approach, a saturate filter with a value of 200% might get something close to what you want.

svg rect:hover {
  filter: saturate(200%);
}
<svg>
  <rect width="50%" height="100%" fill="cadetblue"/>
  <rect x="50%" width="50%" height="100%" fill="cornsilk"/>
</svg>


text:
Q: Using Windows function SendMessage results in linking error with MSVC but not with MinGW I'am using the Windows function SendMessage in one of my functions.
If I compile with MinGW everything is fine.
If I compile with MSVC2013 I'm getting this linking error
myClass.obj:-1: error: LNK2019: unresolved external symbol __imp__SendMessageW@16 referenced in function "private: virtual void __thiscall ...

Why is that?

A: You can do this:
#ifdef _MSC_VER
 #pragma comment(lib, "user32.lib")
#endif

A: Visual C++ only links in kernel32.dll by default.
g++ additionally links in a number of other DLLs (Windows API sub-libraries). Exactly what depends on the options.
Relevant line from the specs file with the Nuwen distro of MinGW g++ 4.9.1:

%{pg:-lgmon} %{pthread:-lpthread} %{!no-pthread: } %{mwindows:-lgdi32 -lcomdlg32} -ladvapi32 -lshell32 -luser32 -lkernel32


text:
Q: Firebase and Facebook Authentication I am trying to use Firebase and Facebook login and it is working, but when the Facebook page opens and you close it without logging in it throws an error and says "fatal error: unexpectedly found nil while unwrapping an Optional value"
The line that is highlighted as causing the error is let credential....
Here is my code:
// Login button is pressed
    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {

        if let error = error {

          print(error.localizedDescription)

        } else {

            let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
            FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in

                if let error = error {

                    print(error.localizedDescription)

                } else {

                    self.performSegueWithIdentifier("loginSegue", sender: self)
                    print("Login complete")

                }
            }
        }
    }

Can someone please help me? Thanks

A: You need to check also if you have a user, or probably the user canceled the sign up
if let user = user {

 } else {
   print("Uh oh. The user cancelled the Facebook login."))
}


text:
Q: Can I get a pair of schottky diodes in a single chip? I'm building a motor driver circuit, and am looking at diodes to clamp the output voltage between the supply rails. Apparenly, I should use schottky diodes for this purpose.
My question is, are there ICs out there than contain a pair of diodes arranged as shown below?
┌───►|──┬──►|───┐
│       │       │
0V      S       V+

Or should I just buy a pair of single diodes?

A: Yes, such devices do exist; they are known as dual Schottky or dual diodes.
The most common arrangement is two diodes with a common cathode; these are used in switch mode power supplies to boost the allowable current from a typical single diode in package.
However, dual series diodes do exist; here is one example of a power device: VS-8STH06FP.
Another example of a device not intended for high power applications is BAV99W, which is a very popular device.

A: They're simply called "double Schottky diodes" :-). They often come in different configurations, like for instance the BAT54:

BAT54A: common anode
  BAT54C: common cathode
  BAT54S: in series, one diode's cathode connects to the other's anode
  BAT54: is the single diode version


text:
Q: xdmp http post options for token authentication I have found the https://docs.marklogic.com/xdmp:http-post function.
I would like to use the token authentication method to send out a JSON document from MarkLogic to a middle tier node.js application. We use token authentication.
What http-options should I use to make this work?
Example:
(: Use xdmp:quote to encode the XML as a string
   because the <data> options element is a string :)
let $payload := xdmp:quote('
{"alert": {
                "id": "123abc",
                "type": "sensorAlert",
                "timestamp": "2015-08-12 T 13:48:45 CET",
                "actions": ["go get them!"],
                "status": "active"
            }
}'
)
return
xdmp:http-post("http://cluey-app-ml1:9070/alert",
     <options xmlns="xdmp:http">
       <authentication method="basic">
         <username>myname</username>
         <password>mypassword</password>
       </authentication>
       <data>{$payload}</data>
       <headers>
         <content-type>application/json</content-type>
       </headers>
     </options>)

Ofcourse posting this as-is gives me a 401 unauthorized response:
<response xmlns="xdmp:http">
401
<message>Unauthorized</message>
<headers>
<x-powered-by>Express</x-powered-by>
<access-control-allow-origin>*</access-control-allow-origin>
<content-type>text/html; charset=utf-8</content-type>
<content-length>26</content-length>
<etag>W/"1a-14Zh6wfLQpiHPatjrIEVAQ"</etag>
<set-cookie>connect.sid=s%3AT_lwAwvX9-1rJ7It7x42w126532HtIA2.nr5Zt2dONb6Q0uD7LpryZrpEsOUvXL8ZHUiTr8hOsfg; Path=/; HttpOnly</set-cookie>
<date>Tue, 08 Sep 2015 13:50:27 GMT</date>
<connection>keep-alive</connection>
</headers>
</response>
Text document
Could not broadcast alert.

A: Although not a 'feature' that I know of, there is likely nothing stopping you form doing request "A" to get your token, storing it in ML and then using it for subsequent requests by setting the appropriate header information required by your token system (such as Authentication:Bearerxxxxx as an example)
Tokens are sent back as header information.  You can see the options for how to set header information on this page: https://docs.marklogic.com/xdmp:http-get
Edited below to reflect comment:
<headers>
  <access-token>eyJ0eXAiO...RDHaNEjftfja-MofLqlv6fUKmN7k...</access-token>
  <content-type>application/json</content-type>
</headers>