text:
Q: How to output blank spaces for missing attributes in CSV file from multidimensional array in PHP I'm having a bit of an issue with outputting blank spaces AND making sure all my CSV data is outputted in the right spot, and was wondering how I could do this.
I'm trying to format the outputs of my LDAP server search into a CSV format, but the issue is that some entry's attributes are out of order, or some entries have missing attributes altogether.
Here's an example of the some data
Array
(
    [0] => Array
        (
            [dc=example,dc=com] => Array
                (
                    [o] => example.com
                    [objectclass] => Array
                        (
                            [0] => simpleSecurityObject
                            [1] => dcObject
                            [2] => organization
                        )

                    [dc] => example
                )

        )

    [1] => Array
        (
            [uid=newton,dc=example,dc=com] => Array
                (
                    [sn] => Newton
                    [objectclass] => Array
                        (
                            [0] => simpleSecurityObject
                            [1] => dcObject
                            [2] => organization
                        )

                    [uid] => Newton
                    [mail] => newton@ldap.forumsys.com
                    [cn] => Isaac Newton
                )

        )

)

Notice that in the first ([0]) array, I have an entry named "o" and "dc" whereas in the second, I don't have them.
So essentially, I would want to output this:
distinguishedname,o,objectclass,dc,sn,uid,mail,cn
dc=example,dc=com,example.com,{simpleSecurityObject,dcObject,organization},example, , , ,
uid=newton,dc=example,dc=com, ,{simpleSecurityObject,dcObject,organization}, , ,Newton,newton@ldap.forumsys.com,Isaac Newton

I'm not too sure how to do 2 things:

*

*Make sure any missing attributes are replaced with "" so that it shows as empty

*Make sure the right attributes go to the right place. For instance, "o" might be the 3rd attribute in one entry, but it might be the 6th attribute in another. How do I make sure that my CSV data is in the following order:

distinguishedname,o,objectclass,dc,sn,uid,mail,cn

Here's some code that outputs all the data in a CSV format, but I'm unsure of how to make empty fields and make them line up.. the output is just a print out of all the data.
<?php
$movies = array(

    "dc=example,dc=com" => array(
      "o" => "example.com",
      "objectclass" => array("simpleSecurityObject", "dcObject", "organization"),
      "dc" => "example"),

    "uid=newton,dc=example,dc=com" => array(
      "sn" => "Newton",
      "objectclass" => array("simpleSecurityObject", "dcObject", "organization"),
      "uid" => "Newton",
      "mail" => "newton@ldap.forumsys.com",
      "cn" => "Isaac Newton")

);

function echo1($n){
  echo "
";
  echo $n;
  echo "
";
}
$i=0;
$hi1 = "";

$attributes_list = array("dn", "objectclass", "cn", "userpassword", "description", "sn", "uid", "mail");

echo "

";
$comma_separated = implode(",", $attributes_list);
echo $comma_separated;

foreach ( $movies as $movie => $val ) {

    //echo "

 \n Entry #$i";
    //This prints the name of all the arrays.
    //echo1($movie);
    echo "

";
    echo $movie.",";
    $i = $i + 1;

  //Checks if the value of the key value pair is an array.
  if(is_array($val)){
    //Since it's an array, we access its key value pairs again
    foreach ( $val as $key => $value ) {
      //Check to see if value of key value pair is array
      if(is_array($value)){
        //Prints the name of all the arrays
        echo $key." ";
        //Prints all key value pairs of the array
        $value_array = implode(",", $value);
        print_r($value_array);
        //If $value isn't an array, just prints the key value pairs
      } else{
          /*This is the original code for easier readability
          $hi = "$key : $value";
          echo1($hi);*/
          $hi1 = $hi1.$value.",";
          echo $hi1;
        }
      }
    //If $val isn't an array, prints the key value pairs
  } else{
  foreach ( $val as $key => $value ) {
    $hi = "The key is: $key The value is:$value";
    echo1($hi);
    }
  }

  echo '
';
}
?>

And here's the output:
dn,objectclass,cn,userpassword,description,sn,uid,mail
dc=example,dc=com,example.com,objectclass simpleSecurityObject,dcObject,organizationexample.com,example,
uid=newton,dc=example,dc=com,example.com,example,Newton,objectclass simpleSecurityObject,dcObject,organizationexample.com,example,Newton,Newton,example.com,example,Newton,Newton,newton@ldap.forumsys.com,example.com,example,Newton,Newton,newton@ldap.forumsys.com,Isaac Newton,

EDIT:
Using Nigel Ren's code, I got this output.
distinguishedname,o,objectclass,dc,sn,uid,mail,cn
o,{}
objectclass,,{},,,,,,simpleSecurityObject,dcObject,organization
dc,{}
sn,{}
objectclass,,{},,,,,,simpleSecurityObject,dcObject,organization
uid,{}
mail,{}
cn,{}

This is the exact code I tried:
<?php

// Start with the column list and split into an array
$headers = explode(',', 'distinguishedname,o,objectclass,dc,sn,uid,mail,cn');
// Create template record with the fields you want to end up with
$header = array_fill_keys($headers, null);
$output = [];

$details = array(

    "dc=example,dc=com" => array(
      "o" => "example.com",
      "objectclass" => array("simpleSecurityObject", "dcObject", "organization"),
      "dc" => "example"),

    "uid=newton,dc=example,dc=com" => array(
      "sn" => "Newton",
      "objectclass" => array("simpleSecurityObject", "dcObject", "organization"),
      "uid" => "Newton",
      "mail" => "newton@ldap.forumsys.com",
      "cn" => "Isaac Newton")

);

foreach ( $details as $detail ) {
    foreach ( $detail as $name => $entry )  {
        // Set the values in the template header from the current entry
        $newEntry = array_merge( $header, $entry );
        // Add the name in
        $newEntry ['distinguishedname'] = $name;
        // Process the object class from an array to a string
        $newEntry ['objectclass'] = "{".implode(",", $newEntry ['objectclass'])."}";
        $output [] = $newEntry;
    }
}

// Write file out
$fh = fopen("ad.csv", "w");
fputcsv($fh, $headers);
foreach ( $output as $row ) {
    fputcsv($fh, $row);
}
fclose($fh);

?>

EDIT 7/1/2020:
Here is the output I'm getting
firstname,lastname,email,phone,uid
,,,,,"{top,dcObject,organization}",ec_testing,test123,"{organizationalPerson,person,top,user}"
,,,,,"{simpleSecurityObject,organizationalRole}",admin,"LDAP administrator",{SSHA}0NhB8bVqiqCfUjU7AGE2mtrfj3Q58mj5
,,,,,organizationalUnit,people
,,,,,organizationalUnit,"groups "
,,,,tnguyen,"{top,account,posixAccount,shadowAccount}",tnguyen,16859,100,/home/tnguyen,/bin/bash,tnguyen,{crypt}x,0,0,0
,,,,,"{top,organizationalRole,simpleSecurityObject}","{replica,test}",aDifferentSecret,"Bind object used for replication using slurpd"
,,,,,"{php testing,phptest}",person,TestEdit
,,,,,person,"This is just a test to add an entry in Java",javatest,replacetest
,,,,,gotest,person,Google,"this is to test if replacing works in GoLang"

This is the code I used:
foreach ( $details as $name => $entry )  {
    // Set the values in the template header from the current entry

    $newEntry = array_merge( $header, $entry );
    // Add the name in
    foreach ( $newEntry as &$entry )    {
        if ( is_array($entry))  {
            $entry = "{".implode(",", $entry)."}";
        }
    }
    unset($entry);
    //$newEntry ['distinguishedname'] = $name;
    $output [] = $newEntry;
}

I want the output to be like
firstname,lastname,email,phone,uid
,,,,
,,,,
,,,,
,,,,
,,,,tnguyen
,,,,
,,,,
,,,,
,,,,

It's a bad example since all the entries are missing most if not all the attributes, but you get the idea.
What I've tried is this:
foreach ( $details as $name => $entry )  {
    // Set the values in the template header from the current entry
    if(in_array($entry, $header) || in_array($name, $header)){
      $newEntry = array_merge( $header, $entry );
    }
    // Add the name in
    foreach ( $newEntry as &$entry )    {
        if ( is_array($entry) && in_array($newEntry, $header))  {
            $entry = "{".implode(",", $entry)."}";
        }
    }
    unset($entry);
    //$newEntry ['distinguishedname'] = $name;
    $output [] = $newEntry;
}

But it just outputs my headers instead of just empty entries.
firstname,lastname,email,phone,uid

A: The following code creates a template array so that each record contains all of the values and then uses array_merge() to copy the values from each record into the template.  Any values not in the record will just remain empty to ensure that the alignment is kept (more description in the code comments)...
// Start with the column list and split into an array
$headers = explode(',', 'distinguishedname,o,objectclass,dc,sn,uid,mail,cn');
// Create template record with the fields you want to end up with
$header = array_fill_keys($headers, null);
$output = [];
foreach ( $details as $detail ) {
    foreach ( $detail as $name => $entry )  {
        // Set the values in the template header from the current entry
        $newEntry = array_merge( $header, $entry );
        // Add the name in
        $newEntry ['distinguishedname'] = $name;
        // Process the object class from an array to a string
        $newEntry ['objectclass'] = "{".implode(",", $newEntry ['objectclass'])."}";
        $output [] = $newEntry;
    }
}

// Write file out
$fh = fopen("ad.csv", "w");
fputcsv($fh, $headers);
foreach ( $output as $row ) {
    fputcsv($fh, $row);
}
fclose($fh);

which with the sample data gives...
distinguishedname,o,objectclass,dc,sn,uid,mail,cn
"dc=example,dc=com",example.com,"{simpleSecurityObject,dcObject,organization}",example,,,,
"uid=newton,dc=example,dc=com",,"{simpleSecurityObject,dcObject,organization}",,Newton,Newton,newton@ldap.forumsys.com,"Isaac Newton"

note that using fpustcsv() has the advantage that if fields contain commas (the delimiter) then it will put them in quotes to ensure they are just one field.
Edit:
$headers = explode(',', 'distinguishedname,o,objectclass,dc,sn,uid,mail,cn');
$output = [];
foreach ( $details as $name => $entry )  {
    echo $name.PHP_EOL;
    $newEntry = [];
    foreach ( $headers as $header ) {
        $value = $entry[$header] ?? null;
        if ( is_array($value) ) {
            $value = "{".implode(",", $value)."}";
        }
        $newEntry [$header] = $value;
    }
    $newEntry ['distinguishedname'] = $name;
    $output [] = $newEntry;
}


