text:
Q: Why does the -bs switch on sendmail cause a SELinux denial from within a PHP app? On a CentOS 7.5 server (LAMP, PHP-FPM) with SELinux enabled, I've encountered a strange issue with a Laraval 5.3 application when it tries to send email.
The application's mail config is set to use /usr/sbin/sendmail -bs and when attempting to send an email the application throws a Swift_TransportException' with message 'Expected response code 220 but got code "", with message ""' in vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383
Suspecting SELinux, I dug deeper and audit2why shows:
type=AVC msg=audit(1553606152.177:1240981): avc:  denied  { execute } for  pid=3896 comm="sendmail" name="smtpd" dev="vda1" ino=12904557 scontext=system_u:system_r:system_mail_t:s0 tcontext=system_u:object_r:postfix_smtpd_exec_t:s0 tclass=file
If I disable SELinux, the issue is resolved. If I use the mail driver instead, which I believe instructs SwiftMailer to use PHP's mail() function (and subsequently the sendmail bin with only -t -i switches as per the default php.ini config) it works. If I use the SMTP driver it works and if I change the Laraval mail config sendmail path to /usr/sbin/sendmail -t -i it works.
Why does SELinux complain when using the -bs switch on sendmail?
According to man sendmail:
-bs Stand-alone SMTP server mode. Read SMTP commands from standard input, and write responses to standard output.  In stand-alone SMTP server mode, mail relaying and other access controls are disabled by default. To enable them, run the process as the mail_owner user.

If one were to go ahead and use that configuration (I'm guessing it's there for a reason), is it really expected to compile and install an SELinux module to allow the behaviour? It seems like something that should Just WorkTM.
Bonus question: I was under the impression that the sebool httpd_can_sendmail needed to be 1 for PHP to be able to use mail. Certainly I've found that to be the case on other projects. This flag seems to have no affect whatsoever when using any of the above mail drivers, in that they all still work without it being on (apart from the -bs scenario above). Why?

A: Generally, (web) apps should not be exec-ing smtpd. That's better managed and secured on a central SMTP server. SELinux succeeded at restricting sendmail to be only a mail submission agent.
The alternative sendmail invocation queues mail without starting smtpd, which is allowed under this policy.
Booleans had no effect because this wasn't a transition from httpd context. Note the denial was system_mail_t to postfix_smtpd_exec_t. The default policy doesn't allow sendmail to exec smtpd at all.


text:
Q: How to remove text selection that is highlighted when we copy to clipboard using javascript I am using the below code to copy and paste the text to clipboard using javascript. It basically selects the HTML element and shows a highlighter on that particular element . Is it possible to remove the highlighter or any other way to handle this scenario?
 copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
  }

A: try this
copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
    inputElement.blur();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to forecast in python using machine learning , from a given set of geographical data? I was analyzing some geographical data and attempting to predict/forecast next occurrence of event with respect to time and it geographical position. The data was in following order (with sample data)

Timestamp Latitude     Longitude   Event
13307266  102.86400972 70.64039541 "Event A"
13311695  102.8082912  70.47394645 "Event A"
13314940  102.82240522 70.6308513  "Event A"
13318949  102.83402128 70.64103035 "Event A"
13334397  102.84726242 70.66790352 "Event A"

First step was classifying it into 100 zones, so that reduces dimensions and complexity.

Timestamp Zone
13307266  47
13311695  65
13314940  51
13318949  46
13334397  26

Next step was to do time series analysis then I got stuck here for 2 months, read around a lot of literature and figured these were my options
* ARIMA (auto-regression method)
* Machine Learning
I wanted to utilize Machine learning to forecast using python but couldn't really figure out how.Specifically are there any python libraries/open-source-code specific for use case, which I can build upon.
EDIT 1:
To clarify, data is loosely dependent on past data but over a period of time is uniformly distributed.
The best way to visualize the data would be, to imagine N number of agents controlled by a algorithm which allots them task of picking resource from grids. Resources are function of socioeconomic structure of society and also strongly dependent on geography. Its in interest of " algorithm " to be able to predict demand zone and time wise.
p.s:
For Auto-regressive models like ARIMA Python already has a library http://pypi.python.org/pypi/statsmodels .

A: Without example data or existing code I can't offer you anything concrete.
However, often it's helpful to re-phrase your problem in the nomenclature of the field you want to explore. In ML terms:

*

*Your problem's features: How your inputs are specified. Timestamp is continuous, geographic zone is discrete.

*Your problems's target label: an event, precisely whether or not a given event has occurred.

*Your problem is supervised: target labels for previous data are available. You have previous instances of (timestamp, geographic zone) to event mappings.

*The target label is discrete, so this is a classification problem (as opposed to a regression problem, where the output is continuous).

So I'd say you have a supervised classification problem. As an aside you may want to do some sort of time regularisation first; I'm guessing there are going to be patterns of the events depending on what time of the day, day of the month, or month of the year it is, and you may want to represent this as an additional feature.
Taking a look at one of the popular Python ML libraries available, scikit-learn, here:
http://scikit-learn.org/stable/supervised_learning.html
and consulting a recent posting on a cheatsheet for scikit-learn by one of the contributors:
http://peekaboo-vision.blogspot.de/2013/01/machine-learning-cheat-sheet-for-scikit.html
Your first good bet would be to try Support Vector Machines (SVM), and if that fails maybe give k Nearest Neighbours (kNN) a shot as well. Note that using an ensemble classifier is usually superior than using just one instance of a given SVM/kNN.
How, exactly, to apply SVM/kNN with time as a feature may require more research, since AFAIK (and others will probably correct me) SVM/kNN require bounded inputs with a mean of zero (or normalised to have a mean of zero). Just doing some random Googling you may be able to find certain SVM kernels, for example a Fourier kernel, that can transform a time-series feature for you:
SVM Kernels for Time Series Analysis
http://www.stefan-rueping.de/publications/rueping-2001-a.pdf
scikit-learn handily allows you to specify a custom kernel for an SVM. See:
http://scikit-learn.org/stable/auto_examples/svm/plot_custom_kernel.html#example-svm-plot-custom-kernel-py
With your knowledge of ML nomenclature, and example data in hand, you may want to consider posting the question to Cross Validated, the statistics Stack Exchange.
EDIT 1: Thinking about this problem more you need to really understand if your features and corresponding labels are independent and identically distributed (IID) or not. For example what if you were modelling how forest fires spread over time. It's clear that the likelihood of a given zone catches fire is contingent on its neighbours being on fire or not. AFAIK SVM and kNN assume the data is IID. At this point I'm starting to get out of my depth, but I think you should at least give several ML methods a shot and see what happens! Remember to cross-validate! (scikit-learn does this for you).


text:
Q: Invalid argument to function in access sql WHERE NOT IN I have a table1
  PreA  BaB   CPS  CommName CommName_CPS
    we   ds   123   Degree   123-Degree
    Se   dd   345   arrow    345-arrow
    KM   sd   674   inv      674-inv

I have a table2
  PreA  BaB   CPS  CommName CommName_CPS
    we   ds   123   Degree   123-Degree
    Se   dd   345   arrow    345-arrow
    KM   sd   674   inv      674-inv
    DJ   gfd  435   klm      435-klm
    rt   ggsd 865   hff      865-hff

Table1 (is a query table which is from another table) has field CommName_CPS which is concate two fields,same with table2.
I'm  trying to sort out uncommon data when compare tbl1 with tbl2 by using below query
SELECT table1.PreA, table1.BaB,table1.CPS,table1.CommName,table1.CommName_CPS
FROM table1
WHERE CommName_CPS Not In (select CommName_CPS from table2);

I get an error Invalid argument to function.

A: Try this one, not exists will be better to use if CommName_CPS could be null, you can read more about it in this article http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/
SELECT *
FROM   table1 t1
WHERE  NOT EXISTS (SELECT 1
                   FROM   table2 t2
                   WHERE  t1.CommName_CPS = t2.CommName_CPS)

A: As I mentioned in my comments..
Change your Table 1 query to trap for null values when you concatenate the two fields:
SELECT PreA, BaB, CPS,CommName,
NZ([CPS],"") & "-" & NZ([CommName],"") AS CommName_CPS From <YourOtherTable>


text:
Q: AWS DAX java authentication issue I am attempting to write a flexible authentication mechanism between using DAX and DynamoDB for performance testing.
I have been able to get it to work fine with DynamoDB accross all regions, but it only works correctly in us-west-1 in DAX.
if (this.useDax) {
  try {
    AWSCredentials credentials = new PropertiesCredentials(new File(credentialsFile));
    ClientConfig daxConfig = new ClientConfig().withEndpoints(endpoint).withRegion(daxRegion)
        .withCredentialsProvider(new AWSStaticCredentialsProvider(credentials));
    daxDB = new ClusterDaxClient(daxConfig);
    primaryKeyName = primaryKey;
    LOGGER.info("dynamodb DAX connection created with " + this.endpoint);
  } catch (Exception e1) {
    LOGGER.error("DaxDBClient.init(): Could not initialize DaxDB client.", e1);
  }
} else {
  try {
    AWSCredentials credentials = new PropertiesCredentials(new File(credentialsFile));
    ClientConfiguration cconfig = new ClientConfiguration();
    cconfig.setMaxConnections(maxConnects);
    dynamoDB = new AmazonDynamoDBClient(credentials, cconfig);
    dynamoDB.setEndpoint(this.endpoint);
    primaryKeyName = primaryKey;
    LOGGER.info("dynamodb connection created with " + this.endpoint);
  } catch (Exception e1) {
    LOGGER.error("DynamoDBClient.init(): Could not initialize DynamoDB client.", e1);
  }
}

The error I am getting is:

com.amazon.dax.client.exceptions.DaxServiceException: [1.23.31.33] Connection requires authentication (Service: null; Status Code: -1; Error Code: null; Request ID: null)

