text:
Q: working with array of promises that have promises inside Im doing the following code:
let promises = []
querySnapshot.forEach(function (doc) {
  promises.push(
    promiseFunction()
    .then((postCounters) => {
      promiseFunction2()
        .then((myRate) => {
        console.log('save array with postCounters AND myRate data')
      })
    })
  )
})
Promise.all(promises).then(() => {
  console.log('the array with postCounters AND myRate data')
})

Things are getting wrong. The returned Promise.all doesn't wait until promiseFunction2 is run, so the second function is not working and im not getting the promiseFunction2 data inside my array, just the first.
What i think is happening is: Promise.all is getting after all promiseFunction is run, BUT it doesn't wait until the second function, i would like to wait BOTH to complete before getting promise all, should i use two Promise.all???
Im not very familiar with the syntax of Promise.all and im just using the promiseFunction().then() approach
(event to get my code consistent to scale well)

A: You should use map to turn one array into another. The problem is that you're not returning the promise chain generated from promiseFunction2:
const promises = querySnapshot.map((doc) => (
  promiseFunction()
    .then((postCounters) => (
      promiseFunction2()
        .then((myRate) => {
        console.log('save array with postCounters AND myRate data')
      })
    ))
));
Promise.all(promises).then(() => {
  console.log('the array with postCounters AND myRate data')
});

Or, for far less indentation noise, use async/await:
const promises = querySnapshot.map(async (doc) => {
  const postCounters = await promiseFunction();
  const myRate = await promiseFunction2();
  // do stuff with myRate
  console.log('save array with postCounters AND myRate data')
  // async functions automatically return promises that resolve when the block finishes
});
Promise.all(promises).then(() => {
  console.log('the array with postCounters AND myRate data')
})

A: Use this way
let addQueue = q();

for (let i = 0; i < querySnapshot.length; i++){
 addQueue = addQueue.then(promisFunction.bind(null, querySnapshot[i]))
                        .then(function (r) {
                            console.log('OK: ', r);
                        })
}

function promisFunction(doc){
let deferred = q.defer();

promisFunction2().then((postCounters) =>{
and function for myRate
deferred.resolve({ a: doc, b: postCounters c: myRate }) }
})
return deferred.promise//
}

 addQueue.then(function (result) {
                    console.log('your result is here');
                })

A: See if this helps.
  let promises = []
  querySnapshot.forEach(function (doc) {
    promises.push(
      promiseFunction()
        .then((postCounters) => {
          return promiseFunction2();
        })
    )
  })
  Promise.all(promises).then((values) => {
    console.log(values);
  })

A: Why you don't use promise like this?!
let promises = [],
    promiseArr = [];
querySnapshot.forEach(function (doc) {
    promises.push(
        promiseFunction()
    );
});
Promise.all(promises).then((res) => {
    res.forEach(itm => {
        promiseArr.push(
            promiseFunction2()
        );
    });

    Promise.all(promiseArr).then((res) => {
        console.log('save array with postCounters AND myRate data');
    });

});

A: In your example you don't show why promiseFunction2 needs to wait for promiseFunction. Neither of the functions are returning something so it's not clear what value you claim is missing.
If promiseFunction2 needs to run after promiseFunction then you can do:
let promises = [];
querySnapshot.forEach(function (doc) {
  promises.push(
    promiseFunction()
    .then((postCounters) => {
      return promiseFunction2()//missing return here
      .then((myRate) => {
          console.log('save array with postCounters AND myRate data');
          return [postCounters,myRate];//missing return here
      })
    })
  );
})

If you don't need to wait for promiseFunction to finish to start promiseFunction2 then you can do:
let promises = [];
querySnapshot.forEach(function (doc) {
  promises.push(
    Promise.all(
      promiseFunction(),
      promiseFunction2()
    )
  );
})

In both cases the result is an array of array:
Promise.all(promises)
.then(
  function(results){
    results.forEach(
      function(result){
        console.log("postCounters:",result[0]);
        console.log("myRate:",result[1]);
      }
    )
  }
)


text:
Q: python struct unpack bad char I am trying to write a small package parser, first time using python struct for it:
content = struct.unpack("BBBBBB<HBB", packet[:10])

packet contains the following bytes:
7e03 ffff ff0f 1e00 1001 0c00 0000 0000

I get this error: struct.error: bad char in struct format but I have no clue how I should know whats the bad char mentioned. Also on that note: does struct support grouping tuple elements, because I would rather have the unpacking done like this:
content = struct.unpack("BB(BBBB)<HBB", packet[:10])

Because this is an address, and having it inside its own tuple in content would it make cleaner imo.

A: < can't be in the middle of the format string, it needs to be at the front.
It specifies little-endian byte order and applies to the whole packet (but it makes no difference for single-byte values like those specified with B):
>>> packet = b'\x7e\x03\xff\xff\xff\x0f\x1e\x00\x10\x01\x0c\x00\x00\x00\x00\x00'
>>> struct.unpack("<BBBBBBHBB", packet[:10])
(126, 3, 255, 255, 255, 15, 30, 16, 1)

To interpret four bytes as one unsigned integer, use I or L:
>>> struct.unpack("<BBIHBB", packet[:10])
(126, 3, 268435455, 30, 16, 1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unzip command is Archiving instead of Extracting I m trying to unzip "Data.zip" into the current directory using:
unzip Data.zip

But i get a prompt:
Archive: Data.zip
replace /home/jaggib/Data.zip? [y]es, [n]o, [A]ll, [N]one, [r]ename:'

It looks to me that it is creating archive instead of uncompressing it.
I tried to specify a destination directory, but that gives the same result.
I am using Ubuntu 13.10. Am not following the syntax correctly or is there an additional argument that i have to use.

A: The file itself probably has a file (or a directory) in it called "Data.zip" and therefor prompts you on what to do.Do this:
unzip Data.zip -d tmp/

It will create directory tmp/ and extract the files in that directory. Since that directory does not have a Data.zip it will extract without a warning.


text:
Q: Angular Tooltip on Focus I'm using Angular Tooltip in my application and want to trigger tooltip on focus but having issue to trigger this. It works fine with mouseover and mouseleave but does not work on focus event.
here it is how I'm using it
<input type="password"
   tooltip-show-trigger="focus"
   tooltips tooltip-template="Password must include at least one upper case letter, one lower case letter, one numeric digit and one special character."
   id="Password"
   name="Password"
   class="form-control"
   placeholder="New Password"
   required
   autofocus
   ng-model="Password" />

I don't know what I'm doing wrong or missing something. Any kind of help will be appreciated.

A: It may help someone else...
focus isn't the actual event to trigger angular tooltip on focus. It is actually focusin and focusout according to this issue discussion. it resolved my issue.
 tooltip-show-trigger="focusin" tooltip-hide-trigger="focusout"


text:
Q: How to get records after a certain time using SQL datetime field (not by whole hour) I am on SQL Server 2017.
If I have a datetime field (systime), how do I get just records created later than a certain time, ignoring the date altogether? An example of the field would be: 2015-05-20 18:23:49.000
I want to find any records at or after  5.30 PM  or  another scenario, no later than 7.25 PM. How would I be able to get either result?
The below query would give me the result based on the whole hour.
select *
from myTable
where datepart(hh, sysdate) > 17

Here are more date time examples
2015-08-30 21:34:52.000
2015-09-30 20:20:34.000
2015-11-03 19:53:34.000
2015-12-08 22:49:58.000
2016-02-01 18:47:50.000
2016-02-05 18:41:19.000
2016-02-05 18:41:20.000

A: You can check if time part is after 17:
Select * from myTable where convert(char(8),myDatetimeField,114) > '17:30:00';

Select * from myTable where convert(char(8), myDatetimeField, 114) <= '19:25:00';


text:
Q: From Eclipse to android studio internet problems So,I am importing a project that works perfectly (tested on 4 phones) from Eclipse to Android studio and when I run the application WITHOUT modifying anything at all, it won't allow me to use the internet at all.
As for code...it's pointless to post any ,because I created an application that does nothing but connect to a database and it still won't work, while the exact same code will work perfectly when I run the application from Eclipse to my phone. (Same phone by the way)
Just to make sure that won't be an answer: I HAVE the permissions added in my manifest.
Any suggestions?
//manifest.
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="vlad.tests.com.udptextconnection" >

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

// Build.gradle (module:app)
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "vlad.tests.com.udptextconnection"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

//Build.gradle (project [project-name])
    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

A: Try putting permissions outside of application tag.

A: Not sure if it'd work but, try and clean your project.
Go to Build->Clean Project.
Try Build->Rebuild Project.


text:
Q: docker fails to start elasticsearch start command:docker run --name elasticsearch --restart always -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms128m -Xmx256m" -v /mydata/elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /mydata/elasticsearch/data/:/usr/share/elasticsearch/data -v /mydata/elasticsearch/plugins:/usr/share/elasticsearch/plugins -d elasticsearch:8.2.0
error message:Exception in thread "main" java.nio.file.FileSystemException: /usr/share/elasticsearch/config/elasticsearch.yml.5_UsZrgbT-ORzBHNjBfbEw.tmp -> /usr/share/elasticsearch/config/elasticsearch.yml: Device or resource busy
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:100)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:416)
at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:266)
at java.base/java.nio.file.Files.move(Files.java:1432)
at org.elasticsearch.xpack.security.cli.AutoConfigureNode.fullyWriteFile(AutoConfigureNode.java:1126)
at org.elasticsearch.xpack.security.cli.AutoConfigureNode.fullyWriteFile(AutoConfigureNode.java:1138)
at org.elasticsearch.xpack.security.cli.AutoConfigureNode.execute(AutoConfigureNode.java:687)
at org.elasticsearch.common.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:81)
at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:112)
at org.elasticsearch.cli.Command.main(Command.java:77)
at org.elasticsearch.xpack.security.cli.AutoConfigureNode.main(AutoConfigureNode.java:157)


text:
Q: PHP Soap Client Errors I'm trying to use a web service provided by a third party organisation.
The URL for the service is this
This is what I've tried:
$sc = new SoapClient( $my_wsdl_url, array(
            'soap_version' => SOAP_1_2
        ) );

First problem: When checking for the provided functions, I get a UNKNOWN type:
array(3) {
  [0]=>
  string(26) "UNKNOWN getDeletedHotels()"
  [1]=>
  string(23) "UNKNOWN getMasterData()"
  [2]=>
  string(44) "UNKNOWN getHotelData(dateTime $dRequestDate)"
}

