text:
Q: Conditionally selecting columns in dplyr where certain proportion of values is NA Data
I'm working with a data set resembling the data.frame generated below:
set.seed(1)
dta <- data.frame(observation = 1:20,
                  valueA = runif(n = 20),
                  valueB = runif(n = 20),
                  valueC = runif(n = 20),
                  valueD = runif(n = 20))
dta[2:5,3] <- NA
dta[2:10,4] <- NA
dta[7:20,5] <- NA

The columns have NA values with the last column having more than 60% of observations NAs.
> sapply(dta, function(x) {table(is.na(x))})
$observation

FALSE
   20

$valueA

FALSE
   20

$valueB

FALSE  TRUE
   16     4

$valueC

FALSE  TRUE
   11     9

$valueD

FALSE  TRUE
    6    14

Problem
I would like to be able to remove this column in dplyr pipe line somehow passing it to the select argument.
Attempts
This can be easily done in base. For example to select columns with less than 50% NAs I can do:
dta[, colSums(is.na(dta)) < nrow(dta) / 2]

which produces:
> head(dta[, colSums(is.na(dta)) < nrow(dta) / 2], 2)
  observation    valueA    valueB    valueC
1           1 0.2655087 0.9347052 0.8209463
2           2 0.3721239        NA        NA

Task
I'm interested in achieving the same flexibility in dplyr pipe line:
Vectorize(require)(package = c("dplyr",         # Data manipulation
                               "magrittr"),     # Reverse pipe

char = TRUE)

dta %<>%
  # Some transformations I'm doing on the data
  mutate_each(funs(as.numeric)) %>%
  # I want my select to take place here

A: I think this does the job:
dta %>% select_if(~mean(is.na(.)) < 0.5) %>% head()

 observation    valueA    valueB    valueC
  1           0.2655087 0.9347052 0.8209463
  2           0.3721239        NA        NA
  3           0.5728534        NA        NA
  4           0.9082078        NA        NA
  5           0.2016819        NA        NA
  6           0.8983897 0.3861141        NA

