text:
Q: Discord.Js give all members a role I want to make a command that gives role to all the members
Example: !give
This command should give everyone in the server a specific role
this is my code so far -
const Role = message.guild.roles.cache.get("Role-ID");

const Roled = message.guild.roles.cache.get("Role-ID")

Role.members.forEach((member, i) => {
  setTimeout(() => {
    member.roles.add(Roled); // Adding the Role.
  }, i * 1000);
});

When I tested this code, it just added for me and my bot the role, and not to every member as it should do.
How can i fix it?

A: By using Role.members.forEach you're only getting the members that currently have that role.
If you want to add a role to all the members in a guild you need to use message.guild.members.cache.forEach
First you find the role that you want to assign:
const role = message.guild.roles.cache.get("Role-ID");

Then you create a loop that assigns the role for each member in the guild:
message.guild.members.cache.forEach(member => {

// Check if user has a higher role than the bot
if((member.roles.highest.position > message.guild.me.roles.highest.position)) {
      return;
}

try{ member.roles.add(role)
} catch(error){console.log(error}


text:
Q: Unallocated space as unused space I am using Windows 7 with a total of 500 GB hard drive space(distributed equally in the three drives ie. C drive, D drive and E drive and a 100MB system drive). I have nearly 150 GB unallocated space which I want to be used for Ubuntu installation. But while dual boot and manual installation option the the unallocated space is written as unusable space and there is no option to do changes for that space....so please tell me what to do.
Sanchit

A: You can try formatting that unallocated space as ext4 from Ubuntu Live CD/USB using gparted.
Choose "Try Ubuntu" option during installation of Ubuntu.
To launch gparted, open a terminal by pressing ctrl+alt+t and typing sudo gparted.

A: I'd expect windows would normally allocate all the space in a HD, so just in case he means "free space" inside his 3 partitions (and there really isn't 150GB of unpartitioned HD space) then you'd need to shrink one of the partitions and make some unallocated/unpartitioned space for a new Ubuntu partition.
The solution could be to run gparted (if from terminal sudo gparted) like julka suggests, but involves shrinking a partition first, then when there's enough space making new partition(s).
Or, Windows should be able to shrink one of it's partitions too, especially if it's formatted as NTFS and you don't fully trust Ubuntu to play with NTFS (linux support for ntfs is not perfect, still need windows chkdsk to fix some problems, I read somewhere it's reverse-engineered, MS doesn't want to help write free software for NTFS for some reason).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upload photo and tag friends using javascript sdk i m trying to post photo on users wall and tagging their friends in that photo. i have the permissions of the user of publish stream and photos. Now i m using the fb.api method to post on user wall and tag friends. my codes are working properly if i define the users id who will be tagged in that photo but i wanted to do that automatically and i tried these codes but this is not working because of some mistakes please anyone help me to fix the codes.
// Auto post picture of talent result
        FB.api('/me/photos', 'post', {
        access_token: response.authResponse.accessToken,
        url: 'http://guthrienewspage.files.wordpress.com/2013/10/talent.jpg',
        message: 'this is my new talent that i discovered',
        tags: '[{tag_uid:12312,x:20,y:20},{tag_uid:34212,x:20,y:20},{tag_uid:123122132,x:20,y:20}]'
        }, function(response) {
        if (!response || response.error) {
        alert('Error occured');
        } else {
        alert('Post ID: ' + response.id);
        }
        });

the above code is working properply now i use the below code to retrieve the user friends id:
   FB.api('/me/friends', function(response) {
          if(response.data) {
           $.each(response.data,function(index,friend) {
        // friendidtag = {tag_uid: + friend.id + ,x:20,y:20},
        // alert(friend.name + ' has id:' + friend.id);
         var alltagsid = '{tag_uid: + friend.id + ,x:20,y:20},';
           });
          } else {
              alert("Error!");
              }
         });

and then using this var alltagsid in my first code like this:
// Auto post picture of talent result
    FB.api('/me/photos', 'post', {
    access_token: response.authResponse.accessToken,
    url: 'http://guthrienewspage.files.wordpress.com/2013/10/talent.jpg',
    message: 'this is my new talent that i discovered',
    tags: '[alltagsid]'
    }, function(response) {
    if (!response || response.error) {
    alert('Error occured');
    } else {
    alert('Post ID: ' + response.id);
    }
    });

but this is not working plz help me out to fix this code. and please dont give me reference of api's just make this code fixed and post the answer if you can otherwise leave it.

A: An Array Declaration In Javascript Is Like That. Check It
FB.api('/me/friends', function(response) {
      if(response.data) {
       $.each(response.data,function(index,friend) {
    // friendidtag = {tag_uid: + friend.id + ,x:20,y:20},
    // alert(friend.name + ' has id:' + friend.id);
     var alltagsid = new array '{tag_uid: + friend.id + ,x:20,y:20},';
       });
      } else {
          alert("Error!");
          }
     });


text:
Q: Dynamically Generating Dalvik Bytecode into a running Dalvik/Android application This question has been asked(and answered) many times about dynamically generating and loading java bytecodes at runtime into a running Dalvik VM, but is there any way to load dex files/bytecodes into an app at runtime?
Thanks

A:
is there any way to load dex
  files/bytecodes into an app at
  runtime?

Look at DexFile and DexClassLoader.

A: A related answer suggests Dexmaker for dynamic Dalvik bytecode generation.

A: The Dalvik team would like to build a first-class runtime code generation library. We're tracking the feature request as Android bug 6322. Unfortunately, we have a very long list of performance and correctness issues, so I can't give you a timeline for when we'll spend time on this issue.
There are some alternatives, but they will all take some work:

*

*Run your application on a standard JVM and exercise all runtime code generation there. Dump the .class files from memory to files, and then run dx on those files. If you're quite sophisticated, you could integrate all of this work into your build.

*Include the open source dx tool as a project library, and execute it programatically from within your application, possibly in your application's classloader. This will bloat your application's binary.

A: I have used ASM and BCEL to generate Java classes and then I have converted them to Dex files.
Finally I have created jar files to load dynamically on device.
You can check out my code :)
https://github.com/sciruela/android

A: If inside any C or C++ program, you want to load and call into the DEX classes, you can see how the Dalvik VM is started, inside the AndroidRuntime - for example frameworks/base/cmds/app_process/app_main.cpp:
status_t app_init(const char* className, int argc, const char* const argv[])
{
    LOGV("Entered app_init()!\n");

    AndroidRuntime* jr = AndroidRuntime::getRuntime();
    jr->callMain(className, argc, argv);

    LOGV("Exiting app_init()!\n");
    return NO_ERROR;
}

As "jr" AndroidRuntime is already started, callMain() will be called:
status_t AndroidRuntime::callMain(
    const char* className, int argc, const char* const argv[])
{
    JNIEnv* env;
    jclass clazz;
    jmethodID methodId;

    LOGD("Calling main entry %s", className);

    env = getJNIEnv();
    if (env == NULL)
        return UNKNOWN_ERROR;

    clazz = findClass(env, className);
    if (clazz == NULL) {
        LOGE("ERROR: could not find class '%s'\n", className);
        return UNKNOWN_ERROR;
    }

    methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
    if (methodId == NULL) {
        LOGE("ERROR: could not find method %s.main(String[])\n", className);
        return UNKNOWN_ERROR;
    }
<...>
    env->CallStaticVoidMethod(clazz, methodId, strArray);
    return NO_ERROR;
}

From above, we can see how the DEX classes' codes are loaded and CallStaticVoidMethod() will start interpreting the DEX codes.


text:
Q: How to dynamically assign equal space for Menu items in ReactJs and and Bootstrap 4
I have below Menu Component built using bootstrap 4 and ReactJs
I have four menu Items 1) Home 2) Products 3) 404 4)Login
How to build a component where tomorrow if i have 10 menu items then how will
  i equally space it
currently it appears

import React from "react";
import { Link } from "react-router-dom";

const MENUDATA = [
  { menuLink: "/", menuLabel: "Home" },
  { menuLink: "/products", menuLabel: "Products" },
  { menuLink: "/test", menuLabel: "404" },
  { menuLink: "/login", menuLabel: "Login" }
];

function Menu(props) {
  return (

      {

            {MENUDATA.map(m => {
              if (m.menuLabel == "Login") {
                return (

                    <Link class="nav-link" to={m.menuLink}>

                      {m.menuLabel}
                    </Link>

                );
              } else {
                return (

                    <Link class="nav-link" to={m.menuLink}>
                      {m.menuLabel}
                    </Link>

                );
              }
            })}

      }

  );
}

export default Menu;


text:
Q: Displaying jQuery UI dialog with multiple checkboxes I'm trying to display multiple checkboxes and then submit the selected checkboxes as HTTP GET (i.e. as parameters in URL string) to the same script:

Here is my simplified test code - test.php:

<form>

<input type="button" value="Select name"
       onclick="$('#name').dialog('open');">

<?php

$NAMES = array(
        'project one',
        'project two',
        'project three',
);

foreach ($NAMES as $name) {
        printf('
<input type="checkbox" name="name" value="%s">%s
',
                urlencode($name),
                htmlspecialchars(substr($name, 0, 120))
        );
}

?>

<input type="submit">
</form>

But for some reason, when I select the first 2 checkboxes click the "Submit" button (sorry for the non-English name in the screenshot), then the script http://myserver/test.php? is being submitted and not http://myserver/test.php?name=project+one&name=project+two as I would expect.
If I get rid of all JQuery UI stuff, then it works.
What am I doing wrong? (besides using name="name" which is because that's a database table column name and doesn't seem to be the reason for this problem anyway)
UPDATE:
In my real program (not the above test case) I actually have several such dialogs and would like to set some settings in each dialog and only after that that click a Submit button. So the Submit button must be outside the dialog(s).
Thank you!

A: Assuming all the form inputs are checkboxes  you can use the following to compile and submit the details as a GET.
using your original code add the following function
function compileInputs(){
var string = '';
var inputs = new Array();

//loop through all checkboxes
$(':checkbox').each(function(){
    if($(this).is(':checked')){
        inputs.push($(this).attr('name')+"="+$(this).val());
    }
});

string = "?"+inputs.join("&");
window.location.replace(string);

}
you will need to change the names of the inputs from name='name' to name='name[]'
then change the submit to a button as follows:
<input type="button" onClick='compileInputs()' value='submit'>

you will no longer need the <form> tags
for a more selective approach:
//get all checkboxes from div#name
$('div#name :checkbox').each(function(){
    if($(this).is(':checked')){
        inputs.push($(this).attr('name')+"="+$(this).val());
    }
});

//get all checkboxes from div#appsversion
$('div#appsversion :checkbox').each(function(){
    if($(this).is(':checked')){
        inputs.push($(this).attr('name')+"="+$(this).val());
    }
});
//get all checkboxes from div#osversion
$('div#osversion :checkbox').each(function(){
    if($(this).is(':checked')){
        inputs.push($(this).attr('name')+"="+$(this).val());
    }
});

A: You may need to wrap the whole form in a div and then dialog the new div in the dialog rather than just the div #name

A: Try this:
$("#submitButton").click(function(){
    $("#formId").submit();
});

A: Assuming the dialog is actually the problem, you may have to have your dialogs populate some hidden fields on the page to actually submit.
Here is a very simple sample to get you started.
http://jsfiddle.net/jUH9g/
When you click ok in the dialog it populates the 'names' textbox inside the form that actually gets submitted. In your real code you would change input type="textbox" to input type="hidden"
$("#dlg").dialog({autoOpen: false,
              buttons: {
                  "OK": function () {
                      var names = "";
                      $("input:checkbox").each(function () {
                          if (this.checked) {
                              names += $(this).val() + ",";
                          }
                      });
                      $("#names").val(names);
                  }
              }
         });