text:
Q: What is the correct way to use different `api` with separate query? I have to make 2 queries or more to get data from the server. for example the first i am getting general information like this:
http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectDetails
on user click i need to show the summary of this project. so i need to pass the id to get the data what i requred, the url is :
http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectByID/002
But how to make seperate query according to the page?
at present i am using a server.js like this:
(function () {

    "use strict";

    angular
        .module("tcpApp")
        .factory("server", ['$resource', function ($resource) {

            return $resource('http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectDetails');

        }]);

})();

$scope.splash = server.query(); //getting json.

It works fine. But how to can update this for both request?

A: my opinion  don't need to get service call,
because your database values already you had.
if $scope.splash have your latest value, then you can get the object by using indexOf().
It's may be no sense. but it is a simple way. else you need call server by using separate query
update:-

*

*I does not mean Seperate Query . I mean you need to pass parameter to the function, if the parameter have any value, then write second query , else you write a first query.

*You can get the data from your $scope.splash array by using indexOf() function  or map() or some() functions

redpajama_set_name: RedPajamaStackExchange


text:
Q: sub(): Handling of backreferences say I have a molecular formula like "C5Cl2NO2S" for which I'd like to calculate in R the molecular mass. I though the easiest would be to use a regular expression, to analyze and split the formula into it's elemental components and hand those over to a separate function which performs the calculation. However, I'm facing the problem that, when I hand over the backreferences of my RegEx, these are not evaluated but handed over as "\\1", "\\2".
This is my attempt:
masses <- list(
  C  = 12,
  H  = 1.01,
  Cl = 34.97,
  N  = 14.00,
  O  = 15.99,
  P  = 30.97,
  S  = 31.97
)

elementMass <- function( element, count ) {
  if( count == "" ) {
    count <- "1"
  }
  return( as.character( masses[[ element ]] * as.numeric( count ) ) )
}

sumFormula2Mass <- function( x ){
  y <- 0.0
  for( e in x ) {
    if( e != "" ) {
      y <- y + as.numeric( sub( "^(C|H|Cl|N|O|P|S)([0-9]*)$", elementMass("\\1", "\\2"), e ) )
    }
  }
  return( y )
}

sub(
  "^(C[0-9]*)?(H[0-9]*)?(Cl[0-9]*)?(N[0-9]*)?(O[0-9]*)?(P[0-9]*)?(S[0-9]*)?$",
  sumFormula2Mass( c("\\1", "\\2", "\\3", "\\4", "\\5", "\\6", "\\7") ),
  "C5Cl2NO2S"
)

Any ideas how to improve this?
Many thanks

A: Below we assumed the form of formula in the question, i.e. a string of components each of which is an upper case letter followed optionally by lower case letters followed optionally by digits.  We use gsubfn in the gsubfn package.  It is like gsub except the replacement string can be various other objects.  Here its a proto object.  A proto object is an environment and here its used for containing a property, sum, and two methods, pre and fun.  At the beginning pre is automatically run and has the effect of initializing sum.   Then each time the regular expression matches, the proto object and the two referenced strings are passed to fun and fun is run to process them.  At the end p$sum contains the result.  The variable masses is defined in the question.
library(gsubfn)
p <- proto(pre = function(this) this$sum <- 0,
    fun = function(this, name, count) {
        count <- as.numeric(count)
        if (is.na(count)) count <- 1
        this$sum <- this$sum + masses[[name]] * count
        ""
    })
gsubfn("([[:upper:]][[:lower:]]*)(\\d*)", p, "C5Cl2NO2S")
p$sum # 207.89

A: I don't think that backreferences in sub() work like this. You seem to be treating them as though they are returned values, when they are inputs.
Here is a different solution. It takes a very different approach, namely splitting the string up into individual parts and then referring to these. However, it has some limitations. Firstly, it assumes cannot handle chemical formulae with parentheses. Secondly, it assumes that atoms are written sensibly (i.e. chlorine is written as Cl - upper case C and lower case l). There are probably lots of other limitations, but this should give you an idea about how this solution might look.
sumFormula2Mass2 <- function(x,masses){
  summedMasses <- NULL
  for(e in x){
    ## split up the string
    split.e <- unlist(strsplit(e,''))
    ## join letters from individual elements (since subequent letters should be lower case)
    ilower <- grep('[a-z]',split.e)
    if(length(ilower) > 0){
      for(i in 1:length(ilower)){
        j <- ilower[i]
        split.e <- c(if(j > 2) split.e[1:(j-2)],
                     paste(split.e[(j-1):j],collapse=''),
                     if(j < length(split.e)) split.e[(j+1):length(split.e)])
        ilower <- ilower - 1
      }
    }
    ## join numbers together (in case there are more than 10 atoms)
    inum <- grep('[0-9]',split.e)
    if(length(inum) > 1){
      for(i in 1:(length(inum)-1)){
        if(inum[i + 1] == inum[i] + 1){
          j <- inum[i]
          split.e <- c(split.e[1:(j-1)],
                       paste(split.e[j:(j+1)],collapse=''),
                       if(j+2 <= length(split.e)) split.e[(j+2):length(split.e)])
          inum <- inum - 1
        }
      }
    }
    ## add up the mass
    sumMass = 0
    for(i in 1:length(split.e)){
      if(length(grep('[1-9]',split.e[i])) > 0){
        next
      } else if(split.e[i] %in% names(masses)){
        nMolecules <- 1
        if(i != length(split.e) && length(grep('[1-9]',split.e[i+1])) > 0)
          nMolecules <- as.numeric(split.e[i+1])
        sumMass <- sumMass + nMolecules * masses[[split.e[i]]]
      } else {
        warning(sprintf('Could not match element %s',split.e[i]))
        next
      }
    }
    summedMasses <- c(summedMasses,sumMass)
  }
  return(summedMasses)
}

Here are some results for your compound plus some made-up compounds (I am not a chemist):
> sumFormula2Mass2(c("C5Cl2NO2S","C5Cl2NO2S4","C5Cl10NO2S4"),masses)
[1] 207.89 303.80 583.56

A: Believe it or not, this appears to not be all that uncommon:
Parsing a chemical formula
How to check that a regular expression has matched a string completely, i.e. - the string did not contain any extra character?
http://www.sitepoint.com/forums/php-34/chemical-formula-regular-expressions-317012.html
I found the above by Googling molecular formula regex

A: have a look at
RSiteSearch ("molecular weight")