A: I ended up using a different credentials provider (PropertiesFileCredentialsProvider) and it worked:
if (this.useDax) {
  try {
    ClientConfig daxConfig = new ClientConfig().withEndpoints(this.endpoint).withRegion(daxRegion)
        .withCredentialsProvider(new PropertiesFileCredentialsProvider(credentialsFile));
    daxDB = new ClusterDaxClient(daxConfig);
    primaryKeyName = primaryKey;
    LOGGER.info("dynamodb DAX connection created with " + this.endpoint);
  } catch (Exception e1) {
    LOGGER.error("DaxDBClient.init(): Could not initialize DaxDB client.", e1);
  }
} else {
  try {
    AWSCredentials credentials = new PropertiesCredentials(new File(credentialsFile));
    ClientConfiguration cconfig = new ClientConfiguration();
    cconfig.setMaxConnections(maxConnects);
    dynamoDB = new AmazonDynamoDBClient(credentials, cconfig);
    dynamoDB.setEndpoint(this.endpoint);
    primaryKeyName = primaryKey;
    LOGGER.info("dynamodb connection created with " + this.endpoint);
  } catch (Exception e1) {
    LOGGER.error("DynamoDBClient.init(): Could not initialize DynamoDB client.", e1);
  }
}


text:
Q: PostgreSQL function generate csv file I'm writing a function in order to create multiple CSV file.
DECLARE r RECORD;
DECLARE ra RECORD;
DECLARE ro RECORD;

BEGIN

DROP TABLE IF EXISTS tab1;
DROP TABLE IF EXISTS tab2;
DROP TABLE IF EXISTS tab3;

EXECUTE 'CREATE TABLE tab1 AS SELECT DISTINCT num FROM analysis';

FOR r IN EXECUTE 'SELECT num AS num FROM tab1'
LOOP
    EXECUTE 'CREATE TABLE tab2 AS SELECT id FROM analysis WHERE num_vista = r.num';
    FOR ra IN SELECT id FROM tab2
    LOOP
        EXECUTE 'CREATE TABLE tab3 AS SELECT DISTINCT oid FROM area WHERE analysis_id = ra.id';
        FOR ro IN SELECT oid FROM tab3
        LOOP
            EXECUTE 'COPY
            (
                SELECT created_at, result, updated_at FROM area
                WHERE oid = ro.oid
            ) TO "C:/Program Files/PostgreSQL/9.5/data/Num$rOid$ro.csv" WITH CSV HEADER;';
        END LOOP;

    END LOOP;

END LOOP;
END;

But I have this error:
element FROM for table r is missing
LINE 1: ...tab2 AS SELECT id FROM analysiy WHERE num_vista = r.num

Do you know how can I do?
Thanks in advance!

A: execute "text" query statement cant access values outside the query expression , you must generate those query's addicting values as text ... .
E r RECORD;
DECLARE ra RECORD;
DECLARE ro RECORD;

BEGIN

DROP TABLE IF EXISTS tab1;
DROP TABLE IF EXISTS tab2;
DROP TABLE IF EXISTS tab3;

EXECUTE 'CREATE TABLE tab1 AS SELECT DISTINCT num FROM analysis';

FOR r IN EXECUTE 'SELECT num AS num FROM tab1'
LOOP
    EXECUTE 'CREATE TABLE tab2 AS SELECT id FROM analysis WHERE num_vista = '||r.num::text;
    FOR ra IN SELECT id FROM tab2
    LOOP
        EXECUTE 'CREATE TABLE tab3 AS SELECT DISTINCT oid FROM area WHERE analysis_id = '||ra.id::text;
        FOR ro IN SELECT oid FROM tab3
        LOOP
            EXECUTE 'COPY
            (
                SELECT created_at, result, updated_at FROM area
                WHERE oid = '||ro.oid::text||'
            ) TO "C:/Program Files/PostgreSQL/9.5/data/Num$rOid$ro.csv" WITH CSV HEADER;';
        END LOOP;

    END LOOP;

END LOOP;
END;


text:
Q: Collaborative post submission I am working for a client who wants to implement the following collaborative post submission process:
Allows public users to submit draft posts,
allows admins to give feedback and add to the submitted post,
Admins approve it as the final version,
Finally the contributor needs to be able to approve the final version before the post is actually published
I identified the editflow plugin as a suitable solution. Does anyone else agree with this? Or are there alternative solutions?


text:
Q: Zone File Confusion - i don't understand what's wrong! i've recently changed the few sites I manage to reside on one vps, instead of multiple hosting accounts. All of them successfully transferred except one, which is giving me issues, and I'm unsure why.
Currently, going to example.com will work, but going to www.example.com will not, even though there's a CNAME entry in the zone file for www : @
I have other sites set up the same way and they are not having any issues whatsoever.
The site in question was transferred over from a different registrar. Is this just a propogation issue?
By request: domain name is blanchardscoffee.com

A: There's a thing called negative cache. I guess it hit you...
To quote the wikipedia article:

Some resolvers may override TTL
  values, as the protocol supports
  caching for up to 68 years or no
  caching at all. Negative caching, i.e.
  the caching of the fact of
  non-existence of a record, is
  determined by name servers
  authoritative for a zone which must
  include the Start of Authority (SOA)
  record when reporting no data of the
  requested type exists. The value of
  the MINIMUM field of the SOA record
  and the TTL of the SOA itself is used
  to establish the TTL for the negative
  answer.

This is what it looks like here:
$ dig www.blanchardscoffee.com A blanchardscoffee.com A
www.blanchardscoffee.com. 3582  IN      CNAME   blanchardscoffee.com.
blanchardscoffee.com.   3574    IN      A       173.201.180.189
blanchardscoffee.com.   3574    IN      NS      ns77.domaincontrol.com.
blanchardscoffee.com.   3574    IN      NS      ns78.domaincontrol.com.
;; Received 124 bytes from 192.168.178.1#53(192.168.178.1) in 38 ms

blanchardscoffee.com.   3574    IN      A       173.201.180.189
blanchardscoffee.com.   3574    IN      NS      ns77.domaincontrol.com.
blanchardscoffee.com.   3574    IN      NS      ns78.domaincontrol.com.
;; Received 106 bytes from 192.168.178.1#53(192.168.178.1) in 2 ms

A: OK, DNSStuff.com is reporting that no A or CNAME records exist for www.blanchardscoffee.com. My suggestion would be to specifically create an A record for www or create a CNAME for www aliased to blanchardscoffee.com.
EDIT
I missed the part where you already had a CNAME. Disregard my answer.

A: I think this is/was a caching issue of intermediate name servers. I currently get proper resolution on both blanchardscoffee.com and www.blanchardscoffee.com, with the dig for the latter clearly showing a CNAME pointing to the A record for the former:
$ dig www.blanchardscoffee.com

; <<>> DiG 9.7.3 <<>> www.blanchardscoffee.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13875
;; flags: qr aa; QUERY: 1, ANSWER: 2, AUTHORITY: 2, ADDITIONAL: 0

;; QUESTION SECTION:
;www.blanchardscoffee.com.      IN      A

;; ANSWER SECTION:
www.blanchardscoffee.com. 3600  IN      CNAME   blanchardscoffee.com.
blanchardscoffee.com.   3600    IN      A       173.201.180.189

;; AUTHORITY SECTION:
blanchardscoffee.com.   3600    IN      NS      ns77.domaincontrol.com.
blanchardscoffee.com.   3600    IN      NS      ns78.domaincontrol.com.

;; Query time: 92 msec
;; SERVER: 10.171.3.56#53(10.171.3.56)
;; WHEN: Tue Jun 14 18:19:54 2011
;; MSG SIZE  rcvd: 124

unless, of course, this is your old DNS configuration. But you should be able to verify this.


text:
Q: How to call exported kernel module functions from another module? I'm writing an API as a kernel module that provides device drivers with various functions. I wrote three functions in mycode.c. I then built and loaded the module, then copied mycode.h into < kernel >/include/linux. In a device driver, I have a #include < linux/mycode.h > and call those three functions. But when I build the driver module, I get three linker warnings saying that those functions are undefined.
Notes:

*

*The functions are declared extern in mycode.h

*The functions are exported using EXPORT_SYMBOL(func_name) in mycode.c

*Running the command nm mycode.ko shows all three functions as being available in the symbol table (capital T next to them, meaning the symbols are found in the text (code) section)

*After loading the module, the command grep func_name /proc/kallsyms shows all three functions as being loaded

So clearly the functions are being exported correctly and the kernel knows what and where they are. So why can't the driver see their definitions? Any idea what am I missing?

EDIT: I found some information about this here: http://www.kernel.org/doc/Documentation/kbuild/modules.txt

Sometimes, an external module uses exported symbols from  another
external module. kbuild needs to have full knowledge of   all symbols
to avoid spitting out warnings about undefined    symbols. Three
solutions exist for this situation.
NOTE: The method with a top-level kbuild file is recommended    but may
be impractical in certain situations.
Use a top-level kbuild file         If you have two modules, foo.ko and
bar.ko, where         foo.ko needs symbols from bar.ko, you can use a
common top-level kbuild file so both modules are        compiled in the
same build. Consider the following        directory layout:
  ./foo/ <= contains foo.ko
  ./bar/ <= contains bar.ko

The top-level kbuild file would then look like:
  #./Kbuild (or ./Makefile):
      obj-y := foo/ bar/

And executing
  $ make -C $KDIR M=$PWD

will then do the expected and compile both modules with       full
knowledge of symbols from either module.
Use an extra Module.symvers file        When an external module is built,
a Module.symvers file         is generated containing all exported symbols
which are         not defined in the kernel. To get access to symbols         from
bar.ko, copy the Module.symvers file from the         compilation of bar.ko
to the directory where foo.ko is      built. During the module build,
kbuild will read the      Module.symvers file in the directory of the
external      module, and when the build is finished, a new
Module.symvers file is created containing the sum of        all symbols
defined and not part of the kernel.
Use "make" variable KBUILD_EXTRA_SYMBOLS        If it is impractical to
copy Module.symvers from      another module, you can assign a space
separated list        of files to KBUILD_EXTRA_SYMBOLS in your build file.
These files will be loaded by modpost during the        initialization of
its symbol tables.

But with all three of these solutions, in order for any driver to use my API, it would have to either create a new Makefile or have direct access to my Module.symvers file? That seems a bit inconvenient. I was hoping they'd just be able to #include my header file and be good to go. Do no other alternatives exist?

A: From my research, it seems that those are the only three ways to handle this situation, and I've gotten each of them to work, so I think I'll just pick my favorite out of those.

A: Minimal QEMU + Buildroot example
I have tested the following in a fully reproducible QEMU + Buildroot environment, so maybe having this working version version will help you find out what is wong with your code.
GitHub upstream is centered on the files:

*

*dep.c

*dep2.c