A: Should you not do name="name[]" . Then on the form submit (however you submit it (AJAX or non AJAX), you can get the "name" array as your post variable and handle it as you may wish. Correct me if I am wrong


text:
Q: My + operator changing the value of my class  const Polynomial operator +(const Polynomial lhs, const Polynomial rhs){
        //lhs is 1
        Polynomial result(lhs);

        result+=rhs;
        //when I add rhs to my result it also increments my lhs and lhs is now 3
        cout<<"item: "<<rhs<<endl;
        return result;
    }

        int size;
    Monomial *polynome; // my polynome is an array of monomials
                            //p[0]= 2, p[1]=3x etc.

I am using default copy constructor(i didnt define one) maybe thats the problem since I have a pointer to array I dont know.
I rather not to share my += operator unles necessary since it seem like its working fine but its terribly implemented it would take 30 minutes to explain whats going on.
 This is driving me crazy, any solutions?
EDIT: defining a deep copy constructor solved my problem. Thanks a lot for the tips!

A: I'm going to hazard a wild guess that your class looks something vaguely like this:
// DO NOT write code like this. The default copy semantics are incorrect.
struct Polynomial {
    Polynomial(size_t order) : coefs(new double[order+1]) {}
    double * coefs;
};

attempting to manage dynamic memory with a dumb pointer. Unless you write your own copy constructor and assignment operator to correctly copy the dynamic array, copying this will simply copy the pointer, leaving both pointing to the same array.
The simplest solution is to use the standard vector container, which has the copy semantics that you'd expect:
// Better: the default copy semantics correctly copy the vector
struct Polynomial {
    Polynomial(size_t order) : coefs(order+1) {}
    std::vector<double> coefs;
};


text:
Q: multimodule maven gwt project - dependency resolution in hosted mode problem Recently I've split my GWT 2.4 application into two maven modules: domain and webapp. Domain module (according to its name) contains domain classes and webapp contains all other GWT-related stuff. Webapp depends on domain.
Everything is almost the same as described here:
http://mojo.codehaus.org/gwt-maven-plugin/user-guide/multiproject.html
When I run (from reactor):
mvn clean package

maven builds application WAR appropriately: first it compiles domain, then webapp, next creates war file which can be deployed on tomcat and works fine.
However, if I try to run application in the hosted mode:
mvn gwt:run

maven tries to resolve dependency to domain module in my local repository and remote repositories. Since I've deleted it from my local repo, maven can not find it and build (hosted mode) fails. Of course I can install domain module into my local repo first, but it's smells like a dirty workaround for me. Domain has been removed from local maven repository intentionally in order to make sure that hosted mode runs with the old (outdated) version taken from local repo, instead of working with the previously built domain artifact.
If domain module was installed in my local repository, after mvn clean package completed, webapp target directory contains exploded WAR with the recent version of domain JAR. When I run gwt:run, new version of domain artifact (in target) is replaced with the outdated one taken from local repo (I can see changes)!
How is this possible? Is it a bug in gwt maven plugin? Is there any way to avoid such strange plugin behavior?

A: might this be a solution for you?
http://mojo.codehaus.org/gwt-maven-plugin/user-guide/productivity.html
For me it works. I have different modules as well. With the help of the link I can make changes in the domain module and simply restart the hosted mode. Doesn't work for all changes though.


text:
Q: catching DbUpdateException won't catch DbUpdateConcurrencyException I have my db.SaveChangesAsync() inside a try catch block as below, but checking my logs I see a log of DbUpdateConcurrencyException but DbUpdateConcurrencyException derives from DbUpdateException.
try
{
   await _context.SaveChangesAsync();

}
catch (DbUpdateException)
{
}

But I notice the following logs:
Microsoft.EntityFrameworkCore.Update| An exception occurred in the
database while saving changes for context type 'xxx.MyContext'.
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database
operation expected to affect 1 row(s) but actually affected 0 row(s). Data
may have been modified or deleted since entities were loaded.

Didn't I catch DbUpdateConcurrencyException by catching DbUpdateException or I totally missed how exceptions work or nlog?
edit:
my nlog config:
<targets>
  <target xsi:type="File" name="all-log" layout="${longdate}|${logger}|${uppercase:${level}} ... />

  <target xsi:type="File" name="own-log" ... />
</targets>

<rules>
   <logger name="*" minlevel="Error" writeTo="all-log" />
   <logger name="Microsoft.*" minlevel="Trace" finale="true" />
   <logger name="*" minlevel="Trace" writeTo="own-log" />
</rules>

A: When you use the ASP.NET Core Logging, all components of Microsoft could write to the ASP.NET Core Logging. The NLog (NLog.Web.AspNetCore) integration will get also those logs and so you can write them to file etc.
So probably the EF component wrote that exception to the logging. You could check that by use ${stracktrace} or ${logger} in your config


text:
Q: Program type already present: com.google.gdata.util.common.base.Preconditions I am trying to integrate https://github.com/uservoice/uservoice-android-sdk/ and get the error:
Program type already present: com.google.gdata.util.common.base.Preconditions
I am trying to exclude that dependency, but not sure which module it's being pulled from.
Excluding gdata-java-client or gdata doesn't resolve the error. Any pointers to the dependency to be excluded?

A: Here you go:
compile ('com.uservoice:uservoice-android-sdk:1.2.+') {
    exclude module: 'signpost-core'
}

The 'signpost-core' dependency has a transitive dependency on 'com.google.gdata'. Since signpost-core already exists in your project, you have to exclude it.


text:
Q: short_open_tags displaying NULL values in while loop I have the following code that's supposed to use the oci_fetch_array() function to fill in some arguments for a new link to display on a website, however instead of

"
  http://website.com/reporttest.php?type=1&mode=1&dis=MECH&unit=3&rfo=20
  "

it is outputting

http://website.com/reporttest.php?type=1&mode=&dis=&unit=3&rfo=20

Notice "Mode" and "Dis" are non-existent. I'm sure I'm doing something wrong in the while loop, but I'm not too familiar with PHP to figure out why exactly this is performing the way it is.

<?
$count = 0;
?>

None

<?
while ($count < $TotalB) {
    $row = oci_fetch_array($stid, OCI_NUM);
?>

        <?= trim($row[1]) ?>	<a href="http://website.com/reporttest.php?type=1&mode=<?= urlencode($row[2]) ?>&dis=<?= urlencode(trim($row[1])) ?><?= $endofurl ?>"><?= trim($row[0]) ?>

<?
    $count = $count + trim($row[0]);
}
?>

Output from rows:
Array ( [0] => 1 [1] => [2] => )
Array ( [0] => 20 [1] => ELEC [2] => )
Array ( [0] => 1 [1] => EPCP [2] => )
Array ( [0] => 4 [1] => EPPG [2] => )
Array ( [0] => 13 [1] => I&C [2] => )
Array ( [0] => 43 [1] => MECH [2] => )
Array ( [0] => 15 [1] => MNTS [2] => )
Array ( [0] => 1 [1] => OPS [2] => )
Array ( [0] => 7 [1] => VLVT [2] => )
Array ( [0] => 1 [1] => WHSE [2] => )

$TotalB defined here:
while ($row = oci_fetch_array($stid, OCI_NUM)) {
    if (trim($row[1]) == "") {$TotalB = $row[0];}
    else if (trim($row[1]) == 0) {$Total0 = $row[0];}
    else if (trim($row[1]) == 1) {$Total1 = $row[0];}
    else if (trim($row[1]) == 2) {$Total2 = $row[0];}
    else if (trim($row[1]) == 3) {$Total3 = $row[0];}
    else if (trim($row[1]) == 4) {$Total4 = $row[0];}
    else if (trim($row[1]) == 5) {$Total5 = $row[0];}
    else if (trim($row[1]) == 6) {$Total6 = $row[0];}
}

In this case print $TotalB outputs 106.

A: try to do away from the inline php with html and also don't forget to close that h2 tag.
<?php

$data = array(
    array ( 1, "",""),
    array ( 20, "ELEC", ""),
    Array ( 1, "EPCP", ""),
    Array ( 4, "EPPG", ""),
    Array ( 13, "I&C", ""),
    Array ( 43, "MECH", ""),
    Array ( 15, "MNTS", ""),
    Array ( 1, "OPS", ""),
    Array ( 7, "VLVT", ""),
    Array ( 1, "WHSE", "")
);

//print_r($data);

$endofurl = "#"; //if you don't set this you get a notice because you call this var, i assume it's the unit=3&rfo=20 bit

// mode will be empty because you set mode=$row[2] and that last key is always empty

foreach ($data as $row){
?>

    <?= trim($row[1]) ?>	<a href="http:website.com/reporttest.php?type=1&mode=<?=urlencode($row[2])?>&dis=<?=urlencode(trim($row[1]))?><?=$endofurl?>"><?=trim($row[0])?>

<?php } ?>

or you can try without the inline php like so
<?php
while ($count < $TotalB) {
    $row = oci_fetch_array($stid, OCI_NUM);
    print'

        '.trim($row[1]).'	'.trim($row[0]).'

';

    $count = $count + trim($row[0]);
}
print '

	';

?>


text:
Q: If two vectors are normal to the same plane in $\mathbb{R}^3$, must they then be parallel to each other? Following this article on MathWorld define the plane passing through a point $x_0$ perpendicular to a vector $n$ as the set of all points $x$ satisfying
$$n \cdot (x - x_0) = 0.$$
Define a normal vector to a plane to be a nonzero vector $N$ that satisfies
$$N \cdot (x_1 - x_2) = 0$$
for all points $x_1$ and $x_2$ on the plane.
Question: Let $\alpha$ be a plane. If $N_1$ and $N_2$ are both normal vectors to $\alpha$, must they be parallel to each other (i.e., does there exist a nonzero number $c$ such that $N_1 = cN_2$)?
I've tried to resolve the question using the cross product and some linear algebra as follows: Let $x_1$ and $x_2$ be two distinct points on $\alpha$ and set $v = (x_1 - x_2) \times N_1$. Then $v$ is orthogonal to both $(x_1 - x_2)$ and $N_1$; so the set $\{v, N_1, x_1 - x_2\}$ is an orthogonal basis of $\mathbb{R}^3$. It follows that there exist numbers $c_1$, $c_2$ and $c_3$ such that
$$N_2 = c_1v + c_2N_1 + c_3(x_1 - x_2).$$
The dot product $N_2 \cdot (x_1 - x_2)$ is zero since $N_2$ is a normal vector to $\alpha$; hence
$$0 = N_2 \cdot (x_1 - x_2) = c_3\lVert x_1 - x_2 \rVert^2,$$
where $\lVert v \rVert = \sqrt{v \cdot v}$ for all vectors $v$. Since $x_1 \neq x_2$, this forces $c_3 = 0$. It remains to prove that $c_1 = 0$. I'm stuck on this point; all ideas are welcome.

A: Look at dimensions.
First, let
$$ W = \{ x_1-x_2 \mid x_1,x_2\text{ are in the plane}\} $$
It is an easy matter of algebra to see that this is the same as
$$ W = \{ x_1-x_0 \mid (x_1-x_0)\cdot n = 0 \} $$
which is a linear subspace of $\mathbb R^3$, namely the solution space of
$$ n_x x + n_y y + n_z z = 0 $$
which has dimension $2$ because it is the null space of the $1\times 3$ matrix $[n_x\;n_y\;n_z]$, and by the rank-nullity theorem the dimension must be either 2 or 3 and can be 3 only if $n=0$.
Thus, $W$ has some basis $\{w,u\}$. It should be easy to see that $N$ is a normal vector exactly if $N\cdot w=0$ and $N\cdot u=0$ -- one doesn't need to check for all members of $W$, only the two basis vectors.
This means that the set of all normal vectors is the solutions to
$$ w_x x + w_y y + w_z z = 0 \\ u_x x + u_y y + u_z z = 0 $$
which is two linear equations of three unknowns. By the rank-nullity-theorem again this solution space has dimension 1, because the matrix $$\begin{bmatrix} w_x & w_y & w_z \\ u_x & u_y & u_z \end{bmatrix}$$ has rank 2 (if the rank were any lower, $\{w,u\}$ would not be linearly independent, contradicting their being a basis for $W$).
This means the set of normal vectors is an $1$-dimensional linear subspace.
Finally, if you have two normal vectors $N_1$ and $N_2$, they must be linearly dependent, because a linear subspace cannot contain a linearly independent subset with more elements than its dimension. And if you have two linearly dependent vectors, one is always a multiple of the other.


text:
Q: Saving the state of a view after action executes I was wondering how you would save the state of a view after it runs an action that leaves for another view then comes back?
Please Help

A: Store state variables in NSUserDefaults or use NSArchive / sqlite database. Depends on what kind of state information you wish to store. Always assume your previous view will 'unload' if a new view is loaded (using presentModalView or the UINavigationController). This way you're always prepared for the worst. Under low memory conditions the view currently not visible gets its 'view' unloaded and thus you must recover your previous state yourself (you could even simply use class variables if the first view isn't destroyed).