I found this, but I have no access to the SOAP-Server. So, how can I change settings in my SOAP-Client in order to get the correct return types?
Nevertheless, I tried to call the above function getHotelData(), but it takes about 2 minutes to get a response. And the response is an error:
Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http
body, No Content-Length, connection closed or chunked data in [...]

There are several posts with the same error message. I read this post here and tried it by adding these settings to the client:
 $sc = new SoapClient( $my_wsdl_url, array(
            'soap_version' => SOAP_1_2,
            'trace' => 1,
            'stream_context' => stream_context_create( array(
                'http' => array(
                    'protocol_version' => 1.0
                ) ) );
        ) );

After that, the server is not responding at all!
So, I am a little bit stuck here. Can somebody push me in the right direction?
PHP-Version is 5.4.19, on a mac running xampp
Update
I reduced the above code to the minimal requirements (without the login stuff), but still I cannot get the complete list.
When testing with one of Amazon's Webservices, I get a complete list of all available functions.
$sc = new SoapClient( 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl', array(
    'soap_version' => SOAP_1_2,
) );

// List all functions. This works
var_dump( $sc->__getFunctions() );

So, could it be that the webservice itself is not setup correctly?

A: I ended up with a working solution, inspired by this answer here: Sending Raw XML via PHP SoapClient request after getting the required request XML by using the software from http://www.soapui.org/


text:
Q: Unique constraint and index I have a table in SQL Server containing some user related info where the primary key is id (auto increment by 1) and has a column named userId. Each user can only has one record in the table, so I have added a unique constraint on column userId. As per SQL Server docs, SQL Server will automatically create an index for the unique constraint column.
For the usage on the table, there can be many update and insert operations, as well as select operations, and that's where my questions arise.
I see that the index that got created automatically by SQL Server on the unique constraint column is a non-clustered index, where it is good for update and insert operations, but for select operation, it is not as fast as the clustered index. (ref. differences-between-a-clustered-and-a-non-clustered-index)

*

*For this table, there can be many select by userId operations. From the performance perspective, should a clustered index on userId be created, given that clustered index is the fastest for read operations ?

*If yes, but a non-clustered index has already been automatically created on column userId, could a clustered index still be created on the userId column? (I have found some similar question, from the answers, it seem like if doing so, it will first search through the non-clustered index, then it will points to the clustered index and continue that search non-clustered-index-and-clustered-index-on-the-same-column)

A: Assuming your table was created in the following manner:
CREATE TABLE dbo.users
(
  id int identity(1,1),
  userId int,
  userName varchar(100),
  emailAddress varchar(100),
  constraint PK_dbo_users primary key (Id)
);

alter table dbo.users
add constraint UNQ_dbo_users_userId UNIQUE(userId);

... then you already have a clustered index on "id" column by default.
A table can only have one clustered index, as Jonathon Willcock mentioned in the comments. So you cannot add another clustered index to userId column.
You also cannot recreate the clustered index to switch it to the userId column, as the constraints must much the existing constraint. Also, assuming there are foreign key references involved from other tables, you would have to drop the foreign keys before you can drop the users table.
Another option is to create a nonclustered covering index with an INCLUDE clause that contains all the columns needed for your query. This will avoid key lookups in the query plan.
For example:
create nonclustered index IX_dbo_users
on dbo.users (userId) include (id, userName, emailAddress);

Whether the PK and/or clustered index should be on userId or Id column depends on your users queries. If more queries, or more important queries, rely on "id" having clustered index, then keep it. Etc.
But if your table does not already have a clustered index, then yes, add it on userId column.


text:
Q: Is the surreal number $\omega(\sqrt{2}+1)+1$ a prime? In the 1986 book An Introduction to the Theory of Surreal Numbers, Gonshor, on page 117, notes that it is an open problem whether $\omega(\sqrt{2}+1)+1$ is a prime, using the standard definition of integral number he introduces earlier in the chapter.
I'll give a little background, as requested, using Gonshor as a reference.
The surreal numbers are a superclass of the infinitesimals, though I'm not familiar with their exact sizes.
A surreal number is a function from an initial segment of the ordinals into $\{+,-\}$. (An ordinal sequence which terminates)
Then, given two surreals, $a$, $b$, let $a < b$ if $a(\alpha) < b(\alpha)$ where $\alpha$ is the first place they differ, with the convention $- < 0 < +$, where $0$ is an abuse of notation that simply means that the function is undefined at that point. So, $(++) > (+) > (+-)$. Some investigation gives that
$0\sim (),\ 1 \sim (+),\ 2 \sim (++), \ldots$ Most of the book is spent on embedding the reals and infinitesimals in the surreals.
Then you can define the generalized integers in the surreals: $a$ is an integer if the exponents in normal form of $a$ are non-negative, and if a $0$ exponent occurs, then the real coefficient is an integer. Normal form is a bit complicated to define, but basically you write numbers in terms of $\omega$ and $\epsilon$ where $\omega$ is the first infinite ordinal, so $(+++...)$ times and $\epsilon = 1/\omega$, which also exists in the surreals. So, $1/3\omega^2+3$ is a generalized integer, and so is $\sqrt{\omega}+2$, but not $0.5+\omega^{-1}$, as both terms violate the definition.
For the definition of prime, $1=(+)$ is still a unit, so primality amounts to proving that a surreal has more than two factors (itself and $1$). $\omega$ is factorizable since $n \in  \mathbb{N}$ and $\omega/n$ are both generalized integers.
That trick doesn't work with $\omega(\sqrt{2}+1)+1$.
Is this still an open problem? The book is a couple decades old (picked it up at the library), and searching for surreal numbers doesn't turn up many results.
Thanks

A: This is not an answer but it is too long for a comment. I think that the question is still open, and that in general there are no known prime elements with finite support besides primes in $\mathbb{Z}$.

There are a few papers, besides Conway and Gonshor's books, that deal with this type of question. A more general problem is the existence of prime or irreducibles in integer parts of real-closed fields, such as $\mathbf{Oz}$ (the "omnific integers"), which can be written as a Hahn series ring $K((G^{\leq 0}))$ where $G$ is an additively denoted ordered group.
For those with more emphasis on $\mathbf{Oz}$, you can look at Alessandro Berarducci's Factorization in generalized power series (Trans. Amer. Math. Soc. 352 (2000) 553-577, doi:10.1090/S0002-9947-99-02172-8), which I think first found out that one could apply valuation theoretic insight to this question. A more recent paper which in particular gives more recent references for this type of question is Sonia L'Innocente and Vincenzo Mantova's preprint Factorisation theorems for generalised power series, arXiv:1710.07304.
Berarducci gave a positive answer to Conway's conjecture that $\omega+\omega^{\frac{1}{2}}+\omega^{\frac{1}{3}}+ \cdot \cdot \cdot+1$ is irreducible. Daniel Pitteloud subsequently proved that this number is prime in $\mathbf{Oz}$.
L'Innocente and Mantova generalised some results and proved that certain numbers with infinite support as series are prime.

A: The answer is no. The factorization is $(\sqrt{\sqrt{2}+1}\omega^{1/2} - \sqrt{2\sqrt{\sqrt{2}+1}}\omega^{1/4}+1)(\sqrt{\sqrt{2}+1}\omega^{1/2} + \sqrt{2\sqrt{\sqrt{2}+1}}\omega^{1/4}+1)$


text:
Q: performance between define variable global and initialize regularly As the title of the article, I'm not sure which is faster and more optimal. Can someone help?
My Example:
bootstrap.php
$query = new Query();

file1.php
include bootstrap.php;
$query->where('a = b')->get('table');

file2.php
include bootstrap.php;
$query->where('a = b')->get('table');

OR Measure 2
bootstrap.php
function query() {
  return new Query();
}

file1.php
include bootstrap.php;
query()->where('a = b')->get('table');

file2.php
include bootstrap.php;
query()->where('a = b')->get('table');

Currently, I am prioritizing the second method because it supports code prompts better.
Thanks


text:
Q: Convergence of $\sum_{n=0}^{\infty}(-1)^{a_n}$ for non-negative integer $a_n$. I am interested (purely for the sake of curiosity) in sums of the form $\sum_{n\geq0}(-1)^{a_n}$ and particularly which sequences $a_n$ (of non-negative integers only) lead to the series being conditionally convergent (I say conditionally because clearly $\sum|(-1)^{a_n}|$ diverges). We can reduce each such sequence of exponents modulo $2$ since the parity completely determines the value of each summand.
My question is: "Does there exist a non-trivial condition on the $a_n$ that is both necessary and sufficient for such a series to converge?"
A motivating example: Does the series $S = \sum_{n=0}^{\infty}(-1)^{F_n}$ , where $F_n$ is the $n$-th Fibonacci number, converge?
$$S = 1 - 1 - 1 + 1 - 1 - 1 + \cdots $$
$$ = (1 - 1) - 1 + (1 - 1) - 1 + \cdots $$
$$ = 0 - 1 + 0 - 1 + \cdots = -\infty$$
But the above may just be a consequence of Riemanns rearrangement theorem if the series is in fact conditionally convergent.

A: Since the general term does not go to zero, the series never converges.

A: I think this can interest you. I'd add that you can use another definition of "convergence of series".
Yes, this one does not converge. But, as you pointed out with your example, you can think of it as a "mean" of its term.
Let's define $S_n = \sum_{k=0}^n (-1)^{a_k}$. What can you say about the convergence of $u_n := \dfrac{S_0 + ... + S_n}{n+1}$? It depends on $a_n$. One could say that it defines another way of convergence of the serie (even if stricto sensu, it does NOT converges with its classic definition!).
You can call it "Cesaro-convergence" or C-convergence (see this).