*Makefile
dep.c
#include <linux/delay.h> /* usleep_range */
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/module.h>

MODULE_LICENSE("GPL");

int lkmc_dep = 0;
EXPORT_SYMBOL(lkmc_dep);
static struct task_struct *kthread;

static int work_func(void *data)
{
    while (!kthread_should_stop()) {
        printk(KERN_INFO "%d\n", lkmc_dep);
        usleep_range(1000000, 1000001);
    }
    return 0;
}

static int myinit(void)
{
    kthread = kthread_create(work_func, NULL, "mykthread");
    wake_up_process(kthread);
    return 0;
}

static void myexit(void)
{
    kthread_stop(kthread);
}

module_init(myinit)
module_exit(myexit)

dep2.c
#include <linux/delay.h> /* usleep_range */
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/module.h>

MODULE_LICENSE("GPL");

extern int lkmc_dep;
static struct task_struct *kthread;

static int work_func(void *data)
{
    while (!kthread_should_stop()) {
        usleep_range(1000000, 1000001);
        lkmc_dep++;
    }
    return 0;
}

static int myinit(void)
{
    kthread = kthread_create(work_func, NULL, "mykthread");
    wake_up_process(kthread);
    return 0;
}

static void myexit(void)
{
    kthread_stop(kthread);
}

module_init(myinit)
module_exit(myexit)

And now you can do:
insmod dep.ko
insmod dep2.ko

With that Buildroot setup, things are already configuring depmod /lib/module/*/depmod with the dependency, so just this is enough to load both:
modprobe dep

Also, if you built your kernel with CONFIG_KALLSYMS_ALL=y, then the exported symbol can be seen with:
grep lkmc_dep /proc/kallsyms

see also: Does kallsyms have all the symbol of kernel functions?

A: OK: You have one module where the function is and one place what wants to import it right?
You must use "EXPORT_SYMBOL("name of the function") such as foo in the place where the function is. So in the "c" file have the function "foo" defined and put in:
EXPORT_SYMBOL(foo)
Make sure you have the prototype for "foo" in a common header file (you can have it in separate places for each module and it will work but you are asking for trouble if the signatures change). So say: void foo(void *arg);
Then the other module that wants it just invoke "foo" and you are good.
Also: Make sure that you load the module with foo first. If you have cross dependencies like module2 needs foo from module1 and module1 needs bar from module2 you need to have one register functions with another. If you want to know please ask a separate Q.


text:
Q: Why jQuery sometimes overwrites window.onbeforeunload? I am having strange problem with jQuery (1.6.x). I have this simple call on my page:
window.onbeforeunload = function() { return 'Are you sure ?'; };

But it doesn't work, because as I've found out, jQuery overwrites content of the window.onbeforeunload. In JS console, I can see that window.onbeforeunload contains piece of jQuery code:
function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
    jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined;
};

Is there a way I can find why and where jQuery overwrites my onbeforeunload function? When I try to run empty jsfiddle with just jQuery loaded and with my onbeforeunload function, it works as expected.
Any hints will be appreciated.
EDIT:
Just in case, somebody suggests using:
$(window).bind('beforeunload', function() { return 'Are you sure';} );

I've already tried it and it behaves the same way as using pure Javascript.

A: Ok, I've finally figured a solution, which is probably not the cleanest one - because I don't know the exact cause of the problem - but it works. I've put my beforeunload function into jQuery's load function so it is executed after DOM and other elements are loaded.
$(window).load(function () {
  $(window).bind('beforeunload', function() { return 'Are you sure ?';} );
});

A: You might have some luck trying a setTimeout(function(){ ... },0), I ran into the same problem and this worked as a viable solution.


text:
Q: Difficulty in understanding cantor normal form Cantors normal form of x is defined as the following
$x = \omega^{a_1} n_1 + \dots + \omega^{a_k} n_k$, Where $x$ is an ordinal and where $\langle a_i \rangle$ is a strictly decreasing finite sequence of ordinals, $\langle n_i \rangle$ is a finite sequence of ordinals and $k\in \Bbb N$.
My problem in the understanding of the cantor normal form is the fact that i don't understand why one can write any finite ordinal in terms of cantors normal form, and why each ordinal has a unique cantor normal form.

A: First, prove that the map $\alpha\mapsto\omega^\alpha $ is normal, that is, strictly increasing and continuous at limits. Use this to show that for any $\alpha $ there is a least $\beta $ such that $\alpha <\omega^\beta $, and that, if $\alpha\ne0$, then this least $\beta $ is a successor ordinal, say $\beta=\beta_0+1$.
This shows that, for $\alpha\ne0$, there is a unique $\beta_0$ such that $\omega^{\beta_0}\le\alpha <\omega^{\beta_0+1}=\omega^{\beta_0}\cdot\omega $. Conclude from this that there is a unique positive integer $n_0 $ such that $\omega^{\beta_0}\cdot n_0\le \alpha <\omega^{\beta_0}\cdot (n_0+1) $.
Conclude from the above that there is a unique $\gamma <\omega^{\beta_0} $ such that $\alpha=\omega^{\beta_0}\cdot n_0+\gamma $. Now argue inductively, with $\gamma $ in place of $\alpha $.
The argument shows existence of the normal form. Uniqueness follows easily as well: Given two potential representations of $\alpha $, check that they are equal term by term by contradiction, considering the first term from left to right where they disagree.


text:
Q: Display mongodb multiple group by query results in a nested format Given the following dataset:
[
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "20",
    "hours": "18"
  },
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "20",
    "hours": "12"
  },
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "21",
    "hours": "10"
  },
  {
    "account_id" : "1111"
    "task_id" : "bbbb",
    "workweek" : "21",
    "hours": "5"
  },
  {
    "account_id" : "2222"
    "task_id" : "cccc",
    "workweek" : "21",
    "hours": "15"
  }
]

I'd like to group the documents and have the results in the following format:
[
  {
    "account_id": "1111",
    "tasks": [
      {
        "task_id": "aaaa",
        "workweeks": [
          {
            "workweek": "20",
            "total_hours": "30"
          },
          {
            "workweek": "21",
            "total_hours": "10"
          }
        ]
      },
      {
        "task_id": "bbbb",
        "workweeks": [
          {
            "workweek": "21",
            "total_hours": "5"
          }
        ]
      }
    ]
  },
  {
    "account_id": "2222",
    "tasks": [
      {
        "task_id": "cccc",
        "workweeks": [
          {
            "workweek": "21",
            "total_hours": "15"
          }
        ]
      },
    ]
  }
]

My broken aggregation code is the following:
db.tasks.aggregate([
  {"$group": {
    "_id": {
      "account_id": "$account_id",
      "task_id": "$task_id",
      "workweek": "$workweek",
    },
    "total_hours": {$sum: "$hours"}
  }},
  {"$group": {
    "_id": "$_id.account_id",
    "tasks": {
      "$push": {
        "task_id": "$_id.task_id",
        "workweeks": {
          "$push": {
            "workweek": "$_id.workweek",
            "total_hours": "$total_hours"
          }
        }
      }
    }
  }}
]);

I receive this error:
    "errmsg" : "exception: invalid operator '$push'",
And I assume it is because I can only $push once per $group block.
Any ideas on how to achieve the desired result?

A: Please try with one additional (middleware) "group-by" step:
db.tasks.aggregate([
  {"$group": {
    "_id": {
      "account_id": "$account_id",
      "task_id": "$task_id",
      "workweek": "$workweek",
    },
    "total_hours": {$sum: "$hours"}
  }},
  {"$group": {
    "_id": {
        "$_id.account_id",
        "$_id.task_id"
    },
    "workweeks": {
      "$push": {
        "workweek": "$_id.workweek",
        "total_hours": "$total_hours"
      }
    }
  }},
  {"$group": {
    "_id": "$_id.account_id",
    "tasks": {
      "$push": {
        "task_id": "$_id.task_id",
        "workweeks": "$workweeks"
      }
    }
  }}
]);


text:
Q: FaceId either crashes or shows error on authentication? App either hangs with a white screen (if installed from fresh) or shows a error message (if installed over an older 6.X app) "Bootstrap error page: Your app specifies authentication at startup, but there are no credentials. Did you run [[SalesforceSDKManager sharedManager] launch]? Error context: AppLoading"
Should use biometric authentication when passcode policy is enabled in the connected app.

A: if started from a sample app created with forceios please ensure that you add the required entry in the apps plist for FaceId (NSFaceIDUsageDescription) and try. If upgrading your app from 6.x to 7.x there will be a few changes required for launching your app. Please get a template from forcehybrid and proceed.
    <dict>
        <key>NSFaceIDUsageDescription</key>
        <string>"Unlock the app"</string>
    </dict>

This feature is linked with the usage of pin code in your connected app. So please make sure that the connected app in salesforce is setup with that policy.


text:
Q: Determine if Record is New Record I am trying to insert a condition to check if a record is a new record vs. an existing record in a trigger, but I'm not sure how to incorporate it in my condition?  I'm sure it's fairly simple, I'm just not sure how.
if(opp.Account.Type != null && opp.Account.Type.equals('Test') && opp.Advertiser__c == null)

A: You can use the Trigger Context Variables to determine your current state:
if(Trigger.isInsert && opp.Account.Type != null ...


text:
Q: Chisel randomly initialize register value when simulating with verilator I'm using Chisel and blackbox to run my chisel logic against a verilog register file.
The registerfile does not have reset signal so I expect the register to be randomly initialized.
I passed the --x-initial unique to verilator,
Basically this is how I launch the test:
  private val backendName = "verilator"

  "NOCDMA" should s" do blkwrite and blkread correctly (with $backendName)" in {
    Driver.execute(Array("--fint-write-vcd","--backend-name",s"$backendName",
      "--more-vcs-flags","--trace-depth 1 --x-initial unique"),
      ()=>new DMANetworkWithMem(memAddrWidth,memDataWidth)(nocDataWidth)(nNodesX,nNodesY)){
      c => new DMANetworkRWTest(c)
    }
  }

But The data I read from the register file is all zero before I wrote anything to it.
The read data is correct after I wrote to it.
So, is there anything inside chisel that I need to tune or I did not do everything properly ?
Any suggestions?

A: I'm not certain, but I found the following issue on Verilator with a similar issue: https://github.com/verilator/verilator/issues/1399.
From skimming the above issue, I think you also need to pass +verilator+seed+<value> and +verilator+rand+reset+<value> at runtime. I am not an expert in the iotesters, but I believe you can add these runtime values through the iotesters argument: --more-vcs-c-flags.
Side note, I would also set --x-assign unique in Verilator if there are cases in the Verilog where runtime would otherwise inject an X (eg. out-of-bounds index).
I hope this helps!


text:
Q: python-How to set global variables in Flask? I'm working on a Flask project and I want to have my index load more contents when scroll.
I want to set a global variable to save how many times have the page loaded.
My project is structured as :
├──run.py
└──app
   ├──templates
   ├──_init_.py
   ├──views.py
   └──models.py

At first, I declare the global variable in _init_.py:
global index_add_counter

and Pycharm warned Global variable 'index_add_counter' is undefined at the module level
In views.py:
from app import app,db,index_add_counter

and there's ImportError: cannot import name index_add_counter
I've also referenced global-variable-and-python-flask
But I don't have a main() function.
What is the right way to set global variable in Flask?

A: With:
global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:
index_add_counter = 0

Now you can import it with:
from app import index_add_counter

The construction:
global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)


text:
Q: RestRequest RequestBody instead of Params I am leveraging a webhook from a third party API (Mandrill) that sends me JSON, and have set up a Force.com public site with a RestResource to handle the incoming request. I've been noticing that if the request body gets too big (the JSON is all on a single parameter), it cuts off around ~10k characters (my current request has about ~80k). While this is definitely not the normal size of the payload, when an error occurs it adds subsequent values to the payload for the next retry, and that appears to how I got to this point.
What I'm mostly curious about is whether there is any way to force the use of RequestBody instead of Params. If I could leverage the Blob instead of a String, I shouldn't have the same issue (I tested it by POSTing a request with the same body, but without setting the Content-Type (in this case application/x-www-form-urlencoded) and I was able to see the entire request. From the documentation, it appears that if your request params are JSON, SF will deserialize it into a Map of Strings for you and clear out the RequestBody.
UPDATE: Adding Sample Code
The pertinent request headers:
POST /services/apexrest/Webhook HTTP/1.1
Host:
Content-Type: application/x-www-form-urlencoded
Content-Length: 462817
Connection: close
Accept: */*