text:
Q: Why my page not work when i add www.irctc.co.in in my url then page redirect on that site while its working good I want irctc.co.in page load in my page.Why my page not work when i add www.irctc.co.in in my url then page redirect on that site while its working good. So please tell me the thing that it do not redirect on that site that site load in my webpage.
<?php
// URLs we want to retrieve
$urls = array(
'http://www.google.com',
'http://www.bing.com',
'http://www.yahoo.com',
'http://www.twitter.com',
'http://www.facebook.com',

'www.irctc.co.in'         //it creates problem WHY

);

// initialize the multihandler
$mh = curl_multi_init();

$channels = array();
foreach ($urls as $key => $url) {
// initiate individual channel
$channels[$key] = curl_init();
curl_setopt_array($channels[$key], array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true
));

// add channel to multihandler
curl_multi_add_handle($mh, $channels[$key]);
}

// execute - if there is an active connection then keep looping
$active = null;
do {
$status = curl_multi_exec($mh, $active);
}
while ($active && $status == CURLM_OK);

// echo the content, remove the handlers, then close them
foreach ($channels as $chan) {
echo curl_multi_getcontent($chan);
curl_multi_remove_handle($mh, $chan);
curl_close($chan);
}

// close the multihandler
curl_multi_close($mh);

A: Add the https:// before the www.irctc.co.in , Also you need to enable this cURL parameter.
CURLOPT_SSLVERIFYPEER => false


text:
Q: How to ensure that is_search() return false after query_posts I know I am not supposed to use query_posts
The thing is I have a program that already do that.
query_posts("");
echo "is_search():" . is_search();
query_posts("s=kucing");
echo "is_search after():" . is_search();

Now the first echo returns empty.
The second returns 1
I wonder if there is some global variable I can set to 0 so that is_search() will return false even though I did
query_posts("s=kucing");

A: Your real big problem here is the use of query_posts. It breaks the main query object, and sets the main query object to the query made by query_posts. What you are seeing is quite normal.
Your real solution here with the use of query_posts would be is to reset the main query back to what it should be. This is where wp_reset_query() comes in. If this is a normal page, is_search() will return false after wp_reset_query() as the main query is reset to the page's main query.
query_posts( '&s=crap' );
// Do your loop as normal
wp_reset_query(); // Add this after your loop
var_dump( is_search() ); // Will return bool ( false )

Remember, use of query_posts is highly discouraged. You should be using WP_Query

A: You can use global $wp_query and set the is_search to false;
global $wp_query;
query_posts(""); //is_search is false now
query_posts("s=kucing"); //is_search is set to true
$wp_query->is_search = false; //is_search is set to false


text:
Q: html/css How to aling all pictures with same spaces. I want to make same spacing between all pictures. Their width would be the same only height differs. It should look like in the picture. example: http://prntscr.com/2ugt3z

A: do you mean something like, this will place margin of 5px on every image tag inside #content:
#content img{
 margin: 5px;
}

or make:
.image-margin{
margin: 5px;
}

and do something like:

or: http://isotope.metafizzy.co/

A: That kind of layout cannot be done using only floats, your options are:

*

*Use Flex layout (ie10+)

*Position each element manually

*Use a plugin, if you are using jquery then Isotope (http://isotope.metafizzy.co/) or Masonry (http://masonry.desandro.com/) are what you need, if you're using pure javascript, Salvattore (http://salvattore.com/) will do the trick.


text:
Q: Django haystack: elasticsearch how to delete by query ElasticSearch offers a way to delete_by_query and I see that it is being called on the clear method of the backend with:
self.conn.delete_by_query(index=self.index_name, doc_type='modelresult', body=query)

where the query is something like this:
{'query': {'query_string': {'query': "Model1 OR Model2"}}}

Now, I don't know much about ElasticSearch and I created my Index like:
class MyIndex(indexes.SearchIndex, indexes.Indexable):
    ...
    category = indexes.CharField(model_attr='category_id')
    ...

And now I want to delete from my index all the documents that match category=5 and I tried something like:
backend.conn.delete_by_query(index='haystack', doc_type='modelresult', body= {'query': {'match': {'category': '5'}}})

and it outputs something like this:

{'_version': 4, 'created': False, '_id': '_delete_by_query', '_index': 'haystack', '_type': 'modelresult', '_shards': {'successful': 1, 'failed': 0, 'total': 2}}

But it didn't delete it, I assume I need a better query, so what would it be? I also read that I can use the bulk method from ElasticSearch.
Btw I also checked that I can get a "query" from a SearchQuerySet instance with:
sqs.query.build_query()

that gives:
'category:(5)'

so it would be very helpful if I could use that query output for the delete_by_query method, but I don't know how to use it


text:
Q: emacs 256 colour support I am using ubuntu 9.04 and GNU Emacs 22.2.1
I am using the terminal to load emacs i.e. emacs -nw
However, I am only running in 8 colours.
M-X list-colors-display

Only displays 8 colours.
In the terminal I run this command
tput colors and I get 8 displayed
How can I get full 256 colour support?
Many thanks for any advice,

A: Just testing on my Debian machine, I get the same as you (8 colours).
You don't say whether you are using an xterm, but in my xterm I have typed
export TERM=xterm-256color

and then  emacs -nw followed by list-colors-display shows 256 colours.


text:
Q: Simple C++ .Net console app crashing in 64 bit Win7 My company uses a 3rd-party DLL to interface to some hardware (I've renamed it hwLib here). It was written long ago in VB6, I think. The DLL comes with an installer to register itself, etc.
We have a C# app that uses it and which runs just fine on XP and Win7, 32 or 64 bit. But I wrote a simple C++ console app which runs fine on XP/32 bit but crashes on Win7/64 bit.The console app looks like this,
#include "stdafx.h"
using namespace System;

int main(array<System::String ^> ^args)
{
    using namespace hwLib;
    ChwLib^ myLib = gcnew ChwLib();
    String^ str = myLib->GetDllVersion();
    Console::WriteLine(L"Hello hwLib");
    Console::WriteLine(str);
    Console::ReadLine();  //to keep window open til you hit the "any" key
    return 0;
}

Unhandled Exception: System.InvalidCastException: Unable to cast COM
object of type 'hwLib.ChwLibClass' to interface t ype 'hwLib._ChwLib'.
This operation failed because the QueryInterface call on the COM
component for the interface with  IID
'{E0560D1E-9A54-4EBF-83E8-D7BD2C936512}' failed due to the following
error:
No such interface supported (Exception from HRE SULT:
0x80004002 (E_NOINTERFACE)).    at
System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr
pCPCMD, Boolean& pfNeedsRelease)    at
hwLib.ChwLibClass.GetDllVersion()    at main(String[] args)    at
mainCRTStartupStrArray(String[] arguments)

The C# program, which is a much bigger and more complex program, else I would post it here, runs without problems on the same system.
COM is before my time - I took a course in it maybe 10 or 15 years ago but I don't remember it - Any suggestion on how to start debugging this?  Thanks!!

A: COM provides thread-safety guarantees for a COM component that declares itself to not support threading.  Any component written in VB6 certainly does this.  Directed by an entry in the registry named ThreadingModel.
Your test program does not provide a safe home for such a component, your console mode app creates a Multi-Threaded Apartment, MTA for short.  Which promises to not provide thread safety.  COM then creates its own STA thread to run the code for the component.  Every call to the component will be marshaled from the main thread to that helper thread.
But it then runs into a wall in your case, your component doesn't have the required proxy/stub registered.  Extra code that COM needs to figure out how to copy the method's arguments.  Easy in .NET thanks to Reflection, not in COM.  The proxy/stub is selected by entries in the HKCR\Interface registry key, a VB6 component always uses the standard marshaller that works with the type library.  The E_NOINTERFACE error code is for the IMarshal interface, COM's last gasp to find a way, not implemented by VB6.
Short from getting the registration right, the band-aid is to let your console mode app create an STA thread instead of an MTA thread.  That's very easy to do, it just takes an attribute:
[STAThread]
int main(array<System::String ^> ^args)
// etc..

COM now no longer creates that helper thread and calls don't have to marshaled.  This isn't actually enough, an STA thread must also pump a message loop.  Application::Run() as is probably used in your larger C# program.  The message loop provides the way to marshal calls, very similar to Control.BeginInvoke() and Dispatcher.BeginInvoke().  You might get away with it since you don't actually make calls on the component from another thread.  But many COM components rely on the message loop to do their own stuff.  You'll know you have a problem when you see deadlock or the component doesn't raise an event.  The VB6 code could use a Timer for example, it won't tick without that message loop.


text:
Q: How can I run Linux GUI apps on Ubuntu-touch 16.04 on Nexus 5? I have a Nexus 5 with Ubuntu-touch 16.04.
I mistakenly removed the Desktop Apps app. I can't install it again, because the open store says that my phone doesn't support the app.
So how can I run Linux GUI apps, with libertine or natively?

A: You do not need to install the scope separately any more. If you open the scopes overview/manager by swiping up from bottom edge on the dash, you can favorite the already installed desktop apps scope, to see the list of apps in your libertine containers again.


text:
Q: Displaying an image in a UICollectionViewCell I am trying to display an image on a UICollectionViewCell:
Here is the Page Class:
struct Page {
        let imageName: UIImageView
        let headerText: String
        let bodyText: String
    }

Here is where I assign the image and text to each part of the view:
func one(){
        let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))

        pages = [
            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),

            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),

            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),

            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),

            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),

            Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText")
        ]
    }

This is how I set image constraints:
  private let bearImageView: UIImageView = {
            let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))
            imageView.translatesAutoresizingMaskIntoConstraints = false
            imageView.contentMode = .scaleAspectFit
            return imageView
        }()