I guess the 2nd or 3rd hit is what you are looking for (the first is for proteins).
(sorry, didn't see your comment on the other answer - however, I leave this in case someone is really looking for molecular weight calculation).


text:
Q: AngularJS 4.0 / TFS - TFS not allowed to checkin $data folder I am writing a code in AngularJS 4.0. We are using TFS as source code management tool.
We have

$data.js

file added in our project. But TFS is not allowed us to check-in this file.
I am getting below message -

--------------------------- Microsoft Visual Studio
  --------------------------- Add to Source Control
No eligible items were found for addition.
--------------------------- OK   Help

Please help me in resolving this error.
Any help will be appreciated.
Thanks

A: The error message in the exception is correct.  Please take a look at official Naming Syntax, Conventions, and Limitations:

Most names in Team Foundation version control cannot begin or end with spaces or tabs. Any character can be used for names or labels, except
...
A dollar sign ($) cannot be the first character in a file name.

You cannot place files with those names in TFVC. Otherwise you may get a similar error as below:

TF10122: The path '$/xx/$data.js' contains a '$' at the beginning of a path component. Remove the '$' and try again."

You have to rename this file $data.js to another name syntax then check in TFS again.


text:
Q: converting text date with am/pm time into 24 hour time in excel non VBA I am looking to convert a text time with a and p on the end into usable time in excel I have used the mid function and I does not seem to recognize the a/p and makes all the times am unless its 12--. Then it will return a PM time. I have used the Mid function and have searched the threads.
Times in the database look like
10/ 1/14  5:14P
These are text
I have used the mid function
=TIMEVALUE(MID(B6,9,6))
Returning
5:14:00 AM
when the time should be a Pm or 17:14
Help would be appreciated
Thanks

A: Try this :
=SUBSTITUTE(SUBSTITUTE(A1,"A", " AM"),"P", " PM")+0
where A1 has the value.
Format the cell to the kind of date / time / datetime format that you want ; formatting it to :

dd-mm-yyyy h:mm:ss AM/PM

will display :

10-01-2014 5:14:00 PM


text:
Q: Creating an array matrix in python i'm trying to create an 2-dimensional matrix with an array, but i don't quit understand it yet.
I've tried this
for i in range(x):
for k in range(y):
array.array('u', [i] : [k])

I'm trying to make an field with x, y as in height and width.
edit:
well, i've changed it now and came to this solution, wich fixs my problem
import array

x = int(input('width: '))
y = int(input('height: '))

Matrix = array.array("u", ['.' for i in range(x) for k in range(y)])
Matrix.tounicode
print(Matrix)

With this i'm creating an field as an array, although i have to see how tounicode really works, possible i need a hash-function.

A: This I believe is your answer. I don't know how to mark as a duplicate.
How to define two-dimensional array in python


text:
Q: How to create a Mesh from normals and uv in Unity? Hi I have this data coming from an API and I know it is a cube:
    {
  "position": {
    "itemSize": 3,
    "type": "Float32Array",
    "array": [
      0.5,
      0.5,
      0.5,
      0.5,
      0.5,
      -0.5,
      0.5,
      -0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      -0.5,
      0.5,
      -0.5,
      -0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      -0.5,
      -0.5,
      -0.5,
      0.5,
      -0.5,
      0.5,
      -0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      0.5,
      0.5,
      0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      0.5,
      0.5,
      -0.5,
      0.5,
      -0.5,
      -0.5,
      -0.5,
      0.5,
      -0.5,
      -0.5,
      -0.5,
      0.5,
      0.5,
      0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      0.5,
      0.5,
      -0.5,
      0.5,
      0.5,
      0.5,
      -0.5,
      -0.5,
      0.5,
      -0.5,
      0.5,
      -0.5,
      -0.5,
      -0.5,
      -0.5,
      -0.5
    ],
    "normalized": false
  },
  "normal": {
    "itemSize": 3,
    "type": "Float32Array",
    "array": [
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1,
      0,
      0,
      -1
    ],
    "normalized": false
  },
  "uv": {
    "itemSize": 2,
    "type": "Float32Array",
    "array": [
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      1,
      0
    ],
    "normalized": false
  }
}

How can I now create from these data a cube and its material in Unity? Is there a library or a built-in function?

A: First in general for parsing your JSON data into useful structure you need to have an according class structure and the use e.g. JsonUtility
[Serializable]
public class DataSet
{
    public int itemSize;
    public int[] array;
    public bool normalized;
}

[Serializable]
public class Example
{
    public DataSet position;
    public DataSet normal;
    public DataSet uv;
}

and do
var data = JsonUtility.FromJson<Example>(yourJsonString);

Next this data is still quite raw and we have to parse it further since we want valid vector values
var vertices = new List<Vector3>();

for(var i = 0; i < data.position.array.Length; i+=3)
{
    if(i+2 > data.position.array.Length - 1) break;

    var x = data.position.array[i];
    var y = data.position.array[i+1];
    var z = data.position.array[i+2];
    vertices.Add(new Vector3(x,y,z));
}

And similar for normals and UVs(just that here you use Vector2 instead)

Then to the main question: Since you already have positions (I assume vertices), normals and UVs I guess you are wondering where to get the triangles from.
UVs don't help here at all since they are only texture coordinates defining how the texture is later mapped on triangles.
Also the normals can't really help you here. A normal is just a direction and doesn't provide any helpful information about which three vertices together make up a triangle.
To get the triangles would only be possible if you know e.g. that always 3 sequential vertices make up a triangle - meaning your mesh has duplicate vertices.
Otherwise I'ld say it is not possible to know that triangles from your given data.
In Unity the triangles is simply a flat int[] where always three sequential elements are the indexes of the three vertices from the vertices array.
So under the one assumption that they are just consequent something like
var triangles = new int[vertices.Length];
for(var i = 0; i < triangles.Length; i++)
{
    triangles[i] = i;
}

Then you could simply put it all together and create a mesh like
var mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
// Etc


text:
Q: SSRS SubReport - Set to Not Grow, but it continues to grow I am building out a report that contains a Sub Report, I need that Sub Report to be a static size. I've researched and read that you can place it in a tabix and set the row CanGrow to False. However, as soon as I put the sub report in the row, the tablix automatically resets CanGrow to True.
What am I doing wrong? How do I get around this? Any help would be greatly appreciated as I am at a loss right now and can't seem to figure it out.

A: You can't prevent it from showing the whole subreport. But, you can pass the subreport a parameter. And that parameter could be a flag that controls how much of it is visibile. So, when the subreport is viewed from the main one, you could have it cut off where you want. Then when it's viewed by itself have that parameter default to show everything.


text:
Q: Naming variables within nested list comprehensions in Python? Like the title says, is there any way to name variables (i.e., lists) used within a nested list comprehension in Python?
I could come up with a fitting example, but I think the question is clear enough.
Here is an example of pseudo code:
[... [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension] ... [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension] ...]
Is there any way to avoid the repetition here and simply add a variable for this temporary list only for use within the list comprehension?
CLARIFICATION:
The list comprehension is already working fine, so it's not a question of 'can it be done with a list comprehension'. And it is quicker than it's original form of a for statement too, so it's not one of those 'for statements vs list comprehensions' questions either. It is simply a question of making the list comprehension more readable by making variable names for variables internal to the list comprehension alone. Just googling around I haven't really found any answer. I found this and this, but that's not really what I am after.

A: Based on my understanding of what you want to do, No you cannot do it.
You cannot carry out assignments in list comprehensions because a list comprehension is essentially of the form
[expression(x, y) for x in expression_that_creates_a_container
                  for y in some_other_expression_that_creates_a_container(x)
                  if predicate(y, x)]

Granted there are a few other cases but they're all about like that. Note that nowhere does there exist room for a statement which is what a name assignment is. So you cannot assign to a name in the context of a list comprehension except by using the for my_variable in syntax.
If you have the list comprehension working, you could post it and see if it can be simplified. Solutions based on itertools are often a good alternative to burly list comprehensions.

A: I think I understand exactly what you meant, and I came up with a "partial solution" to this problem. The solution works fine, but is not efficent.
Let me explain with an example:
I was just trying to solve a Pythagorean triplet which sum was 1000. The python code to solve it is just:
def pythagoreanTriplet(sum):
    for a in xrange(1, sum/2):
        for b in xrange(1, sum/3):
            c = sum - a - b
            if c > 0 and c**2 == a**2 + b**2:
               return a, b, c

But I wanted to code it in a functional programming-like style:
def pythagoreanTriplet2(sum):
    return next((a, b, sum-a-b) for a in xrange(1, sum/2) for b in xrange(1, sum/3) if (sum-a-b) > 0 and (sum-a-b)**2 == a**2 + b**2)

As can be seen in the code, I calc 3 times (sum-a-b), and I wanted to store the result in an internal varible to avoid redundant calculation. The only way I found to do that was by adding another loop with a single value to declare an internal variable:
def pythagoreanTriplet3(sum):
    return next((a, b, c) for a in xrange(1, sum/2) for b in xrange(1, sum/3) for c in [sum-a-b] if c > 0 and c**2 == a**2 + b**2)

It works fine... but as I said at the begin of the post, is not an efficent method. Comparing the 3 methods with cProfile, the time required for each method is the next one:

*

*First method: 0.077 seconds

*Secnd method: 0.087 seconds

*Third method: 0.109 seconds

A: Some people could classify the following as a "hack", but it is definitely useful in some cases.
f = lambda i,j: int(i==j) #A dummy function (here Kronecker's delta)
a = tuple(tuple(i + (2+f_ij)*j + (i + (1+f_ij)*j)**2
                for j in range(4)
                for f_ij in (f(i,j),) ) #"Assign" value f(i,j) to f_ij.
          for i in range(4) )
print(a)
#Output: ((0, 3, 8, 15), (2, 13, 14, 23), (6, 13, 44, 33), (12, 21, 32, 93))

This approach is particularly convenient if the function f is costly to evaluate. Because it is somewhat unusual, it may be a good idea to document the "assignment" line, as I did above.

A: I'm just gonna go out on a limb here, because I have no idea what you really are trying to do.  I'm just going to guess that you are trying to shoehorn more than you should be into a single expression.  Don't do that, just assign subexpressions to variables:
sublist = [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension]
composedlist = [... sublist ... sublist ...]

A: This feature was added in Python 3.8 (see PEP 572), it's called "assignment expressions" and the operator is := .
Examples from the documentation:
results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
stuff = [[y := f(x), x/y] for x in range(5)]


text:
Q: Should the Router be responsible for network requests? (Backbone.js) I'm in disagreement with a co-worker about the responsiblities of a Router. Inside of our single page application, it's my impression to have network requests (AJAX) handled via events being triggered (i.e. Backbone.Events), like so:
events : {
    'click a#getUsers' : 'updateModels'
}

updateModels: function() {
    $.ajax(); or this.Model.fetch();
}

Yet it is his understanding that network requests should be handled via the router on URL change (depending on a click which changes the url like a[href="#getThings"] like so:
var App = Backbone.Router.extend({
    routes: {
        "" : "main",
        "thing" : "getThings"
    }

    getThings: function() {
        this.newView = new NewView();
        $.ajax(); // which populates the view with data
    }
});

I wanted to know what the backbone reason is for doing network requests.

A: The vast majority of your AJAX requests should start with a backbone model or collection and be handled via the backbone.sync function. The key methods are model.fetch(), collection.fetch(), and model.save().
Backbone is flexible and only handles a very primitive set of use cases, so there are cases when you need to step outside these boundaries, but any call to $.ajax in a view or a router is a strong code smell of MVC failure.
To address some of your specifics.

Can a view call model.fetch() to load data?

Yes, this is perfectly fine and idiomatic backbone.

Can a view emit an event which will eventually load data?

Yes, this is perfectly fine. This is only necessary beyond just calling model.fetch() as your application grows in complexity and the decoupling that event emitting allows is valuable and warranted. For a todo list, it's usually overkill. For a huge application, this can be a clean approach.

Does every model fetch cause a change in the browser URL?

No. In fact many single page applications simply live at "/" forever. Routing to unique URLs is optional. Some applications lend themselves easily to it, others not so much. Don't equate "the application needs data X" with "the browser URL needs to be X". These are orthogonal. If a user clicks on the view for "Bill Clinton" in a list of presidents and you want to change the URL to "/presidents/clinton", then go ahead and fire a new route and that makes perfect sense, but sometimes you just want some data without changing the URL.
To summarize the responsibilities of the router, I think of it as follows:

*

*Based on the URL, which View is supposed to be displayed?

*Also based on the URL, are there model IDs that need to be extracted and instantiated into model instances?

*Wire things up and render the view

So a typical router method pseudocode might be:

*

*when the URL matches /presidents/:name, respond as follows

*grab the :name parameter and make a President model

*instantiate a PresidentView, passing it the model

*call presidentView.render() and swap the view's element into the DOM at the appropriate spot in the overall page layout

A: With Backbone, you should let Backbone be doing most of the ajax requests for you, which will be more often than not triggered from your view, not the router. And I would never use a jQuery ajax request when you could use a Backbone request instead. this.model.fetch() is the right way to get the model. I see the router as a way to orient your page, but the finer details should be left to the views. However, choosing between logic in the router vs. in the views/collections/models is more art than science, and I would take a look at other Backbone examples to get more guidance. I think, in a lot of cases, the network requests are handled in the views because it's easier.
In response to your comment below, whenever data is returned from the server, Backbone uses parse to get the information it needs, so rewriting fetch would be a poor decision. You can overwrite the parse method for your model to get the information that you want, and nothing more. i.e.:
var YourModel = Backbone.Model.extend({
    parse: function(response) {
        //You can manipulate the object in other ways as well,
        //but here's how you'd delete info
        delete response.junk;
        return response;
    }
});

Similarly, every time you do this.model.save(), it uses toJSON() before the model gets sent to the server, which you can also overwrite:
toJSON: function() {
    // default -> return _.clone(this.attributes);
    return _new code here_;
}


text:
Q: Get minimum and maximum value of expression by using brackets I have one-line expression without brackets, for instance 1+5*6-3. We can use all operators (+, -, *, /). What I need to know? What is maximum and minimum value of expression when we can use brackets.
Examples
1)
Input: 1+5*6-3
Output: 33 16
Explanation: 33 = (((1+5)*6)-3) | 16 = (1+(5*(6-3))
2)
Input: 15*5-12-9
Output: 72 -240
3)
Input: 3*10*16-14-11*2
Output: 954 -600
4)
Input: 8-5*18+5-13+0*2+14-6*6+1
Output: 7233 -13482
5)
Input: 6+5-15*18+14-3-5-3-2-2*8-14+12
Output: 11081 -4935
6)
Input: 13-4*6*18+12+8-5*8-4+2+11*6+9-7+6*12*18+8-7+3*1-15*1-12*1-12-14+7-14*9*6
Output: 74388962089190 -72949270802716
And why I'm writing this post? I have fast algorithm, but it works for tests number 1, 2, 3, but for 4, 5, 6 a get bad results. Why? Maybe you will see what I have done wrong. Here is my code:
public static long[] parenthesis(String expression, int start, int end) {
    if(resultStorage[start][end][2] == 1)
        return resultStorage[start][end];

    if(isNumber(expression))
        return new long[] { Long.parseLong(expression), Long.parseLong(expression), 1 };

    long[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE, 1 };
    for(int i = 1; i < expression.length() - 1; i++) {
        if(Character.isDigit(expression.charAt(i)))
            continue;

        long[] left = parenthesis(expression.substring(0, i), start, start + i);
        long[] right = parenthesis(expression.substring(i + 1, expression.length()), start + i + 1, end);
        switch(expression.charAt(i)) {
            case '+' : result[0] = Math.min(result[0], left[0] + right[0]);
                       result[1] = Math.max(result[1], left[1] + right[1]);
                       break;
            case '-' : result[0] = Math.min(result[0], left[0] - right[0]);
                       result[1] = Math.max(result[1], left[1] - right[1]);
                       break;
            case '*' : result[0] = Math.min(result[0], left[0] * right[0]);
                       result[1] = Math.max(result[1], left[1] * right[1]);
                       break;
            case '/' : if(right[0] != 0)
                           result[0] = Math.min(result[0], left[0] / right[0]);
                       if(right[1] != 0)
                           result[1] = Math.max(result[1], left[1] / right[1]);
                       break;
        }
    }

    resultStorage[start][end] = result;
    return result;
}