Sample Data (extrapolate this to a bigger size, my actual data has sensitive information). The key is there is one parameter, and a lot of data within it (my actual values have about 15 fields per item):
events=[{"event":"test", "msg":"test"}, {"event":"test2", "msg":"test2"}, ...]

Code:
@RestResource(urlMapping='/Webhook/*')
global without sharing class RESTWebhook
{
    @HttpGet
    global static String doGet()
    {
        return 'Please use POST. No data saved.';
    }

    @HttpPost
    global static String doPost()
    {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        return PostHelper(req, res);
    }

    global static String PostHelper(RestRequest req, RestResponse res)
    {
        try
        {
            System.debug('Body: ' + (req.requestBody != null ? req.requestBody.toString() : ''));
            System.debug('Params: ' + req.params);

            // here I can create a new custom records with the params.
            Webhook_Test__c wt = new Webhook_Test__c();
            wt.LongText__c = req.params.get('events');
            insert wt;
        }
        catch (Exception e)
        {
            res.statusCode = 500;
            return e.getStackTraceString();
        }

        res.statusCode = 200;
        return 'Success';
    }
}

A: Per RestRequest methods, if the function accepts parameters, it will be deserialized into the provided parameters, otherwise it will be in RestRequest.requestBody. The solution, then, is to make sure your function takes no parameters.

If the Apex method has no parameters, then Apex REST copies the HTTP
  request body into the RestRequest.requestBody property. If there are
  parameters, then Apex REST attempts to deserialize the data into those
  parameters and the data won't be deserialized into the
  RestRequest.requestBody property.

Update 1

I tested the behavior this morning, using the following test class:
@RestResource(urlMapping='/demoRest')
global class RestDemo1 {
    @HttpPost
    global static String doPost() {
        RestRequest req = RestContext.request;
        System.debug(LoggingLevel.ERROR, req.requestBody.toString());
        return '';
    }
}

I used the following JavaScript in my browser to simulate the request:
(function() {
    var xhr = new XMLHttpRequest(), d = {}, i=50000;
    while(i--) d['d'+i] = i;
    d = JSON.stringify(d);
    xhr.open('POST','/services/apexrest/demoRest');
    xhr.setRequestHeader('Authorization','Bearer '+document.cookie.match(/sid=(.+?);/)[1]);
    xhr.send(d);
}())

The debug statement started off as:
{"d49999":49999,"d49998":49998,...}

Obviously, I can't post the entire debug statement here, as the payload was 727,781 characters long. My entire log was 730,252 bytes in size. Therefore, I have confirmed that the entire payload was transferring correctly, as I could visually review the string.
I then adjusted the loop from 50,000 to 200,000, resulting in a payload of 3,177,781 characters in length, and was able to confirm that the entire resource still loaded. In short, I'm not able to replicate any sort of problem with a simple 10,000 character payload, and in fact can read much larger payloads without a problem.
Finally, I adjusted the code to parse it using the standard JSON classes:
@RestResource(urlMapping='/demoRest')
global class RestDemo1 {
    @HttpPost
    global static String doPost() {
        RestRequest req = RestContext.request;
        System.debug(JSON.deserializeuntyped(req.requestbody.tostring()));
        return '';
    }
}

And was able to load a map with 50 elements that contained 1000 elements each, 678,268 characters of payload, using the following code:
(function() {
    var xhr = new XMLHttpRequest(), d = {}, i=50000, v = 1000, c = {};
    while(i--) { c[i] = i; if(i/v==Math.floor(i/v)) { d[i] = c; c = {}; } }
    d = JSON.stringify(d);
    xhr.open('POST','/services/apexrest/demoRest');
    xhr.setRequestHeader('Authorization','Bearer '+document.cookie.match(/sid=(.+?);/)[1]);
    xhr.send(d);
}())

Assuming your JSON is well-formed, your controller should load the request just fine. Since my example code is able to handle far greater numbers than what you're working with (8 times more!), the problem might be with some other error in your code.

Update 2
I wrote some new code to test this:
(function() {
    var a = new XMLHttpRequest(), b = [], c, d = 0, e;
    for(;d<10000;d++) {
        c = {}
        for(e = 0; e < 15; e++) {
            c['a'+e] = d+e;
        }
        b.push(c);
    }
    a.open('POST','/services/apexrest/phyrfox/demoRest');
    a.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    a.setRequestHeader('Authorization','Bearer '+document.cookie.match(/sid=(.+?);/)[1]);
    a.send('q='+escape(JSON.stringify(b)));
}());

I honestly expected the system to place the data into the responseBody portion of the RestRequest, so I was unpleasantly surprised when it was empty and params was populated with one element (q) that contained the JSON. I re-checked the documentation to see what it had to say about RestRequest:
Name        Return Type             Description
params      Map <String, String>    Returns the parameters that are received by the request.
requestBody Blob                    Returns or sets the body of the request.
                                    If the Apex method has no parameters, then Apex REST
                                    copies the HTTP request body into the
                                    RestRequest.requestBody property. If there are parameters,
                                    then Apex REST attempts to deserialize the data into those
                                    parameters and the data won't be deserialized into the
                                    RestRequest.requestBody property.

The requestBody bit seems to suggest that the original question is legitimate, because it would suggest that there is a bug; as far as I am concerned, I would state that the documentation or the functionality should match in order to avoid calling this a bug.
Given this, however, the params map seems to be pretty clear about what it does: it maps named parameters into the map. We would expect this behavior in other languages, such as PHP's $_REQUEST global variable, because it is documented this way. While the description for requestBody is misleading (and clearly wrong, since there are other exceptions to the rule), the fact that it is being placed in params actually does make sense.
Consider Visualforce as logical extension of this. The view state parameter is submitted with postbacks, but clearly it must be treated as a parameter instead of request-body content. The reason why the view state isn't in the URL is two-fold: first, query parameters are more exposed, both to the user and to everyone else, and query parameters are limited in size compared to a request body.
The W3C recommendations for handling POST requests suggests that all parameters should be sent with the request body instead of the URL query-string method. The logical extension of this statement is that application/x-www-form-urlencoded payloads are query strings, which in turn are query string parameters. Since the payload is considered to be part of the query string, it is no longer content, but simply an extension of the action URL's query string. This is a perfectly sane way of handling/parsing the content, and one widely accepted on the Internet as a whole.
In any case, this actually is not a bug, but standard, expected behavior consistent with W3C recommendations and implemented practices around the web with regards to POST requests. You should either change your content type, or you should use the params map.
Finally, in regards to truncation of the data, I presume that your field is configured with a maximum length of ~10k characters. You can increase this to 32,000 or so, if you'd like, but you won't be able to capture 80k worth of text in a single field. You should consider using multiple long text area fields, or even better, storing the payload as an attachment or document, which won't suffer the same limitations on storage limits.
Webhook_Test__c wht = new Webhook_Test();
insert wht;
Attachment att = new Attachment(ParentId=wht.Id, ContentType='text/plain', Body=Blob.valueOf(req.params.get('events')));
insert att;

All of this being said, I would suggest that salesforce.com update their documentation on requestBody to note that form content types will transform the payload into the query string parameters.


text:
Q: binding with @ObjectBinding and @EnvironmentObject 28-07-2019. I still have a question about the code below. I would like to separate the data model out of the ContentView. So I made a separate file and added the class, like this:
import SwiftUI
import Combine

class User: BindableObject {
    let willChange = PassthroughSubject<Void, Never>()
    var username : String = "Jan" { willSet { willChange.send() }}
    var password : String = "123456" { willSet { willChange.send() } }
    var emailAddress : String = "jan@mail.nl" { willSet { willChange.send() } }
}

#if DEBUG
struct User_Previews: PreviewProvider {
    static var previews: some View {
        User()
            .environmentObject(User())
    }
}
#endif

This doesn't work however, I'm getting an error:
Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocols

Error occurs on the .environmentObject(User()) line in # if DEBUG.

After watching some video's I made the following code (including changes for Xcode 11 beta 4). Tips from both answers from dfd and MScottWaller are already included in the code.
import Combine
import SwiftUI

class User: BindableObject {
    let willChange = PassthroughSubject<Void, Never>()
    var username = "Jan" { willSet { willChange.send() } }
    var password = "123456" { willSet { willChange.send() } }
    var emailAddress = "jan@mail.nl" { willSet { willChange.send() } }
}