`

A: We can use extract from magrittr after getting a logical vector with summarise_each/unlist
library(magrittr)
library(dplyr)
dta %>%
    summarise_each(funs(sum(is.na(.)) < n()/2)) %>%
    unlist() %>%
    extract(dta,.)

Or use Filter from base R
Filter(function(x) sum(is.na(x)) < length(x)/2, dta)

Or a slightly compact option is
Filter(function(x) mean(is.na(x)) < 0.5, dta)

A: Like this perhaps?
dta %>% select(which(colMeans(is.na(.)) < 0.5)) %>% head
#  observation    valueA    valueB    valueC
#1           1 0.2655087 0.9347052 0.8209463
#2           2 0.3721239        NA        NA
#3           3 0.5728534        NA        NA
#4           4 0.9082078        NA        NA
#5           5 0.2016819        NA        NA
#6           6 0.8983897 0.3861141        NA

Updated with colMeans instead of colSums which means you don't need to divide by the number of rows any more.
And, just for the record, in base R you could also use colMeans:
dta[,colMeans(is.na(dta)) < 0.5]

A: Update for 2020 perhaps, now that dplyr reached 1.0.0, which incorporates where():
dta %>% select(where(function(x) sum(is.na(x)) / length(x) < 0.5))

A: With purrr::keep
library(dplyr); library(purrr)
dta %>% keep(~ sum(is.na(.))/length(.) < 0.5)

   observation     valueA     valueB     valueC
1            1 0.26550866 0.93470523 0.82094629
2            2 0.37212390         NA         NA
3            3 0.57285336         NA         NA
4            4 0.90820779         NA         NA
5            5 0.20168193         NA         NA
6            6 0.89838968 0.38611409         NA
7            7 0.94467527 0.01339033         NA
8            8 0.66079779 0.38238796         NA
9            9 0.62911404 0.86969085         NA
10          10 0.06178627 0.34034900         NA
11          11 0.20597457 0.48208012 0.47761962
12          12 0.17655675 0.59956583 0.86120948
13          13 0.68702285 0.49354131 0.43809711
14          14 0.38410372 0.18621760 0.24479728
15          15 0.76984142 0.82737332 0.07067905
16          16 0.49769924 0.66846674 0.09946616
17          17 0.71761851 0.79423986 0.31627171
18          18 0.99190609 0.10794363 0.51863426
19          19 0.38003518 0.72371095 0.66200508
20          20 0.77744522 0.41127443 0.40683019


text:
Q: Run sql file for a specific derby database Using the ij tool and Apache Derby, is it possible to execute an sql file in a single command line?
In other words, is it possible to supply the connection string to ij?
At the moment I'm doing it with several steps:
java org.apache.derby.tools.ij
connect 'jdbc:derby://someserver:1527//databases/timesheets';
run 'my_file.sql';

A: It is possible to run ij using properties, see examples here.
Use the following command:
java -Dij.database="jdbc:derby://someserver:1527//databases/timesheets" org.apache.derby.tools.ij my_file.sql

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compose image with mask image using ImageMagick Suppose I have some image a.jpg and some other image b.jpg.
The desired output out.jpg should be obtained by copying all the pixels from b.jpg that are not black onto a.jpg, all other pixels shall remain untouched.
I tried using composite but had no success whatsoever.

A: EDITED TO ADD: A solution here can be quite simple and generic, but going forward, please remember to always include your version of ImageMagick and which OS or platform you're working on. There are some syntax differences that can make that important.
At the very simplest, using ImageMagick v6, you should be able to do something like this...
convert b.jpg -background none -transparent black a.jpg +swap -composite out.jpg

That reads in the B image, changes all the pure black pixels to transparent, then reads in the A image, swaps the images so they're in the right order, then composites the modified B image over the A image and writes the output.
You can add a fuzz value like "-fuzz 5%" ahead of the "-transparent" operation to expand the selection to include near-black pixels, also.
To use with IMv7 change "convert" to "magick".


text:
Q: Pass variable with spaces into array I'm parsing a HTML page with a bash script and extracting (with grep and sed)
    string number one
    string number two
    string number three
    etc

as $str in a parsing loop followed by
    array+=($str)

When the array is printed with
    for each in "${array[@]}"
    do
        echo "$each"
    done

I end up with
    string
    number
    one
    string
    number
    ....

Clearly spaces are being used as a delimiter when adding a new element in the array, but I can't seem to work out how to pass the entire string as an element!

A: To avoid splitting each element of the array on whitespace, you should double quote your variable:
array+=("$str")


text:
Q: OpenPGP Signing I'm reading RFC4880 in an attempt to produce an implementatdion of a subset
of OpenPGP (RSA signatures) using http://phpseclib.sourceforge.net/.  I
have the publickey and compression-literal-signature packets
 parsed out.  I
can extract n and e and feed them to Crypt_RSA to construct a verifier.  I
tell it I'm using sha256.  It then needs a "message" and a "
signature"
parametre.  I get the signature data out of the signature packet no problem.
The question I have is: what is "message"?  According to sec
tion 5.2.4 it's
some combination of the literal data packet(s?) (their bodies or the whole
packet?) and the "hashed" subpackets.  Do I just concat all
the data packets
and the hashed packets together in the order they appear?

A: The hash is of the literal data packet contents (not the whole body, just the data), followed by the "trailer" (literal bytes from signature packet up to and including hashed subpackets), followed by { 0x44, 0xff, trailer_length_as_4_octet_network_order_unsigned_integer }


text:
Q: Colimits in full subcategory (of all monics) of arrow category Consider the category $\mathrm{mon}(C)$ (objects are monics in $C$) as full subcategory of $\mathrm{Arrow}(C)$. We know that $\mathrm{Arrow}(C)$ is finitely complete and cocomplete, assuming that $C$ has limits as well as colimits. Is $\mathrm{mon}(C)$ (finitely) cocomplete?
For example consider coproducts: For objects $m_1 \colon A \rightarrow C$ and $m_2 \colon B \rightarrow D$ in $\mathrm{Arrow}(C)$, the coproduct is given by $[m_1, m_2] \colon A+B \rightarrow C+D$ (using the couniversal property of $A+B$). Does $m_1$, $m_2$ being monic imply $[m_1, m_2]$ being monic?
I think it is not true in general. If it is assumed that $C$ is a topos, does that help in cocompleteness of $\mathrm{mon}(C)$ in any way? (For $C$ a topos, $\mathrm{mon}(C)$ will have exponents, but not subobject classifier).

A: The full subcategory of monomorphisms is closed under limits inside the category of morphisms. (Easy exercise.)
In general, colimits in the category of monomorphisms are not the same as colimits in the category of morphisms (assuming they even exist). But there is sometimes a relation. Assuming the category in question has image factorisation:

*

*The inclusion of the subcategory of monomorphisms has a left adjoint.

*If the category has colimits, then so too does the category of monomorphisms.

*To calculate a particular colimit in the category of monomorphisms, first take the colimit in the category of morphisms and then apply the left adjoint to it.

In particular, if your category is a topos, then you are in the above situation.


text:
Q: Jackson Mixin: to deserialize routeId I am using Jackson Mixin to deserialize mongo object and the Mixin looks as below.
public interface MyMixin {
  /**
   * Mixin to set key value for pojo.
   * @param key key
   * @param value value
   */
  @JsonAnySetter
  void put(String key, Object value);
}

The mixin works really well for all fields including list except for the id field.
The pojo looks as below.
public class MyPojo {
  @JsonProperty("_id")
  @javax.persistence.Id
  private String id;
  private String name;
}

The exception

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
   at [Source: (String)"{"_id": {"$oid": "5e049cb30eb7811fec0c7029"}

I understand that its failing to deserialize string from a nested json.
One way through which I solved the problem is via writing custom mapper
 public static MyPojo map(final Document document) {
    final MyPojo pojo = new MyPojo();
    pojo.setUd(document.getObjectId("_id").toHexString());
    // set other fields
    return pojo;

But this requires change is mapper whenever there is a change in pojo, adding/removing fields.
The Mixin works without any change, How shall I update my Mixin to handle objectId as well?

A: I am not sure if you can have a mixin to handle this kind of case in a generic way.   I propose a solution that has not much to do with mixin but gives one generic way to deserialize such fields. First create a class to represent the json id:
@Getter @Setter
public class OidId {
    @JsonProperty("$oid")
    private String oid;
}

Then an abstract class to have the mapping stuff:
public abstract class HasOidId {

    // moved from MyPojo
    @JsonProperty("_id")
    @javax.persistence.Id
    private String id;

    @JsonSetter("_id") // this is the trigger for mapping "_id" stufff
    public void setId(OidId oidId) {
        this.id = oidId.getOid();
    }
}

Then let MyPojo extend above:
@Getter @Setter
public class MyPojo extends HasOidId {
    private String name;
}


text:
Q: Programmatically create attribute - Core Data i have a simple iphone project which contains a simple xcdatamodel that has a single entity
with roughly 3 attributes..
i want to know if there is a way to programmatically add an attribute to an entity..
i.e. if the user presses an "add" button of some kind, a simple string attribute is added to the entity and saved..
If this is not possible could someone point me in the right direction..

A: You can programmatically alter entities but you can't alter a managed object model after it has been assigned to a managed object context so that makes it useless for any user defined alterations. In any case, you wouldn't want to add entities programmatically because that would make your previously created persistent store file useless.
If you want to create a more free-form , user extensible data model, you have to back out and make your entities more flexible by adding an optional relationship to another entity or entity inheritance group that can model additional data.
For example: Suppose you have a contact list and you want to add free form fields to each contact. You would set up your entities like this.
Contact{
    name:string
    phone:string
    userDefinedFields<-->>UserDefined.contact
}

UserDefined{
    name:string
    contact<<-->Contact.userDefinedFields
}

Whenever the user adds a new field, you create a new UserDefined object and add it the Contact.userDefinedFeilds relationship. You can flesh that out as needed. If you need more than one type of user defined field you should set it up like this:
Contact{
    name:string
    phone:string
    userDefinedFields<-->>UserDefined.contact
}

UserDefined{
    name:string
    contact<<-->Contact.userDefinedFields
}

TextField:UserDefined{
    text:string
}

NumberField:UserDefined{
    numValue:Number
}

You can then drop in a TextField or NumberField object into the Contact.userDefinedFields as needed.

A: i am not so sure if you can add an attribute with code, but maybe you can consider using one to many relationship?


text:
Q: Merging two columns with survival times into one (loses survival property once merged) I am trying to run a cox regression for survival data. I am comparing two groups that have different censoring dates, and now in the dataset I have two columns, one for each survival data (days). In other words, some individuals have their survival data on the first column, while others have the data in the second column.
id censorgrp  days1  days2
1      1       30+    NA
2      2       20+    10+
3      1       50+    NA
4      1       35+    NA
5      1       100+    NA
6      2       80+    30
7      2       75+    15
8      2       40+    20+
9      1       30+    NA
10     1       30+    NA

In order to run the regression model, I need to combine the two columns into one. Right now I am doing the following:
data$newcolumn<-ifelse(data$censorgrp==2,data$days2,data$days1)

where censorgrp==2 is the second group, so if the person belongs to the second group, this variable will take the survival data from the second column, otherwise first column for group 1.
However, with this approach, I lose the property of the survival data (i.e., previously the data looked like this "50+", meaning 50 days and was censored, but now it becomes simply "50"). Is there a better way to merge the two columns together? Many thanks.


text:
Q: Consideraciones para elegir nombres de tablas Tengo un programa donde el usario debe ingresar un texto que más adelante será el nombre de una tabla, quisiera saber cuales son las limitantes a la hora de elegir un nombre para estas, haciendo pruebas me encontré conque no pueden empezar con números, porque a la hora de ejecutar las querys me arroja un error, por ejemplo esta:
SELECT * FROM 123TABLE

Cabe acotar que estoy trabajando en Python así que no se si sea cuestión del lenguaje. En todo caso, ¿Existe parámetros a tener en cuenta para elegir los nombres de las bases de datos? Ya que me gustaría hacer una validación al texto que ingrese el usuario.

A: Efectivamente, en Python por regla general no se nombra empezando por números, ya que normalmente te daría error a la hora de ejecutar.
La primera regla es que los nombres sólo pueden contener letras, números y barras bajas (solo barras bajas, cuidado ya que los guiones te crearán un error de sintaxis...).
Segundo, Python es "case sensitive" es decir, que es capaz de distinguir entre mayúsculas y minúsculas, por lo que no será lo mismo una variable llamada "nombre" que "Nombre" o "nomBRE" por ejemplo.
Te recomiendo que nombres en torno a algo que te sirva de referencia y sea reconocible, tanto como para ti como para el resto de personas que puedan usar/leer tu código.
Te propongo algunos nombres en base a tu código:
    Table_123
    Table123
    table1_23
    table12_3
    table123_

A: Hace un tiempo busqué documentación sobre esto y no la encontré, aunque hoy he encontrado este enlace. En general son admitidos los caracteres del abecedario y algunos símbolos como guiones y puntos. No se pueden utilizar nombres de palabras reservadas.
Al crear la tabla debes rodear su nombre por comillas dobles, que es el estándar en SQLLite3. De esta manera, estos nombres de tabla son válidos:
sqlite> CREATE TABLE "123abc"(columnas);
sqlite> CREATE TABLE "123abc.txt"(columnas);
sqlite> CREATE TABLE "123abc-ABC.txt"(columnas);


text:
Q: How do i show Objects in PUG Template Engine? I'm working with NodeJS, Express and some Modules. Now I'm stuck at a Problem with the PUG Template Engine. I cant show my Object that I get from flash messages.
Im sure that I get an Answer of my Process, because I have an Object with the Data I want to show

But I'm unable to show this Data in my Browser. My Code looks like this at the moment.
if message
        div(class='alert alert-danger alert-dismissable', style='width: 100%;')
        button(class='close', data-dismiss='alert') ×
              div(class='row', style='padding-top: 10px; padding-left: 15px;')
                  span(class='oi oi-warning', style='padding: 2px;')
                       strong Fehler!
                       hr(class='horizontal-divider')
                       div(class='row', style='padding-left: 15px;')
                              p= message.username
                              p= message.password

A: First of all, you are checking if message in the first line, whereas in the response its msg.
Secondly, make sure you are pointing the msg object correctly, like array.[0].username.msg.
Hope this helps.


text:
Q: How to update cryptsetup till version 1.6.1? Hello current version of cryptsetup is not capable working with truecrypt partitions.
Versions after 1.5.x are capable.(http://code.google.com/p/cryptsetup/wiki/Cryptsetup160)
So here is the latest version of cryptsetup: http://cryptsetup.googlecode.com/files/cryptsetup-1.6.1.tar.bz2
Is it possible to install on Ubuntu and how?
Thanks in advance.

A: 1.3 System specific warnings
Ubuntu as of 4/2011: It seems the installer offers to create LUKS partitions in a way that several people mistook for an offer to activate their existing LUKS partition. The installer gives no or an inadequate warning and will destroy your old LUKS header, causing permanent data loss. See also the section on Backup and Data Recovery.
This issue has been acknowledged by the Ubuntu dev team.
Update 4/2013: I am still unsure whether this has been fixed by now, best be careful. They also seem to have added even more LUKS killer functionality to the Ubuntu installer. I can only strongly recommended to not install Ubuntu on a system with existing LUKS containers without complete backups.

Update 11/2014: There seem to be other problems withe [sic!] existing LUKS containers and Ubuntu as well, be extra careful when using LUKS on Ubuntu in any way, but exactly as the Ubuntu installer does.

(source)


text:
Q: How to drag layers on two stages with KineticJS? I have layers on two separate stages. When one gets dragged, I want the other to move to the same position. However, once one is dragged, the other becomes undraggable. Is this a bug or is there a better way to do it?
layer1.on('dragmove', function() {
    layer2.setPosition(layer1.getPosition());
    layer2.draw();
});

layer2.on('dragmove', function() {
    layer1.setPosition(layer2.getPosition());
    layer1.draw();
});

http://jsfiddle.net/aWsuJ/

A: It looks like we have to draw the other layer on drag end--not sure why.
layer1.on('dragmove', function() {
    layer2.setPosition(layer1.getPosition());
    layer2.draw();
});

layer1.on('dragend', function() {
    layer2.draw();
});

layer2.on('dragmove', function() {
    layer1.setPosition(layer2.getPosition());
    layer1.draw();
});

layer2.on('dragend', function() {
    layer1.draw();
});


text:
Q: Replace text in string with exceptions I want to replace some text in a java string, but I don't want to replace it if the text is inside a section defined by $ and &.
Example: The string "$foo& bar foo" with replace text foo would be "$foo& bar $foo&".
So the replace text must be escaped using $ and & but not if the escape is already applied. Currently I'm using the regular expression ([^\\$]|^)text([^&]|$) and it works quite well but if only one of the symbols is found the regex doesn't match.
Example: for the text "bar $foo" the regular expression ([^\\$]|^)foo([^&]|$) doesn't matches but I want a not match only if both sign are found.

A: Use negative lookbehind for $ and negative lookahead for &. This will work for you :
public static void main(String[] args) {
    String s = "$foo& bar foo";
    s= s.replaceAll("(?<!\\$)foo(?!&)", "\\$foo&");
    System.out.println(s);
}

O/P :
$foo& bar $foo&


text:
Q: c struct question #include <stdio.h>
struct audiocd {
    char title[256];
    int trackNo;
    char type;
    char publisher[256];
};
int main() {
    struct audiocd* cdptr;
    struct audiocd cdarray[4];
    cdptr = cdarray;

    printf("%d\n", &(cdarray[2]));
    printf("%d\n", cdptr);
}

What is cdarray[2] & cdptr?
EDIT: Thanks, but if printf("%d\n", &cdarray) is 4291520 , is it possible to trace printf("%d\n", &(cdarray[2])) & printf("%d\n", cdptr)?

A: The overall effect of the program is simply undefined behavior. It's passing addresses to printf, but using the %d conversion, which expects an int. The mismatch causes undefined behavior.
In a typical case that int and a pointer happen to be the same size, it'll print out the address in cdptr and the address of cdarray[2].
If you want to print out those addresses, the obvious way is something like:
printf("%p", (void *)&cdarray[2]); // (void *)cdarray+2
printf("%p", (void *)cdptr);

As for what those expressions "are", they're addresses -- the addresses of the beginning of the array and the third element of the array, respectively.

A:
thanks, but if printf("%d\n",
  &cdarray) is 4291520 , is it possible
  to trace printf("%d\n", &(cdarray[2]))
  & printf("%d\n", cdptr).

If I got your question correctly, I think you want to infer the values of &(cdarray[2]) and &(cdptr) from value of cdarray.
As you assigned cdarray to cdptr, cdptr will store the starting address of the array. Now &(cdarray[2]) is just
cdarray + 2*sizeof(struct audiocd)

Also, as discussed above, %p should be used to print memory addresses instead of %d.


text:
Q: Expose SOAP 1.2 web service from java which calls another REST service I'm a Python programmer, we have a python back-end for a web project where we use Python web server (Tornado) to offer REST web services.
Few months ago, we were asked to offer SOAP for a client, and to our surprise Python 3 has very poor SOAP exposing capabilities. We tried Ladon & TornadoWS packages but both has it's limitations. Even some of them generate invalid response which does not comply with corresponding WSDL.
So Now I think a better way is to make the SOAP interface with Java which will consume our Python back-end's web service. I've some experience in Java but that was mainly using Struts framework. I need to find a lightweight, but heavily customizable solution.

What I'm currently looking for is:

*

*Imitate the WSDL exactly as it appears on our client's existing WSDL (Client will use our service but they want to make minimum changes).

*100% valid soap/xml response and WSDL! (Surprisingly, some 3rd party Python packages we tried generate invalid response). The SOAP service will be consumed by .NET platforms.

*We need to have maxmimum control over generated WSDL's element names and namespaces, so that client can transparently switch to our web services.

*A lightweight solution for exposing SOAP 1.1 & 1.2 services in Java which will be scalable to many concurrent requests.

*This Java interface will call our Python back-end's REST web service. So I'm looking for something which is specifically suitable for this purpose.

*Right now we use nginx + tornado for our REST web services, I'm looking for something similar in Java. Specially, something which address c10k problem. Basically what the Java interface do will just accept SOAP requests, and make HTTP calls and return those response. So I think this is reasonable to expect something similar like Tornado which offers non-blocking network I/O and scales well.

I'm aware that this question may be  considered not constructive, but I'm really looking for some good opinion here as I did not find information in the web (maybe due to my poor searching).
I'm also open to other possible solutions to address our problem.

A: To consume your Python REST service, check out this answer:
Calling a web service with no wsdl
To create SOAP service, you should use Apache CXF and Spring Framework (Spring MVC). Checkout this example for details: http://cxf.apache.org/docs/writing-a-service-with-spring.html


text:
Q: Getting some invalid response(some random characters) in c# I am doing a get request in c# but i am getting some invalid response than the original content
code
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test
{
    // Specify the URL to receive the request.
    public static void Main(string[] args)
    {
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=849262004629");

        // Set some reasonable limits on resources used by this request
        myHttpWebRequest.MaximumAutomaticRedirections = 4;
        myHttpWebRequest.MaximumResponseHeadersLength = 4;
        // Set credentials to use for this request.
        myHttpWebRequest.Credentials = CredentialCache.DefaultCredentials;
        myHttpWebRequest.Method = "GET";
        myHttpWebRequest.AllowAutoRedirect = false;
        myHttpWebRequest.ContentLength = 0;
        myHttpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
        myHttpWebRequest.Headers.Add("Cookie", "ShippingCountry=US;");
        myHttpWebRequest.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36";
        myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
        myHttpWebRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
        myHttpWebRequest.Headers.Add("X-Macys-ClientId", "NavApp");
        var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
        var rmyResponseHeaders = response.Headers;

        Console.WriteLine("Content length is {0}", response.ContentLength);
        Console.WriteLine("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream();

        // Pipes the stream to a higher level stream reader with the required encoding format.
        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

        Console.WriteLine("Response stream received.");
        Console.WriteLine(readStream.ReadToEnd());
        Console.ReadLine();
        response.Close();
        readStream.Close();
    }
}

The above getting invalid character like ???????? and some other characters
You can check original response here
curl 'http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=849262004629' -H 'Cookie:shippingCountry=US;' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36' -H 'Accept-Language: en-US,en;q=0.8' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'X-Macys-ClientId: NavApp' --compressed

How to fix this and get exact response(orginal response)?

A: You're not decompressing the response stream. Set the Accept-Encoding header to empty string until you're ready to work out which compression was used and decompress it.


text:
Q: AngularJS: how do I code an element directive with optional attribute parameters? I'm doing my first steps in AngularJS directives. Just set up this one as an exercise to output a product name:
.directive('productname', function (Prefs) {
        return {
            restrict: 'E',
            replace: true,
            transclude: true,
            templateUrl: '/partials/productname.html',
            link: function (scope, element, attrs) {
                scope.brand = Prefs.owner;
            }
        }
    })

productname.html
{{brand}} {{productname}}

and so the usage is plainly: <productname>{{product.name}}</productname>
Now, could someone tell me how I should go about making this directive configurable by adding a flag to output the productname linked?
The usage would be: <productname linked>{{product.name}}</productname> and the output/template would be:
 {{brand}} {{productname}}

Seems complicated and I cannot quite figure out where the logic should be injected...

A: First of all, you should use the scope property of the directive declaration. Also, you do not need transclude in this case. Like so:
.directive('productname', function (Prefs) {
    return {
        restrict: 'E',
        scope: {
            product: "=",
            linked: "="
        },
        replace: true,
        templateUrl: '/partials/productname.html',
        link: function (scope, element, attrs) {
            // scope.product and scope.linked are automatically set
            scope.brand = Prefs.owner;
        }
    }
})

And the template:

        {{brand}}
        {{product.name}}

        {{brand}}
        {{product.name}}

Call the template like so:
<productname product="product"></productname>

or:
<productname product="product" linked="'true'"></productname>

Update
If you want to use the linked attribute as a flag, you could do that by using the attrs variable:
.directive('productname', function (Prefs) {
    return {
        restrict: 'E',
        scope: {
            product: "="
        },
        replace: true,
        templateUrl: '/partials/productname.html',
        link: function (scope, element, attrs) {
            // scope.product is automatically set
            scope.linked = typeof attrs.linked != 'undefined';
            scope.brand = Prefs.owner;
        }
    }
})

Call it like so:
<productname product="product" linked></productname>


text:
Q: In a normed vector space, the convex function $f:C \to \mathbb R$ is locally Lipschitz if and only if $f$ is upper bounded on an open subset of $C$ Disclaimer: This thread is meant to record. See: SE blog: Answer own Question and MSE meta: Answer own Question. Anyway, it is written as problem. Have fun! :)

Let $(X, \| \cdot\|)$ be a normed vector space, $C$ its open convex subset, and $f:C \to \mathbb R$ convex. Then the following statements are equivalent.

*

*(i) $f$ is locally Lipschitz on $C$;

*(ii) $f$ is continuous on $C$;

*(iii) $f$ is continuous at some point of $C$;

*(iv) $f$ is locally bounded on $C$;

*(v) $f$ is upper bounded on a nonempty open subset of $C$.

A: We need the following useful lemma:

Let $(X, \| \cdot\|)$ be a n.v.s. Recall that $B(x, r)$ (resp. $\overline B(x, r)$) denotes the open (resp. closed) ball of radius $r$ and center $x$. Fix $a \in X, r>0, \varepsilon \in (0, r)$, and $m, M \in \mathbb R$. Let $f: \overline B(a, r) \to \mathbb R$ be convex.

*

*If $f(x) \le m$ for all $x \in \overline B(a, r)$, then $|f(x)| \le |m| + 2|f(a)|$ for all $x \in B(a, r)$.

*If $|f(x)| \le M$ for all $x \in \overline B(a, r)$, then $f$ is $\frac{4M}{\varepsilon}$-Lipschitz on $\overline B(a, r - \varepsilon)$.

The implications $(i) \Rightarrow(i i) \Rightarrow(i i i) \Rightarrow(v)$ and $(i i) \Rightarrow(i v) \Rightarrow(v)$ are obvious. It remains to show that $(v)$ implies $(i)$.
Assume $f$ is upper bounded by $m \in \mathbb R$ on a nonempty open subset $D$ of $C$, i.e., $f(x) \le m$ for all $x \in D$. WLOG, we assume $D := B(0, R)$ for some $R>0$. By our Lemma, $f$ is locally Lipschitz on $D$.
In particular, $f$ is continuous at $0$. Then there are $m>0$ and $R>r>0$ such that $|f(x)| \le m$ for all $x \in B(0, r)$. We fix $a\in C$. Then
$$
f(x) = f \left ( \frac{2(x-a)+2a}{2} \right ) \le \frac{1}{2} f(2(x-a)) + \frac{1}{2}f(2a).
$$
It follows that $f(x) \le \frac{m+f(2a)}{2}$ for all $x\in B(b, r/2)$. By our Lemma again, $f$ is locally Lipschitz at $a$. This completes the proof.


text:
Q: Create a property writer in SOLR I need to add a property to return a timestamp, I use below example to test print a sample date in "dataimport.properties" file to get last modified time. And it's not working
dataconfig.xml:
<dataConfig>
<dataSource type="JdbcDataSource"
driver="org.apache.cassandra.cql.jdbc.CassandraDriver"
url="jdbc:cassandra://localhost:9160/sample"
user="cassandra"
password="cassandra"
autoCommit="true"/>
<document name="content">
<entity name="defaults" query="SELECT id from sample.contacts"
deltaImportQuery="select id from sample.contacts where modifiedtime >'${dataimporter.defaults.last_index_time}'  allow filtering"
deltaQuery="select id from sample.contacts where modifiedtime > '${dataimporter.last_index_time}' limit 1 allow filtering "
autoCommit="true">
<field column="id" name="id" />
</entity>
</document>
<propertyWriter dateFormat="yyyy-MM-dd" type="SimplePropertiesWriter"   directory="conf" filename="dataimport.properties"  locale="en-US"/>
</dataConfig>`