text:
Q: Paging Error: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip' I have this following codes. I did not use a sorting just with the filtering or searching of information. I did not use skip method also. Please see codes below.
public ActionResult Index(string currentFilter=null, string search=null, string searchBy=null, int? page=1)
    {
        var student = from d in db.Student_vw
                      where d.is_active == true
                      select d;
        if (searchBy == "default")
        {
            student = student.OrderByDescending(x => x.ID_Number);
        }

        //searching of an item
        if (!String.IsNullOrEmpty(search))
        {
            student = student.Where(x => x.ID_Number.Contains(search) || x.student_fname.Contains(search)
                || x.student_lname.Contains(search) || x.section_name.Contains(search) || x.course_name.Contains(search)
                || x.student_address.Contains(search) || x.batch_name.Contains(search) || x.adviser_fname.Contains(search) || x.adviser_lname.Contains(search) || x.student_email_add.Contains(search));
        }
        else {
            student = student.OrderByDescending(x => x.ID_Number);
        }
        ViewBag.CurrentFilter = search;

        int pageSize = 25;
        int pageNumber = (page ?? 1);

        var returnMe = student.ToPagedList(pageNumber, pageSize);

        return View(returnMe);
    }

Thanks in advance for the help.

A: in your code, when search having value, students not ordered. do as below
public ActionResult Index(string currentFilter=null, string search=null, string searchBy=null, int? page=1)
    {
        var student = from d in db.Student_vw
                      where d.is_active == true
                      select d;
        //if (searchBy == "default")
        //{
        //    student = student.OrderByDescending(x => x.ID_Number);
        //}

        //searching of an item
        if (!String.IsNullOrEmpty(search))
        {
            student = student.Where(x => x.ID_Number.Contains(search) || x.student_fname.Contains(search)
                || x.student_lname.Contains(search) || x.section_name.Contains(search) || x.course_name.Contains(search)
                || x.student_address.Contains(search) || x.batch_name.Contains(search) || x.adviser_fname.Contains(search) || x.adviser_lname.Contains(search) || x.student_email_add.Contains(search));
        }
        //else {
        //    student = student.OrderByDescending(x => x.ID_Number);
        //}
        ViewBag.CurrentFilter = search;

        int pageSize = 25;
        int pageNumber = (page ?? 1);

        var returnMe = student.OrderByDescending(x => x.ID_Number).ToPagedList(pageNumber, pageSize);

        return View(returnMe);
    }

A: @Jen- You need to use OrderBy before student.ToPageList(pageNumber, pageSize)

A: SQL doesn't guarantee the order of results unless you give it an order by, so using Take or Skip (which PagedList does internally) without an order by doesn't make any logical sense and in theory could give you totally different results each time.
The way you have written your logic you can fall through without every hitting on of the order by statements.


text:
Q: How to get value in order with a small average value I've got a data frame like
x  y    cluster
0  112  4
0  113  4
1  111  4

and I'll get locations from this code:
for n in range(0,9):
...
    location = np.array(cluseter_location )

I want to sort it out in the order of column 'cluster' with small columns 'y' means, so I tried:
for n in range(0,9):
    cluster_ = data2[data2['cluster_id']== n]

    ...

A: Modifying your code to sort list of tuples
In your code, instead of appending the cluster_int, just append the tuple (n, cluster_int), and then later while sorting, use lambda to sort by the second value of each tuple.
for n in range(0,9):
    cluster_ = data2[data2['cluster_id']== n]

    cluster_list = cluster_['y'].tolist()
    cluster_avg = sum(cluster_list)/len(cluster_list)

    cluster_int = int(cluster_avg)

    print("cluster_id : %d" %n ,"average : %d" %cluster_int)
    lst.append((n,cluster_int))                              #<-------
    a = sorted(lst, key = lambda x:x[1])                     #<-------

print(a)                                                     #<-------

ordered_average = [average for cluster, average in a]        #<-------
ordered_clusters = [cluster for cluster, average in a]       #<-------

print(ordered_average)                                       #<-------
print(ordered_clusters)                                      #<-------

#cluster and average together
[(4,112),(8,121,(1,127),(6,139),(5,149)]

#averages sorted
[112, 121, 127, 139, 149]

#clusters sorted
[4,8,1,6,5]

Alternate way using pandas
A quicker way to do this would be directly sorting the pandas dataframe after groupby.
print(df.groupby('cluster')['y'].mean().reset_index().sort_values('y'))


text:
Q: Cooresponding CopyResource method in D3D9 I know it's easy to copy vertex/index buffer in D3D10 with
IDirect3D10::CopyResource(...)
interface.
How to do the same work in D3D9? Is there any similar API for this?

A: Just lock the vertex/index buffers and memcpy the data from one to the other.


text:
Q: Sharing class among processes in multiprocessing I implemented the following code:
import numpy as np
import time
import multiprocessing as mp

class RandomStater():

    def __init__(self, num_per_chunks=1e7, seed = 42):
        np.random.RandomState(seed)
        self.num_per_chunks = int(num_per_chunks)
        self.d = {}
        self.i = {}
        self.random_numbers = {}

    def _choice_n(self, n):
        if self.i[n] % self.num_per_chunks == 0:
            self.random_numbers[n] = np.random.choice(n, size=self.num_per_chunks)
        self.i[n] += 1
        return self.random_numbers[n][self.i[n]]

    def choice(self, actions, p=None):
        num_actions = len(actions)
        if num_actions not in self.d:
            print('Creating action', actions)
            self.i[num_actions] = 0
            self.d[num_actions] = self._choice_n
        return actions[self.d[num_actions](num_actions)]

class SampleNumber():
    def __init__(self):
        self._random_start = RandomStater()

    def sample_number(self, _):
        return self._random_start.choice([1,2,3])

Basically, the class RandomStater is a batch version of the method np.random.choice, which pre-computes a large number of random samples to be used next. The second class instead is a test class to collect in sequence these random samples.
I would like to use the method sample_number among different processes in parallel. What should happen is that the values self.d[num_actions] and self.i[num_actions] are created just the first time the first process execute the method choice, while for all the other calls the counter self.i[num_actions] is incremented and the result is so returned very quickly.
I guess the class should be shared among the processes or something, but I am new to multiprocessing and do not well how to do that.
Up to now I tried the following without any luck:
ns = range(0, 2000)
rn = RandomStater()
sn = SampleNumber()
s = time.time()

p = mp.Pool(4)
got = p.map(sn.sample_number, ns)
print(got)
print(time.time() - s)

A: There is a difference between multithreaded  and parallel random number generation.
Code like what you have in the question is not designed so much to allow multiple processes (threads) to access random numbers in parallel, as it is to reduce the time needed to generate a serial batch of random numbers, since more than one thread is generating them at once.  This is multithreaded random number generation. (See also the sample code in the NumPy documentation.)
A better approach for your purposes (namely, parallel random number generation) is to give each process its own PRNG and to initialize those PRNGs based on a common seed.  This is explained in detail in my section "Seeding Multiple Processes", and the NumPy-specific page "Parallel Random Number Generation".
Also, note that numpy.random.RandomState is now a legacy class as of NumPy 1.17; NumPy 1.17 introduces a new random number generation system that uses so-called bit generators, such as PCG, and random generators, such as the new numpy.random.Generator.  It was the result of a proposal to change the RNG policy.


text:
Q: GCP Cloud Build via trigger: Dockerfile not found I attempt to trigger building a Docker image on GCP Cloud Build via webhook called from Gitlab. The webhook works, but the build process stops when I run docker build with this error:
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory
The YAML for this step is:
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - '-t'
      - '${_ARTIFACT_REPO}'
      - .

where I later supply the variable _ARTIFACT_REPO via substitutions.
My Gitlab repo includes the Dockerfile on the root level. So the repo structure is:
app/
.gitignore
Dockerfile
README.md
requirements.txt

The error message indicates that the Dockerfile cannot be found, but I do not understand why this is the case. Help is much appreciated!

A: Just solved the issue:
I followed the GCP docs (link) where they include these two steps in the cloudbuild:
- name: gcr.io/cloud-builders/git
  args:
    - clone
    - '-n'
    - 'git@gitlab.com/GITLAB_REPO'
    - .
  volumes:
    - name: ssh
      path: /root/.ssh
- name: gcr.io/cloud-builders/git
  args:
    - checkout
    - $_TO_SHA

As I did not require a specific checkout, I deleted the second step of those but I overlooked the -n flag in the first step that prevents checking out the cloned repo.
So I just deleted the - '-n' and issue solved.


text:
Q: Can I get more amps than SMPS is rated? An SMPS is rated at 12 V and 30 A, 360 watts as output.
If I step down the voltage to 5 V and use this 5 V with a device consuming 70 A, can this SMPS deliver 70 A of current with 5 V, 350 W, even if rated for 30 A?

A: If you used a 95% efficient buck regulator you would be able to get about 340 watts but this would be a very sophisticated design. I don't think that a design that drops the voltage from 12 volts to 5 volts is available with a power efficiency of \$\frac{35}{360} = 0.972\$ without considerable investment in time and dedication to reach what you want.

A: The supply you have provides a 12V, 30A output. That's it. The supply doesn't know nor care what you do with that power. It doesn't "know" that you're stepping it down to 5V.
Realistically speaking, you can bet on getting 5V, 300W out of a buck converter that's fed with 12V, 30A. That's not hard, and you can probably even buy a pre-made module or a couple and parallel them.
To get 350W at 5V out of 12V, the 12V supply would need to be 450W. That's because it needs derating as well - you shouldn't be running it non-stop at 100% load. The buck converters would need to be rated for at least 400W total as well.


text:
Q: How to type Ctrl-^? I'm a bit embarrassed of asking this, but how to make the ^ (I can't see it in my keyboard).
I want to do this: CTRL-^

A: According to Wikipedia:

Control characters are often rendered into a printable form known as caret notation by printing a caret (^) and then the ASCII character that has a value of the control character plus 64. Control characters generated using letter keys are thus displayed with the upper-case form of the letter. For example, ^G represents code 7, which is generated by pressing the G key when the control key is held down.

As "^" is ASCII 94 (decimal), "Ctrl-^" might represent ASCII 30. Hence, holding down Alt and typing 30 on the numeric keypad might do the trick to "type" Ctrl-^?

A: The ^ character (which looks like an inverted V) is known as caret. It's also known as a hat, control or uparrow.
It's Shift+6 on my UK keyboard, and I think it's the same for US layouts as well, so you could try Ctrl+Shift+6
If you have a different layout you could have a look at this page on Wikipedia which has pictures of many different keyboard layouts.
If you're on Windows you can get a ^ by hold down Alt and typing 094 on your numeric keypad which will work for all layouts, but unfortunately this won't work if you're holding down Ctrl