also
let topImageContainerView = UIView()
        addSubview(topImageContainerView)

        topImageContainerView.translatesAutoresizingMaskIntoConstraints = false

        topImageContainerView.topAnchor.constraint(equalTo: topAnchor).isActive = true

        topImageContainerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        topImageContainerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
    topImageContainerView.addSubview(bearImageView)
            bearImageView.centerXAnchor.constraint(equalTo: topImageContainerView.centerXAnchor).isActive = true
            bearImageView.centerYAnchor.constraint(equalTo: topImageContainerView.centerYAnchor).isActive = true
            bearImageView.heightAnchor.constraint(equalTo: topImageContainerView.heightAnchor, multiplier: 0.6).isActive = true

The problem is that when I run the code the text is displayed perfectly, but the image is no appearing at all.
I am totally lost with this and any help would be welcome!

A: You use a refrence type imageView inside a struct
let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))

it will be 1 item eventuallyb regardless of posts count , despite you should have
let imageName: String

or
let image: UImage

Outlets are weak so when you assign UIImageView type it won't be retained even for that 1 single imageView object

Edit : set a height constraint for topImageContainerView and a bottom to view same for the inner imageView


text:
Q: Execute HTTP call once and cache value until some condition changes I am looking to cache the result of a specific Angular2 HTTP call (getting my user profile from the server), and I want that cache to remain valid until I update the profile.
This is the code I have, which does cache the value, but never updates it, even if the profile is changed.
readonly user$: Observable<User> = this.http
    .get(`${this.baseUrl}/me`)
    .map(r => r.json())
    .publishLast()
    .refCount();

updateProfile(user: User): Observable<any> {
    return this.http.put(`${this.baseUrl}/me`, user);
    // cause the existing user$-subscriptions to update with the user value
}

Preferably I want the profile to update the existing subscriptions with the user value passed to updateProfile. Can this be done nicely in an Rx-y way, or do I have to resort to using a Subject and updating that manually?

A: I was apparently just a few minutes away from the answer. A working solution seems to be to create a Subject for user updates.
Merge that subject with the HTTP observable (that you force to only execute once). Then, on update, you put the new user value into the subject. That gets you an initial HTTP request followed by cached responses.
private readonly userSubject = new Subject<User>();
readonly user$: Observable<User> = this.userSubject
    .merge(this.http
        .get(`${this.baseUrl}/me`)
        .map(r => r.json())
        .publishLast()
        .refCount()
    );

updateProfile(user: User): Observable<any> {
    return this.http.put(`${this.baseUrl}/me`, user)
        .map(r => r.json())
        .do(() => this.userSubject.next(user));
}

Any more elegant approaches would be highly appreciated. :)


text:
Q: How to search through dictionaries? I'm new to Python dictionaries. I'm making a simple program that has a dictionary that includes four names as keys and the respective ages as values. What I'm trying to do is that if the user enters the a name, the program checks if it's in the dictionary and if it is, it should show the information about that name.
This is what I have so far:
def main():
    people = {
        "Austin" : 25,
        "Martin" : 30,
        "Fred" : 21,
        "Saul" : 50,
    }

    entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
    if entry == "ALL":
        for key, value in people.items():
            print ("Name: " + key)
            print ("Age: " + str(value) + "\n")
    elif people.insert(entry) == True:
                print ("It works")

main()

I tried searching through the dictionary using .index() as I know it's used in lists but it didn't work. I also tried checking this post but I didn't find it useful.
I need to know if there is any function that can do this.

A: Simple enough
if entry in people:
    print ("Name: " + entry)
    print ("Age: " + str(people[entry]) + "\n")

A: If you want to know if key is a key in people, you can simply use the expression key in people, as in:
if key in people:

And to test if it is not a key in people:
if key not in people:

A: You can reference the values directly. For example:
>>> people = {
... "Austun": 25,
... "Martin": 30}
>>> people["Austun"]

Or you can use people.get(<Some Person>, <value if not found>).

A: Python also support enumerate to loop over the dict.
for index, key in enumerate(people):
    print index, key, people[key]

A: You can make this:
#!/usr/bin/env python3

people = {
    'guilherme': 20,
    'spike': 5
}

entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")

if entry == 'ALL':
    for key in people.keys():
        print ('Name: {} Age: {}'.format(key, people[key]))

if entry in people:
    print ('{} has {} years old.'.format(entry, people[entry]))
else:
    # you can to create a new registry or show error warning message here.
    print('Not found {}.'.format(entry))

A: Of all of the answers here, why not:
try:
    age = people[person_name]
except KeyError:
    print('{0} is not in dictionary.'.format(person_name))

The canonical way to test if something is in a dictionary in Python is to try to access it and handle the failure -- It is easier to ask for forgiveness than permission (EAFP).

A: One possible solution:
people = {"Austin" : 25,"Martin" : 30,"Fred" : 21,"Saul" : 50,}