A: Try this
<propertyWriter dateFormat="yyyy-MM-dd" type="SimplePropertiesWriter" />

You will start getting your last_index_time in desired format (yyyy-MM-dd) in conf/dataimport.properties.


text:
Q: QGIS: Plug-in to determine optimal distance between coordinate and shape file I have coordinates of power plants and I would like to determine their optimal distance (shortest distance) to electric grid lines (shape file).
How could this be done in QGIS?


text:
Q: How to create different type of user with Entity Framework Core identity? Example: I have 3 types of user like x, y, z and X has properties a, b, c; Y has properties a, b, c  d, e and Z has properties f, g, h.
These three type of users may have different types of claims and roles and in the future, new types of users may appear. What is the best approach to handle this kind of scenario and implementation?
Thank you.


text:
Q: PHP switch statement VS if elseif statement benchmark I check this PHP website benchmark for check switch statement VS if else if statement. And I see this result:
Is a there a difference between switch and if structures?. Call 1'000x

*

*141 % *if and elseif (using ==)* Total time: 165 µsview code

*139 % *if, elseif and else (using ==)* Total time: 162 µsview code

*110 % *if and elseif (using ===)* Total time: 128 µsview code

*100 % *if, elseif and else (using ===)* Total time: 117 µsview code

*149 % *switch / caseTotal* time: 174 µsview code

*181 % *switch / case / default* Total time: 211 µsview code

In result i see if else if is faster (+ **100 %** *if, elseif and else (using ===)* Total time: 117 µsview code).
This benchmark is true and if, elseif and else (using ===) is better and faster as switch statement?!

A: Whether you get exactly the same results will vary based on what conditions you are evaluating, your equipment, settings, and other factors. But yes, generally if/elseif/else with strict comparison (===) will outperform switch. The reason is that switch uses "loose" (i.e., type-insensitive) comparison (==), which is slower than type-sensitive comparison (===).
Keep in mind that these differences are extremely tiny and are going to be dwarfed by any inefficiencies in your algorithm. So, you should only tune for details like this after you are sure you have eliminated other major bottlenecks.

A: Default PHP switch is not with exact match.
Some examples for exact match switch.


text:
Q: C# Parallelism / Multi-Threading / Multi-Tasking on multi core computers I am facing a problem, on which I already spent numerous hours but which I couldn't solve by now.
First of all a rough outline of the project at hand: I receive round about 170k complex XML files with varous sizes (from 5 KB to 10 MB), which have to be loaded into a SQL Server DB. Since they might slightly differ in structure (not all values / nodes are mandatory) I have a XSLT file which helps in "flattening" them and with this simplyfiy the process of loading them. Due to the massive amount of files (and data) we chose to use a rather good proportioned Server: 24 physical cores, virtualized to 48 cores, and round about 512 GB RAM.
Coming to the problem itself: since the XML Source in SSIS proved to be quite inperformant for this task, I decided to create a C# source component, which takes care of the loading and XSLT transforming of the XML files. However, in order to narrow performance issues down, I first created a console application in order to design and debug my approach. To speed up the described loading process, I planned to use multi threading in my source component: the idea was to load and transform numerous XML files parallely (since I loaded the XSLT as compiled transformation). So, basically what I planned to have as result in SSIS is a component, which loads maybe 50 or 100 files parallely and then sends the data to (currently) 10 outputs (for 10 tables).
The funny thing is: no matter what structure I use (Parallel.For, task factory, thread queue), my C# code will never create more than 24 threads (the number of physical cores).
To my general understanding: As far as I am informed, a TASK will require one core, whereas one core can have numerous THREADS...
So, what am I doing wrong? Is my general understanding of multi threading wrong?