A: I think that (in a terminal under linux) you can hit Ctrl+v Ctrl+^ .
Ctrl+v  is by default bound to:
quote-insert
      Add the next character typed to the line verbatim.  This is  how
      to insert characters like C-q, for example.

In order to verify my claim I used xxd (xxd - make a hexdump or do the reverse.) which comes with vim. I typed the following keys:
xxd Enter, Ctrl+v, Ctrl+^, Ctrl+d, Ctrl+d and the result looked like:
% xxd
^^
0000000: 1e                                      .

Now the explanation is a little complicated:

*

*xxdEnter launches the application xxd.

*Ctrl+v, Ctrl+^ sends a 0x1e. In order to understand this you have to remember that Ctrl+x  sends the character code of X (0x58, note: capital X) minus 0x40, that is 0x18. In case of ^ (0x5e) this results in 0x01e

*Ctrl+d, Ctrl+d  terminates the input. (I don't know why I had to type it twice though).
And finally man ascii is really helpful in remembering all those character codes.

A: Press Ctrl+Shift+6. The ^ usually represents the Ctrl key, [ie ^C for a Keyboard Interrupt], but in this case, I think the ^ represents a literal caret.

A: The so called aschii-caret on a swedish keyboard -
hold CTRL and press the key with the caret-symbol two times

A: To type caret symbol on my Italian keyboard, I had to go to
settings -> region and language -> input sources -> Italian (no dead keys)
The italian keyboard didn't work well, so I had to choose the "no dead keys" variant.

A: That thing is called Circumflex Accent AKA Circum Accent
Unicode: 005E
ASCII: 94
GID: 65
Most of the times it works by pressing Shift+6 or Ctrl+Shift+6
And of course it depends on the keyboard model and the layout that you're using.
But IF you couldn't type it you can use it by adding symbols.
ヽ(ヅ)ノ


text:
Q: del /s /q "file location" isn't working     del /S /Q "C:\TEST\TESTFOLDER\"

isn't actually deleting TESTFOLDER.

A: Del command is used for deleting files. If you want to delete folder, you should use rmdir with /s /q switches to force delete the folder and all it's files without prompt
rmdir /S /Q "C:\TEST\TESTFOLDER\"


text:
Q: Prevent users from liking a photo multiple times I have a django project and I am using tastypie to turn my app into a REST based API.
I let users upload photographs and then other registered users can like them. I want to prevent a single from liking a photo more than once.
I know that using views or tastypie specific code I could add functionality to check if a user has already like a photograph and if they have then not increment the count. But I was wondering if there is a way to do this check within the model (and if that is good or bad)
Thanks

A: I hope you have a model for likes? If not, create it as an intermediary model for M2M User <-> Photo relation. Next, add a simple unique constraint:
unique_together = ("user", "photo")

It's enforced on the database level, so it will give you good performance.
If you don't want a dedicated model for keeping likes, unfortunately I cannot help – there is no other elegant way of saving a fact that some user liked some photo. At the end you should be happy with M2M because of extra features you can easily add afterwards: unlike photos, show who liked a particular photo, when the most likes occurred, add a degree of "liking" and so on.
Good luck!


text:
Q: Updating a Bool on load in coredata I'm trying to check to see if the app has already been installed and if so, delete all pending local notifications. I'm trying to use this code, but it doesn't seem to be saving correctly to my Core Data.
// check to see if the app has already been installed

    let global = Global(context:coreDataStack.managedContext)

    print("Has the app been installed before = \(global.wasLoaded)") // returns false

    if(global.wasLoaded == false){

        print("remove local notifications")
        // remove all notifications
        center.removeAllPendingNotificationRequests()

        global.wasLoaded = true
        coreDataStack.saveContext()
        print("Has the app been installed before = \(global.wasLoaded)") // returns true
    }

The next time I run the app, the wasLoad bool comes back as false still.
Do I have run a fetch request here to make this work properly?

A: Each time you're making a new Global managed object, so it always has the default value. To achieve what you want, you'd have to fetch the already set Global managed object and check it's properties.
Core Data is a very heavy solution to this problem, a better one would be to use UserDefualts like this:
    if UserDefaults.standard.bool(forKey: "isFirstLaunch") == false {
        // Perform first launch actions

        UserDefaults.standard.set(true, forKey: "isFirstLaunch")
    }

    // Continue with regular setup

You compare to false because bool(forKey:) returns false if the value was never set for a given key.


text:
Q: Guest session stopped working on Ubuntu versions later than 16.04 After a recent package update, the guest session feature is no longer available on Ubuntu 16.10 and 17.04. What happened?

A: The guest session was intentionally disabled by default due to a security issue, where the guest session was not contained by the AppArmor profile that usually limits guest sessions. This AppArmor profile, among other things, prevents a guest user from using su to switch to other users, or viewing other users' home directories.
You can enable it, if you consider the issue to be manageable on your system, as explained in comment #24 of the bug report or by using this one liner:
sudo sh -c 'printf "[Seat:*]\nallow-guest=true\n" >/etc/lightdm/lightdm.conf.d/40-enable-guest.conf'

To reverse it back to the disabled state, simply do:
sudo rm /etc/lightdm/lightdm.conf.d/40-enable-guest.conf


text:
Q: Integers to two bytes in binary files I want to write some integers to a binary file and I want to force them to be written in two bytes even if a few of them don't fit (trim these). I get an error when I do this (below). Is there another way to do it? Thanks!
Error in writeBin(Info_Differences, file_differences, size = 2) :
  size 2 is unknown on this machine

A: Yeah, you probably have doubles that look like integers. Try this:
writeBin(as.integer(Info_Differences), file_differences, size = 2)

or, to check what Info_Differences really is:
typeof(Info_Differences) # double or integer?


text:
Q: regex to check if a link is valid on an image I have an input field for input a URL to an image.
Now I want to take care, that the image is correct (syntax) and the image matched to an image file.
I tried it with this
function check_link(url){
   url_validate= /(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png)/;
   if(!url_validate.test(url)){ return false; }else{  return true; }
}

In some cases it failed

*

*http://www.bla/ig.png - will be not ok but it return true

*http://bla/ig.png - will be also not ok but it also return true

*http://www.bla.jpg - will be also not ok but it also return true

*http:www.bla.jpg  - will be also not ok but it also return true

What do I have to change in my code that the function will only return if the URL has a correctly, possible syntax and the file is a image?
Thanks a lot.

A: you are missing a check for the TLD, followed by a forward slash :
url_validate = /(http(s?):)([\/|.|\w|\s|-])*\.[A-z]{2,}\/[a-zA-Z0-9]{1,}\.(?:jpg|gif|png)/;

The part that checks for the TLD is this : \.[A-z]{2,}\/
(match a period, match any letter between two and infinite times, match a forward slash)
Then i check the file name:
[a-zA-Z0-9]{1,}\.
Match any alphanumeric between one and infinite times, match a Period (.)
Then comes the file extension (like in your example)
If it is still unclear, check https://regex101.com/r/IGK58B/1


text:
Q: Windows partition no longer visible under Ubuntu I dual boot Ubuntu 16.04 and Windows 10. It was convenient to just click the Windows partition in the Ubuntu desktop launcher. This function gradually disappeared and now nothing happens when I click it. My Windows is shut down, not hibernated.
I could maybe start making experiments with fstab. But I think the result is better if someone here guides me how to get back this nice function, just to click the icon in the launcher.
(This question is not about GRUB and boot-loaders. They work fine and both Ubuntu and Windows start as I choose. This is about the Ubuntu desktop, where I can no longer reach the Windows partition with one click from the Ubuntu launcher.)
Sorry for many edits, I have been struggling with wrapping code tags around the listings.
parted
ycc@x360:~$ sudo parted -l
Model: ATA WDC WD5000LPCX-6 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt
Disk Flags:

Number  Start   End    Size    File system     Name                          Flags
 1      1049kB  274MB  273MB   fat32           EFI system partition          boot, esp
 2      274MB   290MB  16.8MB                  Microsoft reserved partition  msftres
 3      290MB   315GB  315GB   ntfs            Basic data partition          msftdata
 4      315GB   319GB  4194MB  linux-swap(v1)  Basic data partition          msftdata
 5      319GB   382GB  62.9GB  ext4            Basic data partition          msftdata
 6      382GB   483GB  101GB   ext4            Basic data partition          msftdata
 7      483GB   484GB  1028MB  ntfs            Basic data partition          hidden, diag
 8      484GB   500GB  16.1GB  ntfs            Basic data partition          hidden, msftdata

gparted
.
fstab
ycc@x360:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda5 during installation
UUID=c9b9e601-f78a-41d8-a4f4-87e276b4aeb7 /               ext4                        errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=9ADF-D1D2  /boot/efi       vfat    umask=0077      0       1
# /home was on /dev/sda6 during installation
UUID=782e4b9f-4941-48bc-a1bf-5883e28cb174 /home           ext4            defaults        0       2
# swap was on /dev/sda4 during installation
UUID=c35d5bd1-960c-4e1a-8f6e-d73af393bfc3 none            swap    sw                  0       0

mount
ycc@x360:~$ mount
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
udev on /dev type devtmpfs (rw,nosuid,relatime,size=1916132k,nr_inodes=479033,mode=755)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
tmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=387088k,mode=755)
/dev/sda5 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)
efivarfs on /sys/firmware/efi/efivars type efivarfs (rw,nosuid,nodev,noexec,relatime)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=32,pgrp=1,timeout=0,minproto=5,maxproto=5,direct)
mqueue on /dev/mqueue type mqueue (rw,relatime)
debugfs on /sys/kernel/debug type debugfs (rw,relatime)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)
fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)
/dev/sda6 on /home type ext4 (rw,relatime,data=ordered)
/dev/sda1 on /boot/efi type vfat (rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro)
tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=387088k,mode=700,uid=1000,gid=1000)
gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000)
ycc@x360:


text:
Q: How to change key value based on comparison of array of objects in jQuery? I have two arrays in jQuery as below.
var arr1 = [{A: "t1"},{A: "t3"}];

var arr2 = [{A: "t1",B:""},{A: "t2",B:""},{A: "t3",B:""},{A: "t4",B:""},{A: "t5",B:""},{A: "t6",B:""}];

var arr3 = []; //Only for output

Now, the output in arr3 should be:

*

*all the values from arr2

*the 'B' key should be Yes if 'A' key exists
in arr1