entry =raw_input ("Write the name of the person whose age you'd like
to know, or write 'ALL' to see all names and ages: ")

if entry == 'ALL':

    for key in people.keys():
        print(people[key])

else:

    if entry in people:
        print(people[entry])


text:
Q: AWS set alarm with reboot from Beanstalk In AWS it is possible to set an alarm for an EC2 instance, using CloudWatch to reboot, recover, stop, etc an EC2 instance based on memory, cpu, network, disk usage.
My problem is that my EC2 instances are managed by Beanstalk and when Beanstalk is replacing an EC2 instance, any alarm that is set on the instance is lost.
In Beanstalk interface, from monitoring is possible to set alarms by clicking on the bell for desired topic (CPU, memory, network, disk), but the only option for those alarms is notify, not reboot, recover, stop.
My question is: How can I set from Beanstalk alarms for EC2 instance to reboot the instance when CPU goes over 80%?

A: I believe the Beanstalk way to do it is NOT by setting an external trigger. Beanstalk is more of a closed garden, managing its own instances.
In the Beanstalk console check out Configuration>Scaling Trigger>Trigger measurement.
You'll see that there's an option to set the scaling (up/down) via CPU utilization, which is what you requested.


text:
Q: DIsplay employee working status per day of week I have a query:
SELECT
    users.name AS USER,
    TIMESHEET.timesheet_date AS DAY,
    TIMESHEET.STATUS AS STATUS
FROM TIMESHEET
JOIN users ON TIMESHEET.`rep_id` = users.`id`
WHERE WEEK(TIMESHEET.timesheet_date) = WEEK(CURDATE()) - 1

that returns the following: per employee, the working status for each date of LAST WEEK:
(sample)
USER                DAY         STATUS
Lee Fenelon         2012-07-02  Working
Tom Price           2012-07-02  Working
Kevin Duffy         2012-07-02  Working
Keith Donnelly      2012-07-02  Working
Graham Foley        2012-07-02  Sick Leave - No Medical Cert
Dominic Mallinson   2012-07-04  1/2 Day Sick Leave - No Medical Cert

What I'd like to do is modify the above so that I get 5 status per employee per week, ie STATUS_MONDAY = Working, STATUS_TUESDAY=Sick leave etc etc
The overall required output will be a report showing, for each employee, one columne per day with their working staus for that day.

A: May be Pivot Table Works for You. you can refer this link if it works


text:
Q: Error when Update QueryDefinition with SOAP API I try to update an existing SQL query activity in Marketing Cloud with SOAP API but I keep getting the same error.
The request I send is this:
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-
wssecurity-utility-1.0.xsd">
   <s:Header>
    <fueloauth xmlns="http://exacttarget.com">{{accessToken}}</fueloauth>
   </s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UpdateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
   <Options>
   </Options>
     <Objects xsi:type="QueryDefinition">
       <CustomerKey>Prod_Bronze_SK</CustomerKey>
       <Name>Prod_Bronze_SK</Name>
       <QueryText>SELECT SubscriberKey, Email, Is_Action_NL,
Is_Club_NL, Is_Fashion_NL
FROM [Prod_Bronze]
WHERE SendoutCountry = 'SK'
       </QueryText>
       <TargetType>DE</TargetType>
    <DataExtensionTarget>
     <PartnerKey xsi:nil="true">
     </PartnerKey>
     <ObjectID xsi:nil="true">
     </ObjectID>
     <CustomerKey>Prod_Bronze_SK</CustomerKey>
     <Name>Prod_Bronze_SK</Name>
     </DataExtensionTarget>
     <TargetUpdateType>Overwrite</TargetUpdateType>
   </Objects>
  </UpdateRequest>

I always get back this response:
<Results>
  <StatusCode>Error</StatusCode>
  <StatusMessage>Exception occurred during [UpdateQueryDefinition] ErrorID: 148844611</StatusMessage>
  <OrdinalID>0</OrdinalID>
  <ErrorCode>2</ErrorCode>

In the documentation I found this for that Error code:

You may encounter this error code on a SOAP fault during authentication (login has an unexpected exception). Log error information and contact Marketing Cloud support.

So it seems like there is a problem with the authentication.
I tried to process my call with token authentication and also with Username/PW authentication.
With both authentication types I could perform create requests.
In the QueryDefinition documentation page I found this (and set the permissions accordingly for my API user - with no change in result):

To update a QueryDefinition where the CategoryID is greater than 0, you need the Email | Interactions | Activities | Query | Move permission.

For the Token authentication, I enabled all rights in the API package.
Can anyone help me finding the cause of the error?
Do I need to set additional rights?
Is there an error in my request?
Thanks for your answers!
Best regards,
Sebastian

A: To successfully update a QueryDefinition using SOAP, I had to include (1)the account's MID and (2)the query activity's ObjectID. I found the ObjectID by hovering over the link to the query activity in Email Studio, down in the browser's status bar — it'll be the "id" query parameter value.
<Objects xsi:type="QueryDefinition">
  <Client>
    <ID>{{ mid }}</ID>
  </Client>
  <ObjectID>{{ id }}</ObjectID>
  <CustomerKey>Prod_Bronze_SK</CustomerKey>
  ...

A: I came across this post whilst trying to troubleshoot an upsert issue.
We had the same error which we solved by creating an MID/Business Unit specific endpoint/package.
With this we noticed we did not need to specify the Client ID
Edit: MID is the company account ID or 'Business Unit' you're assigned in Marketing Cloud. You can find it by navigating to the top bar, then clicking the Down arrow next to your company/account name
Otherwise you can inspect and search for the following:

MID: 11111212

Finding out which package you have assigned to which MID:
1. Nav to top right
2. Click user, dropdown should appear
3. Click Administration (if you don't have access to it, an admin will need to do this)
4. new page will load. Go to Account -> Installed packages
5. Select the package you're using to interact with SFMC from the list
6. look for 'Business Unit'


text:
Q: HTML5 canvas break up image My overall aim is to make a sliding puzzle piece game. Using the canvas, I have managed to split up the image into multiple pieces. In order to shuffle the pieces, I wrote the co-ordinates of the pieces into an array, shuffled the co-ordinates, and re-drew the image on the canvas. However, the puzzle ends up with some pieces being duplicated! I have no idea why?!
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("map");

//img,sx,sy,swidth,sheight,x,y,width,height

function recreate_map(){

ctx.drawImage(img,0,0,133,100,0,0,133,100);
ctx.drawImage(img,133,0,133,100,133,0,133,100);
ctx.drawImage(img,266,0,133,100,266,0,133,100);

ctx.drawImage(img,0,100,133,100,0,100,133,100);
ctx.drawImage(img,133,100,133,100,133,100,133,100);
ctx.drawImage(img,266,100,133,100,266,100,133,100);

ctx.drawImage(img,0,200,133,100,0,200,133,100);
ctx.drawImage(img,133,200,133,100,133,200,133,100);
ctx.drawImage(img,266,200,133,100,266,200,133,100);
}

 function shuffle_array(arr){
  var i = arr.length;

  while(--i>0){
    var n = Math.floor(Math.random()*(i));
    var temp = arr[n];
    arr[n] = arr[i];
    arr[i] = temp;
  }

  return arr;
}

function shuffle_tiles(){
  var positions_x = [0,133,266,0,133,266,0,133,266];
  var positions_y = [0,0,0,100,100,100,200,200,200];

  shuffle_array(positions_x);
  shuffle_array(positions_y);

ctx.drawImage(img,0,0,133,100,positions_x[0],positions_y[0],133,100);
ctx.drawImage(img,133,0,133,100,positions_x[1],positions_y[1],133,100);
ctx.drawImage(img,266,0,133,100,positions_x[2],positions_y[2],133,100);
ctx.drawImage(img,0,100,133,100,positions_x[3],positions_y[3],133,100);
ctx.drawImage(img,133,100,133,100,positions_x[4],positions_y[4],133,100);
ctx.drawImage(img,266,100,133,100,positions_x[5],positions_y[5],133,100);
ctx.drawImage(img,0,200,133,100,positions_x[6],positions_y[6],133,100);
ctx.drawImage(img,133,200,133,100,positions_x[7],positions_y[7],133,100);
ctx.drawImage(img,266,200,133,100,positions_x[8],positions_y[8],133,100);

}

If it helps, I'm using JS Bin, on Firefox. Thanks.

A: You need to clear the canvas for each redraw or else the previous content will remain.
Try this:
function recreate_map(){

    /// call this first
    ctx.clearRect(0, 0, c.width, c.height);

    ctx.drawImage(img,0,0,133,100,0,0,133,100);
    ...


text:
Q: Fast enumeration with NSDictionary holding NSDictionary objects I have an NSDictionary with four objects. Each object is an NSDictionary containing thousands of objects. I have verified through logging of the description of the top level dictionary that it contains what it is supposed to. However, when I run the code below, to enumerate the objects in that top level dictionary, the debugger is showing an error, indicating that the returned object is a sting rather than a dictionary.
Here is the code:
for(id synsetsForPos in dictionaryOfSynsetDictionaries) {
    NSLog(@"synsetsForPos is class of %@ with description %@", [synsetsForPos class], [synsetsForPos description]);

(I originally typed synsetsForPos as NSDictionary, but the results described here are the same.)
In the debugger, I halt at the log statement to get this in the console:
(lldb) po [synsetsForPos class]
(id) $2 = 0x016e2c8c __NSCFConstantString
(lldb) po [[dictionaryOfSynsetDictionaries objectForKey:@"n"] class]
(id) $3 = 0x016d3e0c __NSCFDictionary
(lldb) po [[dictionaryOfSynsetDictionaries objectForKey:@"r"] class]
(id) $6 = 0x016d3e0c __NSCFDictionary
(lldb) po [[dictionaryOfSynsetDictionaries objectForKey:@"v"] class]
(id) $7 = 0x016d3e0c __NSCFDictionary
(lldb) po [[dictionaryOfSynsetDictionaries objectForKey:@"a"] class]
(id) $8 = 0x016d3e0c __NSCFDictionary
(lldb) po [dictionaryOfSynsetDictionaries allKeys]
(id) $10 = 0x653662a0 <__NSArrayI 0x653662a0>(
r,
n,
v,
a
)

Then, letting the log statement execute, I get this:
2012-11-24 22:32:41.069         [6037:fb03] synsetsForPos is class of __NSCFConstantString with description r
(lldb)

followed by this error message:
2012-11-24 22:41:21.287         [6037:fb03] -[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1faf8

I don't understand what's going on here, why this is not being treated as a dictionary in the fast enumeration code.

A: Fast enumeration of a dictionary iterates over keys not objects: documentation.
Use enumerateKeysAndObjectsUsingBlock:
 instead. It is probably just as fast - see discussion here.

A: In fast enumeration of dictionaries in Objective-C are returned values of keys. In your example, your for-loop is the same as for(NSString *synsetsForPos in [dictionaryOfSynsetDictionaries keys]).
What you need to add is get value for a particular key and work with it:
NSDictionary *value = [dictionaryOfSynsetDictionaries valueForKey:synsetsForPos];

A: The question is old but for future travelers another simple solution is to just specify the dictionary values in the for clause:
for(NSDictionary *synsetsForPos in [dictionaryOfSynsetDictionaries allValues]) {
    NSLog(@"synsetsForPos is class of %@ with description %@", [synsetsForPos class], [synsetsForPos description]);
}


text:
Q: Ssh console prints ^H when pressing the return key I did not know if I had to post that in a more system specific stack exchange. So please inform me where to go if this question does not belong here.
I am using mobaXterm tu SSH into a server. It worked fine for the last week, but since today, I have a behavior modification.
When I press the return key, it prints ^H instead of deleting previous character.
For example:
# cd bni/^H^H^H

Why did it suddenly change and how can I configure it to actualy delete the character instead of printing this ?
Edit: With a new terminal, the "problem" does not occur.

A: In MobaXterm's changelog https://mobaxterm.mobatek.net/download-home-edition.html, you can see they added a New option for sending ^H when pressing the backspace key in Version 3.0. It has a checkbox setting 'Backspace sends ^H' in Settings --> Terminal tab.
You can also use Shift+Backspace to remove a character.

A: You could also use the stty command to set your erase character:
stty erase {press backspace to get the ^H character}

You may need to include this in your login scripts to make it permanent.


text:
Q: Problem on continuous probability distribution Problem:We  pick two random numbers, x and y, between 0 and 2. What is the probability that x*y<1 AND y/x<1.
I am familiar with continuous probability distributions for one variable, but it seems to me that I have to handle two variables, and I have no idea how. Any help would be appreciated
Apostolos

A: Let random variables $X$ and $Y$ be the numbers picked. We will need to assume that $X$ and $Y$ are independent.
Draw the square with corners $(0,0)$, $(2,0)$, $(2,2)$, and $(0,2)$. Our joint density function is $\frac{1}{4}$ in this square and $0$ elsewhere.
Draw the line $y=x$ and the part of the hyperbola $xy=1$ that lies in the first quadrant.
Shade in the part of the square that is below $y=x$ and below the hyperbola. Our answer is the area of this shaded region $D$, times $\frac{1}{4}$. Another way of putting it is that our probability is
$$\iint_D \frac{1}{4}\,dy\,dx.$$
We use the area approach. To find the area, note that $y=x$ and $xy=1$ meet at $(1,1)$. So the area of $D$ is
$$\int_0^1 x\,dx+\int_1^2\frac{dx}{x}.$$
Integrate. We get $\frac{1}{2}+\ln 2$. for the probability, divide by $4$.


text:
Q: how to jump to another jade file from a jade file using hyperlink //in index.jade
a(href="another.jade") //I try this way,but it don't work
I put two jade files into same directory,how to jump to anther jade file form index jade file using hyperlink,not use redirect!
Thanks a lot!


text:
Q: Covariance between ordinal variable and discrete variable I have two variables $y$ and $p$. Since $p$ is a discrete variable (numeric vector) and $y$ is an ordinal variable (total time watching TV).
  Values and categories of the variable y
  00 No time at all
  01 Less than 0,5 hour
  02 0,5 hour to 1 hour
  03 More than 1 hour, up to 1,5 hours
  04 More than 1,5 hours, up to 2 hours
  05 More than 2 hours, up to 2,5 hours
  06 More than 2,5 hours, up to 3 hours
  07 More than 3 hours

I want to calculate the covariance between $p$ and $y$ , so my questions are :

*

*Is Kendall's Tau the advisable to calculate the correlation between $y$ and $p$ ?, or does it make sense if I categorize the vector $p$ according to intervals (convert it into ordinal data ) , then calculate Kendall's Tau correlation ?.

*How can I calculate the variance of $y$ ?.


text:
Q: Tensorflow: MultiGPU Training on a Portion of the Graph All code is assuming Tensorflow 1.3 and Python 3.x
We are working on a GAN algorithm which has an interesting loss function.
Stage 1 - Compute only the completion/generator loss portion of the network
          Iterates over the completion portion of the GAN for X iterations.

Stage 2 - Compute only the discriminator loss portion of the network
          Iterates over the discriminator portion for Y iterations (but
          don't train on Stage 1)

Stage 3 - Compute the full loss on the network
          Iterate over both completion and discriminator for Z iterations
          (training on the entire network).

We have this working single GPU.  We want to make it work multi GPU since training times are long.
We have looked at the Tensorflow/models/tutorials/Images/cifar10/cifar10_multi_gpu_train.py, which talks about tower loss, averaging the towers together, computing your gradients on the GPUs then applying them on the CPU.  This is a great start.  However, since our loss is more complicated, it has complicated everything a bit for us.
The code is decently complicated, but is roughly similar to this, https://github.com/timsainb/Tensorflow-MultiGPU-VAE-GAN, (but that won't run because it was written around Tensorflow 0.1, so it has some oddities that I haven't gotten working, but that should give you an idea of what we're doing)
When we compute gradients, it looks something like this (pseudocode to try to highlight the important portions):
for i in range(num_gpus):
    with tf.device('/gpu:%d' % gpus[i]):
        with tf.name_scope('Tower_%d' % gpus[i]) as scope:
            with tf.variable_scope( "generator" )
                generator = build_generator()

        with tf.variable_scope( "discriminator" ):
            with tf.variable_scope( "real_discriminator" ) :
                real_discriminator = build_discriminator(x)

            with tf.variable_scope( "fake_discriminator", reuse = True ):
                fake_discriminator = build_discriminator(generator)

        gen_only_loss, discm_only_loss, full_loss = build_loss( generator,
            real_discriminator, fake_discriminator )

        tf.get_variable_scope().reuse_variables()

        gen_only_grads = gen_only_opt.compute_gradients(gen_only_loss)
        tower_gen_only_grads.append(gen_only_grads)

        discm_only_train_vars= tf.get_collection(
            tf.GraphKeys.TRAINABLE_VARIABLES, "discriminator" )
        discm_only_train_vars= discm_only_train_vars+ tf.get_collection(
            tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES, "discriminator" )

        discm_only_grads = discm_only_opt.compute_gradients(discm_only_loss,
            var_list = discm_only_train_vars)
        tower_discm_only_grads.append(discm_only_grads)

        full_grads = full_opt.compute_gradients(full_loss)
        tower_full_grads.append(full_grads)

# average_gradients is the same code from the cifar10_multi_gpu_train.py.
We haven't changed it.  Just iterates over gradients and averages
them...this is part of the problem...
gen_only_grads = average_gradients(tower_gen_only_grads)
gen_only_train = gen_only_opt.apply_gradients(gen_only_grads,
global_step=global_step)

discm_only_grads = average_gradients(tower_discm_only_grads)
discm_only_train = discm_only_opt.apply_gradients(discm_only_grads,
    global_step=global_step)

full_grads = average_gradients(tower_full_grads)
full_train = full_opt.apply_gradients(full_grads, global_step=global_step)

If we call only "compute_gradients(full_loss)", the algorithm works properly on multiple GPUs.  This is pretty equivalent to the code in the cifar10_multi_gpu_train.py example.  The tricky part comes when need to restrict the network in stage 1 or 2.
Compute_gradients(full_loss), has a var_list parameter with a default value of None, which means it trains all the variables.  How does it know to not train Tower_0 variables when in Tower_1?  I ask, because when we deal with the compute_gradients( discm_only_loss, var_list = discm_only_train_vars), I need to know how to gather up the correct variables to restrict training to that portion of the network.  I found one thread talking about this, but found it to be inaccurate/incomplete - "freeze" some variables/scopes in tensorflow: stop_gradient vs passing variables to minimize.
The reason being, that if you look at the code in compute_gradients, var_list is filled out with is a combination of trainable variables and trainable resource variables when None is passed in.  So that's how I've limited it as well.  This all works properly if we don't attempt to split across multiple GPUs.
Question 1:
Now that I've split the network  by towers, am I responsible for gathering up the current tower as well?  Do I need to add a line like this?
discm_only_train_vars= tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, "Tower_{}/discriminator".format( i ) )
discm_only_train_vars= discm_only_train_vars + tf.get_collection( tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES, "Tower_{}/discriminator".format( i ) )

In order to train the proper variables for tower (and ensure I don't miss the training of those variable?)
Question 2:
Probably the same answer as question 1.  Getting "compute_gradients(gen_only_loss)" is a bit harder...in the non towered version, gen_only_loss never touched the discriminator, so it activated the tensors in the graph that it needed and everything was fine.  However, in the towered version, when I call "compute_gradients", it returns gradients for tensors it hasn't activated yet - so some of the entries are [(None, tf.Variable), (None, tf.Variable)].  This causes average_gradients to crash because it can't convert a None value to a Tensor.  This makes me think I need to restrict these as well.
The confusing thing about all of this is that the cifar example, and my full_loss example does not care about training on specific towers, but I'm guessing once I specify a var_list, any magic that compute_gradients was using to know which variables to train on which towers disappear?  Do I need to worry about grabbing any other variables?

A: For question 1, you are responsible for gathering if you split manually, yes.
For question 2 you might want to restrict the call to compute_gradients or filter the result.


text:
Q: Carriage return on button How can I add a carriage return on the label below after Submit and before abs($model->total)?
This is a yii bootstrap button.  I have tried combos of \n\r and <br /> put those just appear in the button then...tried with using both "" and ''
 $this->widget('bootstrap.widgets.TbButton',array(
        'htmlOptions' => array('class'=>'btn'),
        'label' => 'Submit'.abs($model->total),
        'url' => array('/myPage'),
    ))

;

A: I think you need to set this to false
encodeLabel boolean true    Whether the label should be encoded.


text:
Q: Convert Numbers to Numbers and Letters in PHP I have the following number 353711000 and I need to convert it to 35371TH in PHP.
How would I go about this?

A: Without regular expressions:
$i = 353711000;
if ($i % 1000 == 0) {
    $s = strval($i / 1000) . 'TH';
} else {
    $s = strval($i);
}
print_r($s);


text: Q: Desktop application needs to support all versions of SharePoint and SPO I am connecting to the different SharePoint environments using the CSOM. Whats the best way to deploy the available DLLs to support all SharePoint environments? Do I need to dynamically instantiate objects based on the SharePoint version selected?


text:
Q: Recursively update parent and sort item value I am sending an object array to the server side for drag and drop menu ordering. I want to update each menu item's parent_id and it's sort value into my database and all root items parent will be 0, but I can't define my function correctly.
[
    {
        "id": 2,
        "children": [
            {
                "id": 1,
                "children": [
                    {
                        "id": 3,
                        "children": []
                    }
                ]
            }
        ]
    },
    {
        "id": 4,
        "children": [
            {
                "id": 5,
                "children": []
            }
        ]
    }
]

I have tried with
public static function sort($menus, $parent_id = 0)
{
    $i = 0;
    foreach ($menus as $menu) {
        $menuItem = MenuItem::find($menu['id']);
        $menuItem->parent_id = $parent_id;
        $menuItem->sort = $i;
        $menuItem->save();
        $i += $i;
        if (count($menu['children'])) {
            MenuController::sort($menus, $menu['id']);
        }
    }
}

public function postSaveMenuOrder(Request $request)
{
    if ($request->has('menu-data')) {
        $menuData = $request->get('menu-data');
        MenuController::sort($menuData);
    }
}

A: Your array contains objects but you are trying to use them as arrays:
public static function sort($menus, $parent_id = 0)
{
    foreach ($menus as $key => $menu) {
        $menuItem = MenuItem::find($menu->id);
        $menuItem->parent_id = $parent_id;
        $menuItem->sort = $key;
        $menuItem->save();

        if (count($menu->children)) {
            // note that here we are passing the children of the menu,
            // not all the menus as in your example
            self::sort($menu->children, $menu->id);
        }
    }
}

Also you can use the key instead of a the $i variable.


text:
Q: NoClassDefFoundError: javax/mail/Session I'm trying to send an email filled with data from the form. Currently trying to do with Gmail, the goal is to send from the local server. But it throws me an exception. I have added .jar into lib. Sorry if the question is stupid, im novice.
How to fix it step by step?

    public void sendMail(String from, String password, String recipient, FormModel formModel) {
            Properties properties = new Properties();

            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls", "true");
            properties.put("mail.smtp.host", "smtp.gmail.com");
            properties.put("mail.smtp.port", "587");

            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, pass);
                }
            });

            Message message = pmessage(session, from, recipient);
            try {
                Transport.send(message);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

        private Message pmessage(Session session, String myaccount, String recipient) {
            Message message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(myaccount));
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                message.setSubject("formular");
                message.setText("TEST");
                return message;
            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
    }

lib

Expected output is sent mail.

A: Try one of the following. Worked for me earlier for a similar issue:

*

*Along with mail.jar add the activation.jar to your classpath.
[http://repo2.maven.org/maven2/javax/activation/activation/1.1.1/activation-1.1.1.jar]
OR

*

*Click File from the toolbar

*Project Structure

*Select Modules at the left panel

*Dependencies tab Select '+' → JARs or directories


text:
Q: Rams and DQ lines I'm studying DRams and SRams at university and on the slides the lines where a data is read or written is called DQ. But whats does it means? Maybe D is for Data, but Q?

A: I think that the origin of the name comes from the convention for flip flops. On a D flipflop the data in pin is generally called D, and the data out pin, Q. Since the memories data bus is bidirectional, a data pin can be D when it is input or Q when it is output hence the name DQ.

A: I quote from this IBM article - http://www.archive.ece.cmu.edu/~ece548/localcpy/sramop.pdf
The DQ pins are used for data input and output. DQs on SRAMs come in two forms — on some devices, the inputs and outputs are separate, on others, they are common, with the input and output using the same pin on the memory device. All of IBM Microelectronics' SRAM offerings have common I/O.
Edit: Q is the normal designation for the output line of a flip flop, counter etc. D stands for Data.


text:
Q: Given an $n \times n $ grid, how many squares exist? How many squares exist in an $n \times n$ grid?  There are obviously $n^2$ small squares, and $4$ squares of size $(n-1) \times (n-1)$.
How can I go about counting the number of squares of each size?

A: Another way to view this: for each size, there is one square that you move inside the larger one.
How much can it move? A square of size $k\times k$ inside a square of size $n\times n$ has $n-k+1$ possible positions in each direction (up-down and left-right): consider the position of the top left corner for instance. Hence there are $(n-k+1)^2$ such squares.
Can you finish from here?

A: NOTE:
For $n\times n$ grid the answer is $n^2+(n-1)^2+(n-2)^2+.....+1^2$
So, the answer is
$$
\frac{n(n+1)(2n+1)}{6}
$$

A: Another way of counting:
For each
$(i, j, k)$
with
$1 \le i, j \le n$
and
$0 \le k \le \min(n-i, n-j)$
there is a square
with upper left corner
at $(i, j)$
and lower right corner at
$(i+k, j+k)$.
Therefore the total is
$\begin{array}\\
s(n)
&=\sum_{i=1}^n \sum_{j=1}^n (1+\min(n-i, n-j))\\
&=\sum_{i=0}^{n-1} \sum_{j=0}^{n-1} (1+\min(i, j))\\
&=n^2+\sum_{i=0}^{n-1} \sum_{j=0}^{n-1} \min(i, j)\\
&=n^2+\sum_{i=0}^{n-1} (\sum_{j=0}^{i-1} \min(i, j)+\sum_{j=i} \min(i, j)+\sum_{j=i+1}^{n-1} \min(i, j))\\
&=n^2+\sum_{i=0}^{n-1} (\sum_{j=0}^{i-1} j+i+\sum_{j=i+1}^{n-1} i)\\
&=n^2+\sum_{i=0}^{n-1} (\frac12i(i-1)+i+i(n-1-(i+1)+1))\\
&=n^2+\sum_{i=0}^{n-1} (\binom{i}{2}+i+i(n-i-1))\\
&=n^2+\binom{n}{3}+\frac12 n(n-1)+\sum_{i=0}^{n-1} (ni-i(i+1))\\
&=n^2+\binom{n}{3}+\frac12 n(n-1)+\frac12 n^2(n-1)-\sum_{i=1}^{n} i(i-1)\\
&=n^2+\binom{n}{3}+\frac12 n(n-1)+\frac12 n^2(n-1)-2\binom{n+1}{3}\\
&=\frac13(n+1)n(n-1)\\
\end{array}
$

A: Let the vertices of the $n \times n$ grid by $\{(x,y)| 0\le x \le n; 0 \le y \le n\}$.
(Is that what an $n \times n$ grid is?  A $1 \times 1$ has $4$ vertices and an $n \times n$ grid has $(n+1)^2$ vertices?  Or is a $1 \times 1$ grid a single point?  I'm assuming the former.)
A $k \times k$ square will have an lower left hand vertex as $(x,y)$ and a upper right hand vertex at $(x+k, y+k)$ with the stipulation $0 \le x; 0 \le y; x+k \le n; y+k \le n$ or in other words: $0 \le x \le n-k; 0 \le y \le n-k$.
There are $n-k+1$ possible options for $x$ and $n-k+1$ options for $y$ so there $(n-k+1)^2$ $k\times k$ squares.
So the total number of squares is $\sum{k=1}^n(n-k+1)^2$.  Let $j = n-k+1$ and we have #squares = $\sum_{j = n;j--}^1j^2 = \sum_{j=1}^n j^2 = \frac{n(n+1)(2n+1)}6$
Or to put it more simply.... A $k \times k$ square has a side of length $k$.  There are $n-(k-1)$ ways to choose this side from the grid that is $n$ long so for squares of lengths $1,2, ...., n$ there are $n, n-1....., 1$ way to choose the horizontal side and $n, n-1,...., 1$ ways to choose the vertical sides.  So there are $n^2, (n-1)^2,....., 1^2$ possible $1\times 1, 2\times 2, ...,n \times n$ squares. So there are $\sum k^2 = \frac{n(n+1)(2n+1)}6$ total squares.


text:
Q: Cannot use webService Copy I want to move some xls file to SP 07 server (C:\folderPath) and i find some web services can do that.
I found that the we can call the Copy class from here with the URL http:///_vti_bin/Copy.asmx(ref.) to upload files to specific folder path. However, i got an error when connect to destination Url.
The error message is:

The request failed with HTTP status 401: Unauthorized.

Does anyone know how to use the Copy web service to move file to to SP 07 server?


text:
Q: Calculate age in excel I have a date of birth in excel 23-05-2015(dd/mm/yyyy) and I need to calculate age.I tried the formula =DATEDIF(C3,TODAY(),"Y") but am getting an error as #VALUE!.When I evaluate the formula it shows as =DATEDIF("23/05/2015",42866,"Y").
I guess it is because of date format (dd/mm/yyyy), is there any method where I can achieve this.

A: Simply write =Today-C3 and then press Ctrl+1 and select Number for the format. The answer is in days.
Or try like this:
=DATEDIF(DATE(YEAR(A24),MONTH(A24),DAY(A24)),TODAY(),"Y")

A: You need to convert string to date inside DATEDIF():
=DATEDIF(DATE(RIGHT(A1,4),MID(A1,4,2),LEFT(A1,2)),TODAY(),"y")

And if you love big formulas:
=DATE(RIGHT(A1,LEN(A1)-FIND("@",SUBSTITUTE(A1,"-","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"-","")))))),MID(A1,FIND("-",A1)+1,FIND("@",SUBSTITUTE(A1,"-","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"-","")))))-FIND("-",A1)-1),LEFT(A1,2))

A: I used the following formula which returned me the correct answer in years.
=DATEDIF(DATE1, DATE2, "Y")
You can use the following link to get the required info.
https://exceljet.net/excel-functions/excel-datedif-function
You can check the screenshot here


text:
Q: redux - reducer -- change property of an object within an array i need change property of an object within an array that is part of another object in me reducer ,
I'm going to show you that I tried and I was unsuccessful but the truth is that I don't know if it is possible to change that property
function
 function handleQuantity(e) {
    if (e.target.name === "resta" && quantityProduct > 0) {
      setQuantityProduct(quantityProduct - 1);
    }
    if (e.target.name === "suma" && quantityProduct < props.stock) {
      setQuantityProduct(quantityProduct + 1);
    }
    const actionquantity = {
      orderlineId: props.id,
      orderlineQuantity: quantityProduct,
    };
    props.changequantity(actionquantity);
  }

executor
  function handleChangeQuantity(actionquantity){
      dispatch(changeQuantityProductLine(actionquantity , id))
    }

action
export const changeQuantityProductLine = (actionquantity, userId) => async(dispatch) =>{
    try{
        dispatch({type: CHANGE_QUANTITY_PRODUCT_LINE})

        const {data} = await axios.put(`${url}users/${userId}/cart`, actionquantity);
        console.log('-----------------------------------------------------------------------------------------------------------------------------------',actionquantity)
        dispatch({
            type: CHANGE_QUANTITY_PRODUCT_LINE_SUCCESS,
            payload: actionquantity
        })
    }catch(error){
        dispatch({
            type: CHANGE_QUANTITY_PRODUCT_LINE_ERROR,
            payload:
            error.response && error.response.data.message
            ? error.response.data.message
            : error.message,
        })
    }
}

reducer

export const orderlineByIdReducer = (
  state = {
    //cart: []
    order: {},
    error: null,
    loading: false,
  },
  action
) => {
  switch (action.type) {
    case ORDER_LINE_BY_ID:
      return { ...state, loading: true};
    case ORDER_LINE_BY_ID_SUCCESS:
      return {...state, loading: false, order: action.payload };
    case ORDER_LINE_BY_ID_ERROR:
      return {...state, loading: false, error: action.payload };
    case REMOVE_ORDER_LINE_BY_ID:
      return { ...state, loading: true };
    case REMOVE_ORDER_LINE_SUCCESS:
      return {
        ...state,
        order: {...state.order, orderlines: state.order.orderlines.filter(
          (orderline) => orderline.product.id != action.payload
        ), }
      };
    case REMOVE_ORDER_LINE_ERROR:
      return {...state, loading: false, error: action.payload };
      case CHANGE_QUANTITY_PRODUCT_LINE:
        return { ...state, loading: true };
      case CHANGE_QUANTITY_PRODUCT_LINE_SUCCESS:
        return {
          ...state,
           order: {...state.order, orderlines: state.order.orderlines.map(
             orderline => orderline.id === action.payload.actionquantity.orderlineId
              ? Object.assign({}, orderline, {quantity: action.payload.actionquantity.orderlineQuantity})
              : orderline) }
          }
      case CHANGE_QUANTITY_PRODUCT_LINE_ERROR:
        return {...state, loading: false, error: action.payload };

    default:
      return state;
  }
};

With that attempt the action breaks, but taking out what I put in the reducer works fine ... I suspect that I am not managing to change the property of that orderline

A: It doesn't look like your payload has actionquantity as a property. The payload is the actionquantity. So, action.payload.actionquantity.orderlineId should be action.payload.orderlineId.


text:
Q: How to specify output folder for self-extracting ZIP file extracting ZIP files that have been created using:
PKSFX(R)  Version 2.50  FAST!  Self Extract Utility for Windows 95/NT 4-15-1998
Is there an option to specify which folder the files contained in the EXE should be extracted to?
By typing "/help" I was able to find some useful options (like Overwrite, Exclude, etc.), but I cannot see anything related to the Output Folder.
Any suggestion?
Thank you!

A: I found the following over at ousob.com.  It appears as part of a larger article which seems to have the documentation for the whole PKSFX suite.  It looks like you run the executable and then specify any flags followed by the path to extract to and, optionally, specific named files from within the archive to be extracted if you don't want them all.
PKSFX Command Summary
Command line syntax and options are the same as PKUNZIP.  The options
listed below are offered by a self-extracting file.
Syntax: pksfx [option] [d:\path] [file]* [file]*
PKSFX indicates the name of the self-extracting file you are executing.
No options are necessary if you wish to simply extract all files to the
current directory.  If you wish to extract the contents to another
directory, indicate the drive and/or path the files should extract to.  To
extract only particular files, indicate the name(s) at the end of the
command line.
Options:
 @listfile.lst            Specify list of files for extraction*

 -c[m]                    Extract to console*

 -d                       Re-create directories stored in .ZIP file*

 -l                       Display software license agreement*

 -n                       Extract only newer files*

 -o                       Overwrite existing files

 -p[a|b][c][#]            Extract to printer*

 -s<password>             Decrypt with password*

 -t                       Test file integrity*

 * Indicates options not available in the PKSFX Junior and PKUNZIP Junior
   programs.

Options should be placed after the self-extracting files name.  If
multiple options are used they must be separated by a space and each must
have its own option indicator (either - or /).
All options behave in the same manner as they do with PKUNZIP, with one
exception.  The -s option cannot accept keyboard entry.  A password
entered with a self-extracting file must be able to be entered from the
command line.


text:
Q: Text editor disappeared in LibreOffice Math Here is a screen shot that shows that the text editor of writing equations is missing.
How can I retrieve it?
Thanks in advance

A: One slightly blunt fix is to close all of your LibreOffice windows down and then rename your user details. This will allow LibreOffice to receate the defaults which may be enough to bring your window back!
Trusty Tahr has LibreOffice 4 so for this Ubuntu release run the following:
mv -v $HOME/.config/libreoffice/4/user $HOME/.config/libreoffice/4/user_bak

Then reopen LibreOffice Math and hopefully all will be well...


text:
Q: Copy NULL values present in csv file to postgres I have csv file (y.csv) in the folowing format:
 's', '1999-10-10', '1999-12-12'
 'b', '99-10-10 BC', '1-10-10 BC'
 'c', 'NULL', 'NULL'

I have a few NULL values (for date) in it which I have indicated through the string 'NULL'.
I am trying to copy the csv file into postgres. For doing so I have created a table:
create table r (id character varying(255), timebegin date, timeend date);

Now I am trying to copy the above .csv file into postgres using the command
copy r from '/home/y.csv' delimiter ',' csv;
ERROR:  invalid input syntax for type date: " 'NULL'"
CONTEXT:  COPY r, line 1, column timebegin: " 'NULL'"

On doing so I am getting an error with NULL. Can someone please help me figure out the error and correct it.

A: after giving the path of the file, we need to use 'With' before adding other paramters -
copy r from '/home/y.csv' with delimiter ','  NULL AS 'null' csv header;

A: Have you tried it?
 copy r from '/home/y.csv' delimiter ',' csv WITH NULL AS 'null';

A: The error is because you are inserting NULL as string. Remove the quotes around NULL and it should work.

A: 1st
Replace all NULL with ' ' (Space).
Then
COPY r FROM '/home/y.csv' WITH DELIMITER ',' NULL as ' ' CSV;


text:
Q: Parse Push on WP 8.1 I'm using ionic/cordova to build an app and I've chosen Parse to handle Push Notifications. It works well on iOS and Anrdoid, but it won't work on WP 8.1.
I know 8.1 is not officially supported by Parse. Is there anyway I could still use it? Like with an C# plugin I could write myself?
Are there any other push services I could use for WP 8.1? Probably with a REST API?

A: I'm not familiar with Parse but you said a REST API would be fine. In this case the easiest approach would be an Azure Mobile Service. Depending on the number of push notifications Mobile Services and Notifications Hubs are even free.
Here is what you have to do:

*

*Create a free Azure Account

*Create a Mobile Service (I am using .Net but you can also use JavaScript for the "backend")

*Open your Mobile Service in Visual Studio and create a new "custom api". Here is a step by step tutorial on how to do this: CustomAPIs - Azure

*You now have a REST API that you can call form your server.

*To send your push notification just use something along the lines of this in your custom api and you are ready to go Add push notifications - Azure:

var hub = NotificationHubClient.CreateClientFromConnectionString("YOUR_NOTIFICATIONHUB_ENDPOINT", "YOUR_NOTIFICATIONHUB_NAME");
notification = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
           @"<toast><visual><binding template=""ToastText01"">" +
           @"<text id=""1>YOUR TEXT</text>" +
           @"</binding></visual></toast>";

await hub.SendWindowsNativeNotificationAsync(notification, tags);

With tags you can specify who receives the notifications. Use the tags as UserIds to send targeted notifications.

A: The push service I use for WP 8.1 (and iOS and Android too) is Azure mobile services.  Their push notification hub makes it really simple on the backend to support all three platforms without issue.  On the client side they have an Azure plugin that uses the existing Phonegap Push plugin.

A: I know 8.1 is not officially supported by Parse. Is there anyway I could still use it? Like with an C# plugin I could write myself?

You can just include WinRT libraries in Windows Phone 8.1 project. It's works perfectly!


text:
Q: nesting multiple dockerized angular applications under a unique domain name with nginx( with the location block) I have 3 angular applications that have been dockerized. Using a docker-compose file I would like to run all of them with an nginx server as a reverse proxy. Here is my docker compose file
*version: '3.9'
services:
  reverse_proxy:
    container_name: nginx_rp_beta
    image: nginx:1.23.3
    restart: always
    volumes:
      - ./nginx_proxy_html:/var/www/html
      - ./nginx_proxy_conf:/etc/nginx/conf.d
    ports:
      - 80:80
      - 443:443

  site01:
    container_name: site01
    image: image1
    ports:
      - 8081:80
  site02:
    container_name: site02
    image: image3
    ports:
      - 8082:80
  site03:
    container_name: site03
    image: image3
    ports:
      - 8083:80*

My nginx config file for reverse proxy is this one
*server {
    listen 80;
    listen 443 ssl;
    server_name dummy.server.cm;
    ssl_certificate /etc/nginx/conf.d/ssl/front/server.crt;
    ssl_certificate_key /etc/nginx/conf.d/ssl/front/server.key;

    location ~* /site03 {
        rewrite ^/site03(.*) $1 break;
        proxy_pass http://site03;
    }

    location ~* /site02 {
        rewrite ^/site02(.*) $1 break;
        proxy_pass http://site02;
    }

    location / {
        proxy_pass http://site01;
    }
}*

So that the first site is accessible through dummy.server.cm, site 2 (dummy.server.cm/site02) and site 3 (dummy.server.cm/site03)
But except from the first one(site01) which is OK, all the others try to open but turn infinitely trying to load scripts with an 404 error.
Any suggestion will be greatly appreciated
I added this to each location block in my nginx conf
proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

but all to no avail.
I fixed the problem by having a domain name for each site but this was not what I was asked for


text:
Q: Android makefile call import path variable value In an android makefile I have a following line
$(call import-add-path,/Users/bruno/Dev/cocos2d-x-2.1.5)

Now, I am working with several people and having that line is not very people-friendly. I have tried defining that path in an environment variable but it gets ignored when I add it to the call import-add-path line. I output the variable as a warning and the makefile obviously has the vatiable present:
$(warning $(NMP))    # outputs: jni/Android.mk:29: /Users/bruno/Dev/cocos2d-x-2.1.5
$(call import-add-path,$(NMP))

How can I make this work so that is multiple developers friendly?
Edit: Eclipse on OSX, building a cocos2d-x 2.1.5 TestCpp project, android NDK r10c. The error message I get is actually about the missing ABI and asking me if I have set the NDK_MODULE_PATH variable properly and it happens only on a debug build (perhaps GDB makes a difference?).

A: In the end this setup worked for me:
LOCAL_PATH := $(call my-dir)   # ./Project/proj.android/jni/ folder

...

IMPORT_PATH := $(LOCAL_PATH)/../../..    # ./ this gets me to where the modules are located

$(call import-add-path, $(IMPORT_PATH))
$(call import-add-path, $(IMPORT_PATH)/cocos2dx/platform/third_party/android/prebuilt)

$(call import-module,cocos2dx)    # ./cocos2dx
$(call import-module, ... etc.

I could not pass environment variables through Eclipse to the ndk-build, but it worked if I called import-add-path with a value relative to $(call my-dir). This should work with multiple developers as well.


text:
Q: This policy contains the following error: JSON strings must not have leading spaces I am facing the issue "This policy contains the following error: JSON strings must not have leading spaces"
Here is my code, could anyone help please
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Deny",
      "Action": [
        "iam:CreateServiceSpecificCredential",
        "iam:DeleteAccessKey",
        "iam:GetServiceLastAccessedDetailsWithEntities",
        "iam:GenerateServiceLastAccessedDetails",
        "iam:PutRolePermissionsBoundary",
        "iam:ListPoliciesGrantingServiceAccess",
        "iam:UpdateOpenIDConnectProviderThumbprint",
        "iam:ResetServiceSpecificCredential",
        "iam:DeleteSSHPublicKey",
        "iam:ListServiceSpecificCredentials",
        "iam:CreateSAMLProvider",
        "iam:TagSAMLProvider",
        "iam:DeleteRolePermissionsBoundary",
        "iam:GetServiceLastAccessedDetails",
        "iam:GetOrganizationsAccessReport",
        "iam:CreateAccessKey",
        "iam:ListSSHPublicKeys",
        "iam:GenerateOrganizationsAccessReport",
        "iam:ListOpenIDConnectProviderTags",
        "iam:CreateAccountAlias",
        "iam:ListSAMLProviderTags",
        "iam:UploadSSHPublicKey",
        "iam:DeleteAccountAlias",
        "iam:DeleteOpenIDConnectProvider",
        "iam:UpdateSAMLProvider",
        "iam:GetSAMLProvider",
        "iam:ListAccessKeys",
        "iam:UpdateServiceSpecificCredential",
        "iam:UntagSAMLProvider",
        "iam:ListSAMLProviders",
        "iam:RemoveClientIDFromOpenIDConnectProvider",
        "iam:PutUserPermissionsBoundary",
        "iam:GetAccessKeyLastUsed",
        "iam:GetSSHPublicKey",
        "iam:UpdateAccessKey",
        "iam:DeleteUserPermissionsBoundary",
        "iam:UpdateSSHPublicKey",
        "iam:CreateOpenIDConnectProvider",
        "iam:ListOpenIDConnectProviders",
        "iam:ListAccountAliases",
        "iam:UntagOpenIDConnectProvider",
        "iam:GetOpenIDConnectProvider",
        "iam:AddClientIDToOpenIDConnectProvider",
        "iam:DeleteServiceSpecificCredential",
        "iam:TagOpenIDConnectProvider",
        "iam:DeleteSAMLProvider"
      ],
      "Resource": ""
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Deny",
      "Action": [
        "iam:UpdateAssumeRolePolicy",
        "iam:PutUserPermissionsBoundary",
        "iam:PutUserPolicy",
        "iam:CreatePolicyVersion"
      ],
      "Resource": ""
    },

    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": ["iam:CreateUser"],
      "Resource": "*"
    },

    {
      "Sid": "VisualEditor3",
      "Effect": "Deny",
      "Action": ["iam:AttachGroupPolicy", "iam:AttachUserPolicy", "iam:AttachRolePolicy"],
      "Resource": "*",
      "Condition": {
        "StringNotEquals": {
          "iam:PolicyARN": "arn:aws:iam::758773684219:policy/KodeKloudIAMPolicy"
        },
        "StringNotEqualsIgnoreCase": {
          "iam:PolicyARN": "arn:aws:iam::758773684219:policy/KodeKloudEC2Policy"
        }
      }
    }
  ]
}