A: I had to write my own solution to understand the problem. My solution isn't that fast so there's no need to make it public. However, the reason why your solution doesn't work in all cases is, that it's not enough to use
new min = min left <op> min right
... analog for new max ...

because some min operands in combination with some operands (I suspect subtract and divide) produce a greater result and vice versa. Therefore all combinations of min/max left/right must be checked for the new min and new max value:
new min = min left <op> min right
new min = min left <op> max right
new min = max left <op> min right
new min = max left <op> max right
... analog for new max ...

So I introduced two nested loops into your code to do this:
public static void main(String[] args) {
    parenthesis("1+5*6-3");
    parenthesis("15*5-12-9");
    parenthesis("3*10*16-14-11*2");
    parenthesis("8-5*18+5-13+0*2+14-6*6+1");
    parenthesis("6+5-15*18+14-3-5-3-2-2*8-14+12");
    parenthesis("13-4*6*18+12+8-5*8-4+2+11*6+9-7+6*12*18+8-7+3*1-15*1-12*1-12-14+7-14*9*6");
}

private static void parenthesis(String expression) {
    resultStorage = new long[100][100][100];
    long[] results = parenthesis(expression, 0, 0);
    System.out.println("=====> " + expression + " -> " + results[0] + "/" + results[1]);
}

private static long[][][] resultStorage;

public static long[] parenthesis(String expression, int start, int end) {
    if (resultStorage[start][end][2] == 1)
        return resultStorage[start][end];

    try {
        long parsedLong = Long.parseLong(expression);
        return new long[] { parsedLong, parsedLong, 1 };
    } catch (NumberFormatException e) {
        //
    }

    long[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE, 1 };
    for (int i = 1; i < expression.length() - 1; i++) {
        if (Character.isDigit(expression.charAt(i)))
            continue;
        long[] left = parenthesis(expression.substring(0, i), start, start + i);
        long[] right = parenthesis(expression.substring(i + 1, expression.length()), start + i + 1, end);
        for (int li = 0; li < 2; li++) {
            for (int ri = 0; ri < 2; ri++) {
                switch (expression.charAt(i)) {
                case '+':
                    result[0] = Math.min(result[0], left[li] + right[ri]);
                    result[1] = Math.max(result[1], left[li] + right[ri]);
                    break;
                case '-':
                    result[0] = Math.min(result[0], left[li] - right[ri]);
                    result[1] = Math.max(result[1], left[li] - right[ri]);
                    break;
                case '*':
                    result[0] = Math.min(result[0], left[li] * right[ri]);
                    result[1] = Math.max(result[1], left[li] * right[ri]);
                    break;
                case '/':
                    if (right[ri] != 0)
                        result[0] = Math.min(result[0], left[li] / right[ri]);
                    if (right[ri] != 0)
                        result[1] = Math.max(result[1], left[li] / right[ri]);
                    break;
                }
            }
        }
    }

    resultStorage[start][end] = result;
    return result;
}

This produces exactly what you want:
=====> 1+5*6-3 -> 16/33
=====> 15*5-12-9 -> -240/72
=====> 3*10*16-14-11*2 -> -600/954
=====> 8-5*18+5-13+0*2+14-6*6+1 -> -13482/7233
=====> 6+5-15*18+14-3-5-3-2-2*8-14+12 -> -4935/11081
=====> 13-4*6*18+12+8-5*8-4+2+11*6+9-7+6*12*18+8-7+3*1-15*1-12*1-12-14+7-14*9*6 -> -72949270802716/74388962089190

What I'm really interested in is, what this optimization does:
if (resultStorage[start][end][2] == 1)
        return resultStorage[start][end];

The code works pretty well without resultStorage at all. But this recursion end condition makes it really fast without losing results. I'd be happy to hear how it works ...
EDIT: Okay, the optimization seems to terminate on already calculated results. However, as a sceptic I wanted to see the term with paranthesis to throw it into my calculator. So I did two more changes to the code: (1) Optimization by returning already calculated results for an expression, but with a HashMap Expression->Results (2) Evaluate the resulting term with paranthesis.
And here it is:
public static void main(String[] args) {
    parenthesisOuter("1+5*6-3");
    parenthesisOuter("15*5-12-9");
    parenthesisOuter("3*10*16-14-11*2");
    parenthesisOuter("8-5*18+5-13+0*2+14-6*6+1");
    parenthesisOuter("6+5-15*18+14-3-5-3-2-2*8-14+12");
    parenthesisOuter("13-4*6*18+12+8-5*8-4+2+11*6+9-7+6*12*18+8-7+3*1-15*1-12*1-12-14+7-14*9*6");
    parenthesisOuter("1/0");
    parenthesisOuter("1/1-1");
}

private static void parenthesisOuter(String expression) {
    Object[] results = parenthesis(expression);
    System.out.println(expression + " -> " + results[MINVAL] + "=" + results[MINEXPR] + " "
            + results[MAXVAL] + "=" + results[MAXEXPR]);
}

private static Map<String, Object[]> resultMap = new HashMap<>();

private static final int MINVAL = 0;
private static final int MAXVAL = 1;
private static final int MINEXPR = 2;
private static final int MAXEXPR = 3;

public static Object[] parenthesis(String expression) {
    Object[] result = resultMap.get(expression);
    if (result != null) {
        return result;
    }

    try {
        Long parsedLong = new Long(expression);
        return new Object[] { parsedLong, parsedLong, expression, expression };
    } catch (NumberFormatException e) {
        // go on, it's not a number
    }

    result = new Object[] { Long.MAX_VALUE, Long.MIN_VALUE, null, null };
    for (int i = 1; i < expression.length() - 1; i++) {
        if (Character.isDigit(expression.charAt(i)))
            continue;
        Object[] left = parenthesis(expression.substring(0, i));
        Object[] right = parenthesis(expression.substring(i + 1, expression.length()));
        doOp(result, (Long) left[MINVAL], expression.charAt(i), (Long) right[MINVAL],
                (String) left[MINEXPR], (String) right[MINEXPR]);
        doOp(result, (Long) left[MINVAL], expression.charAt(i), (Long) right[MAXVAL],
                (String) left[MINEXPR], (String) right[MAXEXPR]);
        doOp(result, (Long) left[MAXVAL], expression.charAt(i), (Long) right[MINVAL],
                (String) left[MAXEXPR], (String) right[MINEXPR]);
        doOp(result, (Long) left[MAXVAL], expression.charAt(i), (Long) right[MAXVAL],
                (String) left[MAXEXPR], (String) right[MAXEXPR]);
    }

    resultMap.put(expression, result);
    return result;
}

private static void doOp(Object[] result, Long left, char op, Long right, String leftExpression,
        String rightExpression) {
    switch (op) {
    case '+':
        setResult(result, left, op, right, left + right, leftExpression, rightExpression);
        break;
    case '-':
        setResult(result, left, op, right, left - right, leftExpression, rightExpression);
        break;
    case '*':
        setResult(result, left, op, right, left * right, leftExpression, rightExpression);
        break;
    case '/':
        if (right != 0) {
            setResult(result, left, op, right, left / right, leftExpression, rightExpression);
        }
        break;
    }
}

private static void setResult(Object[] result, Long left, char op, Long right, Long leftOpRight,
        String leftExpression, String rightExpression) {
    if (result[MINEXPR] == null || leftOpRight < (Long) result[MINVAL]) {
        result[MINVAL] = leftOpRight;
        result[MINEXPR] = "(" + leftExpression + op + rightExpression + ")";
    }
    if (result[MAXEXPR] == null || leftOpRight > (Long) result[MAXVAL]) {
        result[MAXVAL] = leftOpRight;
        result[MAXEXPR] = "(" + leftExpression + op + rightExpression + ")";
    }
}