text:
Q: Emacs - Predictive mode I am trying to setup the Predictive Mode of Emacs and to use it with the LaTeX-mode. I have one problem: as soon as LaTeX-mode is loaded, it loads "auto-overlays" and it takes up to two minutes before I can begin to work, which is very annoying. I believe that this "auto-overlays" is used to switch between dictionaries according to where I am in the LaTeX document.
Here is the part of my .emacs that concerns the predictive mode:
(require 'predictive)
(autoload 'predictive-mode "predictive" "predictive" t)
(set-default 'predictive-auto-add-to-dict t)
(setq predictive-main-dict 'dict-english
      predictive-auto-learn t
      predictive-add-to-dict-ask nil
      predictive-use-auto-learn-cache nil
      predictive-which-dict t)
(add-hook 'latex-mode-hook 'predictive-mode)
(setq completion-use-hotkeys nil)
(setq predictive-ignore-initial-caps t)
(custom-set-variables
   '(auto-completion-syntax-alist (quote (accept . word))))

Do you have a solution?


text:
Q: Possible? Assign blade template to variable I want to assign a blade template to a variable in blade for code organization.
So basically let's say I have the variable $response['actions']
And the blade template admin.actions which contains
<a href="javascript:void(0);" class="btn btn-success btn-sm" onclick="loadLeadComments('.$lead->id.')">

I want to basically be able to do something like
$response['actions'] = admin.actions (template)

so it renders that html inside of the variable

A: Use the render() method:
 $response['actions'] = view()
                        ->make('admin.actions', array('lead' => $lead))
                        ->render();

The idea is the same as returning a view with data from a controller, with the extra render() method chained at the end.


text:
Q: Include js file script in php observer file I am using Magento 2.3.5-p2
I am adding a new module to add an Observer that will trigger some js code during an event that happens
below are the file and its content I have added
File Name and Path :
app/code/Vendor/MyModule/registration.php
Content :
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_MyModule',
    __DIR__
);

File Name and Path :
app/code/Vendor/MyModule/etc/module.xml
Content :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_MyModule" setup_version="1.0.1">
    </module>
</config>

File Name and Path :
app/code/Vendor/MyModule/etc/events.xml

Content :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="wishlist_add_product">
        <observer name="myObserverNameWishlistAddProduct" instance="Vendor\MyModule\Observer\WishlistAddProduct" />
    </event>
    <event name="wishlist_add_item">
        <observer name="myObserverNameWishlistAddItem" instance="Vendor\MyModule\Observer\WishlistAddItem" />
    </event>
    <event name="wishlist_update_item">
        <observer name="myObserverNameWishlistUpdateItem" instance="Vendor\MyModule\Observer\WishlistUpdateItem" />
    </event>
    <event name="wishlist_product_add_after">
        <observer name="myObserverNameWishlistProductAddAfter" instance="Vendor\MyModule\Observer\WishlistProductAddAfter" />
    </event>
</config>

File Name and Path for Observer to trigger during wishlist add an item :
app/code/Vendor/MyModule/Observer/WishlistAddItem.php
Content :
<?php

namespace Vendor\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class WishlistAddItem implements ObserverInterface
{
  public function __construct()
  {
    // Observer initialization code...
    // You can use dependency injection to get any class this observer may need.
  }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    // Observer execution code...
    $myEventData = $observer->getData('myEventData');

    var_dump('wishlist_add_item');die;
  }
}

?>

File Name and Path for Observer to trigger during wishlist product add after
app/code/Vendor/MyModule/Observer/WishlistProductAddAfter.php
Content :
<?php

namespace Vendor\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class WishlistProductAddAfter implements ObserverInterface
{
  public function __construct()
  {
    // Observer initialization code...
    // You can use dependency injection to get any class this observer may need.
  }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    // Observer execution code...
    $myEventData = $observer->getData('myEventData');

    var_dump('wishlist_product_add_after');die;
  }
}

?>

the code above is able to work perfectly fine, and I am able to get the below output when adding an item to the wishlist
string(26) "wishlist_product_add_after"

but now I want to add a javascript code when an observer is executed
so instead of var_dump('wishlist_product_add_after')
it will be something like
<script>

dataLayer.push({
'event': 'trackEvent',
'eventDetails.category': 'product search result engagement',
'eventDetails.action': 'add to wish list',
'eventDetails.label': '18 grains dried fruits granola (7 X 40g) X 4 packs',

//product name
'sellingPrice': '103.00', //selling price
'salePrice': '115.20', //sale price
'productID': '1329543075804', //product id
'productName': '18 grains dried fruits granola (7 X 40g) X 4 packs',

//product name
'productCategory': 'grocery', //product category
'marketPrice': '200.00', //market price
'shippingWestMalaysia': '0.00', //shipping fee
'shippingEastMalaysia': '4.00' //shipping fee

});

</script>

how do I add this type of javascript code inside the PHP observable file?
any help would be appreciated
Thank you

A: You can bind his into event observer by echo statement like this one :
echo '<script>';
echo 'dataLayer.push({';
.......
.......
.......
echo '</script>';

A: I don't think that you will be able to achieve what you want by using php observers. In this particular case, when you press an 'Add to Wishlist' button, a post request is sent. During this request, the mentioned observer events are triggered. And when the request is finished, it returns a 302 redirect to the Wishlist overview page. So if you add some content in your observer, it will not work.
I guess you'd better add a mixin for the vendor/magento/module-wishlist/view/frontend/web/js/add-to-wishlist.js widget. Here is how you can do it:
1. app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
    config: {
        mixins: {
            'Magento_Wishlist/js/add-to-wishlist': {
                'Vendor_Module/js/add-to-wishlist-mixin': true
            }
        }
    }
};

2. app/code/Vendor/Module/view/frontend/web/js/add-to-wishlist-mixin.js
define([
    'jquery'
], function ($) {
    'use strict';

    return function (addToWishlistWidget) {
        $.widget('mage.addToWishlist', addToWishlistWidget, {
            _bind: function () {
                this._super();

                var updateWishlist = 'click ' + this.options.actionElement,
                    additionalEvents = {};

                additionalEvents[updateWishlist] = 'updateDataLayer';

                this._on(additionalEvents);
            },

            updateDataLayer: function () {
                if (dataLayer) {
                    dataLayer.push({
                        // ...
                        // event info here
                        // ...
                    });
                }
            }
        });

        return $.mage.addToWishlist;
    };
});


text:
Q: C# Mongodb - Get document and matching array elements Been stuck on trying to query for a document with ratings and comments in a BsonArray.
The result i am trying to get is the root document and the matching elements in the array that matches a user.
    public class Blends
{
    public BsonObjectId _id { get; set;}
    public BsonObjectId GinID { get; set;}
    public BsonObjectId TonicID { get; set;}
    public BsonObjectId GarnishID { get; set;}
    public string GinName { get; set;}
    public string TonicName { get; set;}
    public string GarnishName { get; set;}
    public double Rating { get; set;}
    public double RatingSum { get; set;}
    public double RatingCount { get; set;}
    public List<Reviews> Review { get; set;}
}

    public class Reviews
{
    public int Commentnumber { get; set; }
    public string User { get; set; }
    public int Rating { get; set; }
    public string Comment { get; set; }
    public int Helpfull { get; set; }
}

I have tested many methods, and this only returns 1 match in "Review"
var client = new MongoClient(connectionString);
IMongoDatabase db = client.GetDatabase("GinAndTonic");
var collection = db.GetCollection<Blends>("Blends");
var builder = Builders<Blends>.Filter;
var filter = builder.Eq("Review.User", username);
var fieldsbuilder = Builders<Blends>.Projection;
var fields = fieldsbuilder.Include("Review.$");

var result = await collection.Find(filter).Project<Blends>(fields).ToListAsync();

Hope someone can help with this issue.

A: This should get you going:
var result = await collection
                .Aggregate().Match(b => b.Review.Any(r => r.User == username))
                .Project(b => new { Review = b.Review.Where(r => r.User == username) })
                       .ToListAsync();


text:
Q: NET Core 3.1 - How can I exclude parameters from being lowercased in urls In my web application I want the urls to be lowercased, but the parameters should preserve their case, since they are case-sensitive. I use this in my ConfigureServices method:
services.AddRouting(options => options.LowercaseUrls = true);

And in the Configure method in app.UseEndpoints I have this:
endpoints.MapAreaControllerRoute(
    name: "area",
    areaName: "App",
    pattern: "app/{controller}/{action=Index}/{id?}"
);

The problem is that the id of the entity can't be lowercase and when I create a route like this:
Some link

The id will be lowercased, thus the generated link would be wrong. Does anyone have an idea of an easy way to exclude the id from being lowercased?


text:
Q: Stub authentication server used by ember-simple-auth during development I'm using ember-simple-auth in my emberjs app to authenticate via oauth2-password-grant with my own (currently unimplemented) service.
I'd like to continue developing the front-end before creating the authentication service.
Can the authentication service be stubbed so login/logout features can be used? I'm aware that I mock it with http-mock during tests, but I would also like to work on the front-end design and view it in the browser.

A: HTTP mocks also run during development. You can also use Pretender or Mirage (a library built on top of Pretender) to clientside mocks.
In Mirage your route may look something like this:
// app/mirage/config.js
this.post('/users/sign_in', (db, request) => {
  return {
    user_email: "some.user@gmail.com",
    user_id: 1,
    user_token: "LcsBEYP2yjTcc-G7drto"
  };
});

depending on the shape of your backend response.


text:
Q: Pass javascript variable to server side in php sql query I have a javascript variable from a previous page that is passed to the header as "namer". Now I also want to use that variable in a sql query in php. How do I go about sending this javascript variable to php on the server side as the variable "namer"?
<!DOCTYPE html>

        <title>My Page</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

"namer"

                <?php
                $link = mysql_connect("xxxx", "xxxx", "xxxx") OR DIE ("Unable to connect to database! Please try again later.");
                mysql_select_db("abxusername");
                $query = "SELECT class FROM Antibiotics WHERE name="."namer".";";
                echo $query;
                echo mysql_query($query);
                ?>

A: If it's not sensitive data and you can afford a reload, just use a GET variable.
client side (javascript)
document.location.href = "?namer=" + namer

Server side (PHP)
if (isset($_GET['namer']) && !empty($_GET['namer'])){
  $namer = $_GET['namer'];
  // Now sanitize data and use it on your SQL query
}