*the 'B' key should be No if 'A' key doesn't exist
in arr1

So, the output I want in arr3 should be:
arr3 = [{A: "t1",B:"Yes"},{A: "t2",B:"No"},{A: "t3",B:"Yes"},{A: "t4",B:"No"},{A: "t5",B:"No"},{A: "t6",B:"No"}];

This is what I have tried so far

var arr1 = [{A: "t1"},{A: "t3"}];
var arr2 = [{A: "t1",B:""},{A: "t2",B:""},{A: "t3",B:""},{A: "t4",B:""},{A: "t5",B:""},{A: "t6",B:""}];
var arr3 = []; //Only for output

arr1.forEach(function(x) {
  arr2.forEach(function(y) {
    if (x.A == y.A) {
      arr3.push({
        A: x.A,
        B: "Yes"
      });
    } else {
      arr3.push({
        A: x.A,
        B: "No"
      });
    }
  });
});

console.log(arr3);

//Output
0: {A: "t1", B: "Yes"}
1: {A: "t1", B: "No"}
2: {A: "t1", B: "No"}
3: {A: "t1", B: "No"}
4: {A: "t1", B: "No"}
5: {A: "t1", B: "No"}
6: {A: "t3", B: "No"}
7: {A: "t3", B: "No"}
8: {A: "t3", B: "Yes"}
9: {A: "t3", B: "No"}
10: {A: "t3", B: "No"}
11: {A: "t3", B: "No"}

Issue here is that it repeats for each item in arr1, and count gets doubled.
I know it should break somewhere between if and else, so that it does not repeat.
I have tried checking below links too, but couldn't get much help.
filter array of objects based on separate object keys, values
js - How to change one key's value based on another key's value in array of objects
Object comparison based on keys
compare array of objects
Thanks in advance.

A: Use map and find if the arrays are not huge.
Saves a reduce and push

var arr1 = [{ A: "t1" }, { A: "t3" }];
var arr2 = [{ A: "t1", B: ""}, { A: "t2", B: "" }, { A: "t3", B: "" }, { A: "t4", B: "" }, { A: "t5", B: "" }, { A: "t6", B: "" }];
var arr3 = arr2.map(
  item2 => ({
    A: item2.A,
    B: arr1.find(item1 => item1.A === item2.A) ? 'Yes' : 'No'
  }));

console.log(arr3);

A: You can make an array of the A values in arr1 using Array.reduce(), then use Array.includes to check if each of the A values in arr2 is present in that array, using that to decide whether to set B to Yes or No:

var arr1 = [{ A: "t1" }, { A: "t3" }];
var arr2 = [{ A: "t1", B: ""}, { A: "t2", B: "" }, { A: "t3", B: "" }, { A: "t4", B: "" }, { A: "t5", B: "" }, { A: "t6", B: "" }];
var arr3 = []; //Only for output

var arr1values = arr1.reduce((c, v) => c.concat([v.A]), []);

arr2.forEach(function(y) {
  arr3.push({
    A: y.A,
    B: arr1values.includes(y.A) ? 'Yes' : 'No'
  });
});

console.log(arr3);