which shows (the last two to see whether it's divide-by-zero-safe):
1+5*6-3 -> 16=(1+(5*(6-3))) 33=(((1+5)*6)-3)
15*5-12-9 -> -240=(15*((5-12)-9)) 72=((15*5)-(12-9))
3*10*16-14-11*2 -> -600=(3*(10*((16-14)-(11*2)))) 954=(((3*(10*16))-(14-11))*2)
8-5*18+5-13+0*2+14-6*6+1 -> -13482=(((((8-(5*(18+5)))-(13+0))*(2+14))-6)*(6+1)) 7233=(8-(5*(18+(((5-((13+0)*(2+14)))-6)*(6+1)))))
6+5-15*18+14-3-5-3-2-2*8-14+12 -> -4935=(6+((5-(15*((18+(14-((((3-5)-3)-2)-2)))*8)))-(14+12))) 11081=(6+(5-(15*((18+(14-((((3-5)-3)-2)-2)))*(8-(14+12))))))
13-4*6*18+12+8-5*8-4+2+11*6+9-7+6*12*18+8-7+3*1-15*1-12*1-12-14+7-14*9*6 -> -72949270802716=((((((((((13-4)*(6*(18+(12+8))))-5)*(((8-4)+(2+11))*(6+9)))-7)+6)*(12*(18+8)))-7)+3)*(1-(15*((1-(12*(((1-12)-(14+7))-14)))*(9*6))))) 74388962089190=((((13-4)*(6*(18+(12+8))))-5)*(((((8-((4+(2+11))*(6+9)))-(7+6))*(12*(18+8)))-(7+3))*(1-(15*((1-(12*(((1-12)-(14+7))-14)))*(9*6))))))
1/0 -> 9223372036854775807=null -9223372036854775808=null
1/1-1 -> 0=((1/1)-1) 0=((1/1)-1)


text:
Q: Bokeh plot doesn't show I'm looking to build a slider with bokeh like this one:

However, when I copy and paste the code block from the link to my jupyter notebook, the cell runs perfectly, but it doesn't show the plot. What am I missing here?. The code:
import numpy as np

from bokeh.layouts import column, row
from bokeh.models import CustomJS, Slider
from bokeh.plotting import ColumnDataSource, figure, show

x = np.linspace(0, 10, 500)
y = np.sin(x)

source = ColumnDataSource(data=dict(x=x, y=y))

plot = figure(y_range=(-10, 10), width=400, height=400)

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude")
freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency")
phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase")
offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset")

callback = CustomJS(args=dict(source=source, amp=amp_slider, freq=freq_slider, phase=phase_slider, offset=offset_slider),
                    code="""
    const data = source.data;
    const A = amp.value;
    const k = freq.value;
    const phi = phase.value;
    const B = offset.value;
    const x = data['x']
    const y = data['y']
    for (let i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }
    source.change.emit();
""")

amp_slider.js_on_change('value', callback)
freq_slider.js_on_change('value', callback)
phase_slider.js_on_change('value', callback)
offset_slider.js_on_change('value', callback)

layout = row(
    plot,
    column(amp_slider, freq_slider, phase_slider, offset_slider),
)

show(layout)

A: Solutions:

*

*Maybe version of your jupyer notebook is so old, so you can downgrade library or upgrade jupyer notebook.

*This code may work too:
from bokeh.resources import INLINE
import bokeh.io
from bokeh import *
bokeh.io.output_notebook(INLINE)
More details: bokeh not showing in jupyter notebook


text:
Q: Error adding React with HTML page,Unexpected token '<' I have added a React functional component with existing HTML page, getting a strange error : Uncaught SyntaxError: Unexpected token '<'
HTML

connected JS
"use strict";

function Like_button() {
  const [like, setLike] = React.useState(false);
  return (

      {like ?
you liked t
 : null}
      <button onClick={() => setLike(true)}>click</button>

  );
}

const domContainer = document.querySelector("#like_button_container");
ReactDOM.render(React.createElement(Like_button), domContainer);

A: trying replacing this in the html:
from:

to:

you need to tell it to use jsx

A: first, you should add babel-core CDN.

then add text/babel to your script like this:


text:
Q: Relation between Entropy and Temperature I have read the Entropy is defined by:
S = Q/T
which means that Entropy is indirectly proportional to temperature. Still we say that Entropy increases as temperature increases.
For example, if the temperature of a crystal is increased from 0K to 115K, we would instinctively say that entropy is increasing because kinetic energy of the particles is increasing which is leading to more randomness.
Both things contradict.
What am I missing here?

A:
I have read the Entropy is defined by:  S = Q/T

Entropy is not defined by that equation. A differential change in entropy is defined by
$$dS=\frac{\delta Q_{rev}}{T}\tag{1}$$
Where $\delta Q_{rev}$ is a reversible transfer of heat.  Then
$$\Delta S_{1-2}=\int_1^2\frac{\delta Q_{rev}}{T}\tag{2}$$

which means that Entropy is indirectly proportional to temperature.

Your conclusion that absolute entropy is inversely proportional to temperature rise is incorrect because $Q$ is a variable. To determine the entropy change you need to evaluate equation (2) for a reversible path between the initial and final equilibrium temperatures.

Still we say that Entropy increases as temperature increases.

Not necessarily.
Case in point is the reversible adiabatic (isentropic) compression of an ideal gas in which the temperature of the gas increases. Since the process is both adiabatic and reversible $\delta Q_{rev}=0$ and thus it follows from equations (1) and (2) the change in entropy is zero.
At the microscopic level, the increase in temperature results in greater molecular disorder and an increase in entropy. But the lower volume provides fewer ways to distribute the molecules (energy) reducing disorder and entropy. The result is a net change in entropy of the gas of zero.
Hope this helps.

A: The formula has $2$ variables, because heat is not a constant.
Heat is a flow of energy, and we must understand the change of entropy as a result of that flow. Normally the temperature increases when there is an heat input in a mass of material, So, energy and temperature are related. But they don't tell the whole history.
It is necessary $334 kJ$ to melt $1kg$ of water at $273 K$, but the temperature doesn't change in the process. So, the mass has more energy and the same temperature when liquid, compared to solid. And there is a change of entropy: $$\Delta S = \frac{\Delta Q}{T} = \frac{334}{273} = 1.22 kJ/K$$
In order to boil $1kg$ of water at $373 K$, it is necessary $2265 kJ$. Now the change of entropy is:$$\Delta S = \frac{2265}{373} = 6.07 kJ/K$$
So, the denominator increased, but the numerator increased much more.
When the temperature increases along the heat input, the entropy also increases, but the example of a process without change of temperature is more clear in my opinion.


text:
Q: SonarQube generate PDF report I have Jenkins to build my Java deployable and then push code into SonarQube for code scanning,
I am able to see the Bug report on SonarQube as well,
But I want a downloadable report in a PDF format or anything that can be shared after the scan.
I added the following properties in my project's pom.xml-
<properties>
<sonar.analysis.mode>preview</sonar.analysis.mode>       <sonar.issuesReport.html.enable>true</sonar.issuesReport.html.enable>
</properties>

On my local Jenkins I have the following commands -
echo ** Executing SQ Analysis **
mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.projectKey=Demo -Dsonar.sources=src/main/java    -Dsonar.login=[someKey] -Dsonar.ProjectName=Demo -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true

I am getting the following error while trying to build -
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ Linear-ingestion ---
[INFO] Installing /home/user/.jenkins/workspace/Linear/target/Linear-ingestion-1.0-SNAPSHOT.jar to /home/user/.m2/repository/com/cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT.jar
[INFO] Installing /home/user/.jenkins/workspace/Linear/pom.xml to /home/user/.m2/repository/com/cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT.pom
[INFO] Installing /home/user/.jenkins/workspace/Linear/target/Linear-ingestion-1.0-SNAPSHOT-jar-with-dependencies.jar to /home/user/.m2/repository/com/cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT-jar-with-dependencies.jar
[WARNING] Attempt to (de-)serialize anonymous class hudson.maven.reporters.MavenArtifactArchiver$2; see: https://jenkins.io/redirect/serialization-of-anonymous-classes/
[WARNING] Attempt to (de-)serialize anonymous class hudson.maven.reporters.MavenFingerprinter$1; see: https://jenkins.io/redirect/serialization-of-anonymous-classes/
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 26.531 s
[INFO] Finished at: 2018-07-04T13:41:08+05:30
[INFO] ------------------------------------------------------------------------
Waiting for Jenkins to finish collecting data
[JENKINS] Archiving /home/user/.jenkins/workspace/Linear/pom.xml to com.cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT.pom
[JENKINS] Archiving /home/user/.jenkins/workspace/Linear/target/Linear-ingestion-1.0-SNAPSHOT.jar to com.cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT.jar
[JENKINS] Archiving /home/user/.jenkins/workspace/Linear/target/Linear-ingestion-1.0-SNAPSHOT-jar-with-dependencies.jar to com.cloudlytics/Linear-ingestion/1.0-SNAPSHOT/Linear-ingestion-1.0-SNAPSHOT-jar-with-dependencies.jar
[Linear] $ /bin/sh -xe /home/user/office/R&D/apache-tomcat-8.5.31/temp/jenkins3011322823073246601.sh
channel stopped
+ echo RemoteSystemsTempFiles bin log4j.properties pom.xml src target Executing SQ Analysis RemoteSystemsTempFiles bin log4j.properties pom.xml src target
RemoteSystemsTempFiles bin log4j.properties pom.xml src target Executing SQ Analysis RemoteSystemsTempFiles bin log4j.properties pom.xml src target
+ mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.projectKey=Linear -Dsonar.sources=src/main/java -Dsonar.login=f51956611fa53b292bb19e25752cb22b5afe893e -Dsonar.ProjectName=Linear sonar-runner -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.cloudlytics:Linear-ingestion:jar:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework:spring-core:jar -> version ${springframework.version} vs ${spring.version} @ line 52, column 15
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework:spring-context:jar -> version ${springframework.version} vs ${org.springframework-version} @ line 67, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------< com.cloudlytics:Linear-ingestion >------------------
[INFO] Building Linear-ingestion 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- sonar-maven-plugin:3.4.1.1168:sonar (default-cli) @ Linear-ingestion ---
[INFO] User cache: /home/user/.sonar/cache
[INFO] SonarQube version: 6.7.4
[INFO] Default locale: "en_IN", source code encoding: "UTF-8"
[INFO] Issues mode
[WARNING] The use of the issues mode (sonar.analysis.mode=issues) is deprecated. This mode will be dropped in the future.
[INFO] Load global settings
[INFO] Load global settings (done) | time=454ms
[INFO] Server id: AWRKrQutLb-E1SWiQK4O
[INFO] User cache: /home/user/.sonar/cache
[INFO] Exclude plugins: devcockpit, ldap, authgithub, authbitbucket, pdfreport, authaad, googleanalytics, governance
[INFO] Load plugins index
[INFO] Load plugins index (done) | time=141ms
[INFO] Scanning only changed files
[INFO] Process project properties
[INFO] Load project repositories
[WARNING] Project doesn't exist on the server. All issues will be marked as 'new'.
[INFO] Load project repositories (done) | time=72ms
[INFO] Load quality profiles
[INFO] Load quality profiles (done) | time=2536ms
[INFO] Load active rules
[INFO] Load active rules (done) | time=1558ms
[INFO] Load metrics repository
[INFO] Load metrics repository (done) | time=80ms
[INFO] Project key: Linear
[INFO] -------------  Scan Linear-ingestion
[INFO] Load server rules
[INFO] Load server rules (done) | time=804ms
[INFO] Base dir: /home/user/.jenkins/workspace/Linear
[INFO] Working dir: /home/user/.jenkins/workspace/Linear/target/sonar
[INFO] Source paths: src/main/java
[INFO] Source encoding: UTF-8, default locale: en_IN
[INFO] Index files
[INFO] 68 files indexed
[INFO] Quality profile for java: Sonar way
[INFO] Sensor JavaSquidSensor [java]
[INFO] Configured Java source version (sonar.java.source): 7
[INFO] JavaClasspath initialization
[INFO] JavaClasspath initialization (done) | time=14ms
[INFO] JavaTestClasspath initialization
[INFO] JavaTestClasspath initialization (done) | time=2ms
[INFO] Java Main Files AST scan
[INFO] 68 source files to be analyzed
[INFO] 45/68 files analyzed, current file: /home/user/.jenkins/workspace/Linear/src/main/java/com/blazeclan/sqs_polling_manager/xml/parser/dao/LogicallyDeleteDAO.java
[INFO] 68/68 source files have been analyzed
[INFO] Java Main Files AST scan (done) | time=12267ms
[INFO] Java Test Files AST scan
[INFO] 0 source files to be analyzed
[INFO] 0/0 source files have been analyzed
[INFO] Java Test Files AST scan (done) | time=3ms
[INFO] Sensor JavaSquidSensor [java] (done) | time=12972ms
[INFO] Sensor SurefireSensor [java]
[INFO] parsing [/home/user/.jenkins/workspace/Linear/target/surefire-reports]
[INFO] Sensor SurefireSensor [java] (done) | time=3ms
[INFO] Sensor JaCoCoSensor [java]
[INFO] Sensor JaCoCoSensor [java] (done) | time=0ms
[INFO] Sensor SonarJavaXmlFileSensor [java]
[INFO] Sensor SonarJavaXmlFileSensor [java] (done) | time=1ms
[INFO] Sensor Analyzer for "php.ini" files [php]
[INFO] Sensor Analyzer for "php.ini" files [php] (done) | time=11ms
[INFO] Performing issue tracking
[INFO] 79/79 components tracked
[INFO] ANALYSIS SUCCESSFUL
[INFO] Task total time: 22.039 s
[INFO]
[INFO] ------------------< com.cloudlytics:Linear-ingestion >------------------
[INFO] Building Linear-ingestion 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 32.370 s
[INFO] Finished at: 2018-07-04T13:41:51+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "sonar-runner". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
Build step 'Execute shell' marked build as failure
Finished: FAILURE

A: You want to execute unexistent sonar-runner goal:

mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.projectKey=Demo -Dsonar.sources=src/main/java -Dsonar.login=[someKey] -Dsonar.ProjectName=Demo sonar-runner -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true

You have to remove it:

mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.projectKey=Demo -Dsonar.sources=src/main/java -Dsonar.login=[someKey] -Dsonar.ProjectName=Demo -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true

I would recommended to remove more parameters:

*

*sonar.projectKey - maven plugin is responsible for generating this parameter

*sonar.ProjectName - doesn't exist (correct name is sonar.projectName), maven plugin will use vaule of name or artifactId nodes from your pom.xml file

*sonar.sources=src/main/java - maven plugin is responsible for generating value of this parameter

*sonar.analysis.mode=preview - deprecated and shouldn't be used (since 6.6, you use 6.7.4)

*sonar.issuesReport.html.enable - Issues Report Plugin which uses this parameter is incompatible with SonarQube 6.7.4

Finally you can execute a simple and short command:

mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.login=[someKey]


text:
Q: Not all branches created when migrating from CVS to ClearCase We are moving our code from CVS to ClearCase in order to consolidate our history in only one vcs system following the guidelines provided here http://www.ibm.com/developerworks/forums/message.jspa?messageID=13728313.
At first glance everything looked fine. All versions of all files appear to have been migrated, all branches and tags from CVS exist in ClearCase.
However not all files have branches created correctly (in my opinion). The example file.bat
has the following history (hope the ascii drawing is understandable).
1.1
1.2 --- SOME_TAG
1.3 --- SOME_OTHER_TAG
   |---- BRANCH_1
1.4 --- BRANCH_2
       |- 1.4.2.1
       |- 1.4.2.2

Now, both SOME_TAG and SOME_OTHER_TAG is created and applied correctly in ClearCase. BRANCH_2 is created from CVS version 1.4 with version 0 on the branch having the same creation date/time as the CVS version 1.4. Which is good. Version 1.4.2.1 and 1.4.2.2 is created as version 1 and 2 respectively on BRANCH_2.
The problem is BRANCH_1 which is not created. As a minimum I would have liked to have the branch possibly only with version 0 on it.
I can see from the output of clearexport_cvs that the issue stems from here. The BRANCH_1 tag is not included in the output from clearexport_cvs command, only SOME_OTHER_TAG.
Any good ideas as how to rectify this? I couldn't find any options or switches on the clearexport_cvs command which seemed to help me.

It is important that we keep the original timestamp from CVS in order to be able to get the correct sourcecode for old builds.  We used Parabuild so the only reference to CVS we have per build is similar to this "cvs update -P -A -d -D "2012-12-20 13:31:42 GMT" -r BRANCH_1"

Kind regards
Peter

A: If the clearexport_cvs doesn't work completely, and since there is no way to export only one branch, It is best to try fixing the import incrementally, and do a clearfsimport on a a dedicated ClearCase branch.
That would allow you to "patch" the history import with a few selected revisions from the CVS repo, but this isn't an automated process (unless you script the update of a CVS workspace, a bit like I did for Subversion).


text:
Q: Insert a picture with its path in Javascript Here is the image that I would like to use (HTML path - "Marlene.jpg"):

This is the javascript code where I need to put the picture:
var possible_results = [
    {

        name: "Marlene",
        //THE ANIMALS CHARACTERISTICS BY WHICH ITS MEASURED:
        colourfulness: 10,
        hairiness: 10,
        landiness: 55,
        size: 80,
        carnivore: 0,
        scariness: 40,
        sociability: 70,
        //THE SCORE IT GETS COMPARED TO THE QUIZ TAKER:
        similarity: 0,
        //BITS FOR THE RESULTS PANEL:
        desc: "Bold, beautiful and brilliant - your best match is Marlene!
 You're intelligent and powerful. Your friends love you and whilst no-one wants to mess with you,  everyone agrees - you are great!
 In the wild there are only 600,000 African elephants and it is officially classed as vulnerable.",
        img: "../../Doggo-particular/dist/pictures/Marlene/Marlene.png",

I have used this website as a tutorial:

https://moonbooks.org/Articles/How-to-add-an-image-in-a-HTML-page-using-javascript-/

The path on "img:" does not work and the code reference from the website gives me errors .
Can someone help me on how to display the image? I wouldnt mind placing the picture in the same folder and then calling it, I tried this method as well and it did not work.


text:
Q: Show that there exist an open set $V$ containing $s=1$ Let $$m=\lim_{s→1}\frac{(s-1)f′(s)}{f(s)}$$ where $f$ is an analytic function with $s=1$ as a zero of order $m$.
My question is: By using the definition of the limit show that there exist an open set $V$ containing $s=1$ such that $$((s-1)f′(s))/f(s)≤m$$

A: In general no such set exists. Let $f(s)=e^s(s-1)^m$. Then
$$
\frac{(s-1)f'(s)}{f(s)}=s-1+m>m \text{ if } s>1.
$$


text:
Q: How to send a chatlog of all written chats to a newly joined client using socket programming in Python? I have written a simple server and client py using UDP. The base is working, however I want that every time a user (client) joins, he would receive a chatlog of everything that has been said.
This is my code until now:
Server:
import socket
import threading
import queue
import pickle

messages = queue.Queue()
clients = []

# AF_INET used for IPv4
# SOCK_DGRAM used for UDP protocol

ip = "localhost"
port = 5555
chatlog=[]
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# binding IP and port

UDPServerSocket.bind((ip, port))

def receive():
    while True:
        try:
            message, addr = UDPServerSocket.recvfrom(1024)
            messages.put((message, addr))
            chatlog.append((message,addr))
        except:
            pass

def broadcast():
    while True:
        while not messages.empty():
            message, addr = messages.get()
            print(message.decode())
            if addr not in clients:
                clients.append(addr)
            for client in clients:
                try:
                    if message.decode().startswith("SIGNUP_TAG:"):
                        name = message.decode()[message.decode().index(":") + 1:]
                        UDPServerSocket.sendto(f"{name} joined!".encode(), client)
                        if len(chatlog)>0:
                            sending= pickle.dumps(chatlog)
                            UDPServerSocket.sendto(sending, client)
                        else:
                            pass
                    else:
                        UDPServerSocket.sendto(message, client)
                except:
                    clients.remove(client)

t1 = threading.Thread(target=receive)
t2 = threading.Thread(target=broadcast)

t1.start()
t2.start()

And the client
import socket
import threading
import random

client= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind(("localhost", random.randint(7000, 8000))) # random port for every client

name =  "Henk" #test name

def receive():
    while True:
        try:
            message, _ = client.recvfrom(1024)
            print(message.decode())
        except:
            pass

t= threading.Thread(target= receive)
t.start()

#this gives the server the name of the people who have entered the server
client.sendto(f"SIGNUP_TAG: {name}".encode(), ("localhost", 5555))

while True:
    message= input("")
    if message=="!q":
        exit()
    else:
        client.sendto(f'[{name}]: {message}'.encode(), ("localhost",5555))

So I am actually a bit stuck on how I will approach this. Shall create a text file where every time that a message is written it gets written on the file as well? Or shall I create some kind of string list/database where every message is stored :/


text:
Q: How can I attach a list of custom color palettes to a list of ggplot objects without printing each plot object to the screen? I have a data frame in R in which several of the columns are factors.  I'd like to create a series of bar charts showing the relative sizes of each of the factor levels.  I want to associate my own customized color palettes to each of the factors, and then customize the final layout of all of the bars and legends using the gridExtra package.
I wrote a an example script which I think should achieve that, however, I obtained a rather surprising result:
library(ggplot2)
library(grDevices)
library(gridExtra)

# Define some dummy data and put it in a data frame
fruit <- factor(c("apple", "orange", "pear", "pear", "pear",
                  "orange", "apple", "apple", "apple", "pear"))
cheese <- factor(c("cheddar", "mozarella", "gruyere", "gruyere", "gouda",
                   "parmesan", "gruyere", "gouda", "mozarella", "cheddar"))
mydata <- data.frame(fruit, cheese)
mydata$dummy <- 0

# Define some custom color schemes
foodclrs <- list()
# Plot the fruit factor in shades of red
h <- c(0.0,  0.0,  0.0)
s <- c(0.95, 0.85, 0.45)
v <- c(0.45, 0.85, 0.95)
foodclrs[[1]] <- hsv(h, s, v)
# Plot the cheese factor in shades of green
h <- c(0.33, 0.33, 0.33, 0.33, 0.33)
s <- c(0.95, 0.93, 0.85, 0.69, 0.45)
v <- c(0.45, 0.69, 0.85, 0.93, 0.95)
foodclrs[[2]] <- hsv(h, s, v)

# Create vectors with individualized text for each plot
bsiz=20
fillvars <- c("fruit", "cheese")
xlabels <- c("Fruits", "Cheeses")
lgdlabels <- c("Types of Fruit", "Types of Cheese")

# Generate a list of plots
plots <- list()
for (ii in 1:2) {
  plots[[ii]] <- ggplot(data=mydata) +
    geom_bar(aes_string(x="dummy", fill=fillvars[ii]),
             position=position_stack(reverse=TRUE)) +
    scale_fill_manual(values=foodclrs[[ii]], drop=FALSE) +
    theme_bw(base_size=bsiz) +
    labs(x=xlabels[ii], y="") +
    theme(axis.ticks.y=element_blank(),
          axis.text.y=element_blank()) +
    guides(fill=guide_legend(title=lgdlabels[ii])) +
    coord_flip()
#  print(plots[[ii]])
}

# Print the plots on my own custom-shaped grid
print(grid.arrange(plots[[1]], plots[[2]], ncol=1, nrow=2))

The output of the script looks like this:

This is not what I was expecting: the color palette for the upper bar chart should have been a range of shades of red.  It seems that, although I originally defined the plot object plots[[1]] to have a red color palette associated with it, when I actually went to print it, either R or ggplot2 (I'm not sure which) decided to use the most recent color palette instead; i.e., the one associated with plots[[2]].
Now here's the weird part.  If I uncomment the print statement in the for loop, I get two individual plots which are rendered in the correct color scheme (for brevity, I do not bother to include either of them here), and, even more interestingly, the combined bar chart object inside the grid.arrange() function now also displays the correct color scheme:

While I am happy to have stumbled across this little workaround, now I'm curious: why does it even work in the first place?
That is to say, how is it that calling the "print" statement just at the correct moment inside of the for loop causes a color palette to become permanently attached to each ggplot object, when otherwise it would not?
What's really going on here, "underneath the hood", so to speak?  And also, is there a less kludgy way that I could correct the problem?  For example, is there some other function that I could call instead of print(), to get the color palette to attach correctly to each plot object, without creating a bunch of individual "dummy" plots that I don't actually need?

A: ggplot2 isn't very good with scoping. A possible workaround is to wrap things in a function, but even then I was surprised to need force(),
f <- function(var, fill, xlab, lab){
  force(fill)
  ggplot(data=mydata) +
    geom_bar(aes_string(x="dummy", fill=var),
             position=position_stack(reverse=TRUE)) +
    scale_fill_manual(values=fill) +
    theme_bw(base_size=bsiz) +
    labs(x=xlab, y="") +
    theme(axis.ticks.y=element_blank(),
          axis.text.y=element_blank()) +
    guides(fill=guide_legend(title=lab)) +
    coord_flip()
}

pl <- purrr::pmap(.f = f,
                  .l = list(var=fillvars, fill=foodclrs,
                            xlab=xlabels,lab=lgdlabels))

grid.arrange(grobs=pl, nrow=2)

A: Explanation for what's going on under the hood: You specified your scale values as foodclrs[[ii]]. All the plot objects were evaluated at the end of the loop with the current (i.e. last) value of ii.
Workaround 1: Assuming you know beforehand how many colours you need from each palette, one possible workaround is to name all of them explicitly in a single combined palette:
combined.foodclrs <- c(foodclrs[[1]][seq_along(levels(fruit))],
                       foodclrs[[2]][seq_along(levels(cheese))])
names(combined.foodclrs) <- c(levels(fruit), levels(cheese))

> combined.foodclrs
    apple    orange      pear   cheddar     gouda   gruyere mozarella  parmesan
"#730606" "#D92121" "#F28585" "#087306" "#10B00C" "#24D921" "#4DED4A" "#87F285"

You can then use the combined palette in the loop & get correct colours in each plot:
plots <- list()
for (ii in 1:2) {
  plots[[ii]] <- ggplot(data=mydata) +
    geom_bar(aes_string(x="dummy", fill=fillvars[ii]),
             position=position_stack(reverse=TRUE)) +
    scale_fill_manual(values=combined.foodclrs, drop=FALSE) + #one combined palette
    theme_bw(base_size=bsiz) +
    labs(x=xlabels[ii], y="") +
    theme(axis.ticks.y=element_blank(),
          axis.text.y=element_blank()) +
    guides(fill=guide_legend(title=lgdlabels[ii])) +
    coord_flip()
}

print(grid.arrange(plots[[1]], plots[[2]], ncol=1, nrow=2))

Workaround 2: As per @baptiste's comment, you can store them using grobs:
plots <- list()
for (ii in 1:2) {
  p <- ggplot(data=mydata) +
    geom_bar(aes_string(x="dummy", fill=fillvars[ii]),
             position=position_stack(reverse=TRUE)) +
    scale_fill_manual(values=foodclrs[[ii]], drop=FALSE) +
    theme_bw(base_size=bsiz) +
    labs(x=xlabels[ii], y="") +
    theme(axis.ticks.y=element_blank(),
          axis.text.y=element_blank()) +
    guides(fill=guide_legend(title=lgdlabels[ii])) +
    coord_flip()
  plots[[ii]] <- ggplotGrob(p)
}

print(grid.arrange(plots[[1]], plots[[2]], ncol=1, nrow=2))

(Output is the same for both methods)


text:
Q: Where to locate CORE_VM_ENDPOINT core.yaml file when setting up fabric network? I am following instructions on Fabric Network Setup. Using Vagrant. Need to cetermine value for CORE_VM_ENDPOINT variable in core.yaml.
There is two core.yaml files in my ~/go/src/github.com/hyperledger/fabric located in examples folder and sampleconfig folder. However none of these mentions CORE_VM_ENDPOINT
So, what would be the appropriate file to edit, or I am missing any steps?

A: core.yaml file is a file that you can refer to find information regarding environment variables the fabric-peers use. Eg: If you see the following:
vm:
   endpoint:

in core.yaml file then it's corresponding environment variable will be CORE_VM_ENDPOINT. This environment variable is specified in another file (usually named docker-compose.yaml).
So you need to specify CORE_VM_ENDPOINT in a new yaml file that you will use with docker-compose to start containers.
Here is a sample yaml file
Here is another one


text:
Q: Find the maximum of $xy(72-3x-4y)$? $x$ and $y$ are positive. I have been stuck on this problem for a while now, any hints please?

A: If $72-3x-4y\leq 0$, then the product is $\leq 0$, which clearly can't be the maximum.
Hint: Multiply by 12. Apply AM-GM to $3x, 4y, (72-3x-4y)$ (which are all positive)

 $$\sqrt[3]{12xy(72-3x-4y)} \leq \frac{ 3x + 4y + (72-3x-4y) } { 3} = 24. $$

Hint: Write it as a quadratic in one variable.
If $x$ is fixed, then let $72-3x = L$, and we want to maximize $y(L-4y) = -4y^2 + yL$. This achieves its maximum when $8y = L= 72-3x$.
If $y$ is fixed, then let $72-4y = K$, and we want to maximize $x(K-3x) = -3x^2 + xK$. This achieves its maximum when  $6x = K = 72-4y$.
Thus, this gives us $8y+3x = 72 = 6x+4y$, or that $4y=3x = 24$, which agrees with the AM-GM equality case.


text:
Q: Error: Can't find a simulator to match with "iPhone 6s" Detox was working fine as expected a couple of weeks ago - i've not updated anything to my knowledge and now I keep getting the following error when trying to test (it builds fine):
Error: Can't find a simulator to match with "iPhone 6s", run 'xcrun simctl list' to list your supported devices.
      It is advised to only state a device type, and not to state iOS version, e.g. "iPhone 7"
    at AppleSimUtils.findDevicesUDID (/Users/user/Documents/work/app/e2e/node_modules/detox/src/devices/ios/AppleSimUtils.js:47:13)
    at process._tickCallback (internal/process/next_tick.js:68:7)

If I run applesimutils --list --byName "iPhone 6s" it shows 2 devices:
[
  {
    "deviceType" : {
      "name" : "iPhone 6s",
      "bundlePath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/DeviceTypes\/iPhone 6s.simdevicetype",
      "identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-6s"
    },
    "state" : "Shutdown",
    "isAvailable" : true,
    "name" : "iPhone 6s",
    "udid" : "A87C2EF9-95D2-4562-99BE-E1A39A63ABB1",
    "os" : {
      "buildversion" : "17B102",
      "bundlePath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime",
      "isAvailable" : true,
      "name" : "iOS 13.2",
      "identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-13-2",
      "version" : "13.2.2"
    }
  },
  {
    "deviceType" : {
      "name" : "iPhone 6s",
      "bundlePath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/DeviceTypes\/iPhone 6s.simdevicetype",
      "identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-6s"
    },
    "state" : "Shutdown",
    "isAvailable" : true,
    "name" : "iPhone 6s",
    "udid" : "F5A2C1D3-5416-431C-A9B5-6054A238283D",
    "os" : {
      "buildversion" : "16E226",
      "bundlePath" : "\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS 12.2.simruntime",
      "isAvailable" : true,
      "name" : "iOS 12.2",
      "identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-12-2",
      "version" : "12.2"
    }
  }
]

I've tried adding and removing the simulator through xcode and xcrun, but nothing seems to work.
Versions:
Mac 10.14.6
applesimutils version 0.7.6
detox 14.3.4
xcode 11.2.1

A: Try upgrading Detox to the latest version (14.7.1, as of 11/15/2019), there was a fix to the simulator selection logic in aa250258 released in 14.5.0 a month ago.


text:
Q: VBScript to have a local user change password at next logon? I am trying to get a script to run for a local user while logged in to have there user account require them to change their password once they log of then log back in. I have about 40 different users that all have there own local internet connection so i don't have active directory for these computers where i can easily set this. I want to be able to push out a script through remote access that will preform this action (having to reset their password).
The user account name that I am trying to run the script for is called: Ual-Lab-Tech
The script I am running is:
' Bind to local user object.
Set objUser = GetObject("Ual-Lab-Tech")

' Require password change at next logon.
objUser.PasswordExpired = 1
objUser.SetInfo

However when I run the script I am getting an error:
Script:  C:\\Users\UAL-Lab-Tech\Desktop\change password at logon.vbs
Line:   2
Char:   1
Error:  Invalid syntax
Code:   800401E4
Source   (null)

What am I doing wrong?

A: You will find a working sample here:
strComputer = "atl-win2k-01"
Set objUser = GetObject("WinNT://" & strComputer & "/kenmyer ")
objUser.Put "PasswordExpired", 1
objUser.SetInfo

A: The sample above is for local accounts.
For an AD account you have to use ADSI like this:
Set objUser = GetObject ("LDAP://CN=username,CN=Users,DC=domain,DC=local")
objUser.Put "PasswordExpired", 1
objUser.SetInfo


text:
Q: Regex expression for digit followed by dot (.) I want to find a text with with digit followed by a dot and replace it with the same text (digit with dot) and "xyz" string.
For ex.
1. This is a sample
2. test
3. string

**I want to change it to**
1.xyz This is a sample
2.xyz test
3.xyz string

I learnt how to find the matching text (\d.) but the challenge is to find the replace with text.
I'm using notepad ++ editor for this, can anyone suggest the "Replace with" string.

A: First of all, you need to escape the dot since it means "match anything (except newline depending if the s modifier is set)": (\d\.).
Second, you need to add a quantifier in case you have a 2 digit number or more: (\d+\.).
Third, we don't need group 1 in this case: \d+\..
In the replacement, it's quite simple: just use $0xyz. $0 will refer to group 0 which is the whole match.

A: For notepad++...
You must escape the period/dot character in the expression - precede it with a backslash:
\.
In my case, I needed to find all instances of "{EnvironmentName}.api.mycompany.com"
(dev.api.mycompany.com, stage.api.mycompany.com, prod.api.mycompany, etc.)
I used this search expression:
.*\.api.mycompany.com

Notepad++ RegEx Search Screenshot

A: I think the right answer is as follow:
Find: ^(\d)([.])(\s)
Replace: $1$2XYZ
That will work with "n. " being "n" a digit [0-9]. If the input should accept digits with different lengths like 10, 100, 1000... or multiples dots "." after the digit or multiple spaces after the dot, then the answer is:
Find: ^(\d*)([.])([.]*)(\s*)
Replace: $1$2XYZ
Input:

1. This is a sample
2. test
3. string
30. string
10..... string
50005...     string

Output:

1.XYZ This is a sample
2.XYZ test
3.XYZ string
30.XYZ string
10.XYZ string
50005.XYZ string


text:
Q: xcode complaining about unsupported armv7 architecture in framework which contains armv7 architecture I am building an iOS app. While linking a framework I get the following warning and error:
ld: warning: ignoring file /Users/XXX/libs/abc.framework/abc, file was built for unsupported file format ( 0x56 0x65 0x72 0x73 0x69 0x6F 0x6E 0x73 0x2F 0x41 0x2F 0x69 0x43 0x6F 0x6E 0x6E ) which is not the architecture being linked (armv7): /Users/XXX/libs/abc.framework/abc
[TRACE] :  Undefined symbols for architecture armv7:
[TRACE] :    "_OBJC_CLASS_$_myMethod", referenced from:
[TRACE] :        objc-class-ref in libcom.abc.def.a(ComAbcDefModule.o)
[TRACE] :  ld: symbol(s) not found for architecture armv7
[TRACE] :  clang: error: linker command failed with exit code 1 (use -v to see invocation)
[ERROR] :  ** BUILD FAILED **
[ERROR] :  The following build commands failed:
[ERROR] :   Ld build/Debug-iphoneos/MyApp.app/MyApp normal armv7

When I run lipo -info and file on the library inside the abc.framework file (abc.framework/Versions/A/abc.1.0.1), I see this saying that it contains the armv7 architecture:
lipo -info abc.1.0.1
Architectures in the fat file: abc.1.0.1 are: armv7 armv7s arm64 x86_64

file abc.1.0.1
abc.1.0.1: Mach-O universal binary with 4 architectures
abc.1.0.1 (for architecture armv7): current ar archive random library
abc.1.0.1 (for architecture armv7s):    current ar archive random library
abc.1.0.1 (for architecture cputype (16777228) cpusubtype (0)): current ar archive random library
abc.1.0.1 (for architecture x86_64):    current ar archive random library

So I can't link. I've spent a whole day trying everything. Why is it complaining about not being able to find the armv7 architecture when it is in there? Also, can someone explain what unsupported file format this is?


text:
Q: Delete lines from a file which opened in less mode I have a file (huge size) which cannot be opened in vi but in less mode and I want to delete the lines which I do not required. But I am unable to delete lines from file open in less mode.
Please suggest how can I delete lines in less mode

A: Probably the easiest thing would be to use sed.
sed '/pattern/d' file to delete lines containing a certain pattern.
sed 'start_line_number,end_line_number d' file to delete a range of lines.
Both examples above will just print the file contents to STDOUT without modifying the contents. If you want to modify the actual file add -i or --in-place immediately after sed.

A: Yes it is possible

*

*Open the file in less.

*Type vi. The file will open in vi.

*Press Esc [number_of_lines] dd, then save the file (type :wq to write and quit).

*It will go back to less with modified content.

*Exit


text:
Q: MySQL and Visual Studio not recognizing primary key I've reduced this as basic as I can.  I'm getting the error: "dynamic sql generation for the update command is not supported against a selectcommand that does not return any key column information".
This would normally mean I don't have a primary key.  But I do and here is the create table for it (MySQL):
CREATE TABLE `testtable1` (
  `test_id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `test_label` varchar(10) NOT NULL,
  PRIMARY KEY (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

MySQL and such are a fresh install of the latest stable release.  My Visual Studio is Community 2019.
I can add the Data Connection in Server Explorer just fine and I can see all two columns.  This is the only table in the testdb.  The above create statement comes from that connection in fact and it identifies that there is a primary key (test_id).  Looking at the column properties in Server Explorer shows the Column Key property having "PRI" in it.  Seems like it knows it's the primary key to me.
I go and add a new winform and only put a DataGridView on it.  From the Wizard on "Choose Data Source I select Add Project Data Source and pick database, dataset, select the connection string, pick all columns from the table, and click finish.
That's when I get the error.
Can't get much more basic than that.  What am I screwing up?  Is there some setting in MySQL or Visual Studio that's set wrong?  This is my first time trying MySQL and I'm not having any luck.
Gurr, Greg.
:)

A: Found an answer of sorts.  The Unsigned in the MySQL definition was definitely causing the Connector or Visual Studio to choke.  Removing it from the column definition allowed it to work correctly.
I can live with a Signed BIGINT primary key column for my table.
-gg


text:
Q: Quais seriam as formas de utilizar o return no JavaScript e como elas funcionam? Acho que por mais simples que possa parecer, eu acabei não entendendo muito bem o return do JavaScript.
Ficaram algumas dúvidas que eu gostaria de compreender melhor, e quais seriam as melhores situações para utilizá-las.
function soma(valor1,valor2){
    var resultado = 0;
    resultado = valor1 + valor2;
    return resultado;
}

Por que quando eu uso return resultado o código funciona e na segunda opção não?
function soma(valor1,valor2){
    var resultado = 0;
    resultado = valor1 + valor2;
    return;
}

A:
A declaração return finaliza a execução de uma função e especifica
  os valores que devem ser retornados para onde a função foi chamada.
  (Documentação MDN)

Ao omitir no return a variável resultado, criada dentro da função, quem chamou a função não recebe nenhum valor, apenas executou a função e finalizou no return, que nem é necessário no final da função, já que o final da função é onde ela acaba.
O return (sem nada) só é útil no meio da função, quando você quer finalizar ela naquela linha.
Por exemplo:
function f(x){

   if(x != 1){
      return; // finaliza a função sem retornar nada
      // return x*10; // ou finaliza retornado alguma coisa
   }

   alert("alerta");

}

No caso acima, se a condição x != 1 for atendida, a função termina e não chega nem no alert.
Mas o return geralmente é usado para retornar um valor criado dentro da função, como no seu primeiro exemplo.

A: O return é utilizado para retornar algo, se você não definir nada para ele, ele somente retornará uma saída do método:
   function soma() {

    //retorna soma 3 mais 4 => 7
    return (3 + 4);

    }

   function verdadeOuMetira(p1, p2) {
      //retorna true (caso a soma seja 7), ou false (caso a soma seja diferente de 7)
      return ((p1 + p2) == 7);
   }

    function soma() {
    var soma = (3 + 4);
    //retornando um valor de uma variável, retorna soma 3 mais 4 => 7
    return soma;

    }

    function soma(callback) {

    //retorna soma 3 mais 4 => 7
    return callback();

    }

   // passando um método callback de soma para o método de cima
      soma(function(){
            return 3 + 4;
       })

Para entender melhor, veja o exemplo abaixo:
    function soma() {
    var soma = (3 + 4);
    return; //aqui você está saindo da função (pois você não definiu nenhum parâmetro para ser retornado...

    //o código foi retornado acima, então essa soma não será retornada
    return soma;

    }

Usando return;você está fazendo uma saída do código, para ter um valor de saída, pode utilizar return false;, neste caso você consegue testar seu método:
Exemplo:
function checkValor(valor) {
  //aqui você está dizendo em qual caso ele vai retornar (verdadeiro ou falso)...
  if(valor.indexOf('texto') !== -1) {
    return true;
  }
  return false;
}
if (!checkValor('onnoon')) {
    console.log('sucesso, não existe mesmo!')
}
if (checkValor('onnoon')) {
    console.log('não é válido!')
}
if (checkValor('texto')) {
    console.log('É válido!')
}


text:
Q: DDR3 SE signal, is 50Ohm impedance necessary? I want to design a 6 layer PCB for an Allwinner H3 and DDR3, but the PCB workshop just have the stack-up shown in the image.

With this stack-up, The calculation for striplines impedance is difficult. The width of SE signal at 50 Ohm is 18 mils. So big for DDR3 signals.
Can I layout the DDR3 SE signal with 80 or 100 Ohm instead of 50 Ohm ?

A: It might work or not...
The only thing we can be sure of is that it should work if you use a 50 Ohm impedance. Anything else is pure speculation because it's out of specs.
Of course, there is no "brick wall" (i.e.: at 50 Ohm it works but at 51 Ohm it doesn't work at all.). The transition is smooth and there is a region between the "it works" and "it doesn't work" : The infamous "It sometimes works".
Intermittent failures are part of the most difficult things to debug.
DDR3 memory buses are very sensitive to signal integrity. And you will find documents that list an intimidating set of rules one has to follow to ensure good integrity on that bus. For instance :

*

*Length matching between some signals (but no all)

*Impedance: single ended and differential

*Grounding: Don't cross a plane boundary (GND plane or power plane)

*Kind of decoupling caps: Use Y5V and you are stuck...

*...

Because debugging memory issues can be very difficult and time consuming, I strongly suggest that you try to follow exactly all the recommendations and guidelines. It's difficult enough to ensure a reliable design when trying to follow the rules...
If your PCB shop cannot provide a suitable stack-up, find another one that can.

A: With signal routing on top and bottom layer, and GND on layer 2 and 5, you should have to trouble reaching 50 ohm SE impedance with the 0.11mm prepreg and about ~5mil traces.