text:
Q: Why doesn't this method for looping through a dictionary work I have a dictionary within a dictionary. I am trying to return the innermost dictionary ie the one with the keys name, teacher etc. To loop through I tried this.
courses = {
'feb2012': { 'cs101': {'name': 'Building a Search Engine',
                       'teacher': 'Dave',
                       'assistant': 'Peter C.'},
             'cs373': {'name': 'Programming a Robotic Car',
                       'teacher': 'Sebastian',
                       'assistant': 'Andy'}},
    'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
                       'teacher': 'Dorina'},
           'cs003': {'name': 'Programming a Robotic Robotics Teacher',
                       'teacher': 'Jasper'},
                 }
}

for e in courses:
     for y in e:
         return courses[e][y]

The console returns key error, what am I doing wrong?

A: If you were to do:
for e in courses:
    print e

You'd find that it prints "feb2012", "jan2044" -- the values are strings.
So the for y in e: on the next line iterates through the characters of those strings.
You meant
for e in cources:
    for y in cources[e]:
        return courses[e][y]

However, because you return there, you'll only ever find one of the inner dictionaries. I wonder if that's what you need.
To get all of them, one of the ways could be to make this a generator, with yield instead of return:
def get_inner(courses):
    for e in courses:
        for y in courses[e]:  # Aside, these variable names are horrible
            yield courses[e][y]

And now you could loop through them with for innerdict in get_inner(courses): ....
But there are many ways...

A: for x in courses:                #Iterate through the outermost keys
    for y in courses[x]:         #Iterate through the second outer most keys
        return courses[x][y]:    #Return the innermost dictionary

A: for k,v in courses.items():             #Iterates through Month/Year keys (feb2012, jan2014
    for k2,v2 in v.items():             #Iterates thought class identifer keys (cs101, cs373, cs001,cs003)
        for k3, v3 in v2.items():       #Iterates though class information (name, teacher, assistant)
            print('Semester: ' + k + '\tCourse: ' + k2 + '\tKey: ' + k3 + '\tValue: ' + v3) #Displays class information

Output:
Semester: feb2012   Course: cs101   Key: assistant  Value: Peter C.
Semester: feb2012   Course: cs101   Key: teacher    Value: Dave
Semester: feb2012   Course: cs101   Key: name   Value: Building a Search Engine
Semester: feb2012   Course: cs373   Key: assistant  Value: Andy
Semester: feb2012   Course: cs373   Key: teacher    Value: Sebastian
Semester: feb2012   Course: cs373   Key: name   Value: Programming a Robotic Car
Semester: jan2044   Course: cs001   Key: teacher    Value: Dorina
Semester: jan2044   Course: cs001   Key: name   Value: Building a Quantum Holodeck
Semester: jan2044   Course: cs003   Key: teacher    Value: Jasper
Semester: jan2044   Course: cs003   Key: name   Value: Programming a Robotic Robotics Teacher


text:
Q: Performing Record Linkage in R I have the following dataset in R:
address = c( "44 Ocean Road Atlanta Georgia", "882 4N Road River NY, NY 12345", "882 - River Road NY, ZIP 12345", "123 Fake Road Boston Drive Boston", "123 Fake - Rd Boston 56789", "3665 Apt 5 Moon Crs", "3665 Unit Moon Crescent", "NO ADDRESS PROVIDED", "31 Silver Way Road", "1800 Orleans St, Baltimore, MD 21287, United States",
"1799 Orlans Street, Maryland , USA")

 name = c("Pancake House of America" ,"ABC Center Building", "Cent. Bldg ABC", "BD Home 25 New", "Boarding Direct 25", "Pine Recreational Center", "Pine Rec. cntR", "Boston Swimming Complex", "boston gym center", "mas hospital" , "Massachusetts Hospital" )

blocking_var = c(1, 1,1,1, 1, 2,2,2,2,3,3)

my_data = data.frame(address, name, blocking_var)

The data looks something like this:
> my_data
                                               address                     name blocking_var
1                        44 Ocean Road Atlanta Georgia Pancake House of America            1
2                       882 4N Road River NY, NY 12345      ABC Center Building            1
3                       882 - River Road NY, ZIP 12345           Cent. Bldg ABC            1
4                    123 Fake Road Boston Drive Boston           BD Home 25 New            1
5                           123 Fake - Rd Boston 56789       Boarding Direct 25            1
6                                  3665 Apt 5 Moon Crs Pine Recreational Center            2
7                              3665 Unit Moon Crescent           Pine Rec. cntR            2
8                                  NO ADDRESS PROVIDED  Boston Swimming Complex            2
9                                   31 Silver Way Road        boston gym center            2
10 1800 Orleans St, Baltimore, MD 21287, United States             mas hospital            3
11                  1799 Orlans Street, Maryland , USA   Massachusetts Hospital            3