text:
Q: How can "order by" change my results here? Using T-SQL, OPENQUERY, SELECT INTO I have a scheduled AM process on SQL Server 2008 that imports data from Oracle using a linked server.  I am overwriting the imported data from Oracle using drop table, then select into pattern
Apparently, the presence of the "order by" affects my end result!  Take a look.
--This works fine to give me the one row I'm expecting from the newly imported table:
drop table t1;
SELECT * into t1 fROM OPENQUERY(ODBC_CSRPT,'
select
 EXTERNAL_ORGANIZATION_ID
 ,ORGANIZATION_DESC
 ,STATE
from sysadm.uv_CS_EXTERNAL_ORGANIZATIONS
order by EXTERNAL_ORGANIZATION_ID asc ');
go

select * from t1
where external_organization_id = '1000107'
go

But this (below) returns no rows. My orgId of 1000107 is now missing?
drop table t1;
SELECT * into t1 fROM OPENQUERY(ODBC_CSRPT,'
select
 EXTERNAL_ORGANIZATION_ID
 ,ORGANIZATION_DESC
 ,STATE
from sysadm.uv_CS_EXTERNAL_ORGANIZATIONS ');
go

select * from t1
where external_organization_id = '1000107'
go

As you can see the only thing changed is the presence of the order by clause.  Another tidbit is that the linked server query is returning same rowcount (51,225 rows to be exact) whether or not the "order by" exists. Any ideas?

A: May be you need recalculate indexes on Oracle?

A: Is there an option like SET ROWCOUNT in effect?  In particular on the linked Oracle database.  It's been years since I've done anything with Oracle so I don't remember their particulars.

A: Seems that I'm running into some sort of cap at 51,225 rows.  I do not control the Oracle side, another dept at my org does.  One of their people say that exact query is supposed to return 51,324 rows.
So, what's really happening is that I'm 99 rows short of the full result set.  My "order by" clause re-prioritizes the results, and happened to give me the one row I was looking for.  Unfortunately of course, it's still bumping 99 other results out!
I don't know what is significant about the 51,225 number.  Hard for me to imagine that the sql server config of the linked server would have that set somehow (I just went with defaults when setting it up).
Worse case, I'll just split the import into 2 queries, ordered oppositely so I cover all the bases.  I really need to get to the bottom of that mysterious 51,225 "cap" though...
Thanks much for all the input!

A: Linked server based on Provider: "Oracle Provider for OLE DB" (instead of based on a local System ODBC connection "Microsoft OLE DB Provider for ODBC Drivers") returned the full result set first try.
For some reason, there must be a lower ceiling on the ODBC connection regarding maximum rows that can be returned.  Only setting I found was "fetch buffer size," I tried doubling, still same amount of rows returned.
For this query, I'll just use the other linked server.
Thanks again to all for the input!


text:
Q: How to merge unsupervised hierarchical clustering result with the original data I carried out an unsupervised hierarchical cluster analysis in R. My data are numbers in 3 columns and around 120,000 rows. I managed to use cut tree and recognised 6 clusters. Now, I need to return these clusters to the original data, i.e. add another column indicating the cluster group (1 of 6). How I can do that?
# Ward's method
hc5 <- hclust(d, method = "ward.D2" )

# Cut tree into 6 groups
sub_grp <- cutree(hc5, k = 6)

# Number of members in each cluster
table(sub_grp)

I need that as my data got spatial links, hence I would like to map the clusters back to their location on a map.
I appreciate your help.

A: The variable sub_grp is just a vector of cluster assignments so you can just add it to the data frame:
data(iris)                         # Data frame available in base R.
str(iris)
d <- dist(iris[, -5])              # Column 5 is the species name so we drop it
hc5 <- hclust(d, method="ward.D2")
sub_grp <- cutree(hc5, k=3)
str(sub_grp)
iris$grp <- sub_grp
str(iris)
aggregate(iris[, 1:4,], by=list(iris$grp), mean)
xtabs(~grp+Species, iris)

The last two commands compute the means by groups for the 4 numeric variables and cross-tabulate the cluster assignments with the known species. You don't actually need to add the cluster assignment to the data frame. R lets you combine variables from different objects as long as they have the same number of rows.


text:
Q: Identity with laplacian In Peter Topping's text, Lectures on Ricci Flow, he's establishing an identity regarding the Laplacian of the curvature tensor. He quotes the differential Bianchi identity
$$\nabla_iR_{jkla}+\nabla_jR_{kila}+\nabla_kR_{ijla}=0$$
and then say that by taking another derivative and tracing we get
$$\Delta R_{jkla}+\nabla_i\nabla_jR_{kila}-\nabla_i\nabla_k R_{jila}=0$$
where
$$\Delta R_{jkla}=\Delta RM(\partial_j,\partial_k,\partial_l,\partial_a)$$
I don't see how he gets this identity. It seems that if he's tracing over the elements then there should be some Ricci coefficients. Can someone provide some details with regards to the computation. Thanks.

A: Just apply $\nabla_i$ and sum over $i$ to get
$$\nabla_i \nabla_iR_{jkla}+\nabla_i \nabla_jR_{kila}+\nabla_i \nabla_kR_{ijla}=0.$$
Recognising $\nabla_i \nabla_i = \Delta$ (since Topping must be working in an orthonormal frame) and $R_{ijla} = -R_{jila}$ gives you your result. There are no Ricci terms because  at least one of the indices $i$ we are tracing over appears as a derivative.


text:
Q: EAccessViolation Error in application running Windows 10 I've been using this certain application among previous windows versions (Windows XP-Vista-7-8-8.1) and it has worked perfectly without having any issues, after upgrading to Windows 10 though it started showing EAccessViolation error and spams the place with message boxes saying "Runtime error at XXXX" (memory address)
So what I've been trying to achieve is creating a program in C# which runs the application under all compatibility modes one by one, to check which one works and which one doesn't - and sadly, none of them did.
The application is not mine and has stopped development.
Do you guys have any idea what has changed in Windows 10 code-wise, and how am I able to fix this issue? Is there a way to fully emulate another windows version and run it for this application alone? (Without having to set up a Virtual PC or anything)
Thank you in advance.
Note: Microsoft said that Windows 10 is completely backwards compatible, which it doesn't seem like it? The application does not use any driver, it's just a standalone EXE coded in C++/Lua.
Note2: The EXE calls a DLL which might be outdated for Windows 10, any idea what to do about the DLL? Is there a way to make it work as it did in previous windows?

A: You can help prevent these kinds of errors from occurring by updating your device drivers after formatting and reinstalling your operating system or installing a Windows Updates. Always install the latest Windows Updates before going through and updating your device drivers.


text:
Q: Cin.get() issue with C++ I still don't know how this works with Visual Studio.
Supposedly it keeps my console open, but it doesn't. It still flashes and closes.
Am I doing something wrong?
#include <iostream>
using namespace std;

int main()
{
    int a;
    cout << "Please enter an integer: ";
    cin >> a;

    if (a == 1)
    {
        cout << endl << "You typed 1.";
    }
    else
        cout << "That's not 1.";

    cin.get();

    return 0;
}

A: As it was already pointed out in the comments the problem is that the input buffer contains the symbol of the Enter key that is read by cin.get();
You can use either the following sequence
char c;

cin >> c;

Or before cin.get() you should call cin.ignore. For example
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cin.get();

In the last case you must include header <limits>


text:
Q: Android switch (String) doesen't work I have a class in my Android app which send an HTTP POST request to a PHP page. The page "answer" with "Success" or "Error".
I need to switch what the page answered but both switch case and if-else chain doesen't work. Why?
package com.example.mypackage;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class LoginAction extends AsyncTask<String, Void, Boolean> {

    private URL url;
    public String username;
    public String password;
    private HttpURLConnection connection;
    private OutputStreamWriter request;
    private String response;
    private String parameters;
    private static String result;
    private Context context;

    protected  Boolean doInBackground(String ... urls){

        try {

            parameters = "username="+username+"&password="+password;
            url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();

            String line;

            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();

            while ((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            response = sb.toString();

            isr.close();
            reader.close();

            if (response != null){
                //The server said something
                return true;
            } else {
                //The server didn't said nothing
                return false;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    protected void onPostExecute(Boolean success){
        if (success){ //this variable is the return from "doInBackground"
            System.out.println("Message recived from site: "+response);
            whatHappened(response);
            System.out.println("Value of \"response\": "+response);
        } else {
            System.err.println("Nothing to show");
        }
    }

    //Call this in MainActivity to set the parameters
    public void setCredentials(String username, String password){
        this.password = password;
        this.username = username;
    }

    //Call this in MainActivity to set the Context to use Toast from here
    public void setContext(LoginActivity loginActivity){
        this.context = loginActivity;
    }

    private void whatHappened(String result){

        System.out.println("Value of \"result\": "+result);

         switch (result){

            case "Success":
                Toast.makeText(context, "Login success", Toast.LENGTH_SHORT).show();
                break;

            case "Error":
                Toast.makeText(context, "Login failed, please re-try", Toast.LENGTH_LONG).show();
                break;

            default:
                Toast.makeText(context, "Generic error", Toast.LENGTH_SHORT).show();
                break;

        }

       if (result.equals("Success")){
           Toast.makeText(context, "Login success", Toast.LENGTH_SHORT).show();
       } else if (result.equals("Error")){
           Toast.makeText(context, "Login failed, please re-try", Toast.LENGTH_LONG).show();
       } else {
           Toast.makeText(context, "Generic error", Toast.LENGTH_SHORT).show();
       }

    }

}

When I test the bug the output in the System log is correct (Error or Success) for all the steps, but the toast shown is always "Generic Error". No code's errors.

A: Problem is here in the while loop
sb.append(line + "\n");
Here you are appending a new line to the string line. Take off that \n or add \n in the case. like below.
case "Success\n"
case "Error\n"


text:
Q: Dudas de como crear 2 ramas principales en un proyecto angular A la hora de realizar el código no se como crear correctamente las ramas hijas (routing) de la segunda rama principal. Por una lado tengo la rama padre "Home" de la que descienden todos los módulos y quiero crear una "Help" al mismo nivel con otros módulos, no se si tengo que crear otro "app-routing.module.ts" para que haga las mismas funciones junto con su "app.module.ts" pero con otros nombres

A: Se llama routing y si quieres usarlo a través de módulos debes utilizar lazi loading para poder llamar a los componentes hijos. Esto te dará una mejora en el tiempo de carga y en la organización de tus componentes.
Suponiendo que quieres crear un nuevo pages.module deberias ejecutar el siguiente comando:
ng g m pages/pages --route laRutaQueQuieras  --module app.module

Esto creara en tu routing de app-routing.module (en caso de que lo tengas fuera de tu modulo, si no será dentro) la siguiente linea:
{
    path: 'prueba', //Lo puedes dejar en blanco para que sea el principal
    loadChildren: () =>
      import('./pages/pages.module').then(
        m => m.PagesModule
      )
  },

Esto se repite igual si quieres crear más módulos hijos de pages.module:
ng g m pages/home --route home --module pages.module

La creación de componentes es igual que siempre, solo que hay que señalar el directorio.
ng g c pages/home/menu

Esto provocara que se registre el componente en dicho modulo. Solo te restaría registrar el componente al routing.
Tu caso quedaría de la siguiente manera:
{
  path: 'home', //Lo puedes dejar en blanco para que sea el principal
  loadChildren: () =>
    import ('./pages/home/home.module').then(
      m => m.PagesModule
    )
},

{
  path: 'help',
  loadChildren: () =>
    import ('./pages/help/help.module').then(
      m => m.PagesModule
    )
},

En caso de que sean componentes reutilizables pues crear el modulo fuera de pages.module e importarlo en cualquier modulo.
La forma que no recomiendo
Suponiendo que este sea tu routing, puedes lograr lo que quieres sin lazy loading solo modificando el path.
{
  path: 'login',
  component: LoginComponent
}, {
  path: 'usuario/confirmar',
  component: UsuarioConfirmarComponent
}, {
  path: 'usuario/detalles',
  component: UsuarioDetallesComponent
}

{
  path: 'usuario/detalles/masDetallado',
  component: UsuarioDetallesMasDetalladoComponent
}


text:
Q: RSPerl compared to rpy2 I've been told by my coworkers that rpy2 is a great tool to work with data that benefits from the back and forth between python and R. But I am a perl monger, so I wonder if RSPerl will be as wonderful as I've been told rpy2 to be.
The website was last updated in 2007...
Cheers

A: To me, the main difference is that things from Omegahat are exceedingly clever and far-sighted yet don't always build reliably. It's more of an R&D lab.
Rpy2 on the other hand has a dedicated and focussed core developer in Laurent.
[Disclaimer: I'm the Debian maintainer for RPy2 (and a few related things) and tried in vain to package RSPerl, RSPython, ... and a few other Omegahat pieces by Duncan.]

A: Beside wonderful features in an interface between language X and R, continued support is of utmost importance.
RSPerl might have built at some point in time, but there is a non-negligible chance that it does not any longer. In your situation, Perl did not know major transformations over the last years, but R surely did.
[Disclaimer: I am quite involved in rpy2, and within its ~3 years of existence the code base has required several changes because of changes in R and Python - in fact, I am not yet completely out of the woods with Python 3]


text:
Q: ASN.1 definitions for basic SNMP exchanges What online resource is the authority for the complete set of ASN.1 definitions for the SNMP data structures used to request and respond with information? I am interested in versions 2c and version 3.
In RFC 3416 Section 3, I have found most of the definitions needed to use version 2c. However, the document has no mention of something that I have found on other resources referred to as the "snmpv2 message". For example, this shows up in the SNMP Programmers Reference Wiki and in the blog post Simple? Network Management Protocol. It's the data structure that contains the community string, so it's role is essential, but I cannot find where the authoritative source (probably an RFC) with an ASN.1 definition.
Similarly, I cannot find any authoritative ASN.1 definitions of SNMPv3 data structures. I found an ASN file in a github repo's test suite, but I cannot find where this information was taken from.
I would appreciate any help locating these. I'm usually a pretty good Googler, but my usual strategies are not turning anything up beyond what I've already linked to.

A: SNMP v3 message format is defined in RFC3412 page 19 as section 6 as ASN.1.
SNMP v2c reuses most of v1 message format, except defining new message body (PDU). I think that's why in RFC 3416 you don't see all details, because it only mentions the new PDU definitions for simplicity.

A: You might want to dig ASN.1 documents out of SNMP RFCs:

*

*Base data types, RFC2578

*SNMP v2c message, RFC3416

*SNMP v3 message, RFC3412

*SNMP v3 USM, RFC3414


text:
Q: Show Horizontal scrollbar under the header in Kendo grid I have a kendo grid with the Horizontal scrollbar. By default, the position of the scrollbar is at the bottom of the grid.
But my requirement is to show the horizontal scrollbar at top of the grid(Under Grid header).
Is it possible to do it? Please let me know!

A: Using this answer How to change scroll bar position with CSS?
and modifying it to a scrollable kendo grid using style rule
.k-grid-content,
.k-grid-content table {
  transform:rotateX(180deg);
  -ms-transform:rotateX(180deg); /* IE 9 */
  -webkit-transform:rotateX(180deg); /* Safari and Chrome */
}

will put the horizontal scrollbar on top.
Demo: https://dojo.telerik.com/@Stephen/etIYa
If you are using virtual scrolling, then you will have to change the style rule to compensate as the structure of the grid is different between a scrollable and a virtual scrollable kendo grid.


text:
Q: Z-test in excel without input array 100 taxi drivers took a shot of vodka. Their reaction time was measured before and after. Giving us following data:

*

*BEFORE | Mean: 0.4 and s^2: 0.0005

*AFTER | Mean: 0.44 and s^2: 0.0006

Can I rule out with 0.01 probability that taking a shot of vodka doesn't affect reaction time?
I am allowed to use excel, but I can't figure out how to solve this task, because z-test in excel takes in an array of data, but in my case only the mean of sample is given.

A: A paired t test is essentially a one-sample test on the $n$
differences. Let $U_i$ be the reaction time before and $U_2$ be
the reaction time after. Then the increased reaction time for the
$i$th driver is $D_i = U_2 - U_1.$
The t statistic for testing $H_0:\mu_A - \mu_B = 0$
against $H_a; \mu_A-\mu_B \ne 0$ is $T = \frac{\bar D - 0}{S_D/\sqrt{n}},$
where $S_D$ is the standard deviation of the differences $D_i.$
If reaction times are roughly distributed as normal, then $T$ is
approximately distributed as Student's t distribution with $n-1$
degrees of freedom.
You know that $\bar D = \bar U_2 - \bar U_1.$
However, from what you are given, you can't know $S_D$ exactly, because before and after reaction times for the same driver are not independent. But probably $S_D^2 \le S_1^2 + S_2^2 = S_T^2;$ it seems reasonable that the $U_1$ and $U_2$ are positively correlated. So you
might use $S_D \approx S_T$ as a worst-case scenario in computing the statistic $T$.
I will leave it to you to finish this.


text:
Q: ObjectMapper array error I have this json:
    Optional(<__NSSingleObjectArrayI 0x600000016530>(
{
    direccion = "";
    geo =     {
        coordinates =         (
            "25.65313",
            "-100.3611"
        );
        type = "";
    };
    nombre = "Mi Ubicacion";
}
)
)

and my model is this:
class LocationModel: Mappable {
    var nombre = ""
    var direccion = ""
    var geo = GeoModel()

    init(){

    }

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        nombre <- map["nombre"]
        direccion <- map["direccion"]
        geo <- map["geo"]
    }

}

and this is how im mapping it:
locationsGuardadas = Mapper<LocationModel>().mapArray(JSONArray: locationsJson as! [[String : Any]])

that code worked fine until a few days ago, when i updated my sdk to support ios 11.3, then the code stopped working, i have tried updating the objectmapper pod, and reseting simulator content and settings, but for some reason now, when i map the array, the "coordinates" array of the location comes without coordinates, it has a 0 count, and i dont know how to fix this problem, any help will be appreciated.

A: I have already found the problem, for some reason the ObjectMapper doesn't work well with float numbers, so changing every float to double did the trick


text:
Q: Are there perverse sheaves on abelian varieties with small Euler characteristic? Let $A$ be a simple abelian variety of dimension $g$. Let $K$ be an irreducible perverse sheaf on $A$. We know that $\chi(A,K)\geq 0$. (Corollary 1.4 of Franecki and Kapranov.) How small can $\chi(A,K)$ be?
There are some trivial examples. If $K$ is a lisse sheaf on all of $A$ placed in degree $g$, then $\chi(A,K)=0$. If $K$ is a skyscraper sheaf, then $\chi(A,K)=1$.
Beyond these trivial examples, if $A$ is the Jacobian of a curve $C$ of genus $g$ and $K$ is the constant sheaf on $C$, placed in degree $-1$ and pushed forward to $A$, then $\chi(A,K)=2g-2$.
I want to know if there is any nontrivial example with smaller Euler characteristic:

Does there exist a simple abelian variety $A$ of dimension $g$ and an irreducible perverse sheaf $K$ on $A$ such that $K$ is not lisse, $K$ is not a skyscraper sheaf, and $\chi(A,K)<2g-2$?

We know every irreducible perverse sheaf of Euler characteristic $0$ or $1$ is trivial in this sense. (Proposition 10.1 of Kramer and Weissauer.) So it is equivalent to ask:

Does there exist a simple abelian variety $A$ of dimension $g$ and an irreducible perverse sheaf $K$ on $A$ such that $2 \leq \chi(A,K) <2g-2?$

One way to construct a perverse sheaf on an abelian variety is to take a smooth variety $X$ and a finite morphism $f: X\to A$ and pushforward the constant sheaf in degree $-\dim(X)$ along $f$. So a subquestion is:

Does there exist a simple abelian variety $A$ of dimension $g$, a smooth non-abelian variety $X$ of dimension $d$, and a finite map $f:X \to A$, such that $(-1)^{d} \chi(X) < 2g-2$?

A: Mihnea Popa explained this lower bound to me:
If $f: X \to A$ is a finite morphism (or weaker conditions are possible), then we have generic vanishing for every Hodge number of $X$ but $h^{p,q}$ for $p+q=d$. So $(-1)^d \chi(X)$ is just the sum of the generic values of $h^{p,q}$ for $p+q=d$. In particular, it is at least twice the generic value of $h^{0,d}$, which is equal to the arithmetic Euler characteristic of $\omega_X$. A lower bound for this is the codimension of $X$ as long as $A$ is simple or $X$ has no irrational pencils (slight variant on Theorem A of Pareschi and Popa). This gives a lower bound of $2g-2d$.
As far as I know this should hold for any perverse sheaf that arises from any geometric construction, because we should always be able to put a Hodge structure on it (making it a mixed Hodge module) and use the same argument.
I would be interested in further lower bounding arguments or upper bounding examples. The largest gap between the lower bound and the examples I know how to construct occurs for hypersurfaces, where the lower bound is $2$ and the best example I know about it is the theta divisor of a Jacobian, which has Euler characteristic $ \left( \begin{array}{c}  2g-2  \\ g-1\end{array}\right)$, or about $4^g$.


text:
Q: Page no for sub report in BIRT Reporting tool I want to use page numbers for a sub report in Birt 4.2 but it shows only 1 for all pages.
I have used the pageNumber variable in the footer of master page.
It's working fine for single table reports, but for nested or sub reports (table inside table) it shows the number 1 for all pages in .pdf

A: If the sub report is a different report file you could pass a variable with the page number to it from the first report.
If it is in the same file, verify that the page variable is in the master page and not in the standard report flow.
Consider reviewing https://www.eclipse.org/forums/index.php/t/457987/ for more discussion of page numbers and tables.


text:
Q: Docusign-esign document font type and size (Nodejs) I have a document I create with html
const doc1 = new docusign.Document();
  doc1.documentBase64 = Buffer.from(htmlPage(args.htmlArgs)).toString('base64');
  doc1.name = args.documentName;
  doc1.fileExtension = 'html';

The htmlPage method just returns a html string.
I want to specify font type and size for the document.
I have been looking through docusign documentation.
How would I set the font type and size?

A: You should be able to set the font size and type inside the HTML page itself. The buffer that you just create, includes the payload for your HTML page - any configuration you want on that page, including font, should be set in that page.
You can refere to this example where the CSS is included in the header of the HTML doc.
https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/eg002SigningViaEmail.js#L257

World Wide Corp

    <h2 style="font-family: 'Trebuchet MS', Helvetica, sans-serif;


text:
Q: Why do I use Laravel collect() instead of simple PHP function? Recently I have written a code using plain PHP function in Laravel. The code is related to fetching post types and display some meta boxes according to the post type chosen. Post types are hardcoded into the config file.
The problem is that my superior changed that code after reviewing and used Laravel collect() method.
So my question is why should I use that code as the simple code is doing its job very well? Expecting a good reasonable answer.
Please check the code below -
<?php
// $post_type => article, news, event
// In config file, metaboxes holdes array of metaboxes whose keys are post types
// $this->config => it is returning the config variables

**Process - I**
$this->metaBoxes = $this->config["metaboxes"][$post_type] ?? [];

foreach ($this->metaBoxes as $key => $value) {
    if (array_key_exists($key, $boxes)) {
        ($value)->create($post_type);
    } else {
        unset($this->metaBoxes[$key]);
    }
}

**Process - II**
function getMetaboxes($post_type) {
    $config = $this->config['metaboxes'][$post_type] ?? [];
    return collect($this->metaBoxes)
        ->filter(function ($metabox, $name) use ($config) {
            return array_key_exists($name, $config);
        })
        ->map(function ($metabox) {
            return $metabox;
        })
        ->all();
}


text:
Q: How can I see which IP address Google Cloud Function instance use? I want to see the IP address of my google function instance. I've tried to look request object's headers but couldn't find anything useful. Is there any way to find it?
I am using python SDK but I don't think this is language dependent.

A: Cloud Functions do not have a public IP address assigned to the function.
Cloud Function egress traffic is routed to a proxy which then forwards the traffic to the public Internet. The only method to determine the current public IP address is to call a public endpoint which returns the public IP address of the frontend to Cloud Functions.
Here is an example endpoint: https://api64.ipify.org/?format=json

A: If you want to have a outbound static IP with Cloud Functions, you can achieve this by configuration. 3 important steps

*

*Create a serverless VPC Connector and plug it to your Cloud Functions

*Set the egress param to "ALL" to route ALL (private and public IPs) the request from the Cloud Functions

*Configure a Cloud NAT and reserve IP(s) to use when you perform an external call. And you can use the John's answer to check if it works.

A: Just if someone needs this.
After doing the steps described by guillaume and exploring the link that also John suggested, I was able to get my cloud function's IP with the following python code:
from requests import get

ip = get('https://api.ipify.org').text
print(f'My public IP address is: {ip}')

In my case, I was looking to see if my cloud function had the same IP address as my NAT gateway since I need to put the IP in a whitelist and this helped me a lot!


text:
Q: how to find duplicate element with multiple fields I have scenario where in a table contains 2 columns.
product and sub like
Sno    Product  Sub
1      pr1      sub1
2      pr1      sub1
3      pr2      sub1
4      pr2      sub1
5      pr3      sub2
6      pr4      sub3
7      pr5      sub3
8      pr6      sub4
9      pr6      sub4

I want to find element which have col sub assigned to col product more than 1.But diff product not same.
so my result will be sub1,sub3
expected result will be distinct :
    Sub
 1  sub1
 2  sub3

I tried using group by on product and sub something like :
SELECT
    product,
    sub,
    COUNT(*)
FROM table1
GROUP BY
    product,
    sub
HAVING COUNT(*) > 1;

but this is not correct for the given scenario .
Need your advice on this.

A: Aggregate per sub and useHAVING` to only get those with multiple products:
select sub
from table1
group by sub
having min(product) <> max(product);

or
select sub
from table1
group by sub
having count(distinct product) > 1;

A: From the sample data provided in question, it seems that you are looking for all distinct rows from column Sub having more than one product. You can achieve this using below query.
select a.sub from (
select distinct sub, product from table1
    ) a
group by a.sub
having count(*) > 1

Result:
    SUB
--------
1   sub1
2   sub3

You can check demo here

A: how about this ?
SELECT sub FROM table1
GROUP BY sub
HAVING COUNT(sub) > 1

A: SELECT t1.product,t1.sub,t1.Count
FROM
  (SELECT product,sub,DENSE_RANK() OVER (Partition By product ORDER BY Sub) Count
   FROM table1
   ) t1
WHERE t1.Count=2
-- = 2 Means product Repeated more than 1


text:
Q: Runtime exception I am new to Java programming and this has me stumped. I get a runtime exception and a force close when my app starts. It did work before I made a lot of the code into arrays rather than singles. Can someone give me a clue what might be wrong?
07-15 16:30:29.441: INFO/ARMAssembler(61): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x38fe50:0x390018] in 1735976 ns
07-15 16:30:29.551: ERROR/gralloc(61): [unregister] handle 0x4910f0 still locked (state=40000001)
07-15 16:30:58.871: DEBUG/AndroidRuntime(229): Shutting down VM
07-15 16:30:58.871: WARN/dalvikvm(229): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
07-15 16:30:58.871: ERROR/AndroidRuntime(229): Uncaught handler: thread main exiting due to uncaught exception
07-15 16:30:59.252: ERROR/AndroidRuntime(229): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.golfandroid/com.example.golfandroid.GolfScoreActivity}: java.lang.NullPointerException
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.os.Looper.loop(Looper.java:123)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread.main(ActivityThread.java:4363)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at java.lang.reflect.Method.invokeNative(Native Method)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at java.lang.reflect.Method.invoke(Method.java:521)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at dalvik.system.NativeStart.main(Native Method)
07-15 16:30:59.252: ERROR/AndroidRuntime(229): Caused by: java.lang.NullPointerException
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at com.example.golfandroid.GolfScoreActivity.SetupClickListeners(GolfScoreActivity.java:725)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at com.example.golfandroid.GolfScoreActivity.onCreate(GolfScoreActivity.java:551)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
07-15 16:30:59.252: ERROR/AndroidRuntime(229):     ... 11 more
07-15 16:30:59.432: INFO/Process(61): Sending signal. PID: 229 SIG: 3
07-15 16:30:59.462: INFO/dalvikvm(229): threadid=7: reacting to signal 3
07-15 16:30:59.753: INFO/dalvikvm(229): Wrote stack trace to '/data/anr/traces.txt'

Code:
public void SetupClickListeners(){
    for(int holeNum=1; holeNum<18; holeNum++){
        scorePlayHole[currentPlayerNum-1][holeNum-1].addTextChangedListener(this);
    }
    for(int i=1; i<currentPlayerNum*4; i++){
        NextPlayerHoleButton[currentPlayerNum-1][i].setOnClickListener(this);
    }
}

A: This is just a stab in the dark since I only have the stack trace and not the relevant source.
Did you look at this source file?
GolfScoreActivity.java
Line number 725
Looks like you are setting up a Click Listener but something wasn't initialized and is Null

A: Shot in the dark as without seeing the code it's hard to tell - but if you have converted you code to use arrays, did you remember to new the array itself, as well as the objects that go into the array?

A:
07-15 16:30:59.252: ERROR/AndroidRuntime(229): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.golfandroid/com.example.golfandroid.GolfScoreActivity}: java.lang.NullPointerException

This isn't really a runtime exception.  It's a runtime exception that wraps a null pointer exception.  The root cause is a null pointer:
After examining your code, any one of these could be null and therefore causing the null pointer exception.

scorePlayHole
scorePlayHole[currentPlayerNum-1]
scorePlayHole[currentPlayerNum-1][holeNum-1]
NextPlayerHoleButton
NextPlayerHoleButton[currentPlayerNum-1]
NextPlayerHoleButton[currentPlayerNum-1][i]


text:
Q: Absolute Positioning Performance I have a colleague who uses a lot of absolute positioning in his css.
I find I can usually achieve the same visual effects by providing a different structure to the html - in fact I tend to shy away from using absolute positioning except when I absolutely need to.
Question -  are my instincts sound here, other than css complexity, is absolute positioning something to be used sparingly?

A: Excessive use of absolute positioning is a design problem, but it's not so much because of any a performance issues - I don't know of anything performance-wise which would make me hesitate to use absolute positioning when I needed it.
The real problem with absolute positioning everything is that you tend to tie your layout to fixed sizes, which can make things go completely nuts if you have to adjust for things which change size.
For example, what happens if you want to increase the font size of your site? If everything is absolutely positioned, you'll have a huge effort to re-align everything.
In the same vein, absolute positioning almost always means the entire layout is positioned and sized in pixels rather than em units or percent. Again, nothing wrong with using pixel sizing, but it does generate accessibility issues when people try to adjust the site themselves (eg with zoom or a magnifier, or just changing the font sizes, etc)
And have you tried viewing your site on various mobile devices? Sites that are rigidly designed are generally the worst when it comes to viewing on a smaller screen size. Far better to have a fluid design that just works wherever you use it, rather than having to have an entirely separate site for mobiles.

A: To me, using absolute positioning in relatively-positioned elements (like, within a footer) is time-saving.  Using it everywhere could be messy when you have to change a layout (columns, headers...).

A: Many years after the question was asked things look a bit different. Touch screen, mobile devices and evolution of zooming capabilities in regular desktop browsers eliminates all negatives of the absolute layout. Easy zooming makes the effort of avoiding absolute positioning unnecessary. Design your screen as you please. Fonts, pictures, absolute coordinates and sizes scale easily in almost any recent OS/browser.
Most OSes have reasonable default dpi (dots per inch) setting and browsers are configured with screen resolution in mind. Take any high resolution tablet. "font-size: 10px" in your CSS will actually result in text many times "taller" when measured in real screen pixels.
As for performance its not like static layout doesn't require the browser to calculate sizes and position of elements. Layout engine still has to perform those calculations that follows static positioning and sizing rules. Absolute layout simply allows developers to specify those rules explicitly.
An argument can be made that absolute positioning may even require less work from the browser to layout elements. Having 100 children static layout needs to evaluate position and size of 99 elements in order to position the 100th element. Absolute positioning explicitly tells the browser where to put that 100th child.
I didn't run any benchmarks myself but it is highly unlikely there are any significant differences in performance between different types of layouts.

A: If I can, I also always try to avoid absolute positioning. As it tends to make things harder for me in the end. But sometimes I don't really have a choise.

A: Following these interesting performance tests https://www.artlebedev.com/tools/technogrette/html/browser-performance/

For interactive elements it's better to use position: absolute.

But in opera it's "better" (little performance gain).


text:
Q: Printing family emoji, with U+200D zero-width joiner, directly, vs via list I have found some unexpected differences when printing, via print, a string with a family emoji directly, and when it's in a list. The below program
family = ''
print(family)
print([family])

outputs

['\u200d\u200d\u200d']

when I would expect it to output

['']

Another case of multi-character glyph
man_with_skin_tone_modifier = ''
print(man_with_skin_tone_modifier)
print([man_with_skin_tone_modifier])

outputs as I expect:

['']

Why is this?

Context: I discovered this while writing the answer for https://stackoverflow.com/a/49930688/1319998 , and it's using Python 3.6.5 on OS X.

A: The difference, as noted in the comments, is that print(family) calls the str.__str__ method, while print([family]) calls str.__repr__, which escapes non-printable unicode characters.

*

*The print function converts its (non-keyword) arguments using str.

*Calling str on containers (generally) calls repr on their items. Mostly this is because strings inside a container would too easily disturb the presentation of the container itself (e.g. with newlines). A PEP to change this was raised around the release of Python 3 but quickly rejected.

*Calling repr on strings escapes any non-printable characters (but, as of Python 3, preserves other non-ASCII Unicode characters): see PEP-3138 and the description of str.isprintable

Return true if all characters in the string are printable or the string is empty, false otherwise. Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

The CPython implementation can be found here (search for the unicode_repr function).


text:
Q: How to query child nodes in parent node entity of neo4j? For example, I have an entity like this:
@Data
@NodeEntity(label = "Subject")
public class Subject {
     @GraphId
     private Long id;
     private String name;

     @Relationship(type = "HAVE_S", direction = Relationship.OUTGOING)
     private Set<Subject> children = new HashSet<>();
}

Then I need to query a 'Subject' by graphId;
@Query("MATCH (s:Subject)-[r:HAVE_S*1]->(c:Subject) WHERE ID(s) = {graphId} RETURN s, r, c;")
Subject findById(@Param("graphId") Long graphId);

The result I want just like the following json:
{
    "id": 62
    "name": "Java"
    "children": [
        {
            "name": "Collection",
            "id": 105
        },
        {
            "name": "MultipleThreads",
            "id": 0
        }
    ]
}

But when I executed the cypher above through Spring Data,  an error comes out and says "Result not of expected size. Expected 1 row but found 3".
I hope someone can help me with this problem, thanks.

A: As your model suggests A subject have multiple children so when you are fetching it by id it's returning a cartesian product of your subject* children. In this case you need to collect your children(subjects and then return)
@Query("MATCH (s:Subject)-[r:HAVE_S*1]->(c:Subject) WHERE ID(s) = {graphId} RETURN s,  collect(c) as childrens;")

or simply you can use findById() of your repository the SDN will create query by itself

A: You can try like this.
MATCH (k:LabelsTree {name:'465afe3c118589de357745a709c0441f'}) CALL apoc.path.spanningTree(k,{labelFilter:'+LabelsTree', maxLevel:3, optional:true, filterStartNode:true}) yield path return path

Refer to the connection


text: Q: Dim screen in android I have searched a lot but unable to find any solution to dim screen. The question has exactly the same problem. I need to reduce the brightness even below than android system allows as in this app. Please help so I can move on.


text:
Q: Availability set fault domains When creating an availability set the default number of fault domains is 2.
As an example you want to deploy 3 VM's, would you consider using 2 or 3 fault domains? As a requirement 1 VM must be online all the time.
My question: are there any considerations why you would choose 2 fault domains over 3 fault domains? I'm trying to understand why 2 fault domains is the default number, instead of 3? Is it network related, performance?

A: there is no reason to pick 2 instead of 3 as 3 is strictly better, but some regions only support 2 fault domains. so you'd have to go with 2 fault domains in those regions.


text:
Q: where are visual studio 2017 dialog editor tools and controls? I'm a complete newbie to Visual Studio 2017 and now need to update a old windows application.  I down loaded VS 2017 community, found my .RC files and used it to open one of my dialog designs.  It displays correctly but my problem is how do I get the VS to display the tools such as grid lines, alignment tools, etc?  And how do I display the menu of the various controls (boxes and items) that one can add to the dialog design?

A: Those are in the toolbox pane/sidebar/thingie on the side. If you don't see it, go to the View menu and select "Toolbox" to turn it on.


text:
Q: Group file to New Folder? I have to copy files, make a new folder and then paste those files into the new folder so often.
I wonder if we can make a batch file or vbscript file to perform this task? Just select the files and choose "Group to New Folder" from the context menu. That'll be awesome!

A: I've found a solution in .NET 4.0
http://blogs.msdn.com/b/codefx/archive/2010/09/14/writing-windows-shell-extension-with-net-framework-4-c-vb-net-part-1.aspx

A: What you want to do is write an HTA application.  You could have a selection listbox that could be auto-populated with the current folders files when you first launch the hta.  Then just have a simple button than will prompt you for a folder path/name to create when selected and a simple sub to just move the selected files over, maybe through results to the screen or something.  Obviously with error trapping and all that's a little bit much code to just paste in here, but it should be pretty easy to do.
If you're looking for help getting started with the hta interface, I recommend you check out the "HTA Helpomatic" which you can use to get the basic GUI, as well as selection box code.  Obviously you can write the script subs to do the real work.