I got no errors while creating the policy but it wont let me create the policy as this message pops up "This policy contains the following error: JSON strings must not have leading spaces For more information about the IAM policy grammar, see AWS IAM Policies"


text:
Q: Is there any better way doing this query I have a table where I keep the Json data under RelatedObject column. Table structure are as follows;
+------+------------+-----------------+----------------------+
| [Id] | [ActionId] | [RelatedObject] | [InitiatedTimeStamp] |
+------+------------+-----------------+----------------------+

I store two different kinds of Json object. One something like this;
{
    "firstName": "FName",
    "lastName": "LName",
    "emailAddress": "xxx@gmail.com",
    "contactPref": {
        "lm_contclassne": "on",
        "lm_contclassneindustrial": "on",
        "lm_contclassneconstruction": "on"
     }
}

Second kind is the subset of the first one. Something like this;
{
  "lm_contclassne": "on",
  "lm_contclassneindustrial": "on",
  "lm_contclassneconstruction": "on"
}

Now, the problem is selecting the Json path (in some cases properties are lm_contclassne and for others its contactPref.lm_contclassne) for the query. This is how I'm doing it.
SELECT [Id],
  [ActionId],
  [InitiatedTimeStamp],
  JSON_VALUE(RelatedObject, IIF(JSON_QUERY(RelatedObject, '$.contactPref') IS NULL, '$.lm_contclassne', '$.contactPref.lm_contclassne')) lm_contclassne,
  JSON_VALUE(RelatedObject, IIF(JSON_QUERY(RelatedObject, '$.contactPref') IS NULL, '$.lm_contclassneindustrial', '$.contactPref.lm_contclassneindustrial')) lm_contclassneindustrial,
  JSON_VALUE(RelatedObject, IIF(JSON_QUERY(RelatedObject, '$.contactPref') IS NULL, '$.lm_contclassneconstruction', '$.contactPref.lm_contclassneconstruction')) lm_contclassneconstruction