I am trying to follow this R tutorial (https://cran.r-project.org/web/packages/RecordLinkage/vignettes/WeightBased.pdf) and learn how to remove duplicates based on fuzzy conditions. The goal (within each "block") is to keep all unique records - and for fuzzy duplicates, only keep one occurrence of the duplicate.
I tried the following code:
library(RecordLinkage)
pairs=compare.dedup(my_data, blockfld=3)

But when I inspect the results, everything is NA - given these results, I think I am doing something wrong and there does not seem to be any point in continuing until this error is resolved.
Can someone please show me how I can resolve this problem and continue on with the tutorial?
In the end, I am looking for something like this:
                                               address                     name blocking_var
1                        44 Ocean Road Atlanta Georgia Pancake House of America            1
2                       882 4N Road River NY, NY 12345      ABC Center Building            1
4                    123 Fake Road Boston Drive Boston           BD Home 25 New            1
6                                  3665 Apt 5 Moon Crs Pine Recreational Center            2
9                                   31 Silver Way Road        boston gym center            2
10 1800 Orleans St, Baltimore, MD 21287, United States             mas hospital            3

Thank you!

A: You forgot to enable the string comparison on columns (strcmp parameter):
address = c(
   "44 Ocean Road Atlanta Georgia", "882 4N Road River NY, NY 12345", "882 - River Road NY, ZIP 12345", "123 Fake Road Boston Drive Boston", "123 Fake - Rd Boston 56789", "3665 Apt 5 Moon Crs", "3665 Unit Moon Crescent", "NO ADDRESS PROVIDED", "31 Silver Way Road", "1800 Orleans St, Baltimore, MD 21287, United States",
   "1799 Orlans Street, Maryland , USA")

name = c("Pancake House of America" ,"ABC Center Building", "Cent. Bldg ABC", "BD Home 25 New", "Boarding Direct 25", "Pine Recreational Center", "Pine Rec. cntR", "Boston Swimming Complex", "boston gym center", "mas hospital" , "Massachusetts Hospital" )

blocking_var = c(1, 1,1,1, 1, 2,2,2,2,3,3)

my_data = data.frame(address, name, blocking_var)

library(RecordLinkage)

pairs <- compare.dedup(my_data, blockfld=3, strcmp = c("address", "name"))
pairs
#> $data
#>                                                address                     name
#> 1                        44 Ocean Road Atlanta Georgia Pancake House of America
#> 2                       882 4N Road River NY, NY 12345      ABC Center Building
#> 3                       882 - River Road NY, ZIP 12345           Cent. Bldg ABC
#> 4                    123 Fake Road Boston Drive Boston           BD Home 25 New
#> 5                           123 Fake - Rd Boston 56789       Boarding Direct 25
#> 6                                  3665 Apt 5 Moon Crs Pine Recreational Center
#> 7                              3665 Unit Moon Crescent           Pine Rec. cntR
#> 8                                  NO ADDRESS PROVIDED  Boston Swimming Complex
#> 9                                   31 Silver Way Road        boston gym center
#> 10 1800 Orleans St, Baltimore, MD 21287, United States             mas hospital
#> 11                  1799 Orlans Street, Maryland , USA   Massachusetts Hospital
#>    blocking_var
#> 1             1
#> 2             1
#> 3             1
#> 4             1
#> 5             1
#> 6             2
#> 7             2
#> 8             2
#> 9             2
#> 10            3
#> 11            3
#>
#> $pairs
#>    id1 id2   address      name blocking_var is_match
#> 1    1   2 0.4657088 0.5014620            1       NA
#> 2    1   3 0.4256705 0.4551587            1       NA
#> 3    1   4 0.5924184 0.4543651            1       NA
#> 4    1   5 0.5139994 0.4768519            1       NA
#> 5    2   3 0.9082051 0.5802005            1       NA
#> 6    2   4 0.5112554 0.4734336            1       NA
#> 7    2   5 0.5094017 0.5467836            1       NA
#> 8    3   4 0.4767677 0.4404762            1       NA
#> 9    3   5 0.5418803 0.4761905            1       NA
#> 10   4   5 0.8550583 0.6672619            1       NA
#> 11   6   7 0.8749962 0.8306277            1       NA
#> 12   6   8 0.4385965 0.5243193            1       NA
#> 13   6   9 0.5622807 0.5502822            1       NA
#> 14   7   8 0.3974066 0.5075914            1       NA
#> 15   7   9 0.5626812 0.5896359            1       NA
#> 16   8   9 0.3942495 0.6478338            1       NA
#> 17  10  11 0.6939076 0.6843434            1       NA
#>
#> $frequencies
#>      address         name blocking_var
#>   0.09090909   0.09090909   0.33333333
#>
#> $type
#> [1] "deduplication"
#>
#> attr(,"class")
#> [1] "RecLinkData"

It then goes like this, using e.g. the EpiLink algorithm:

# Compute EpiLink weights
pairs_w <- epiWeights(pairs)

# Explore the pairs and their weight to find a good cutoff

getPairs(pairs_w, min.weight=0.6, max.weight=0.8)
#>    id                                             address
#> 1   2                      882 4N Road River NY, NY 12345
#> 2   3                      882 - River Road NY, ZIP 12345
#> 3
#> 4  10 1800 Orleans St, Baltimore, MD 21287, United States
#> 5  11                  1799 Orlans Street, Maryland , USA
#> 6
#> 7   7                             3665 Unit Moon Crescent
#> 8   9                                  31 Silver Way Road
#> 9
#> 10  6                                 3665 Apt 5 Moon Crs
#> 11  9                                  31 Silver Way Road
#> 12
#> 13  2                      882 4N Road River NY, NY 12345
#> 14  5                          123 Fake - Rd Boston 56789
#> 15
#> 16  1                       44 Ocean Road Atlanta Georgia
#> 17  4                   123 Fake Road Boston Drive Boston
#> 18
#> 19  8                                 NO ADDRESS PROVIDED
#> 20  9                                  31 Silver Way Road
#> 21
#> 22  3                      882 - River Road NY, ZIP 12345
#> 23  5                          123 Fake - Rd Boston 56789
#> 24
#>                        name blocking_var    Weight
#> 1       ABC Center Building            1
#> 2            Cent. Bldg ABC            1 0.7916856
#> 3
#> 4              mas hospital            3
#> 5    Massachusetts Hospital            3 0.7468321
#> 6
#> 7            Pine Rec. cntR            2
#> 8         boston gym center            2 0.6548348
#> 9
#> 10 Pine Recreational Center            2
#> 11        boston gym center            2 0.6386475
#> 12
#> 13      ABC Center Building            1
#> 14       Boarding Direct 25            1 0.6156913
#> 15
#> 16 Pancake House of America            1
#> 17           BD Home 25 New            1 0.6118630
#> 18
#> 19  Boston Swimming Complex            2
#> 20        boston gym center            2 0.6099491
#> 21
#> 22           Cent. Bldg ABC            1
#> 23       Boarding Direct 25            1 0.6001716
#> 24

I chose > 0.7 to classify as link, < 0.6 to classify as a non-link.
Matches in-between are labelled as "possible".

pairs_class <- epiClassify(pairs_w, threshold.upper = 0.7, threshold.lower = 0.6)
summary(pairs_class)
#>
#> Deduplication Data Set
#>
#> 11 records
#> 17 record pairs
#>
#> 0 matches
#> 0 non-matches
#> 17 pairs with unknown status
#>
#>
#> Weight distribution:
#>
#> [0.5,0.55] (0.55,0.6] (0.6,0.65] (0.65,0.7] (0.7,0.75] (0.75,0.8] (0.8,0.85]
#>          1          6          5          1          1          1          1
#> (0.85,0.9]
#>          1
#>
#> 4 links detected
#> 6 possible links detected
#> 7 non-links detected
#>
#> Classification table:
#>
#>            classification
#> true status N P L
#>        <NA> 7 6 4

And the results:

# detected links, possible matches, non-links
getPairs(pairs_class, show = "links")
#>    id                                             address
#> 1   6                                 3665 Apt 5 Moon Crs
#> 2   7                             3665 Unit Moon Crescent
#> 3
#> 4   4                   123 Fake Road Boston Drive Boston
#> 5   5                          123 Fake - Rd Boston 56789
#> 6
#> 7   2                      882 4N Road River NY, NY 12345
#> 8   3                      882 - River Road NY, ZIP 12345
#> 9
#> 10 10 1800 Orleans St, Baltimore, MD 21287, United States
#> 11 11                  1799 Orlans Street, Maryland , USA
#> 12
#>                        name blocking_var    Weight
#> 1  Pine Recreational Center            2
#> 2            Pine Rec. cntR            2 0.8801340
#> 3
#> 4            BD Home 25 New            1
#> 5        Boarding Direct 25            1 0.8054952
#> 6
#> 7       ABC Center Building            1
#> 8            Cent. Bldg ABC            1 0.7916856
#> 9
#> 10             mas hospital            3
#> 11   Massachusetts Hospital            3 0.7468321
#> 12

getPairs(pairs_class, show = "possible")
#>    id                           address                     name blocking_var
#> 1   7           3665 Unit Moon Crescent           Pine Rec. cntR            2
#> 2   9                31 Silver Way Road        boston gym center            2
#> 3
#> 4   6               3665 Apt 5 Moon Crs Pine Recreational Center            2
#> 5   9                31 Silver Way Road        boston gym center            2
#> 6
#> 7   2    882 4N Road River NY, NY 12345      ABC Center Building            1
#> 8   5        123 Fake - Rd Boston 56789       Boarding Direct 25            1
#> 9
#> 10  1     44 Ocean Road Atlanta Georgia Pancake House of America            1
#> 11  4 123 Fake Road Boston Drive Boston           BD Home 25 New            1
#> 12
#> 13  8               NO ADDRESS PROVIDED  Boston Swimming Complex            2
#> 14  9                31 Silver Way Road        boston gym center            2
#> 15
#> 16  3    882 - River Road NY, ZIP 12345           Cent. Bldg ABC            1
#> 17  5        123 Fake - Rd Boston 56789       Boarding Direct 25            1
#> 18
#>       Weight
#> 1
#> 2  0.6548348
#> 3
#> 4
#> 5  0.6386475
#> 6
#> 7
#> 8  0.6156913
#> 9
#> 10
#> 11 0.6118630
#> 12
#> 13
#> 14 0.6099491
#> 15
#> 16
#> 17 0.6001716
#> 18

getPairs(pairs_class, show = "nonlinks")
#>    id                           address                     name blocking_var
#> 1   1     44 Ocean Road Atlanta Georgia Pancake House of America            1
#> 2   5        123 Fake - Rd Boston 56789       Boarding Direct 25            1
#> 3
#> 4   2    882 4N Road River NY, NY 12345      ABC Center Building            1
#> 5   4 123 Fake Road Boston Drive Boston           BD Home 25 New            1
#> 6
#> 7   1     44 Ocean Road Atlanta Georgia Pancake House of America            1
#> 8   2    882 4N Road River NY, NY 12345      ABC Center Building            1
#> 9
#> 10  6               3665 Apt 5 Moon Crs Pine Recreational Center            2
#> 11  8               NO ADDRESS PROVIDED  Boston Swimming Complex            2
#> 12
#> 13  3    882 - River Road NY, ZIP 12345           Cent. Bldg ABC            1
#> 14  4 123 Fake Road Boston Drive Boston           BD Home 25 New            1
#> 15
#> 16  7           3665 Unit Moon Crescent           Pine Rec. cntR            2
#> 17  8               NO ADDRESS PROVIDED  Boston Swimming Complex            2
#> 18
#> 19  1     44 Ocean Road Atlanta Georgia Pancake House of America            1
#> 20  3    882 - River Road NY, ZIP 12345           Cent. Bldg ABC            1
#> 21
#>       Weight
#> 1
#> 2  0.5890881
#> 3
#> 4
#> 5  0.5865789
#> 6
#> 7
#> 8  0.5794458
#> 9
#> 10
#> 11 0.5777132
#> 12
#> 13
#> 14 0.5591162
#> 15
#> 16
#> 17 0.5541298
#> 18
#> 19
#> 20 0.5442886
#> 21

Created on 2022-11-17 with reprex v2.0.2


text:
Q: In App Purchase Validation and Verification Server for PHP Is there any open source and universal tool for PHP to validate and verify IN APP Purchase for Android and iOS?
I want to store all information in local database and keep full history.
My applications have to send initial receipt and call an API to verify timeliness of this receipt.

A: For this purpose you have to make webservices in php...which return data to you app in xml or json format. which is readable for your app. you app will send data to that services in xml or json format so you php code will get it and process. For this purpose you must have knowledge about webservices and

A: For iOS applications you can try to use In-App Purchase Server. This is not a open source project, but it has Free service plan (and will have it always).
Service will support Android applications in the future too, but I can't say exactly when it will appear.
If you have any questions about this service we can discuss its here or by e-mail: support@in-app-purchase-server.com


text:
Q: ELKI DBSCAN LngLatDistanceFunction producing one cluster I'm using Elki LngLatDistanceFunction to cluster Lon/lat points but it's only returning one cluster (was returning more clusters when I used Euclid distance). I tried multiple Epsilon values but I'm still getting one cluster.
    int minPts=20;
    double eps=10;
    ListParameterization params = new ListParameterization();
    params.addParameter(DBSCAN.DISTANCE_FUNCTION_ID, LngLatDistanceFunction.class);
    params.addParameter(DBSCAN.Parameterizer.MINPTS_ID, minPts);
    params.addParameter(DBSCAN.Parameterizer.EPSILON_ID, eps);

    params.addParameter(AbstractDatabase.Parameterizer.DATABASE_CONNECTION_ID, dbcon);
    params.addParameter(AbstractDatabase.Parameterizer.INDEX_ID, RStarTreeFactory.class);
    params.addParameter(RStarTreeFactory.Parameterizer.BULK_SPLIT_ID, SortTileRecursiveBulkSplit.class);
    params.addParameter(AbstractPageFileFactory.Parameterizer.PAGE_SIZE_ID, 600);

    Database db = ClassGenericsUtil.parameterizeOrAbort(StaticArrayDatabase.class, params);
    db.initialize();

    GeneralizedDBSCAN dbscan = ClassGenericsUtil.parameterizeOrAbort(GeneralizedDBSCAN.class, params);

A: The distance is in meters. Therefore, you need to choose epsilon such that some - but not all points - have more than minPts neighbors.
You can use the KNNDistancesSampler class to estimate the parameter. It is not an automatic estimation. But you can plot the resuling distances, and check for a "knee" in this plot.
Pay attention to the "noise" flag.

*

*If you get a single cluster, and it is "noise", then epsilon is too small.

*If you get a single cluster, and it is a "cluster" (not noise), then epsilon is too large.

*If you get a single cluster, and it is "noise", then minPts may be too large.

*If you get a single cluster, and it is a cluster, then minPts may be too small.

For most applications, it is easier to fix minPts to 4, or 10, or 20; and then adjust the epsilon parameter as desired. For geographic applications like yours, it may be much easier to fix the epsilon parameter, and vary the minpts parameter instead. For example, you may know that a distance of less than 10000 meter indicates objects to be "neighbors".
Algorithms such as OPTICS are also helpful to choose the parameter visually. (Use the MiniGUI!)


text:
Q: model binding nested objects I'm using a ViewModel to get the data from the HTML form to the MVC controller.
In the ActionResult parameter, there is the ViewModel that is filled, it's working fine.
Now, I want to get one field of the viewmodel separated in addition to the viewmodel. Is it possible? In another word, I want a copy of MyViewModel.MyModel.Id into another actionresult parameter.
Here is the working Controller Method:
public ActionResult Edit(AuditViewModelCritereViewModel model){}

Now I want to have this kind of method
public ActionResult Edit(AuditViewModelCritereViewModel model, int auditId){}

Here are the Models:
public class AuditViewModelCritereViewModel
    {
        public AuditViewModel audit { get; set; }
        ...
    }

public class AuditViewModel
    {
        public int auditId { get; set; }
        ...
    }

I could achieve this by adding HiddenField but clean is the best, I would like to make this prettier than copiing HTML id value.
In the HTML form, here is the field:
<input data-val="true" id="audit_auditId" name="audit.auditId" type="hidden" value="10">

This is HTTP request content that interest us:

This is what I've tried so far as int paramater:

*

*int auditId

*int audit_auditId

Thank you for your help.

A: Yes it is possible
 <input data-val="true" id="audit_auditId" name="auditId" type="hidden" value="10">

Take same name of input field where you want to get the data in action parameter.
Action Parameter name and Field name should be same. It will works fine
OR
You can get this things with using Bind Attribute in Controller
public ActionResult Edit(AuditViewModelCritereViewModel model, [Bind(Prefix = "audit.auditId")]int auditId) { }


text:
Q: Queue class not dequeuing correctly i asked a similar question here yesterday and i corrected some of the issues but the main one still persists.
Im enqueuing and dequeueing Position objects into a Position queue.As i enqueue 2 different Position objects, and dequeue both back out, both Position objects that are returned have the same value as the 2nd object put in. When i check the values that have been enqueued inside the enqueue function they are correct.I dont understand how this wont work as ive worked out the logic and used the dequeue algorithm verbatim from a book;
The Position class has 3 array based stacks as private members
struct Posnode
{
    Position *pos;
    Posnode *next;
};

class Position
{
private:
    Posnode *front,*back,header; //front = back = &header;
    Pegs A,B,C;

    Position::Position(int num): A(num), B(num), C(num)
    {
        front = back = &header;
        A.assignpeg(num);//assigning 1 to n to each Peg
        B.assignpeg(num);
        C.assignpeg(num);
    }

#include "Pegs.h"
#include "Position.h"

    int main ()
    {
        Position pos(4), intial(3),p,m,n;
        intial.geta();//poping Peg A stack
        pos.getc();//poping Peg c stack
        p.enqueue(intial);
        p.enqueue(pos);
        p.dequeue(m);//position 'pos' is returned rather than intial
        p.dequeue(n);//position 'pos' is returned
        cin.get();
        return 0;
    }

    void Position::dequeue(Position&)
    {
        Position p;
        Posnode *ptr=front->next;//front points to an empty node wi
        p = *ptr->pos;//assigning the position in ptr to p
        front->next = ptr->next;
        if (back == ptr) {//if im at the end of the queue
            back = front;
        }
        delete ptr;
        return ;
    }

    void Position::enqueue(Position n)
    {
        Posnode *ptr = new Posnode;
        ptr-> pos =  &n;//copying Position n calls Pegs operator =
        back->next = ptr;//values that are enqueued check back ok
        back = ptr;
        return;
    }

    Pegs& Pegs::operator=(const Pegs & ori)//Pegs copy contructor
    {
        top=-1;
        disks = ori.disks;
        peg = new int[disks];
        int element=0,g=-1,count=0;
        while (count <= ori.top)//copying elements if there are any in ori
        {
            ++count;
            element=ori.peg[++g];
            push(element);
        }
        return *this;
    }

A: Sorry mate, but there are many problems with your code. Some of them seem to be copy/paste errors, but other show lack of C++ understanding. I'll focus on the latter first.
The member function void Position::enqueue(Position n) copies all passed arguments by value. So what happens when you call it? The parameter is copied and inside the function you are dealing with this copy that will be disposed when the function's scope ends. So assignemtn ptr-> pos =  &n will assign an address of a temporary object to pos. Data at the address of disposed object may still be valid for some time, as long as nothing writes over it, but you should never ever depend on this behaviour. What you should do is you should pass the parameter by reference, i.e. change the declaration to void Position::enqueue(Position& n). That way the actual object will be passed, not a automatic copy.
If you don't specify a name for an argument like in void Position::dequeue(Position&), you won't have access to it.  Inside this function you create a local variable p and then assign the result to it. But because p is local it will be disposed when the function returns. Needless to say, the parameter that you pass to this function is inaccessible because it's unnamed. What you should do is you should declare the function like that: void Position::dequeue(Position& p).
As a good advice: you should do better job with isolating your case. For example, are Pegs connected in any way to the problems you are having? Also avoid declarations like Posnode *front,*back,header - in most cases they make code harder to read. And did you notice that your code has #includes inside class body?! You should never to that, except for times when you exactly know what you are doing. #include directives should be usually put in the first lines of a source file.


text:
Q: latexmk cleanup When I do latexmk -c foo.tex, latexmk cleans up as expected. I tried to configure latexmkrc so that this would happen automatically. Here's my latexmkrc file:
$pdf_mode = 1;
$silent = 1;
$cleanup_mode = 2;

However, when I run latexmk, all of the other files (foo.log, foo.aux, etc) are still there. What am I doing wrong?

A: The documentation is out-of-date and wrong.  Currently, when you specify $cleanup_mode=2, the cleanup action is done first, and then a regular run is done.  That's different from what happens when you run latexmk -c foo.tex, which only does the cleanup.
The documentation wasn't updated to reflect a code change many versions ago.  I need to correct the documentation (and probably improve the code).
Perhaps you actually want latexmk to do an automatic cleanup after compiling your document.  That is a sensible idea, but it's not currently implemented.

A: The following command
latexmk -pdf foo.tex && latexmk -c foo.tex
will make latexmk build foo.tex and produce a pdf file. If this is successful, then the cleanup will be executed and you will be left with just the pdf file. You can create an alias for this in your shell if you wish.


text:
Q: Show that $\sinh x \ge 0$ for all $x\ge 0$ Can someone help me show what's written in the title?
I know that $\cosh^2x - \sinh^2x=1$
Note: Not allowed to use derivatives to solve it

A: Hint
Use $ \sinh(x)=\dfrac {e^x-e^{-x}}{2} $
$$\frac {e^x-e^{-x}}{2} \geq 0$$
$$\frac {e^{2x}-1}{2e^x} \geq 0$$
$$ e^{2x} \geq 1=e^0$$
$$x \geq 0$$
For $x \geq 0 , f(x)=e^x $ increase and equal 1 for $x=0$

A: Remember that $\sinh(x)=\frac{e^x-e^{-x}}2$. Now try to calculate $\sinh(0)$ and analyze its derivative for $x\ge 0$, and see if you can get to some conclusion.

A: note that $$(\sinh(x))'=\cosh(x)\geq 0$$ for all real $x$ and so also for $x\geq 0$

A: For $x\geq 0$, $e^{x}-e^{-x}\geq 0$ if and only if $e^{x}\geq e^{-x}$ if and only if $e^{2x}\geq 1$, and this is true for $x\geq 0$.

A: $$\sinh(x)=\frac{e^x-e^{-x}}{2}=$$
$$\frac{\sum\limits_{n\geq 0} \frac{x^n}{n!}-\sum\limits_{n\geq 0} \frac{(-x)^n}{n!}}{2}=$$
$$\frac{\sum\limits_{\text{odd } n} \frac{x^{n}}{n!}+\sum\limits_{\text{even } n} \frac{x^{n}}{n!}+\sum\limits_{\text{odd } n} \frac{x^{n}}{n!}-\sum\limits_{\text{even } n} \frac{x^{n}}{n!}}{2}=$$
$$\frac{2\sum\limits_{\text{odd } n} \frac{x^{n}}{n!}}{2}=\sum\limits_{\text{odd } n} \frac{x^{n}}{n!} >0\text{      for } x>0$$
And $\sinh(0)=0$


text:
Q: Test if value is in array with underscoreJS using _.some method let array = [1234, 1233, 1232];

console.log(_.some(array, 1234));

It returns false. Do you know why?

A: As per the documentation of _.some() method, second argument should be a predicate function
console.log(_.some(array, function(v){ return v === 1234}));

In this particular case you can simply use native javascript Array#indexOf method.

console.log(array.indexOf(1234) > -1);

Also there is native JavaScript Array#some method.

console.log(array.some(function(v){ return v === 1234}));

with ES6 arrow function
console.log(array.some(v => v == 1234))

A: With UNDERSCORE.JS you can simply use,
console.log(_.indexOf(array, 1234) >= 0)

Document for more details:
http://underscorejs.org/#indexOf


text:
Q: Is it possible to delete index of an array in java? I know that following similar thing is possible:-

*

*to delete a character from an array(by replacing with bblank space)

A: Just assign the blank space to the position of the character you want to replace - it's not a real deletion, an array in Java is of fixed length (it can't be resized):
array[index] = ' ';

A: You cannot delete an index from an array. This is because arrays have a fixed length that cannot be changed. If you want a list which you can delete elements, check out the ArrayList class. Here is the documentation: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html


text:
Q: Can there be fractional hyper operators and if so how to they function? If we call addition (and subtraction as they are the same) the first hyperoperator, multiplication (and division) the second, exponentiation (radicals, indices and logarithms) the third, then tetration the fourth and so on, we then have a definition of a hyperoperator.
My question is:

Is there a way to have a fractional hyperoperator such as an operation half way between addition and subtraction which would be the 1 + 1/2'th hyperoperator.


text:
Q: LOAD DATA INFILE - MySQL - Find and Replace (remove) some keywords - before importing I use LOAD DATA LOCAL INFILE and imported a large TXT file, which works great. It imports the data in the mydata Mysql table  using the following
LOAD DATA LOCAL INFILE 'Base.txt' INTO TABLE mydata CHARACTER
SET
   latin1 FIELDS TERMINATED BY '\t' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (keywords , fixedprice, quantity, description, condition1, image1url, merchantcategory, leadtime, Manufacturer, Model_Number, AZ_Code, Volts, Watts, ColorTemp, Shape, Life, Base

)
Before importing the data is it possible to replace the stripoutwords in the  Keywords and the description column and remove it. So check if select name from stripoutwords EXISTS in the Keywordsand thedescription column, If EXISTs then remove those keywords from the import
The schema for both tables is here:
CREATE TABLE `stripoutwords` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `mydata` (
  `keywords` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  `fixedprice` float(6,2) DEFAULT NULL,
  `quantity` varchar(255) DEFAULT NULL,
  `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  `condition1` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `image1url` text CHARACTER SET latin1 COLLATE latin1_general_ci,
  `merchantcategory` text CHARACTER SET latin1 COLLATE latin1_general_ci,
  `leadtime` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Manufacturer` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Model_Number` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `AZ_Code` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `Volts` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Watts` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `ColorTemp` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Shape` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Life` varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
  `Base` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

A: You have to pre processs the data with a function
you would write a sql query like this
LOAD DATA LOCAL INFILE 'Base.txt' INTO TABLE mydata CHARACTER SET   latin1
FIELDS TERMINATED BY '\t'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(@keywords , fixedprice, quantity, @description, condition1, image1url, merchantcategory, leadtime, Manufacturer, Model_Number, AZ_Code, Volts, Watts, ColorTemp, Shape, Life, Base
)
SET keywords = Removetext(@keywords),description = Removetext(@description)

with a function like
CREATE function Removetext (
     texttofilter text
) RETURNS TEXT DETERMINISTIC
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE stopwords TEXT DEFAULT "";

    -- declare cursor for employee email
    DEClARE curlist
        CURSOR FOR
            SELECT `name` FROM `stripoutwords`;

    -- declare NOT FOUND handler
    DECLARE CONTINUE HANDLER
        FOR NOT FOUND SET finished = 1;

    OPEN curlist;

    getwordlist: LOOP
        FETCH curlist INTO stopwords;
        IF finished = 1 THEN
            LEAVE getwordlist;
        END IF;
        -- build email list
        SET texttofilter = REPLACE (texttofilter,stopwords,"");
    END LOOP getwordlist;
    CLOSE curlist;
RETURN texttofilter;
END

Here is an example how the function works https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=28cf0a3ba53afcffcb12740e8d07b912


text:
Q: How to edit and continue in Visual Web Developer 2008 Express Edition and ASP.NET MVC? I've enabled Enable Edit and Continue on the Web Properties page and it's also enabled in my configuration, yet Visual Web Developer 2008 Express Edition refuses to allow me to edit source files of an ASP.NET MVC project. I can edit the aspx file with no problem though.
Any ideas what's wrong or what's missing?

A: If you are targeting x64 or Any CPU on a 64 bit machine you cannot use edit and continue. It only works when you are targeting x32.
I set my Platform target to x32 for the Debug configuration for this reason.

A: My conclusion is that it just doesn't work.

A: Remember after ticking "Enable Edit and Continue" in your project properties to Save your changes before building and testing your app. I made this mistake which cost me more time than I care to share!

A: It works fine at last in Visual Studio 2010 (MVC 4), below are all required steps to do it.
I can change e.g. action code in controller (when application is "paused" or stopped at break point) and all changes are automatically used after "Continue" or in step by step debugging.
Tools > Options > Debuging > Edit and Continue

Tools > Options > Debuging > General

Build > Configuration Manager...

In Solution Explorer right click on main (web) project name > Properties

Change build output path to \bin

Source: Changes are not allowed if the assembly has not been loaded

A: You have to enable this on two places.  See this blog post about Edit and continue for Web Application Projects (WAP)

A: To anyone running Vista 64 bit...
It may be that the IDE is not ready for Edit and Continue (EnC) web apps on Vista 64 bit without a tweek.
My situation: Migrated Web App to Vista 64 bit. Set platform to x86, set EnC in Tools/Options & Web properties, Debug flag in Web.Config, Debug mode set in Build configuration, etc, etc.
No joy - Could hit break points, inspect variables, etc, but could not EnC.
There were 7 Google hits on Msg "Changes are not allowed if the assembly has not been loaded". No new advice there for this situation though.
After trying numerous things finally tried changing the Build output path from "bin\x86\debug" to "bin\".
There was great joy across the land - Debug with EnC works now.


text:
Q: Is listening-on connecting-to the same for SELinux? According to semanage-port(1) ...

*

*-a does the same as --add

*-t does the same as --type

*-p does the same as --port

and the command
 semanage port -a -t http_port_t -p tcp 81

allows Apache to LISTEN ON port 81.
So far, so good. But this solution to a haproxy related problem tells me that the command
semanage port --add --type http_port_t --proto tcp 8001

adds port to the list of ports haproxy can CONNECT TO.
Does that mean listening on and connecting to are always the same, as far as SELinux is concerned? Or is there some rule that associates port lists as either ingress, egress, or both? If so, where can I find this informationin my OS and how can I modify it?

A: As far as SELinux is concerned, "listening on" and "connecting to" are not the same thing. These are two different things and to be able to do either, a process's needs to have the correct permission. In the case of binding to a port and connecting to a port, those permissions are name_bind and name_connect respectively.
In this case, we're interested in class permissions. But again, as is generally the case with SELinux, we're missing one piece of information - permissions on which class? I feel that there must be a better way to find this, but I haven't really come across it yet. So let's use what we know:
sesearch -d -A -t http_port_t
Found 81 semantic av rules:
    allow cloud_init_t http_port_t : tcp_socket name_connect ;
    ...

This will show us all of the allow rules where http_port_t is the target. Thankfully, we can notice that they all operate on the same class - tcp_socket. And that makes sense. Now let's check all of the permissions that the class tcp_socket has (this, as far as I am aware, is defined in the policy itself).
seinfo -ctcp_socket -x

*

*-c prints object classes (note that there must not be a space between the flag and the name)

*-x shows more info (in this case, actually the thing we're interested in - the permissions!)

This will list all the permissions that apply to the tcp_socket class - among them, name_bind and name_connect, which are the LISTEN ON and CONNECT TO meanings from your question.
Let's assume that you want to use haproxy - haproxy has the SELinux type of haproxy_t. Now to see which permissions haproxy has on the ports defined in http_port_t:
sesearch -d -A -s haproxy_t -t http_port_t
Found 1 semantic av rules:
    allow haproxy_t http_port_t : tcp_socket { name_bind name_connect } ;

This shows us that haproxy has name_bind and name_connect permissions. So whichever port you add to http_port_t, that will allow haproxy to bind and connect to said port (however, all other types which use http_port_t will also be able to use their respective permissions on said port! For instance, openvpn will be able to receive and send messages, and bind and connect).
If instead of http_port_t, haproxy used specific types for each permission, say haproxy_connect_port_t and haproxy_bind_port_t with name_connect and name_bind permissions respectively, then if you added the port to only haproxy_connect_port_t, it would only be able to connect to said port, not listen/bind to it.


text:
Q: Contar registros de 4 tablas No logro hacer esta query en mySQL.
Tengo 4 tablas.

*

*Tabla principal socios cuyo campos son id, id_association, num_parter

*Tabla tutores, cuyos registros son id, id_partner

*Tabla children, cuyos registros son id, id_partner

Todas las tablas estan unidad por una clave foranea llamada id_partner
Necesito tener los campos de la tabla partner y cuantos tutores pertenece a cada socio, y cuantos children pertenece a cada socio
A ver si me podeis ayudar, gracias.

A: SELECT  s.id,
    s.id_association,
    s.num_parther,
    ISNULL(COUNT(DISTINCT t.id),0) AS cant_tutores,
    ISNULL(COUNT(DISTINCT c.id),0) AS cant_children
    FROM socios AS s
    LEFT JOIN tutores t
        ON s.id = t.id_parther
    LEFT JOIN children c
        ON s.id = c.id_parther
    GROUP BY s.id,
        s.id_association,
        s.num_parther

*

*Con LEFT JOIN relacionamos las tablas hijas a socios sin invalidar aquellos socios que no tengan filas en estas.

*Contamos en cada caso, los distintos id existentes en cada hija

*Agrupamos por los datos de socios que queremos mostrar.

A: Prueba con la siguiente consulta que te devuelve el número de tutores que tiene cada socio y realiza los cambios necesarios para devolver el número de niños.
SELECT s.id, s.id_association, s.num_parther, COUNT(*) AS num_tutores
FROM socios AS s JOIN tutores AS t ON s.id = t.id_parther
GROUP BY s.id, s.id_association, s.num_parther;


text:
Q: Where does the rotation matrix come from? I looked through many different books, but none of them explain how they derive the matrix below. They just state it as is and move on. Can you explain, please.
$ \begin{bmatrix} R(\vec e_1), R(\vec e_1) \end{bmatrix} =  \begin{bmatrix} cos x & - sinx \\ sinx & cosx \end{bmatrix}$

A: It comes from consideration of the transformed positions of the unit vectors


text:
Q: Exception handling in Spark Scala UDF def parse_values(value: String) = {

      val values = value.split(",").map(_.trim)
      values.foldLeft(Array[(Int, Double)]()) {
        case (acc, present) =>
          val Array(k, v) = present.split(",")(0).split(":")
          acc :+ (k.trim.toInt, v.trim.toDouble)

      }

I am currently using the above UDF to parse a column of string into an array of keys and values.
"50:63.25,100:58.38" to [[50,63.2], [100,58.38]].
In some cases, the string is "\N" and I am unable to parse the column value.
If the string is "\N" then I should return an empty array. Can anyone help me to handle this exception or help me adding a new case? I am new to spark-scala.
Error: scala.MatchError: [Ljava.lang.String;@497cb6a9 (of class [Ljava.lang.String;)

A: You need to check that the resulting Array has two elements. You need a pattern matching like this to avoid that parse error:
def parse_values(value: String) = {
    val values = value.split(",").map(_.trim)
    values.foldLeft(Array[(Int, Double)]()) {
      case (acc, present) =>
        val Array(k, v) = {
          present.split(",")(0).split(":") match {
            case Array(_) => Array("0", "0.0")
            case arr => arr
          }
        }
        acc :+ (k.trim.toInt, v.trim.toDouble)
    }
}


text:
Q: Android Screen Turn On Programmatically I'm using this codes for turn on the screen.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

But after first using this codes, the screen never turn off again.
I want to do turn on the screen but after that the screen again turn off when end of screen off time.
How can I do it?

A: Turning the screen on:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

To turn off, you should clear the flag that you have set:
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Note that an application cannot force the screen to turn off, it can just release locks that it holds, so the system could turn the screen off as it would without your app.


text:
Q: How to make Cytoscape desktop interface font size larger? How to change text size in Cytoscape 3? Not the font of the network labels, but the font of the GUI itself. I tried to look for it in preferences but there is nothing like it there.

A: What OS are you running?  There is a way to do this on Windows and Linux by changing the system font size.  Not sure how to do it on Mac.
-- scooter


text:
Q: Visual Studio. Publish project from command line Is there a way to publish a web project in MS Visual Studio 2010 using CLI? I use DevEnv.exe /Build to build a project and it works fine, but I could not find option to Publish a project.
One other thing I want to mention. I am trying to publish web project NOT to the IIS directly. I have a location where I publish several projects and then build them automatically into NSIS bundle to be deployed.

A: The /t:publish switch is for ClickOnce applications only, it's not applicable to web projects. Hence the error saying it's unpublishable. :)

A: From ASP.NET Web Deployment using Visual Studio: Command Line Deployment, you can use
msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile

where MyPublishProfile is the profile name that you've already set up somewhere

A: What works best is to add following target to the project file:
<Target Name="AfterBuild">
   <Message Text="Copying to Deployment Dir:" />
   <Copy SourceFiles="@(Content)" DestinationFolder="..\XXX\%(Content.RelativeDir)" />
      <CreateItem Include="$(OutputPath)\*">
        <Output TaskParameter="Include" ItemName="Binaries"/>
      </CreateItem>
   <Copy SourceFiles="@(Binaries)" DestinationFolder="..\XXX\bin" />
</Target>

This way, whenever project got build (from command line or from IDE) it automatically get deployed to specified folder. Thank you everybody for pointing me to right direction.

A: @RobKent As https://stackoverflow.com/a/2775437/21233364
using
<Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release' ">
   <Message Text="Copying to Deployment Dir:" />
   <Copy SourceFiles="@(Content)" DestinationFolder="..\XXX\%(Content.RelativeDir)" />
      <CreateItem Include="$(OutputPath)\*">
        <Output TaskParameter="Include" ItemName="Binaries"/>
      </CreateItem>
   <Copy SourceFiles="@(Binaries)" DestinationFolder="..\XXX\bin" />
</Target>

you can have publish only on release compiling.


text:
Q: Big image inside ScrollView won't let scroll I'm trying to add an Image (by the image full size) into a ScrollView component, the idea is to let the image be on it's own size (without limiting it) but instead to let scroll horizontal and vertical (depend on the Image).
so I'm using Image.getSize() for it inside a ScrollView, here is my component,
import React, { Component } from 'react';
import { Image, ScrollView } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      width: 10,
      height: 10,
      image: 'http://www.francedimanche.fr/parole/wp-content/uploads/2017/08/Angelina-Jolie.png',
    }
  }

  componentDidMount() {
    Image.getSize(this.state.image, (width, height) => {
      this.setState({ width, height });
    });
  }

  render() {
    return (
      <ScrollView>
        <Image
          style={{ width: this.state.width, height: this.state.height }}
          source={{uri: this.state.image}}
        />
      </ScrollView>
    );
  }
}

thanks!

A: You can go horizontal or vertical in a ScrollView.  To get both you can just nest them:
  <ScrollView horizontal={true}>
    <ScrollView>
      <Image
        style={{ width: this.state.width, height: this.state.height }}
        source={{uri: this.state.image}}
      />
    </ScrollView>
  </ScrollView>


text:
Q: How to prevent Android's back gesture from selecting text inside of nested webview? We have an app that uses a Webview to render a text editor (contentEditable) inside of a React Native application. This works well overall, except that the Android back gesture can lead to changes in the selection of text inside the Webview and similar strange behaviors.
We've tried things like having an element along the screen edge that pops out to overlay the Webview when a user begins a back gesture, tried with both onPress and onPressIn.
But by that time, it's already too late to evt.preventDefault() - and the text selection takes place even though the Webview is now covered by another element, I guess because it's technically still the same event that triggered the overlay. (Also tried evt.stopPropagation in desperation.)
Is there any way to prevent text selection within our Webview when a user uses the back gesture?