struct ContentView: View {
    @EnvironmentObject var user: User

    private func buttonPressed() {
        print(user.username) // in Simulator
    }

    var body: some View {
        VStack {
            TextField("Username", text: $user.username)
            TextField("Password", text: $user.password)
            TextField("Emailaddress", text: $user.emailAddress)
            Button(action: buttonPressed) {
                Text("Press me!")
            }

        }
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(User())
    }
}
#endif

But now onto the next part. If I have another view... how can I reference the data then? Since the source of truth is in the above ViewContent() view. The answer is:
import SwiftUI

struct DetailView: View {
    @EnvironmentObject var user: User

    var body: some View {
        VStack {
            TextField("Username", text: $user.username)
            TextField("Password", text: $user.password)
            TextField("Email", text: $user.emailAddress)
        }
    }
}

#if DEBUG
struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView()
            .environmentObject(User())
    }
}
#endif

Don't forget to edit the SceneDelegate (answer from dfd):
var user = User()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView()
            .environmentObject(user)
        )
        self.window = window
        window.makeKeyAndVisible()
    }
}

A: In your DetailView preview, don't for get to attach the environmentObject. See how I've added it in the PreviewProvider below. When you run the actual app, you'll want to do the same to you ContentView in the SceneDelegate
import SwiftUI

struct DetailView: View {
    @EnvironmentObject var user: User

    var body: some View {
        HStack {
            TextField("Username", text: $user.username)
            Text("Hello world!")
        }
    }
}

#if DEBUG
struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView()
            .environmentObject(User())
    }
}
#endif

A: If the "source of truth" is User, and you've made it a BindableObject you just need to expose it best to make it available to the various views you want. I suggest @EnvironmentObject.
In your SceneDelegate, do this:
var user = User()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView()
            .environmentObject(user)
        )
        self.window = window
        window.makeKeyAndVisible()
    }
}

Now that a "stateful" instance of User is available to any View, you simply need to add:
@EnvironmentObject var user: User

To any/all vies that need to know about User.
BindableObject (for the most part) reserve memory for what you've denied. @ObjectBinding merely binds a view to what is in that part of memory (again, for the most part). And yes, you can do this for User in all views - but since you are instantiating it in ContentView? Nope.)! @EnvironmentObject makes it available to any views that need to access it.
Absolutely, you can use @ObjectBinding instead of an @EnvironmentObject, but so far,? I've never heard of a reason to do that.


text:
Q: Getting error: java.lang.ClassNotFoundException: org.apache.tomcat.util.http.mapper.Mapper in Spring Boot test When I try to run my Spring Boot test, I get the error:
java.lang.ClassNotFoundException: org.apache.tomcat.util.http.mapper.Mapper

This seems to be due to some conflicts from gradle but I can't figure out what's causing it.
The dependencies:
http://www.heypasteit.com/clip/0IIVEX .
(It's too long to paste here)
The gradle:
repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://repo.hortonworks.com/content/groups/public" }
}

dependencies {

    compile(group: 'com.testcompany', name: 'util-lib', version: "1.0.1", classifier: 'lite')

    //Testing
    testCompile(group: 'com.testcompany', name: 'util-testing', version: "1.0.1", classifier: 'lite')
    testCompile("junit:junit")
    testCompile "org.hamcrest:hamcrest-all:1.3"
    testCompile "org.springframework.boot:spring-boot-starter-test"
    testCompile "org.mockito:mockito-core:${mockitoVersion}"
}


text:
Q: Checking non-standard file extensions with Cppcheck Is there a way to pass custom file extensions to Cppcheck? For example, *.pc.

A: sure. cppcheck will check any file that you give it.
check the file xyz.pc:
cppcheck xyz.pc