FROM [SaveStatus]

Its working fine.
My question is, is there anyway I can optimize the query? You can see I've put the same condition on each and every Json properties. Can I do the checking IIF(JSON_QUERY(RelatedObject, '$.contactPref') IS NULL once and use the result for rest of the select? Any help will be greatly appreciated.

A: You could shrink it down to this I suppose (it's a little more succinct):
SELECT [Id],
       [ActionId],
       [InitiatedTimeStamp],
       JSON_VALUE(RelatedObject, IIF(RO.cP IS NULL, '$.lm_contclassne', '$.contactPref.lm_contclassne')) lm_contclassne,
       JSON_VALUE(RelatedObject, IIF(RO.cP IS NULL, '$.lm_contclassneindustrial', '$.contactPref.lm_contclassneindustrial')) lm_contclassneindustrial,
       JSON_VALUE(RelatedObject, IIF(RO.cP IS NULL, '$.lm_contclassneconstruction', '$.contactPref.lm_contclassneconstruction')) lm_contclassneconstruction
FROM [SaveStatus] SS
     CROSS APPLY(VALUES(JSON_QUERY(RelatedObject, '$.contactPref'))) RO(cP);


text:
Q: Oracle 8i SQL - concatenate strings from different rows I need to concatenate strings from different rows, as below.
The number of rows for each NAME is variable and its range is unknown.
NAME  COLOR
Bob   Red
Bob   Blue
Tom   Green
John  Red
John  Yellow
John  Purple

Desired output:
NAME  COLORS
Bob   RedBlue
Tom   Green
John  RedYellowPurple

The limitations I am facing are :

*

*Oracle 8i (8.1.7.4.0) - I have no control over this and upgrading is
not an option

*read only access

*can't create...

So basically :

*

*no CREATE

*no LISTAGG

*no XMLAGG

*no WM_CONCAT

*no Ref Cursor

*no SYS_CONNECT_BY_PATH

Am I SOL ?

A: Oracle 8i at least supports analytic functions, so you could assign each color value a nominal number with row_number() or dense_rank() (ordering by whatever makes sense to you):
select name, color,
  row_number() over (partition by name order by color) as rn
from your_table;

and then use a variation on a manual pivot with one max(decode()) per possible row number:
select name,
  max(decode(rn, 1, color))
  || max(decode(rn, 2, color))
  || max(decode(rn, 3, color))
  || max(decode(rn, 4, color))
  || max(decode(rn, 5, color))
  || max(decode(rn, 6, color))
  || max(decode(rn, 7, color))
  -- ...
  as colors
from (
  select name, color,
    row_number() over (partition by name order by color) as rn
  from your_table
)
group by name
order by name;

NAME       COLORS
---------- ----------------------------------------------------------------------
Bob        BlueRed
John       PurpleRedYellow
Tom        Green

You said the range is unknown, but even if there are an unlimited number of rows for each name, you're still restricted by the final concatenated string having to be at most 4000 characters - from your knowledge of the actual color values that would give you a maximum usable number. (And you could generate the decode parts automatically as a one-off thing).
You could include delimiters the same way if you needed to:
select name,
  max(decode(rn, 1, color))
  || max(decode(rn, 2, ',')) || max(decode(rn, 2, color))
  || max(decode(rn, 3, ',')) || max(decode(rn, 3, color))
  || max(decode(rn, 4, ',')) || max(decode(rn, 4, color))
  || max(decode(rn, 5, ',')) || max(decode(rn, 5, color))
  || max(decode(rn, 6, ',')) || max(decode(rn, 6, color))
  || max(decode(rn, 7, ',')) || max(decode(rn, 7, color))
  || max(decode(rn, 8, ',')) || max(decode(rn, 8, color))
  -- ...
  as colors
from (
  select name, color,
    row_number() over (partition by name order by color) as rn
  from your_table
  where color is not null
)
group by name
order by name;

NAME       COLORS
---------- ---------------------------------------------------------------------------------------
Bob        Blue,Red
John       Purple,Red,Yellow
Tom        Green

I've included a is not null filter in the inner query just in case that column is nullable - that ought to prevent empty elements in the final list.
(Not tested in 8i as I can't find an instance that old to spin up, but I don't think this is using anything introduced later...)