check all files with extension pc in folder srcfolder (this at least works in linux):
cppcheck srcfolder/*.pc

the --file-list flag may also be useful. you could generate the list of files that you want to check using an arbitrary script. and then run cppcheck on that file list.
cppcheck --file-list=files.txt


text:
Q: How to resolve the issue "Waiting for update signal from WDS..."? export default function SinglePost() {
  const location =useLocation();
  const paths=location.pathname.split("/")[2];
  console.log(paths);
  useEffect(()=>{
    const getpost= async () => {
      const res=axios.get("/posts/"+paths)
      console.log(res);
    }
  },[paths])

What should I do?
I checked out the some solution
The first solution says to change the webpack.config.js file and I am not able find that file. And is this the correct solutions.


text:
Q: How do I test event trigger cloud function? I want to do unit testing on cloud functions, however, the function itself is an event trigger function that contains some helper functions. I want to test those helper functions as well. Here is the code sample
import os
from google.cloud import vision
from google.cloud import storage

def face_detection(uri):
    """
    This function detects the faces in the file
    located in Google Cloud Storage or the web
    Args:
        uri: the file located in Google Cloud Storage or the web
    returns:
        None: Prints the likelihood of the face expressions
        or returns an errors resonse in string format
    """

def trigger_event(event, context):
    """
    Background Cloud Function to be triggered by Cloud Storage.
    This generic function logs relevant data when a file is changed.
    Args:
        event (dict):  The dictionary with data specific to this type of event.
                        The `data` field contains a description of the event in
                        the Cloud Storage `object` format described here:
                        https://cloud.google.com/storage/docs/json_api/v1/objects#resource
        context (google.cloud.functions.Context): Metadata of triggering event.
    Returns:
        None; the output is written to Stackdriver Logging
    """

    bucket_name = event["bucket"]
    source_img = event["name"]
    tmp_download_path = f"/tmp/{source_img}"

    try:
        download_image(bucket_name, source_img, tmp_download_path)
        print(f"Image {source_img} downloaded to {tmp_download_path}")
        # currenlty this makes sure there's one person
        # in the frame and prints a few other details
        face_detection(tmp_download_path)
    except Exception:
        pass
    finally:
        if os.path.isfile(tmp_download_path):
            os.remove(tmp_download_path)
        else:
            print("Error: %s file not found" % tmp_download_path)

def download_image(bucket_name, source_blob_name, destination_file_name):
    """Downloads the specified image from cloud storage
    Args:
        bucket_name = "your-bucket-name"
        source_blob_name = "image-name"
        destination_file_name = "local/path/to/file"
    Returns:
        Local path to downloaded image
    """

def upload_processed_images(bucket_name, source_file_folder):
    """Uploads images to the bucket.
    Args:
        bucket_name = "your-bucket-name"
        source_file_folder = Path to the folder that contains
                                all the processed images
    Returns:
        None;
    """

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    for file_name in os.listdir(source_file_folder):
        blob = bucket.blob(file_name)
        blob.upload_from_filename(os.path.join(source_file_folder, file_name))

        print("File {} uploaded to {}.".format(file_name, bucket_name))

For example, if I want to test if the function upload_processed_images is actually working. I want it to be an unit test. Should I test locally? If the function is tested locally, will it connect to GCP with correct storage.Client()? Or I need to test it on the GCP platform?
Thanks for any help.

A: I actually found a way of testing this. I used functions-framework for the testing. You can find the answer https://github.com/neu-self-image-experiments/sie-backend#test-guidelines


text:
Q: Sanitizing a query for RediSearch Is there any guideline on sanitizing the query term for RediSearch, e.g. certain characters such as * at the end of a term or @ - at start of term have special purposes in the query syntax and would be good to strip some/all of them out for queries where the special purpose doesn't apply. Also, I'm wondering if there are any security implications of passing in arbitrary query strings.

A: Re security - no, redis itself makes sure that injection is impossible. You might want to check the limits on string lengths etc. At worst (barring bugs) a badly formed query will cause a syntax error to be returned.
Re syntax - yes, make sure the reserved symbols like @!{}()|-=> are either escaped or stripped.


text:
Q: PuLP in Python Replit with error in solve() I am trying to solve a very simple Linear Programming problem by using the PuLP library within the Replit platform (https://replit.com/). I've done this process before but just recently I have had this problem.
To start, I create a Repl using a Python template, import the PuLP package and, after defining the problem correctly, when I run the solver (CBC - the solver by default) I get a very strange error on the ".solve()" argument.
I don't think the problem is in the code because when I run this exact same PuLP code in an older Python Repl it works well.
I think the current Repl is using Python 3.8 and PuLP 2.6 while the old Repl is using PuLP 1.6.10 (I'm not sure of the Python version and I'm not sure how to check it). The packager files (poetry.lock and pyproject.toml) in the old and new Repls are different.
The full code is:
import pulp

x=pulp.LpVariable.dicts('x',range(2),cat=pulp.LpContinuous)

model=pulp.LpProblem('test',pulp.LpMaximize)

model += 4*x[0]+3*x[1]

model += 2*x[0]+x[1]<=10
model += 3*x[0]-2*x[1]<=20

status=model.solve()

The error I get is:

Traceback (most recent call last): File "main.py", line 12, in
 status=model.solve() File
"/(...)/lib/python3.8/site-packages/pulp/pulp.py", line 1913, in solve
status=solver.actualSolve(self,**kwargs) File
"/(...)/lib/python3.8/site-packages/pulp/apis/coin_api.py", line 137,
in actualSolve return self.solve_CBC(lp,**kwargs) File
"/(...)/lib/python3.8/site-packages/pulp/apis/coin_api.py", line 198,
in solve_CBC raise PulpSolverError(pulp.apis.core.PulpSolverError:
Pulp: Error while trying to execute, use msg=True for more details
(...)

full error output Note: I've tried to add msg=True but not more information was produced in the log
I've also tried using the older version of PuLP in the new project, but there is an error importing PuLP with that version.
Do you know if there is a way to change the Repl project definitions to be able to use PuLP in the current Python template from Replit? As is, it seems that PuLP is now not functional in Python Repls...

A: For future reference: Please copy & paste the complete error output into your question as text (put a > in front of it to mark it as a blockquote.
In this case the important bit is on top. A compiled shared library used by cbc uses libstdc++ which cannot find the correct glibc (version 2.33) it needs.
You will either need a libstdc++ compiled against the version of glibc that you are actually using, or glibc 2.33.
Since I don't know how that works with nix/NixOS, I cannot tell you how to do that.


text:
Q: "People" or "peoples" when referring to an indigenous population? Let's say we are talking about the indigenous pukapuka who live in Pluto.
What is correct: "the pukapuka people" or "the pukapuka peoples"?
I've read somewhere the usage of "peoples" in this context, and it has surprised me.

A: "Peoples" means a group of populations. So for example "the native American peoples" means the tribes that were living in America before Columbus. "the pukapuka peoples" would mean "the group of tribes/groups collectively known as pukapuka", whereas "the pukapuka people" would mean "the group of people known as (the) pukapuka (tribe/group/etc.)"

A: "People: Persons composing community, tribe, race, or nation."
OED


text:
Q: Make answer highlighting fade to red instead of white for deleted answers This is a really minor issue, but it bothers me more than it should.
When you follow a link to an answer (example) the answer's background flashes to yellow and slowly fades back to white. This works fine.
When you have 10k+ reputation and you follow a link to a deleted answer (example, you need 10k+ on SO) it does the same (fade from yellow to white) but after the animation has finished it "snaps" back to deleted answer's red background. The same applies to comments within deleted posts.
Could the highlighting animation be made to fade from yellow to the post's actual background, which is red for deleted posts?


text:
Q: Should I use raw scores or profile scores for variables in a regression model? I'm trying to build a regression model to predict subjective memory reports based on the following predictors: objective memory test, illness perceptions, verbal fluency, and mood. I also want to control for age, years of education and IQ by putting them into the regression model too. However, there's a problem.
The objective memory memory test (The Rivermead Behavioural Memory Test) gives you both raw scores and profile scores for the various subscales. Some, but not all, of the profile scores are converted based on IQ and age.
Also, the IQ estimate (The Test of Premorbid Functioning) converts raw scores to an IQ estimate, either just with the raw score, or with the raw score AND demographic variables of age, gender and years of education. The IQ estimate that includes demographic information is far more accurate than without.
If I use profile scores (with demographics) then aren't I controlling for them twice?
Should I use raw scores or profile scores? And what, and how should I enter these into the regression model?
Sorry if the above doesn't make sense. I'm not sure I understand it myself. I'm really struggling to get my head around this! Thanks!

A: First, if you are just interested in prediction then you can use whichever predicts better. I would split the data into training and test data sets and then run a few models in the training data, figurbe out which predicts best, and test it in the test data and use those estimates for parameters etc.
But if you are really just interested in prediction there may be better methods than regression, but they can be kind of "black box".
If you are also interested in explanation, that is, you  want your variable to be explicable to others and (perhaps) to illuminate something about how these variables work, then you  have to think about what explanations would add to the knowledge base.
Finally, what do you mean by "far more accurate"?

A: On the IQ test: you have one score that gives raw scores, and another that is adjusted for, say, age. Assuming the adjustment makes sense, you can and probably should use the adjusted score.
Here's why: you know that IQ depends crucially on age, that's why you would ideally want to adjust for it. If you only had the raw scores, you could build an adjusted measure by yourself (assuming you have age of the subject). The easiest way to do this would be via interactions. A linear regression like
$$MemRep_i=\beta_0+\beta_1 Age_i+\beta_2 RawIQ_i+\beta_3 Age_i\times RawIQ_i+e_i,$$
accounts for the fact that the influence of IQ on your dependent variable varies with age. For example, an estimate of $\beta_3=.2$ would mean that every increase in the product $Age*RawIQ$ increases your MemRep score by .2 (I don't know if the scaling makes sense, but you get the idea). This is not to be confused with the direct effect of age, which is estimated in $\beta_1$, or the direct effect of RawIQ ($\beta_2$). In the above specification, however, the interaction is constrained to be linear -- this is the simplest way to adjust, but may be very restrictive or simply wrong. I am guessing the adjusted IQ scores you have are more sophisticated and should therefore be used. Using the adjusted score then replaces the RawIQ and interaction above, i.e., you would estimate
$$MemRep_i=\beta_0+\beta_1 Age_i+\beta_2 AdjIQ_i+e_i.$$
Clearly, this is more convenient (and probably more accurate) than building the adjusted score yourself, especially since you mention IQ does not only depend on age, but also schooling etc., for which you would have to add interactions as well. The one exception is if you think these linear interations produce a better adjusted IQ score than what you have.
The question whether you should use raw or adjusted score for your dependent variable is a different story. I would say the choice is mostly driven by your task: you want to predict the MemRep score - the adjusted one or the raw score? In particular, if you do not have access to adjusted scores later, then there is no point in building a model that predicts adjusted scores, and you should stick to the raw scores. As a side remark, if you estimate a model with adjusted MemRep score and do include predictors that have also been used in the adjustment, then you can actually see whether these predictors have predictive power left. If some predictor is significantly different from zero -- say age is positive -- that would mean the adjustment did not sufficiently account for age differences and with higher age of the subject you would predict a higher MemRep score.
Last remark: since you want to predict well, divide your data set randomly into training and validation data set. You estimate the parameters using only the training set, and then predict the MemRep scores for the validation sample. Do this with different speficiations (using raw scores, adjusted scores, with/without interactions etc.). Then just stick to what works best.


text:
Q: Understanding my mistake when dealing with the direct sum (3 subspaces involved) Given two subspaces $U_1, U_2$, I understand the concept of direct sum
$$ W= U_1 \oplus U_2 \iff W= U_1 + U_2, \quad U_1 \cap U_2 = \{ 0 \}$$
Where $W$ is a subspace of $V$.
I am trying to generalize it for more than $2$ subspaces, say $3$. I thought of the following.
$$ W= U_1 \oplus U_2 \oplus U_3 \iff U_1 \cap U_2 = \{ 0 \}, U_1 \cap U_3 = \{ 0 \}, U_2 \cap U_3 = \{ 0 \}, U_1 + U_2 + U_3 = W $$
It does not seem to have the same structure that for the statement with $k$ subspaces
\begin{align*}
W= U_1 \oplus U_2 \oplus ... \oplus U_k \iff& U_i \cap \left(U_1 + ... + U_{i-1} + U_{i+1} + ... + U_k\right) = \{ 0 \} \\
&U_1 + U_2 + ... + U_k = W
\end{align*}
In particular, the issue lies on the intersection statement. Might you explain why my thought is faulty? I should be able to find a counterexample once I see it :)
Edit 0
Let us use the following definition for the direct sum (Axler, page 21)
$U_1 + U_2 + \ ... \ + U_k$ is a direct sum if $x \in U_1 + U_2 + \ ... \ + U_k$ can be written in a unique way as $x = u_1 + u_2 + \ ... \ + u_k$, where $u_i \in U_i$
I think I found a counterexample:
$$U_1 = \{ (x, 0) | x \in \Bbb R\}, \quad U_2 = \{ (y, y) | y \in \Bbb R\}, \quad U_3 = \{ (0, y) | y \in \Bbb R\}$$
These subspaces satisfy $U_1 \cap U_2 = \{ 0 \}, U_1 \cap U_3 = \{ 0 \}, U_2 \cap U_3 = \{ 0 \}, U_1 + U_2 + U_3 = \Bbb R^2$ but not $\Bbb R^2= U_1 \oplus U_2 \oplus U_3$ because we can write, say, the zero vector in (at least) two ways
$$(0, 0) = (1, 0) + (-1, -1) + (0, 1) \quad \text{and} \quad  (0, 0) = (0, 0) + (0, 0) + (0, 0)$$
Do you agree? :)

A: I guess the problem is that (for three subspaces) $U_1+U_2$ may intersect $U_3$ in a non-zero vector even though $U_1\cap U_3 = \{0\}$ and $U_2\cap U_3 = \{0\}$ - can you find an example of this? If $U_1+U_2$ intersects $U_3$ in a non-zero vector, then the sum $U_1+U_2+U_3$ cannot be a direct sum. (I guess the way to see this depends on the definition of direct sum that you are using - but basically you can represent a vector in the intersection $\left(U_1+U_2\right)\cap U_3$ as a sum of vectors in $U_1$, $U_2$ and $U_3$ in at least two different ways, so uniqueness of representation fails.)
Hope this helps and let me know if you would like further clarifications!

A: This indicates that $U\cap V=\{0\}, U +V = W$ is not the "right" definition (since it does not generalize nicely). Instead, I would take the following as the definition :

Let $(U_i)_{i\in I}$ a family of subspaces. We say that $\bigoplus_{i\in I} U_i = W$ when, for any $x\in W$, there is a unique family $(x_i)_{i\in I}$ with $x_i \in U_i$, equal to $0$ but for a finite number of them and with  :
$$\sum_{i\in I}x_i = x$$

Then you could show that the properties you mention are equivalent to this, when $I$ is finite or has two elements.
Edit 0
Using this, your counterexample shows that :
$$ W= U_1 \oplus U_2 \oplus U_3 \iff U_1 \cap U_2 = \{ 0 \}, U_1 \cap U_3 = \{ 0 \}, U_2 \cap U_3 = \{ 0 \}, U_1 + U_2 + U_3 = W $$
is not true.
It is easy to show from the definition that direct sum are associative : ie $U_1\oplus U_2\oplus U_3 = W$ iff $U_1$ and $U_2$ are in direct sum and $(U_1\oplus U_2) \oplus U_3 = W$. By induction, you get the right characterization.

A: @SolubleFish's definition is the right way to generalize the definition of direct sum for more than two subspaces, from this definition it is easy to show that
\begin{align*}
W=U_{1}\oplus U_{2}\oplus \dots\oplus U_{k} \iff& U_{1}\cap U_{2}=\{0\}, \ \left(
U_{1}+ U_{2}\right) \cap U_{3}=\{0\} \\
&\left( U_{1}+ U_{2}+ U_{3}\right)\cap U_{4}=\{0\} \\
&\vdots \\
&\left( U_{1}+ U_{2}+ U_{3}+\cdots+U_{k-1}\right)\cap U_{k}=\{0\} \\
&U_{1}+ U_{2}+ U_{3}+\cdots+U_{k-1}+U_{k}=W
\end{align*}


text:
Q: Upload file to Google Drive with WebClient In PowerShell v2 I am trying to upload a file to Google Drive. Since v2 has no Invoke-RestMethod cmdlet I have to use .NET class WebClient.
Reference: https://www.connorcg.com/uploading-and-downloading-from-google-drive-via-api-with-powershell-and-oauth2.html
$webclient = New-Object System.Net.WebClient
$webclient.Headers.Add("Authorization", "Bearer $AccessToken")
$webclient.Headers.Add("Content-Type", 'multipart/related; boundary=boundary')
$webclient.Headers.Add("Content-Length", $UploadBody.Length) # This is wrong, why?
$webclient.UploadString($URL, "POST", $UploadBody)

Exception:

'Content-Length' header must be modified using the appropriate property or method.

PS> $Error[0].Exception.ToString()
System.Management.Automation.MethodInvocationException: Exception calling
"UploadString" with "3" argument(s): "An exception occurred during a WebClient
request."
---> System.Net.WebException: An exception occurred during a WebClient request.
---> System.ArgumentException: The 'Content-Length' header must be modified
using the appropriate property or method.

Without "Content-Type" the uploaded file goes to root folder and contains my HTML body.
Without 'Content-Length' the upload is successful and everything looks good.
I still don't understand why 'Content-Length' header is wrong and what is the purpose of this. Is it mandatory in terms of possible failures/drops or proper encoding?


text:
Q: Remove the first N items that match a condition in a Python list If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?
One solution is to iterate over each item, mark it for deletion (e.g., by setting it to None), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data.  Is there a more idiomatic or efficient way to do this?
n = 3

def condition(x):
    return x < 5

data = [1, 10, 2, 9, 3, 8, 4, 7]
out = do_remove(data, n, condition)
print(out)  # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains)

A: One way using itertools.filterfalse and itertools.count:
from itertools import count, filterfalse

data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)

Then list(output), gives you:
[10, 9, 8, 4, 7]

A: If mutation is required:
def do_remove(ls, N, predicate):
    i, delete_count, l = 0, 0, len(ls)
    while i < l and delete_count < N:
        if predicate(ls[i]):
           ls.pop(i) # remove item at i
           delete_count, l = delete_count + 1, l - 1
        else:
           i += 1
    return ls # for convenience

assert(do_remove(l, N, matchCondition) == [10, 9, 8, 4, 7])

A: Write a generator that takes the iterable, a condition, and an amount to drop.  Iterate over the data and yield items that don't meet the condition.  If the condition is met, increment a counter and don't yield the value.  Always yield items once the counter reaches the amount you want to drop.
def iter_drop_n(data, condition, drop):
    dropped = 0

    for item in data:
        if dropped >= drop:
            yield item
            continue

        if condition(item):
            dropped += 1
            continue

        yield item

data = [1, 10, 2, 9, 3, 8, 4, 7]
out = list(iter_drop_n(data, lambda x: x < 5, 3))

This does not require an extra copy of the list, only iterates over the list once, and only calls the condition once for each item.  Unless you actually want to see the whole list, leave off the list call on the result and iterate over the returned generator directly.

A: The accepted answer was a little too magical for my liking.  Here's one where the flow is hopefully a bit clearer to follow:
def matchCondition(x):
    return x < 5

def my_gen(L, drop_condition, max_drops=3):
    count = 0
    iterator = iter(L)
    for element in iterator:
        if drop_condition(element):
            count += 1
            if count >= max_drops:
                break
        else:
            yield element
    yield from iterator

example = [1, 10, 2, 9, 3, 8, 4, 7]

print(list(my_gen(example, drop_condition=matchCondition)))

It's similar to logic in davidism answer, but instead of checking the drop count is exceeded on every step, we just short-circuit the rest of the loop.
Note: If you don't have yield from available, just replace it with another for loop over the remaining items in iterator.

A: Straightforward Python:
N = 3
data = [1, 10, 2, 9, 3, 8, 4, 7]

def matchCondition(x):
    return x < 5

c = 1
l = []
for x in data:
    if c > N or not matchCondition(x):
        l.append(x)
    else:
        c += 1

print(l)

This can easily be turned into a generator if desired:
def filter_first(n, func, iterable):
    c = 1
    for x in iterable:
        if c > n or not func(x):
            yield x
        else:
            c += 1

print(list(filter_first(N, matchCondition, data)))

A: Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can use and increment a variable within a list comprehension:
# items = [1, 10, 2, 9, 3, 8, 4, 7]
total = 0
[x for x in items if not (x < 5 and (total := total + 1) <= 3)]
# [10, 9, 8, 4, 7]

This:

*

*Initializes a variable total to 0 which will symbolize the number of previously matched occurrences within the list comprehension

*Checks for each item if it both:

*

*matches the exclusion condition (x < 5)

*and if we've not already discarded more than the number of items we wanted to filter out by:

*

*incrementing total (total := total + 1) via an assignment expression

*and at the same time comparing the new value of total to the max number of items to discard (3)

A: Using list comprehensions:
n = 3
data = [1, 10, 2, 9, 3, 8, 4, 7]
count = 0
def counter(x):
    global count
    count += 1
    return x

def condition(x):
    return x < 5

filtered = [counter(x) for x in data if count < n and condition(x)]

This will also stop checking the condition after n elements are found thanks to boolean short-circuiting.


text:
Q: Why cannot I invoke nonstatic methods as this argument in constructor? valid code 1:
class ClassForTest{
    ClassForTest(int k){
    };
    ClassForTest(){
         this(2);
         method();
    };
    int method(){return 1;}
}

my resolution - I can invoke non static method in constructor!
non valid code
class ClassForTest{
    ClassForTest(int k){
    };
    ClassForTest(){
         this(method());
    };
    int method(){return 1;}
}

compile error:
java: cannot reference this before supertype constructor has been called

valid code 2:
class ClassForTest{
    ClassForTest(int k){
    };
    ClassForTest(){
         this(method());
    };
    static int method(){return 1;}
}

valid code 3:
class ClassForTest{
    ClassForTest(int k){
    };
    {
        method();
    }
    ClassForTest(){
         this(1);
    };
    int method(){return 1;}
}

This behavior set is strange for me.
Can you explain it in common ?
update
As  I understand compiler merges init blocks following:
constructor(){
   super();
   nonStaticInitBlock;
   remain constructor code;
}

I don't see contradictions why I cannot use this invokation as argument of constructor
EDIT
Instance initializers are invoked after the last constructor call. –  Sotirios Delimanolis Jun 1 at 17:17
@Sotirios you are wrong
research this code:
public class Order {
    {
        System.out.println("initializer!");
    }
    Order(){
        System.out.println("constructor");
    }
    public static void main(String [] args){
        new Order();
    }
}

result:
initializer!
constructor

A: (Changed because earlier answer wasn't right)
I believe the answer lies in the error the compiler gave you:
java: cannot reference this before supertype constructor has been called
                                   ^^^^^^^^^

Looking at JLS Section 12.5:

If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps.

And in JLS 8.8.7:

An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile- time error occurs.

So in order to run the code in your second listing, method() needs to be evaluated before going into the body of this(). However, the spec forbids this, because the object's state may not have been fully initialized, e.g. for a subclass of a type whose constructor sets some state inherited by the subtype.

A: class ClassForTest{
    ClassForTest(int k){
    };
    ClassForTest(){
         this(method());
    };
    int method(){return 1;}
}

Now method() is an instance method meaning it needs to be called on an Object of type ClassForTest. Above code essentially means
ClassForTest(){
             this(this.method());
        };

and you cannot call this.something()  in the constructor as the Object is not created until all the constructors of super class are invoked. So this is not allowed.
Where as in case of static method you do not have to wait till Object creating i.e calling of all superclass constructors. So it is allowed.


text:
Q: Detecting touchstart while detecting touchmove I've been plugging away at a project recently and up until now I've been using chromes debugger mobile emulator. This means I've been able to simulate touches and dragging behaviors with my mouse.
Unfortunately because of just having one mouse I could never do both at the same time.
The project I'm working on adds two half-page sized DOM elements to the page, the one on the left has a touchmove event listener tied to it, and the other on the right has a touchstart event listener tied to it. They both work swimmingly.
But tonight I uploaded my project online to test some stuff out and opened it with an iPad and found I could only perform one action at a time. The page could not detect touchstart events on the right while I touchmoved on the left, and likewise couldn't detect touchmove events on the left while I tapped on the right.
Anyone done anything like this before? Like detecting different sets of touches on separate DOM elements?
Code snippets are a bit large to include here but the link to the github repo is here: https://github.com/matthewolsson/JoyShtick

A: DOM elements share a single touches array. Prior to this phase of testing I was under the assumption that any individual DOM element that had a touch listener applied to it had its own array of relevant touches. Now I know that every element on the page, regardless of its listeners, contributes to one singular touches array that stores any and all current touches on the page.
Knowing this I've rectified the situation by using the targetTouches touchlist. The link gives a good summary but the basics are that this is a single array of touches that is populated by ONLY the touches that occur within the DOM element the first one began in.
You can find a fantastic explanation of this list here ~ (stackoverflow.com/questions/7056026/variation-of-e-touches-e-targettouches-and-e-changedtouches). Last but not least the W3C has a very detailed page on the touch event and all of its features.


text:
Q: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory - NodeJS I'm getting the following error randomly. The code runs fine and all of a sudden I see this error. The code is written using typescript and running using pm2.
Node version: 10.16.3
Npm version: 6.9.0
2019-10-03 23:05 +00:00: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
2019-10-03 23:05 +00:00:  1: 0x8fa0c0 node::Abort() [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  2: 0x8fa10c  [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  3: 0xb0026e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  4: 0xb004a4 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  5: 0xef49b2  [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  6: 0xf041cf v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  7: 0xed3d7b v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  8: 0x101d603 v8::internal::String::SlowFlatten(v8::internal::Handle<v8::internal::ConsString>, v8::internal::PretenureFlag) [node /var/BCS/server/server.ts]
2019-10-03 23:05 +00:00:  9: 0xbd4c29 v8::internal::Builtin_JsonParse(int, v8::internal::Object**, v8::internal::Isolate*) [node /var/BCS/server/server.ts]
10: 0x1a9c8b1dbf7d

Need help as this is happening on a production env.


text:
Q: Why does Ridge model fitting show warning when power of the denominator in the alpha value is raised to 13 or more? I was trying to create a loop to find out the variations in the accuracy scores of the train and test sets of Boston housing data set fitted with a Ridge regression model.
This was the for loop:
for i in range(1,20):
        Ridge(alpha = 1/(10**i)).fit(X_train,y_train)

It showed a warning beginning from i=13.
The warning being:
LinAlgWarning: Ill-conditioned matrix (rcond=6.45912e-17): result may not be accurate.
  overwrite_a=True).T

What is the meaning of this warning?
And is it possible to get rid of it?
I checked to execute it separately without a loop, still didn't help.
#importing libraries and packages

import mglearn
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge

#importing boston housing dataset from mglearn
X,y = mglearn.datasets.load_extended_boston()

#Splitting the dataset
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0)

#Fitting the training data using Ridge model with alpha = 1/(10**13)
rd = Ridge(alpha = 1/(10**13)).fit(X_train,y_train)

Shoudn't display the warning mentioned above for any value of i.

A: In Ridge Regression you construct at Kernel Matrix which contains the similarities between all of your training labels.
The parameters of the Ridge Regression fit are found from both this Kernel Matrix and your training labels.
If you have e.g. two samples that are extremely similar, the matrix to be solved will be over determined.
To get around this, a small value can be added to the diagonal, and that value is the alpha parameter that you give.
So what happens is that when your alpha value approaches 0, the matrix is more likely to be over determined (but depends on the nature of your data).
But this should show up as poor cross validation accuracy, so you don't have to worry too much about it.
So all in all if you keep your alpha above the warning threshold you will be fine, and in a cross validation procedure, the alpha value would likely be selected to be above this threshold anyways.

A: Try fitting your Ridge model with normalization: Ridge(normalize=True). I ran into the same error as you, and it was because my features included both extremely large and extremely small values, which were causing problems with the underlying linear algebra solver used to fit the model.


text:
Q: What is the trade off between history push and replace? I use History package to redirect invalid URL to 404 page on my react component.
I use .replace instead of .push simply because I don't want the browser to record any invalid url I have visited.
Have I missed the point here? And is there a trade-off between choosing one or the other for my purpose?
Can someone explain to me? thanks in advance ;)

A: I like to use .replace() when i have a definitive action and i dont want the user to be able to come back to this page.
Example: i have a product detail page with a delete button to ultimately deletes the product. When i click the button i do router.replace back to the list of all products so when the user uses the back button in the browser he is not able to go back to the details page so he cannot see or even click again the delete button as this product does not exist anymore.

A: I think you have the right idea.
I personally use .replace when redirecting from an invalid url (or non relevant, i.e. redirect to "profile" page when a logged user goes to the "/login" url), so using the browser's "back" button works properly for the end user.

A: router.replace acts like router.push, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry.


text:
Q: How can we highlight a full word and a partial word in php? Below is my code, I want to highlight a full word and a partial word. The code below just highlights the full word but not the partial word.
For example :
$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";

AND
$words ="very written hu want impor";

I want output like below :-
"this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
Function that i have created for it:-
function highlight($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
    return preg_replace($re, '$0', $text);
}

A: Stop struggling with regular expressions when you have inbuilt functions in php.
Same functionality with pure php. without using regular expression, by ignoring case sensitive.
<?php

 $words = "very written hu want impor";
 $words = explode(' ', $words);

function hilight($text, $words){
   foreach ($words as $value) {
    $text = str_ireplace($value,''.$value.'',$text);
   }
  return $text;
}

$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
echo hilight($text, $words);

?>


text:
Q: Using two different data-binds on a single element with knockoutjs Is it possible to attach a click binding and visible binding to one element?
Ie:
<button data-bind="click: function, visible: anotherFunction">Test</button>

The workaround would be wrapping the button in a div and setting the visible binding to that element, however, I wanted to avoid this if possible.

A: Yes. Just enclose them in curly braces:
<button data-bind="{click: function, visible: anotherFunction}">Test</button>

Edit: actually, I don't think you even need the braces, just separate them with commas and you should be good.


text:
Q: Detect 3.5mm jack button press when app is in foreground I have an audio background task with the following:
BackgroundMediaPlayer.Current.SystemMediaTransportControls.IsPauseEnabled = true;
BackgroundMediaPlayer.Current.SystemMediaTransportControls.ButtonPressed += (sender, e) =>
{
    Debug.WriteLine("Button pressed: " + e.Button.ToString());
};

This works when I hold the button and release after a second.
I want to use this in foreground without a background task. Is it possible to do this without using BackgroundMediaPlayer? I have tried using MediaElement, but I couldn't find a ButtonPressed event or something similar.

A: Yes, it is possible by using MediaElement and SystemMediaTransportControls class.The SystemMediaTransportControls class contains the ButtonPressed event.The document System Media Transport Controls guides to how to do this. And there is an offical sample that already meet your requirements. You can test the sample directly. Here is parts of the sample's code.
Xaml Code
<MediaElement x:Name="MyMediaElement" Margin="0,0,10,0" AudioCategory="Media" AreTransportControlsEnabled="True" VerticalAlignment="Top"/>

Code behind
private SystemMediaTransportControls systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
systemMediaControls.IsEnabled = true;
systemMediaControls.ButtonPressed += systemMediaControls_ButtonPressed;
private async void systemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
        {
            switch (args.Button)
            {
                case SystemMediaTransportControlsButton.Pause:
                    Debug.WriteLine("Button pressed: ");
                    break;
            }
        });
    }

Yes, it's not called when I press the button which is plugged into the headset port.

If you want to trigger an event when the headset plugged in, please use this API AudioRoutingManager. And code example as follows:
 private void Detectheadset_Click(object sender, RoutedEventArgs e)
 {
     AudioRoutingManager manager = AudioRoutingManager.GetDefault();
     manager.AudioEndpointChanged += Manager_AudioEndpointChanged;
 }

 private void Manager_AudioEndpointChanged(AudioRoutingManager sender, object args)
 {
 }

Pay attention to add relative capabilities and add reference for Windows Mobile Extensions for the UWP. Since this is a mobile extension namespace, run it on the phone.


text:
Q: How to add image background to text with opacity? What I need is to add an image as a background to my text with opacity
I want it to look like this image :
Someone knows how to do this? Thanks in advance !

A: You could wrap your text in a div and set the opacity to be less than one, which would make everything within that div semi-transparent.
To make just the text see-through, just set the color to be an rgba value, where a < 1. Like this:
color: rgba(255,255,255,0.7);

Here's a fiddle with the last solution: http://jsfiddle.net/fu3r0865/

A: use opacity property like this.
opacity: 0.5;

value of opacity is between 0 to 1.  1 is default.


text:
Q: Compile nested directives within unit test in Angular I have a nested custom directive within the template of a custom directive. Something like:
customDirective definition
<custom-directive></custom-directive>

customDirective.js
angular.module('example')
   .directive('customDirective', function() {
      return {
         restrict: 'E',
         replace: true,
         transclude: true,
         templateUrl: 'directives/customDirective.html'
         link: function(scope, element, attrs) {}
      };
   });

Inside 'directives/customDirective.html

customFallbackSrc.js directive
angular.module('example')
   .directive('customFallbackSrc', function() {
      return {
         restrict: 'A',
         link: function(scope, element, attrs) {

           // if image throws an error, use fallback image
           element.bind('error', function() {
              attrs.$set('src', attrs.customFallbackSrc);
           });

         }
      };
   });

Within my unit test for customDirective, how can I properly compile the directive to include any nested directives?

A: If you wanted full coverage I believe your best strategy would be to:

*

*Write unit tests for customDirective that test it's core functionality. It is very sparse in the example though, so how necessary this is, I'm not sure.

*Write unit tests for customFallbackSrc that test it's core functionality. Based on the example provided, you should be testing for two cases:

*

*That the original image does not get replaced if it loads.

*That the fallback image loads when there is an error loading the original image
.

*Write integration tests using Protractor to cover the relationship between the two.


text:
Q: List files with multiple conditions part2 I have the following rasters and would like to import them in R. My files are now called:
B02_10m.jp2
B03_10m.jp2
B04_10m.jp2
B08_10m.jp2

B05_20m.jp2
B06_20m.jp2
B07_20m.jp2
B8A_20m.jp2
B11_20m.jp2
B12_20m.jp2

They are located in different sub-folders. That's way I am using recursive=TRUE
I have trying with the following options to combine the conditions but it's not working.
 S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m.jp2$ | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

S2 <- "my/path"
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern =  "B0[2348]_10m | B(0[567]_20m)|(1[12]_20m)|(8A_20m).jp2$")

A: For other users and based on @docendo discimus answer, here is the idea to combine different conditions when listing files as in my case. My conditions are based on the numbers that are following the letter B so:
pattern="B( here we need to write the conditions).jp2$

First, we will set the condition to import the files B02_10m, B03_10m, B04_10m, B08_10m
patter="B(FIRST CONDITION OR SECOND CONDITION).jp2$
pattern="B((0[2348]_10m)|SECOND CONDITION).jp2$

Second, we will import the files B05_20m, B06_20m, B07_20m, B8A_20m, B11_20m, B12_20m. In this case, we have to combine several sub-conditions because the pattern changes from e.g.: 02 to 11, 12 and 8A
First we write the code for 5, 6 and 7
pattern="B((0[2348]_10m)|((0[567])_20m)).jp2$

Then we add the code for bands 11 and 12
pattern="B((0[2348]_10m)|((0[567])|(1[12])_20m)).jp2$

Then, the code for 8A
pattern="B((0[2348]_10m)|(((0[567])|(1[12])|(8A))_20m)).jp2$

Hope it's clear


text:
Q: Excel VBA SUM Formula Displaying in Cell I have the following routine called from a procedure
Sub DoTotals()

  With ActiveSheet.Cells(Rows.Count, "F").End(xlUp)(2, 1)
    .Formula = "=SUM(F2:" & .Offset(-1, 0).Address & ")"
  End With

End Sub

The result displayed in the cell is not the result of the summation, but
=SUM(F$1:$F2)
I've used the same routine in other Excel docs and it properly returned the sum - not in this one, however.

A: Cell may have been formatted to Text.......try:
Sub DoTotals()
With ActiveSheet.Cells(Rows.Count, "F").End(xlUp)(2, 1)
    .Clear
    .Formula = "=SUM(F2:" & .Offset(-1, 0).Address & ")"
End With
End Sub

EDIT #1:
Perhaps the Window is in the wrong display mode:
Sub DoTotals()
    With ActiveSheet.Cells(Rows.Count, "F").End(xlUp)(2, 1)
        .Clear
        .Formula = "=SUM(F2:" & .Offset(-1, 0).Address & ")"
    End With
        ActiveWindow.DisplayFormulas = False
End Sub