text:
Q: FOSUserBundle login with email with service Provider, best practice I was looking to create a service provider in order to logIn with Email and not username with FOSUserBundle.
First I wrote this in my security.yml file according to the doc here:
security:
    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

According to the FOS doc, I follow these steps one by one.
Except in MyUserManager.php I wrote this (according to another question on stack here):
namespace Frontend\UserBundle\Model;

use FOS\UserBundle\Entity\UserManager;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class CustomUserManager extends UserManager
{
    public function loadUserByUsername($email)
    {
        /*$user = $this->findUserByUsernameOrEmail($username);

        if (!$user) {
            throw new UsernameNotFoundException(sprintf('No user with name "%s" was found.', $username));
        }

        return $user;*/

        //Change it to only email (Default calls loadUserByUsername -> we send it to our own loadUserByEmail)
        return $this->loadUserByEmail($email);
    }

    public function loadUserByEmail($email)
    {
        $user = $this->findUserByEmail($email);

        if (!$user) {
            throw new UsernameNotFoundException(sprintf('No user with email "%s" was found.', $email));
        }

        return $user;

    }
}

and of course I changed the User class in order to implement specific getter and setter like this:
namespace Acme\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\UserRepository")
 * @ORM\Table(name="users")
 */
class User extends BaseUser
{

    // ...

    // override methods for username and tie them with email field

    /**
     * Sets the email.
     *
     * @param string $email
     * @return User
     */
    public function setEmail($email)
    {
        $this->setUsername($email);

        return parent::setEmail($email);
    }

    /**
     * Set the canonical email.
     *
     * @param string $emailCanonical
     * @return User
     */
    public function setEmailCanonical($emailCanonical)
    {
        $this->setUsernameCanonical($emailCanonical);

        return parent::setEmailCanonical($emailCanonical);
    }

    // ...

}

But I owerride the FOSUser template form in app\Resources\FOSUserBundle\views\Security\login.html.twig like this:
{% block fos_user_content %}
  <form action="{{ path("fos_user_security_check") }}" method="post">

    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}"/>

    E-mail
    <input type="email" class="" id="username" name="_username" required="required"/>

    {{ 'security.login.password'|trans }}
    <input class="" type="password" id="password" name="_password" required="required"/>

      <input type="checkbox" id="remember_me" name="_remember_me" class="">
      {{ 'security.login.remember_me'|trans }}

    <button class="" type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans }}">
      LogIn
    </button>
  </form>
{% endblock fos_user_content %}

It is the good way to only allow user Loged In with email field and
  not the username?

A: Your approach resumes perfectly all mandatory changes for setup an email-password authentication on FOSUserBundle.
For now, I used only the same configuration in entity and security config (not need of the template because my login is done in AJAX).
The only doubt I have is the following :
As the username is always set using the email field value, is it useful to create your CustomUserManager ?
The loadByUsername will works if the username is always equal to the email, as done by your entity in setEmail and setEmailCanonical.
Is it just an additional security ?
EDIT
Change from username to email can involves to change some comportment in form building/validation.
Maybe you have to look at this answer : https://stackoverflow.com/a/21064627/4363634


text:
Q: Correct usage of Java EntityManager I'm using Java EntityManager to work with database as follows:
  Map<String, String> properties = new HashMap<String, String>();
  properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
  properties.put("javax.persistence.jdbc.url", "jdbc:mysql://"+dbProperties.getHost()+":"+dbProperties.getPort()+"/"+dbProperties.getDbName());
  properties.put("javax.persistence.jdbc.user", dbProperties.getUser());
  properties.put("javax.persistence.jdbc.password", dbProperties.getPassword());
  entityManager = Persistence.createEntityManagerFactory("TestDAL", properties).createEntityManager();

And the application is working with several threads and sometimes the application is hanging when many requests come.
The thread dump is as follows:
    - threadId:Thread 11208 - state:BLOCKED stackTrace: - java.util.HashSet.add(java.lang.Object) @bci=8, line=217 (Compiled frame; information may be imprecise)
- java.util.AbstractCollection.addAll(java.util.Collection) @bci=29, line=342 (Compiled frame)
    - java.util.LinkedHashSet. (java.util.Collection) @bci=22, line=169 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.metamodel.ManagedTypeImpl.getAttributes() @bci=13, line=160 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.metamodel.IdentifiableTypeImpl.initializeIdAttributes() @bci=12, line=95 (Compiled frame)
    - org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.initialize(java.lang.ClassLoader) @bci=251, line=493 (Compiled frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.getMetamodel(java.lang.ClassLoader) @bci=25, line=3476 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(java.lang.ClassLoader, java.util.Map) @bci=955, line=754 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession() @bci=54, line=205 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(java.util.Map, javax.persistence.SynchronizationType) @bci=5, line=305 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(java.util.Map, javax.persistence.SynchronizationType) @bci=90, line=337 (Interpreted frame)
    - org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager() @bci=3, line=303 (Interpreted frame)

What would be the possible root cause?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Estimate for multiple harmonic sum I am interested in estimating the following family of sums:
$$S_k(n) \equiv \sum_{\substack{n_1, \ldots, n_k \geq 1\\n_1 + \ldots + n_k = n}}\frac{1}{n_1\ldots n_k}$$
where $k \geq 1, n \geq 1$. A very simple calculation shows that
$$S_k(n) = \frac{k}{n}\sum_{k - 1 \leq j \leq n - 1}S_{k - 1}(j)$$
and
$$S_k(n) = \frac{k!}{n}\sum_{1 \leq j_1 < j_2 < \ldots < j_{k - 1} \leq n - 1}\frac{1}{j_{k - 1}\ldots j_1}$$
Now, from the recursion formula, one can easily see from interated sum-integral comparison that for $k$ fixed, $n \to \infty$, $S_k(n) \sim k\frac{\log(n)^{k - 1}}{n}$.
However, from numerical experiments, this estimate approximates the result pretty badly for small $n$ (actually, typically $n < e^k$ I believe) and the behaviour in this region gets worse and worse as $k$ increases!
Do you know of any finer technique that would allow me to give a sharper estimate for all finite (i.e not asymptotic) $k, n$?

A: That's part of an interesting set of identities involving the (unsigned) Stirling Number of 1st kind
$$
\begin{array}{l}
 \left[ \begin{array}{c}
 n \\
 m \\
 \end{array} \right]\quad \left| {\;1 \le n,m} \right.\quad  =  \\
  = \frac{{n!}}{{m!}}\sum\limits_{\begin{array}{*{20}c}
   {1\, \le \,k_{\,j} }  \\
   {\,k_{\,1} \, + \,k_{\,2} \, + \, \cdots \, + \,k_{\,m} \, = \,n}  \\
\end{array}} {\frac{1}{{k_{\,1} k_{\,2}  \cdots k_{\,m} }}}  =  \\
  = \frac{{n!}}{{m!}}\sum\limits_{\begin{array}{*{20}c}
   {0\, \le \,k_{\,j} }  \\
   {\,k_{\,1} \, + \,k_{\,2} \, + \, \cdots \, + \,k_{\,m} \, = \,n - m}  \\
\end{array}} {\frac{1}{{\left( {k_{\,1}  + 1} \right)\left( {k_{\,2}  + 1} \right) \cdots \left( {k_{\,m}  + 1} \right)}}}  =  \\
  = \sum\limits_{1\, \le \,k_{\,1} \, \le \,k_{\,2} \, \le \, \cdots \, \le \,k_{\,n - m - 1} \, \le \,n - 1} {\;\prod\limits_{1\, \le \,j\, \le \,n - m - 1} {k_{\,j} } }  =  \\
  = n!\sum\limits_{\begin{array}{*{20}c}
   {0\, \le \,k_{\,j} }  \\
   {0\, \le \,k_{\,1}  + k_{\,2}  + \, \cdots \, + k_{\,n}  = \,m}  \\
   {0\, \le \,1\,k_{\,1}  + 2\,k_{\,2}  + \, \cdots \, + n\,k_{\,n}  = \,n\;}  \\
\end{array}\;} {\;\prod\limits_{1\, \le \,j\, \le \,n} {\frac{1}{{k_{\,j} !}}\frac{1}{{j^{\,k_{\,j} } }}} }  \\
 \end{array}
$$
The first in particular, the one of your interest, comes from applying the Cauchy product to
the exponential generating function
$$
\left( {\ln \left( {{1 \over {1 - x}}} \right)} \right)^{\,m}  = \sum\limits_{0\, \le \,k} {{{m!} \over {k!}}\left[ \matrix{
  k \cr
  m \cr}  \right]\,x^{\,k} }
$$
The above confirms the asymptotic expression you found for large $n$, and clearly
you cannot expect it to be "precise" for lower values of $n$.
So, concerning your question about possible "operational bounds" for finite
$n,m$, much depends of course on how you allow the bounds to be expressed
and the precision required.
As far as I am aware, there is an interesting precise expression reported in Concrete Mathematics
in terms of the Eulerian Numbers of 2nd kind
$$
\left[ \matrix{ x \cr  x - n \cr}  \right]
  = \sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)}
   {\left\langle {\left\langle \matrix{n \cr   k \cr}  \right\rangle } \right\rangle
   \left( \matrix{  x + k \cr   2n \cr}  \right)}
\quad \quad \left| {\;0 \le n \in Z} \right.
$$
which is a polynomial in $x$ of degree $2n$, that can also be used to extend the definition of the Stirling N. 1st kind
to real or complex values of $x$.


text:
Q: Java - Simple output to a text file. What am I not seeing? (I was hoping to get a text rendition of the files I am generating as input to the Knapsack Problem, in order to ckeck the results of a bottom-up version I am writing.)  However, this simple instantiation of FileWriter is not working.  Could someone take a minute and give me a hint?  Thanks!
P.S.  This is just my latest attempt to accomplish this simple task.  I hope it is not trivially incorrect, but what I cannot pin down is that the object meant to handle the output not being "resolved".
import java.util.Random;
import java.util.ArrayList;
import java.io.FileWriter;
import java.io.PrintWriter;

public class MainFrag {

       static int N = 20, Capacity;
       static ArrayList<Integer> w = new ArrayList<>(N);
       static ArrayList<Integer> v = new ArrayList<>(N);

       static Random rand = new Random(42);

       public static void main(String[] args) {
              while (w.size()<=N) { w.add( rand.nextInt(N*2)+1); }
              while (v.size()<=N) { v.add( rand.nextInt(N*2)+1); }
              Capacity = (int) (N * 0.50 * N*2);

//  **The FileWriter instance, outFile, "cannot be resolved"**

             PrintWriter outFile = null;
             try {
                          outFile = new PrintWriter(new FileWriter("out.txt"));
                      for (int i : w) { outFile.printf(" %3d", i); }
                      for (int i : v) { outFile.printf(" %3d", i); }

              } catch (Exception e) {
                       System.err.print(e);
              } finally {
                       outFile.close();
              }

        }
}


text:
Q: How to launch myapplication settings tab in settings app from my application in ipad Is there any way to open myapplication settings tab directly from my application like what we will use to open twitter settings
([[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]]).

A: By showing the Facebook or Twitter composer with the standard iOS Social Framework, will present us an AlertView with an option to go directly to FB or Twitter Settings for the users if the accounts are not setup. So this will be helpful when you want to your user to login to them via the Settings app, if they haven't done so.
Have tested this with iOS 6 in iPad with both FB and Twitter.

A: Avoid using the canSendTweet method to check before you tweet, just present the ViewController.  Should work for the Social framework as well, if you are working with iOS6.  Example below.
TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init];
[self presentModalViewController:tweetSheet animated:YES];

//If the user doesn't have twitter enabled then an alertview will pop up giving them to option to go straight to settings.

A: Just show the composer. If no FB Account is available, it will show an AlertView to go to Settings. Works in iOS 8
var controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
controller.setInitialText("My Post")
self.presentViewController(controller, animated: true, completion: nil)

A: As of iOS 8:
[[UIApplication sharedApplication] openURL:UIApplicationOpenSettingsURLString];

I don't believe that opening the settings for any app other than your own (including the Twitter and Facebook configuration page) is supported.


text:
Q: Сферы использования QML, Для чего он используется в разработке? Отличия от Qt? Знакомлюсь с QML, в интернете из описания не нашел ничего кроме

QML - это декларативный язык, используемый для разметки пользовательского интерфейса приложения. Он разбивает пользовательский интерфейс на более мелкие элементы, которые могут быть объединены в компоненты. QML описывает внешний вид и поведение этих элементов пользовательского интерфейса. Такая разметка может быть дополнена кодом JavaScript для обеспечения  более сложной логики UI. С этой точки зрения, QML следует шаблону HTML-JavaScript, но QML разработан с нуля и предназначен для разметки  пользовательских интерфейсов, а не текстовых документов.
  В общем случае QML представляет собой иерархию элементов. Дочерние элементы наследуют систему координат от родителя.

Или чего-то подобного.
Где можно найти подробное описание? Для чего, например, QML используется при разработке мобильных приложений, структуру проекта на QML, Почему в проектах нельзя обойтись обычным Qt?
В общем подробное введение в QML, чтобы разобраться, какие задачи с помощью него можно решить.
Во всех источниках сразу учат писать на нем код, вводной части практически нет, так как QML дают в перемешку с Qt. Может кто рассказать, зачем его вообще придумали и его плюсы по сравнению с Qt?


text:
Q: Copy tasks in build.gradle will not place compile dependencies in one directory and testCompile dependencies in another I'm new to Gradle.
When I run the build, instead of copying specific dependencies to specific directories, the build adds both compile and testCompile dependencies to src/test/resources.
I would like to be able to copy only test compile dependencies to src/test/resources and all other dependencies to main/src/resources.
Thank you
apply plugin: 'java'
apply plugin: 'war'

String spring_version = "3.1.2.RELEASE@jar" ;
String spring_sec_version = "3.1.2.RELEASE@jar" ;
String hibernate_version = "4.1.7.Final@jar" ;

repositories {
    mavenCentral()
}

//  "org.springframework:spring-oxm:"+spring_version,

List spring = [
    "org.springframework:spring-context:"+spring_version,
    "org.springframework:spring-beans:"+spring_version,
    "org.springframework:spring-core:"+spring_version,
    "org.springframework:spring-aop:"+spring_version,
    "org.springframework:spring-expression:"+spring_version,
    "org.springframework:spring-jdbc:"+spring_version,
    "org.springframework:spring-tx:"+spring_version,
    "org.springframework:spring-web:"+spring_version,
    "org.springframework:spring-webmvc:"+spring_version,
    "org.springframework:spring-orm:"+spring_version,
    "org.springframework:spring-asm:"+spring_version
]

List spring_security = [
    "org.springframework.security:spring-security core:"+spring_sec_version,
    "org.springframework.security:spring-security-config:"+spring_sec_version,
    "org.springframework.security:spring-security-web:"+spring_sec_version
]

List spring_aop = [
    "aopalliance:aopalliance:1.0@jar",
    "cglib:cglib-nodep:2.2.2@jar"
]

List validation_lib = [
    "org.hibernate:hibernate-validator:4.3.0.Final@jar",
    "javax.validation:validation-api:1.0.0.GA@jar"
]

List log_lib = [
    "org.jboss.logging:jboss-logging:3.1.2.GA@jar",
    "org.slf4j:slf4j-api:1.6.6@jar",
    "org.slf4j:slf4j-jdk14:1.6.6@jar",
    "org.slf4j:log4j-over-slf4j:1.6.6@jar",
    "org.slf4j:jcl-over-slf4j:1.6.6@jar",
    "log4j:log4j:1.2.17@jar"
]

List hibernate_api = [
    "org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.1.Final@jar"
]

List hibernate = [
    "org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec:1.0.1.Final@jar",
    "org.hibernate.common:hibernate-commons-annotations:4.0.1.Final@jar",
    "org.javassist:javassist:3.16.1-GA",
    "org.hibernate:hibernate-entitymanager:"+hibernate_version,
    "org.hibernate:hibernate-core:"+hibernate_version
]

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.10'
    testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
    compile hibernate_api
    compile hibernate
    compile spring
    compile spring_security
    compile spring_aop
    compile "org.codehaus.jackson:jackson-jaxrs:1.9.9"  //lib jackson for JSON
    compile validation_lib
    compile log_lib
    runtime "postgresql:postgresql:9.1-901.jdbc4@jar"
    compile "rhino:js:1.7R2@jar"
}

task copyDependencies(type: Copy) {
    from (configurations.compile)
    into "src/main/resources"
}

task copyTestDependencies(type: Copy) {
    from (configurations.testCompile)
    into "src/test/resources"
}

build.dependsOn(copyDependencies)
build.dependsOn(copyTestDependencies)

A: Two things before answering:

*

*The Gradle configurations compile and testCompile should be replaced with implementation and testImplementation. See documentation for details. My answer will use these instead.

*Gradle has a great work avoidance approach, which is based on inputs / outputs computation. Copying anything into directories that are inputs of tasks, such as the resources directories, will mess that up. You really should avoid doing that and instead create new directories that are properly wired to be used where needed.

The problem you have is that testImplementation extends implementation and thus you will collect both runtime and test dependencies into the location for test dependencies.

*

*The easiest path is to create a custom configuration for your tests dependencies so that you can access them independently of the runtime ones:
configurations {
    testDependencies
    testImplementations {
        extendsFrom testDependencies
    }
}

dependencies {
    testDependencies group: 'junit', name: 'junit', version: '4.10'
    // And others
}

And then you would copy the contents of testDependencies.
The one downside with this approach is that resolution of testDependencies will not be influenced by the runtime dependencies. This could be a problem but is context sensitive.

*The other option is to filter runtime dependencies when copying the test ones. That solution is required if you realise that runtime dependencies impact the version of test dependencies.


text:
Q: Accessing Other Entities Attributes in Dynamics CRM/365 Forms with javaScript This function buttonBuzz() works inside the Forms of the Entities Account, Contacts and Leads. But not in the Opportunity form.
Mainly because there is no telephone1 attribute. There is however a Contact entity added with "Quick View" in a section with a telephonenumber inside.

I think it can be accessed with the telephone1 as well just not with Xrm.page
Any ideas how i can grab the attribute from inside the "quick view"?
I dont know if the "Quick view" window is a form of an iFrame. And if it is i have no clue how to access it with the Xrm.Page.getAttribute("telephone1").getValue();
function buttonBuzz(exObj) {
var phoneNumber;

// Here i store the "telephone1" Attribute from the current .page
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();

if (phoneNumber != null) {      **Sends phonenumber**           } ...

A: Quick Views display data from a record selected in a lookup field, in this case a Contact. You can query data from related records using the OData endpoint.
You first need to get the Guid of the record selected:
var contactId = Xrm.Page.getAttribute("parentcontactid")[0].id || null;

You would then need to send a SDK.REST request, passing parameters for the Id of the record (contactId), entityName and the columns:
var entityName = "Contact";
var columns = "Address1_Telephone1, FirstName, LastName";

SDK.REST.retrieveRecord(contactId, entityName, columns, null, function(result) {
    // Success, logic goes here.
    var address1_Telephone1 = result.Address1_Telephone1;
}, function(e) {
    console.error(e.message);
});

As well as your JavaScript file, you would need to include the SDK.REST.js file that is  included in the MS CRM SDK download within your Opportunity form libraries.

A: You can pull that field up from the Contact into the Opportunity by creating a Calculated Field, setting it equal to parentcontactid.telephone1
Put the field on the form, and you'll be able to .getAttribute() it like any other Opportunity field (being Calculated, it updates itself whenever the source changes).


text:
Q: Removing per-panel unused factors in a bar chart with nested factors Some time ago I asked a question on how to remove unused factors in a bar chart, and I got a useful solution for that problem, thanks to @Aaron. Now, I am facing a very similar problem, but the solution that I used in the past does not work for this case.
This is the code to reproduce the data frame that I am using:
set.seed(17)
df <- data.frame(BENCH = sprintf('bench-%s', sort(rep(letters[1:8], 4))),
                 CLASS.CFG = sprintf('class-%s',
                     c(rep('C', 4), rep('A', 4), rep('B', 8),
                       rep('C', 8), rep('A', 4), rep('D', 4))),
                 EXEC.CFG = rep(c('st', 'st', 'dyn', 'dyn'), 8),
                 METRIC = rep(c('ipc', 'pwr'), 16),
                 VALUE = runif(32))

The straightforward command to plot this data frame would be:
library(lattice)
barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG, df, groups = METRIC,
         scales = list(x = list(rot = 45, relation = 'free')),
         auto.key = list(columns = 2))

As you can see, I am plotting VALUE for each BENCH constrained to every possible combination of EXEC.CFG and CLASS.CFG (that is what I mean with nested factors), and using METRIC to create groups.
This is the result that I obtain:

Even if I use 'free' scales for the X axis, in the plot there are some (unnecessary) gaps between some of the bars (e.g., between bench-b and bench-g).
I tried to apply the solution that I got for my previous question in the following way:
pl1 <- barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG,
    subset(df, CLASS.CFG == 'class-A'), groups = METRIC,
    auto.key = list(columns = 2))
pl2 <- barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG,
    subset(df, CLASS.CFG == 'class-B'), groups = METRIC)
pl3 <- barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG,
    subset(df, CLASS.CFG == 'class-C'), groups = METRIC)
pl4 <- barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG,
    subset(df, CLASS.CFG == 'class-D'), groups = METRIC)

pls <- c(pl1, pl2, pl3, pl4)
pls <- update(pls, scales = list(y = 'same'))
pls

And this is the result that I obtain:

As you will notice, this plot is not correct. It does not respect the nested factors, mixing values from CLASS.CFG and EXEC.CFG in the panel titles.
I have been fighting with this for a while, but with no success. Does anyone know how this can be achieved? (Basically, what I am trying to obtain is a plot like the first one, but without the gaps between the bars).

A: To do this, you'll need to supply both a modified prepanel function (which sets up the limits of each panel's plotting area) and a modified panel function (which is responsible for plotting the data). In both cases, the key modification is to use x[, drop=TRUE] to drop the unused levels:
library(lattice)

barchart(VALUE ~ BENCH | EXEC.CFG + CLASS.CFG, df, groups = METRIC,
         scales = list(x = list(rot = 45, relation = 'free')),
         prepanel = function(x,y,...) {
             xx <- x[, drop = TRUE]
             list(xlim = levels(xx),
                  xat=sort(unique(as.numeric(xx))))
         },
         panel = function(x,y,...) {
             xx <- x[, drop = TRUE]
             panel.barchart(xx, y, ...)
         },
         auto.key = list(columns = 2))


text:
Q: Rewrite Code Form Callback to Async Await I have been trying to convert my existing Express JS code from function callback to  Async Await.
The function callback code is
app.get('/contactlist', (req, res) => {
  db.contactlist.find((err, docs) => {
    res.json(docs);
  });
});

And the Async Await code is
app.get('/contactlist', async (req, res) => {
  db.contactlist.find(async(err, docs) => {
    res.json(await docs);
  });
});

The new code works good and I have strong feeling that, it is not the right Implementation of Async Await

A: You're still using callbacks. You can only switch to async/await, if the API returns promises. app.get() does not return promises, so the following doesn't work with Express:
let (req, res) = await app.get('/contactlist');
try {
 let docs = await db.contactlist.find();
 res.json(docs);
} catch (err) {
  // Handle the error
}

All of that would have to be inside an async function.
What is db in your example? If db.contactlist.find returns a promise, you can use async/await like this:
app.get('/contactlist', async (req, res) => {
  try {
   let docs = await db.contactlist.find();
   res.json(docs);
  } catch (err) {
    // Handle the error
  }
});

A: you did not convert the callback to async await at all,callback is still there.The right implementation would look like this
    app.get('/contactlist', async (req, res) => {
    const docs = await getContactList();
    res.json(docs)
});

function getContactList() {
    let promise = new promise(function(resolve, reject) {
        db.contactlist.find({}, function(err, results) {
            if (err)
                reject(err)
            else
                resolve(results)

        });
    });
    return promise
}

^EDITS: Here's the complete example, if you have a custom function against await, you can promisify that function by creating and returning a promise in that function


text:
Q: html content not showing when using template in angular 6 I am developing dynamic template creation based on following example. example
but i can't get html output. i.e) dynamic content.
ts file:
@Component({
  selector: 'product-item',
  template: `

      <ng-container *compile="template; context: this"></ng-container>

`,
})
export class DynamicItemComponent {

  @Input() content: string = `<a (click)='changeEditor('TEXT')'>Click me</a>`;
  @Input() template: string = `{{content}}`;

}

Html:
<product-item [content]="selectedTemplate.content"></product-item>

how can i get html output. i already used safethtml pipe, that is also not working.
Thanks in advance.

A: You can create HTML Template using ng-template directive.
<ng-template #anchorRef>
   Click me
</ng-template>

You can pass this templateRef as input to child component using @Input decorator.
Child Component:
Using *ngTemplateOutlet structural directive,
@Component({
  selector: 'hello',
  template: `

Hello !

  <ng-container *ngTemplateOutlet="name"></ng-container>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: TemplateRef<any>;
}


text:
Q: How to add required to react-select? I'm using react-select library to add dropdown menu for my app, but "required" doesn't work (I read a discussion on GitHub for this library, creators haven't added that function yet), so for now how do I make select required? (I read here another post with the same problem, solution presented there didn't work for me). My code is:
import React, { useState } from "react";
import Select from "react-select";

export default function App() {
  const [data, setData] = useState();
  const options = [
    { value: "1", label: "1" },
    { value: "2", label: "2" },
    { value: "3", label: "3" },
    { value: "4", label: "4" }
  ];

  const handleSubmit = (e) => {
    console.log(data);
  };
  return (

      <form onSubmit={handleSubmit}>
        <input required placeholder="name" />
        <Select
          options={options}
          onChange={(e) => setData(e.value)}
          value={options.filter(function (option) {
            return option.value === data;
          })}
          label="Single select"
          placeholder={"Select "}
          menuPlacement="top"
          required
        />

        <button> Submit</button>
      </form>

  );
}

code sandbox
In my code I have a couple of regular inputs (where required works fine) but I want the Select also be required. Any suggestions are greatly appreciated.

A: I would think outside the box — in this case the Select component. What can you add that gets the same result? I took a quick stab at this for you:
const [isValid, setIsValid] = useState(false);

// This effect runs when 'data' changes
useEffect(() => {
  // If there is data, the form is valid
  setIsValid(data ? true : false);
}, [data]);

...

return (

    <Select ... />
    {!isValid &&
You must choose a value
}
    <button disabled={!isValid}>Submit</button>

)

https://codesandbox.io/s/vigilant-wiles-6lx5f
In this example, we check the state of the Select component — if it's empty (the user hasn't chosen anything) the form is invalid and the submit button is disabled.


text:
Q: Crystal Report-Get Value base on row criteria I have a crystal report that when run will look like the below. The fields are  place in the detail section:
Code|Jan|Feb|Mar|Apr|May|Jun|Jul|
405 |70 |30 |10 |45 |5  |76 |90 |
406 |10 |23 |30 |7  |1  |26 |10 |
488 |20 |30 |60 |7  |5  |44 |10 |
501 |40 |15 |90 |10 |8  |75 |40 |
502 |30 |30 |10 |7  |5  |12 |30 |
600 |60 |16 |50 |7  |9  |75 |20 |

I need to create a formula or a parameter to check if the Code=501 and then return the column Jun value of "75" from the footer section.
I wrote this formula:
  whileprintingrecords;
  NumberVar COSValue;

  If {ds_RevSBU.Code}=501
  Then COSValue :={ds_RevSBU.JUN)}
  Else 0;

If I place this formula within the detail it work, it give me the value of 75.  How can I get this value from the report footer section?
Please help.
Thank you.

A: I finally figure a way but I'm not sure if it is the  correct  way. I create the below formula and suppress it in the detail section:
  Global NumberVar COSValue;
  If {ds_RevSBU.Code}=501
  Then COSValue :={ds_RevSBU.JUN)}
  Else 0;

Then in the footer section, I created the below formula:
 WhileReadingRecords;
 Global NumberVar COSValue;
 (COSValue * 4.5)/100


text:
Q: Uploading file via form into GAE from Android I have an app on GAE at: http://1.myawesomecity.appspot.com/
FIXED:
                HttpPost post = new HttpPost("http://1.myawesomecity.appspot.com/");
                http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
                String actualURL = result.substring(result.indexOf("http://"), result.indexOf("\" method"));
                Log.w("asdf", "url " + actualURL );

                post = new HttpPost(actualURL);
                http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
                String mime_type = "image/png";
                File file = new File( filename ); //context.getFilesDir(),
                entity.addPart( "myFile", new FileBody( file, mime_type));
                post.setEntity( entity );

                String res = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
                Log.w("asdf", res);

The above grabs the ACTUAL upload URL from the GAE server, and passes in the file as dictated by the CORRECT answer below.
Old Question:
As you can see, if you choose a file and hit submit, it will 404, but the file actually does get stored (as long as it is not too big, < 100kb). Don't type in anything in the first text field.
Now, putting aside how this particular app is barely functional, I'm trying to upload a file from Android onto this server.
The site's upload script uses blobstore, and the file field's name is "myFile".
Now in my Android app, I have:
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(<my app's url>);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("myFile", <path to a file selected by user> ) );
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    httpclient.execute(httppost);

This throws an exception.
How is this any different from me going to my site through a browser, choosing a file, and hitting submit? Why does going through a browser actually go through with uploading the file, when the Android code does not?
I know that my filepath is valid. Is there something I'm doing wrong? or is clicking on "submit" from a browser different from executing a httpclient from Android?

A: Uploading file to a blobstore on GAE is a two step process:

*

*first you need to get a proper URL where to POST your data, usually people use something like "/bloburl" handler for that purpose

*when you have blob upload URL, you use it in your request.

*the file you send does not go as NameValuePair, it's supposed to go as a MultiPartEntity.
here's the code that works (you'll need apache http library for MultiPartEntry support):
DefaultHttpClient http_client = new DefaultHttpClient();
HttpGet http_get = new HttpGet(Config.BASE_URL + "bloburl");
HttpResponse response = http_client.execute(http_get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String first_line = reader.readLine();
Log.w(TAG, "blob_url: " + first_line);

HttpPost post = new HttpPost(first_line);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );

mime_type = "application/zip";
File file = new File( context.getFilesDir(), filename );
entity.addPart( "file", new FileBody( file, mime_type));
post.setEntity( entity );

String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.i(TAG, result);


text:
Q: Abstract Factory Improvements Edited: I decided to edit this post for future readers. Put simply, it shows an acceptable way to call constructors of template types within the template list. For example, the following:
int main()
{
    unique_ptr<factory> real_widget_factory(new widget_factory(5.0, 6.0));
}

Instead of just being limited to:
    unique_ptr<factory> real_widget_factory(new widget_factory()); // empty

A: The Standard provides all the necessary infrastructure you need. You can delete all of that code.
template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(std::forward<Args>(args)...);
}
struct train_factory {
    train_factory(std::function<std::unique_ptr<locomotive>()> ml,
        std::function<std::unique_ptr<freight_car>()> mc)
        : make_locomotive(std::move(ml)),
        , make_car(std::move(mc)) {}
    std::function<std::unique_ptr<locomotive>()> make_locomotive;
    std::function<std::unique_ptr<freight_car>()> make_car;
};
train_factory make_concrete_factory(double x1, double x2) {
    return train_factory(
        [=] { return make_unique<real_locomotive>(x1); },
        [=] { return make_unique<real_car>(x2); }
    );
}
int main() {
    auto fact = make_concrete_factory(1.0);
    auto loc = fact.make_locomotive();
}

This appears to meet all of your requirements. In this case, the functions have the arguments to the factory bound in (and this binding is arbitrary). You can of course also modify the functions to take the arguments if you like, or use both in arbitrary ways and combinations.
struct train_factory {
    std::function<std::unique_ptr<locomotive>(double)> make_locomotive;
    std::function<std::unique_ptr<freight_car>(double)> make_car;
};
train_factory make_concrete_factory() {
    return train_factory {
        [](double x1) { return make_unique<real_locomotive>(x1); },
        [](double x2) { return make_unique<real_car>(x2); }
    };
}
int main() {
    auto fact = make_concrete_factory();
    auto loc = fact.make_locomotive(1.0);
}


text:
Q: How to remove columns from a pre-selected dataframe which contain only NaN's I want to remove all columns which contain only NaN's. This is my example code:
rutte2[[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
       u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
       u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
       u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
       u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
       u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
       u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
       u'Wijnschenk', u'Wilders']].dropna(axis=1, how='all')

When I do
type(rutte2[[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
           u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
           u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
           u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
           u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
           u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
           u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
           u'Wijnschenk', u'Wilders']])

it returns this:
pandas.core.frame.DataFrame

Here's an image for further explanation:

Why is this not working?

A: So "type" returns the type of the Python object which apparently in your case is a pandas Dataframe. If you want to print the dataframe use
print rutte2

or in Python 3.x.
print(rutte2)

dropna returns a new dataframe with NaN's removed. If you want to remove the NaN's from rutte2 use:
(edit: use subset to do inplace removal on selected columns)
rutte2.dropna(subset=[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
       u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
       u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
       u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
       u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
       u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
       u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
       u'Wijnschenk', u'Wilders'], axis=1, how='all', inplace=True)

Are you sure rutte2 is not an empty dataframe :-) ?


text:
Q: MVC app static files are not accessible when deployed in virtual folder I have a Windows Server 2012R2 running IIS version 8.5.9
Currently it has a single ASP.net Forms web application running on the default http port 80.
The website has an application pool (v4.0 Classic).
The website files are stored in c:\inetpub\wwwroot\formsApp.
( The application can be accessed in a way similar to: http://server-host-name.company.com )
This works fine, with no issues.
I created a new ASP.Net MVC application and published it to c:\inetpub\wwwroot\mvcApp.
I also created a dedicated pool (v4.0 Integrated) and configured it to run on port 8080.
The application works perfectly when I visit: http://server-host-name.company.com:8080.
Now, I created a virtual folder in the formsApp website in IIS and pointed it at mvcApp folder.
I also made sure that the pool used for the virtual folder is the Integrated pool, not the classic. The virtual folder name is mvc.
I could tell that IIS did something special to that folder, since its thumbnail icon is no longer a normal folder, but an application website thumbnail.
Now when I go to http://server-host-name.company.com/mvc I can see the page being loaded and the correct controller is called, the view is rendered, but the static script and CSS files are not loaded. When I examined the network log in the browser, I noticed that any request to the script or CSS static content is redirected to the Login Page, since the MVC app has Forms Authentication.
I have looked everywhere how to resolve this issue. Some answers pointed out that I should add a line in Web.config to add the line
 <modules runAllManagedModulesForAllRequests="false" />

But that did not work. it had no effect, as the same page loaded without CSS or JS. But besides the fact that it worked or not, it does not explain why the app worked fine when IIS served it off of port 8080, without having that line included in Web.config.
Edit: Just to clarify, after the app runs from the virtual directory, the links/urls to the static files are valid with the name mvc prepended to them as expected.
How can I resolve this issue?


text:
Q: Sphinx documenting dictionary content (a module constant) This is somewhat related to How to document a module constant in Python? but not same.
I have a constant in the module (its a dict):
possiblestringencodings = dict(
    StringsAsBytes=1,
    ascii=1,
    utf8=1, utf_8=1, U8=1,
    utf16=2, utf_16=2, U16=2, utf_16_be=2, utf_16_le=2,
    utf32=4, utf_32=4, U32=4, utf_32_be=4, utf_32_le=4,
)

The readthedocs page has (see autodata docs):
.. autodata:: construct.possiblestringencodings

However, this produces the docstring from dict docstring  (its ctor). How can I document the content of that dictionary, ONLY its items using Sphinx?

If someone would like to test patching it up, just fork the repo and run "make html" inside docs/ folder.
https://github.com/construct/construct/blob/1b53d9122a2c652db64c6558d101caee5bbbab3a/construct/core.py#L1280
https://github.com/construct/construct/blob/1b53d9122a2c652db64c6558d101caee5bbbab3a/docs/api/strings.rst

A: The dictionary data member does not have a docstring so you get the one from the dict class.
Add an empty "documentation comment" immediately before the definition (or a docstring immediately after), and you will only get the dictionary items in the output.
#:
possiblestringencodings = dict(
    StringsAsBytes=1,
    ascii=1,
    utf8=1, utf_8=1, U8=1,
    utf16=2, utf_16=2, U16=2, utf_16_be=2, utf_16_le=2,
    utf32=4, utf_32=4, U32=4, utf_32_be=4, utf_32_le=4,
)

You also need to fully qualify the "core" module:
.. autodata:: construct.core.possiblestringencodings


text:
Q: Print the sum of entered numbers I'm using command prompt and notepad and I can't print the sum of the entered numbers.
I tried
 (format t "Sum ~d ~%" I don't know what should put here)

and I know if I put num then there's no value

here's my code
(princ"Enter how many numbers to read: ")
(defparameter a(read))

(defun num ()
  (loop repeat a
        sum (progn
              (format *query-io* "Enter a number: ")
              (finish-output)
              (parse-integer (read-line *query-io* )))))

(num)

Thank you

A: You are almost there. Instead of ... below, format expects a number:
(format t "Sum ~d ~%" ...)

If you put num, this won't work
(format t "Sum ~d ~%" num)

Because num refers to a variable named num, which does not exist in your environment. You defined a function named num. That function computes a value when it is called, so you need to call the function named num.
The way you call a function in Lisp is by writing (num), this is the syntax for calling function num with zero arguments.
Equivalently, you could also call (funcall #'num), which is a bit different: funcall accepts a function object and calls it, and #'num is syntax for accessing the function object bound to the symbol num. In fact #'num is a shorter way of writing (function num), where function is a special operator that knows how to return a callable object given a name.
In your case, you can directly write (num), as follows:
(format t "Sum ~d ~%" (num))

The evaluation of this forms first evaluate all the arguments in order, T, the control string, then (num). While evaluating (num) it will prompt for a numbers. Eventually, it will return the sum thanks to the loop, and the arguments to format will be known. Then format will be executed, will all its parameters bound to the computed values.


text:
Q: CSV remove commas in quotation marks with regexp I have a CSV file and we know excel does its thing with commas in a field by enclosing them in double quotation marks for instance i have a file
Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB

How can I use RegExp to replace the quotation marks with "." instead but only within quotation marks so i get
Product Name,Product Code
Product 1,AAA
Prod.A.B,BBB

as output

A: CSV handling functions (fgetcsv(), fputcsv()) are much better for this - they will handle edge cases and will likely be far more reliable than any regex you can come up with.
// Open the file
$fp = fopen($pathToCsvFile, 'r+');

// Create an array of modified data
$tmp = array();
while (($row = fgetcsv($fp, 8192)) !== FALSE) {
  foreach ($row as &$field) $field = str_replace(',', '.', $field);
  $tmp[] = $row;
}

// Truncate the file and put the pointer at the beginning
ftruncate($fp, 0);
rewind($fp);

// Write the modified data back and close the file
foreach ($tmp as $row) {
  fputcsv($fp, $row);
}
fclose($fp);

EDIT Following your comment about not wanting to read from/write to disk, you can do this:
// Lets say the raw CSV data is held in this variable as a string
$rawCsvData = 'Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB';

// Open a virtual file pointer to memory and fill it with your data
$fp = fopen('php://memory', 'w+');
fwrite($fp, $rawCsvData);

// Start from the beginning of the pointer
rewind($fp);

// ... INSERT CODE FROM ABOVE HERE (minus the fopen()/fclose())

$modifiedCsvData = stream_get_contents($fp);
fclose($fp);

A: This will do multiple replaces, and remove the quotes.
<?php
$data = 'Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB';

$rgx = '/"(.+?)"/';

preg_match_all($rgx, $data, $matches);
$x = 0; $max = count($matches[0]);
while($x < $max){
    $replace = str_replace(",", ".", $matches[1][$x]);
    $data = str_replace($matches[0][$x], $replace, $data);
    $x++;
}
echo $data;
?>


text:
Q: How to initiate an audio call from bot to user? Is it possible to initiate an audio call from Bot to the user? If yes, Could you please provide the sample code where i can refer.

A: It looks like you can do so with use of MS Teams and Graph API.
Docs to help point you in the right direction:

*

*Registering a calling bot for Microsoft Teams

*Blog: Build Your Teams Calling Bot (IVR application) with Microsoft Graph

*

*shows you raw REST call flows

*v4 node sample with msgraph

*

*although you're looking into v3, here's a sample that you can look at to see how they organized msgraph into their bot to help you get ideas of how you'd like to organize it in your own v3 bot


text:
Q: Should I use sharding/replication on a single machine in elasticsearch? I have a large dataset in an index in elasticsearch. I have only one physical machine and that is not about to change in near future.
Is there any point in using sharding and/or replication if I can't have more nodes to run elasticsearch on? Will it still improve performance, or should I stick to having just one shard?

A: In a single machine. replication doesn't make sense as its mainly used for high availability(if machine holding another copy goes down) you can still serve requests from machine where replica is hosted, and to provide better search performance, as you search can happen from any replica but in a single machine both these use-cases are not valid, hence even if you try, ES will not allocate replica of same shard on the same node.
Coming to multiple primary shards, its more complicated as it depends on various factor, if you have good disk and RAM available, and have huge amount of data than having a single primary shard means large segment size and segment size more than 5 GB is big and not eligible for segment merging and difficult to cache, on the other hand too many small segments also badly impact the search performance. you should know that ES creates one thread per shard and having more shards of a single index, means more threads from same machine is involved while searching the data. So best is that based on your data, infra you do some benchmarking and choose what is best for your use-case.

A: Complementing what Opster said.
Hence even if you try, ES cluster status becomes yellow, because the a replica shard cannot be assigned to the same machine where your primary shard resides.
Hence even if you try, all your replica shards  increases the unassigned_shards counter
Check the status of your cluster
curl -XGET  "http://localhost:9200/_cluster/health?pretty"
{
  "cluster_name" : "es-test",
  "status" : "yellow",
  "timed_out" : false,
  "number_of_nodes" : 7,
  "number_of_data_nodes" : 7,
  "discovered_master" : true,
  "active_primary_shards" : 8617,
  "active_shards" : 11975,
  "relocating_shards" : 8,
  "initializing_shards" : 0,
  "unassigned_shards" : 46,
  }

"TIP: The number of shards you can hold on a node will be
proportional to the amount of heap you have available, but there is no
fixed limit enforced by Elasticsearch. A good rule-of-thumb is to
ensure you keep the number of shards per node below 20 per GB heap it
has configured. A node with a 30GB heap should therefore have a
maximum of 600 shards, but the further below this limit you can keep
it the better. This will generally help the cluster stay in good
health."

https://www.elastic.co/blog/how-many-shards-should-i-have-in-my-elasticsearch-cluster
Aplicable to primary and replica shards: When you have too many indices, therefore many shards, you start to reach the limit of shards allowed per node. Also take this into account, if you want to modify the primary shards for your new indices.
Or if you want to reindex in order to modify the primary shard settings of your existing indices.

*

*"Elasticsearch 7.x and later have a limit of 1,000 shards per node, adjustable using the cluster.max_shards_per_node setting." https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/sizing-domains.html

*AWS ElasticSearch support service best practice recommendation: 800 shards per node


text:
Q: conditions (where) mysql Table products:
id|name
-------
1 |computer
2 |microwave
3 |transl

Table product_features:
feature          | id_product | feature_value
------------------------------------
count_of_buttons | 1          | 1
count_of_buttons | 2          | 2
count_of_buttons | 3          | 1
color            | 1          | white
color            | 2          | white
color            | 3          | black

Pls, how to get all white products with one button?
Thank you very much!

A: select product.*

from product
  join product_features as buttons
    on buttons.id_product = product.id
  join product_features as color
    on color.id_product = product.id

where buttons.feature_value = '1'
  and buttons.feature = 'count_of_buttons'

  and color.feature_value = 'white'
  and color.feature = 'color';

A: select
    p.id
    p.name
from
    products p
    join (select * from product_features where feature = 'color') colors on (p.id=colors.id_product)
    join (select * from product_features where feature = 'count_of_buttons') buttons on (p.id=buttons.id_product)
where
    colors.feature_value = 'white'
    and buttons.feature_value = 1

You might consider reorganizing the product_features table so that you have a separate column for each feature (i.e. a color column and a count_of_buttons column) so that you have one row for each product. In fact it could all be in the products table.

A: SELECT
  p.id
FROM products p
JOIN product_features pf
   ON p.id = pf.id
WHERE pf.feature_value = 'white' AND pf.count_of_buttons = 1

A: select p.id, p.name from products p inner join product_features ON p.id=id_product where feature_value='white' and feature='color' and count_of_buttons=1


text:
Q: In VUE 3, how to insert a HTML code containing @click event to a already rendered page I have a VUE3 application with Django (Python) in the backend. I am trying to add a "div" to a DataTable cell with Javascript. See the code below:

let myTable = $('#dtBasicExample').DataTable()
myTable.cell(vm.table_index, 12).data(`

        ${vm.counter_selected}

`)

As you can see, the "a" element has a Vue @click event in it.
When this code is added to the page, it shows as an attribute, and VUE does not detect it. The screenshot below shows how the HTML is right after the code above is applied:

What am I missing in order to make VUE3 recognize the @click event?


text:
Q: youtube api for java/android, how to get started? I'm trying to get started with youtube api for android... downloaded and imported the libraries so far, but wasn't able to find my code snippets.
Maybe you could suggest some simple ones, for example how execute a search query to youtube and get back the list of results? or something like that...
Thanks!

A: youtube have no specific API for Android. You can use java api for youtube.

A: At the google IO of this year (2012) they announced the youtube api for Android apps, it isn't available yet, but it is going to be available soon, see the video here:

A: Now it's available. You can download it from here : YouTube Android API

A: Just posted a new tutorial video on how to utilize the YouTube player and thumbnail in the YouTube for Android API.  The blog post with all the source code is here

A: YouTube provides API to embed video into your Android application. You need to download YouTube API support library.
Fist step is to obtain Google API key from Developers Console.
Add YouTubePlayerView to your layout files and initialize it in your src file with API key generated for your application. After successful intialization of YouTubePlayerView, you will get object of YouTubePlayer which you can use to cue or control video.
You can check detailed step by step tutorial at
http://androidsrc.net/youtube-android-player-api-v1-2-1-embed-video-in-your-android-application/

A: Follow this tutorial:
http://createdineden.com/blog/2015/may/12/android-tutorial-how-to-integrate-youtube-videos-into-your-app/
Hope it helps


text:
Q: How to check whether a directory is readable or writable? I want a way to know whether a directory/folder is readable or writable. I searched for a direct way to do that by a function or like that but I didn't find it.
I tried to do it indirectly as follow:
Is readable:
WIN32_FIND_DATAA dirData;
HANDLE hDir;
hDir = FindFirstFile("C:\\folder", &dirData);
if (hDir == INVALID_HANDLE_VALUE)
    return false;
return true;

Is writable:
DWORD attr = GetFileAttributes(m_dirPath);
if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_READONLY)
    return false;
return true;

*

*The first code is an indirect way to know whether a directory
readable but it is not efficient because when the directory is empty
it returns 0 which is not readable.

*The second code to check whether a directory is writable but it
always returns 1 which is writable although I have changed the
directory permission to read-only.
Is there a direct or indirect way to know whether a directory is readable or writable?

A:
I want a way to know whether a directory/folder is readable or
  writable.

Directly to try to open the directory with read/write access permission via CreateFile API:
HANDLE tDir = CreateFile(L"D:\\testNew", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
    printf("Open directory failed with error %d \n", GetLastError());
else
    printf("Readable. \n");

tDir = CreateFile(L"D:\\testNew", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
    printf("Open directory failed with error %d \n", GetLastError());
else
    printf("Writable. \n");

If it is a read-only directory you will receive access denied error when you open it with GENERIC_WRITE.
For read-only, the directory maybe set to deny current user to write, however it is not a read-only directory. At this time you will get "This directory is not read-only" result but you still can't write.

Update:
As @RaymondChen pointed out, you can confirm the desired access right to a directory more accurately using file access rights constants. Take FILE_LIST_DIRECTORY as an example:
tDir = CreateFile(L"D:\\testNew", FILE_LIST_DIRECTORY, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
    printf("Open directory failed with error %d \n", GetLastError());
else
    printf("Has right to list the contents of the directory.\n");


text:
Q: Form a query in Azure Devops to pull all the work items that moved from one state to another I am looking to form a query in Azure Devops to pull all the work items that moved from one state to another state on or after a particular date, irrespective of what state they are currently in. for example, I would like get all the work items that moved from "Development Completed" to "In QA"  on or after 08-01-2019.

A:
Pull all the work items that moved from one state to another state on
  or after a particular date, irrespective of what state they are
  currently in.

Just refer to the below configuration:

The logic of this query is no matter what state the work item are currently in, query out the work items which was ever changed from Active to Resolved. As you know, it is impossible for the state of one work item was ever in both Active and Resolved if without any state change. So if you specified these states in query, it will query out the work items which ever moved from Active to Resolved. For the last Change date, this does not mean the change date which about state change. It is relevant with this current workitem active date, including link build or other.


text:
Q: C Language, dynamic 3d array I have to create a dynamic and 3 dimensional integer-Array in C.
But I have to create the pointers separately and use malloc. I know how to create 2d Array with malloc but I get confused using the following method, and i couldn't really find other question similar to this.
2x2x2 Integer-Array
First step:
int *firstD;
firstD = (int) malloc(2*sizeof(int));

Second step:
int *secondD;
secondD = (int) malloc(2 * firstD * sizeof(int));

Third step:
int *thirdD;
thirdD = (int) malloc(2 * secondD * sizeof(int));

I think maybe I have to add pointers in the starting (int*) and increase it every stepp by one more pointer?

A: *

*Allocate an array to store pointers to arrays of row pointers.

*Allocate arrays to store row pointers.

*Allocate arrays to store each rows.

#include <stdlib.h>

int main(void) {
    int size1 = 2, size2 = 2, size3 = 2;
    int*** array;
    array = malloc(sizeof(int**) * size1); // 1
    for (int i = 0; i < size1; i++) {
        array[i] = malloc(sizeof(int*) * size2); // 2
        for (int j = 0; j < size2; j++) {
            array[i][j] = malloc(sizeof(int) * size3); // 3
        }
    }

    // free arrays
    for (int i = 0; i < size1; i++) {
        for (int j = 0; j < size2; j++) {
            free(array[i][j]);
        }
        free(array[i]);
    }
    free(array);

    return 0;
}

I wrote type names explicitly in the above example, but I suggest using dereferencing to obtain size of elements to allocate is better to prevent causing typos.
#include <stdlib.h>

int main(void) {
    int size1 = 2, size2 = 2, size3 = 2;
    int*** array;

    // allocate arrays
    array = malloc(sizeof(*array) * size1); // 1
    for (int i = 0; i < size1; i++) {
        array[i] = malloc(sizeof(*array[i]) * size2); // 2
        for (int j = 0; j < size2; j++) {
            array[i][j] = malloc(sizeof(*array[i][j]) * size3); // 3
        }
    }

    // free arrays
    for (int i = 0; i < size1; i++) {
        for (int j = 0; j < size2; j++) {
            free(array[i][j]);
        }
        free(array[i]);
    }
    free(array);

    return 0;
}

Onitted in the above examples to make them simple, but you should check results of malloc() to see if the allocations are successful.


text:
Q: What do the "Energy Impact" numbers displayed in the new OSX 10.9 mean and how are they calculated? I love the new energy tab in OSX 10.9 mostly because I love data about my machine.  I'm curious how the energy impact is calculated, and what the number represents.
It seems clear from using the OS for a week that apps that are running more CUP/memory intense processes (for me: Mathematica and MATLAB) use more energy, or apps that can't take a nap (like listening to pandora in google chrome).
What isn't displayed are some of the bigger energy hogs on a portable: Display settings, WiFi, Bluetooth.  I'm wondering if some of this is wrapped into current apps (i.e., if i'm using safari or chrome full screen, will the display power be lumped into this app?) Do display preferences for the app change the energy being used (i.e., working in a text editor with a white-on black scheme instead of black-on white would theoretically use less energy to display).
If these are percents, they do not sum to 100, which is a little annoying.

A: I don't think you would want this numbers to be percentile and adding to 100 at any point because that would mean that your battery would die nearly instantaneously.
If I was to make an educated guess just to help you out a bit, your computer (specifically MacBooks) have their battery capacity measure in mAh or milli Ampere-hour typically somewhere in the ballpark of 6500 mAh or 6.5 Ampere-hour. I would hazard a guess (if the moderators allow it) that your are seeing the actual usage to the second of how many mA are going to the specific app per refresh (call time by the Activity Monitor daemon).
So if you were to add up the average power draw of your active apps and multiple that per second you would know how long your computer battery would last without power (roughly). Additionally you have to factor in what internal components are working hard (AirPort, Bluetooth, Display brightness, hard drive rotations) and you have yourself the estimated time until depletion.
Oh, and as to how they are calculated. There is a tiny integrated circuit on your main logic board called the SMC and it's job is to allocate DC current to the resource that needs it most. It keeps  track of energy usage and demands by the RAM, CPU, GPU, etc. so that it can help make sure your computer stays energy efficient.


text:
Q: R count the number of rows as a combination I have a dataset that looks like:
order year  value
   1   1990      2
   1   1990      1
   1   1990      1
   2   1990      0
   3   1990      4
   1   1991      3
   2   1991      2
   2   1991      0
I have been trying to get the count of the unique orders in particular year. I tried  table(data$year) which gives me:
1990  1991
   5     3
However, I would like to get:
1990  1991
   3     2

A: This will do the trick. It uses tapply() to separately count the number of unique values of order for each level of year.
df <- read.table(text="order year value
1 1990 2
1 1990 1
1 1990 1
2 1990 0
3 1990 4
1 1991 3
2 1991 2
2 1991 0", header=T)

with(df, tapply(order, year, function(X) length(unique(X))))
# 1990 1991
#    3    2

A: Requisite plyr and data.table options:
dat <- read.table(text = txt, header = TRUE)

library(plyr)
ddply(dat, "year", summarize, val = length(unique(order)))

library(data.table)
dt <- data.table(dat)
dt[, length(unique(order)), by = year]

A: This can also be done by calling table on the unique orders, instead of the detailed ones.
table( unique( df[,c("order","year")] )$year )


text:
Q: Ubuntu stuck Copying large files from internal hard disk to external When ever I try to copy large files from internal hard disk to external the copy will just start fine but then it will stuck at some point. Last night I tried copying 45GB file to my USB 3 harddisk and left it overnight for about 9 hours. When I wake up it's stuck at 18GB. I am using a 4th Generation core i7 Lenovo laptop with 16GB of ram. I am starting to get  worried that I will not be able to get my file back. I have never seen this problem on Windows in my life.
Anyway is there a way to fix this?
Edit: I tried it with 4 files which are 1.3GB in total, it didn't finish in 1 hour. And this is the first time this is happening to me.
File system: NTFS
Capacity: 1TB


text:
Q: OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions while running in PyCharm environment Installed PyCharm for evaluation. When trying to run a "Hello World" Flask application:
from flask import Flask
import os
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True, use_debugger=False, use_reloader=False, passthrough_errors=True)

Getting error:

OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Error occurred in socketserver.py file

File "C:\Python371\lib\socketserver.py", line 463, in server_bind
      self.socket.bind(self.server_address)

I used netstat utility and saw that port that application is trying to use '5555' is not in use. I tryed to run PyCharm as Administrator, but still same problem exists. Note: Same project when opened in Visual Studio 2017 works without any problems. Am I missing some configuration in PyCharm?


text:
Q: Compute Aggregations before running Filter Query I've a simple scenario:

*

*I search for some text, and elastic returns documents and
aggregations.

*I then filter that search with values in the fields returned from    that  aggregations. I'm using a Terms Query inside a filter

*I want the documents to be filtered by my filter conditions, which is working fine.

*But I want the aggregation buckets without applying the filter condition (because if I get the buckets after applying the filter, I'll just get that one value)

*My workaround to get the aggregations without applying filters: Send two request to Elastic search, In first request, Send the query with filters applied,and in second request, Send the query without filters applied
Question: Is there a better way to achieve this? I looked around SO and I guess I can set global:{} while defining aggregations, but I'm not sure!
Or better put, Is there a way I can get aggregation results before filters are applied to a document?
EDIT

I did some searching and it looks that post_filter was designed for cases like this, i.e., if you don't want your filter to affect aggregations. But, there was also massive talks of performance of post_filter
Now I wonder if sending two requests is better than using post_filter in terms of performance.

A: I think post_filter performance is not as bad as you are saying. It just applies a filter on search results post aggregation. So all docs have to pass through this filter. I think you should go with post_filter because-

*

*It will save you network round trip, so you will have minimal latency.

*Will save your ES overhead of allocating resources for handling new request.

*Your needs for post_filtered search and aggregation will be fulfilled by same set of documents, so most of the values it needs will already be in main memory or cache memory (things like doc_values)

So, performance should not get effected to much. You can also do profiling and analyse it yourself.


text:
Q: When to use Facebook AccessTokenTracker Android SDK? I am interested how to handle AccessToken expiration when using the Facebook SDK for Android.
According to documentation of Access Tokens they are saying that developers don't need to worry about token expiration : "When using iOS, Android or our JavaScript SDK, the SDK will handle making sure that tokens are refreshed before they expire."
Assumption A : I assume that the quote above implies that AccessToken.getCurrentAccessToken() returns always non-expired access token, or is my assumption wrong ??
In the Facebook Login for Android documentation they are saying : "If you want your app to keep up with the current access token and profile, you can implement AccessTokenTracker and ProfileTracker classes."
My question is: Why should I implement AccessTokenTracker, if (according to 1 ) the SDK make sure that token are refreshed before they expire ?
If my assumption is correct, then the getCurrentAccessToken() returns always the non-expired token, so there should be no reason to track the AccessToken ?
Thank you for help!
EDIT
My assumption A is wrong, because according to this docu the person has to login again if the access token is invalid.

A: Typically you would use the AccessTokenTracker if you also save the access token elsewhere. Let's say that you keep the access token server side (so you can make requests offline), and the SDK updates the token with a refresh, in that case, you'll want to update the token on your server as well, this allows you to do that.
Alternatively, if your app allows people to log off, or to switch to a different user, you can use the AccessTokenTracker and ProfileTracker to alert you when the user changes.


text:
Q: A boy bends his knees a bit and then straighten his knees out repeatedly several times. Can we say "he is springy for fun"?
springy (adj): returning quickly to the original shape after being pushed, pulled,
stretched, etc.
We walked across the springy grass.

A boy bends his knees a bit and then straighten his knees out.
He does that repeatedly several times.
How do we express this movement in everyday English, for example, "he is springy for fun"?
Note: people often do like that when they play the guitar after the rhythm.

A: He's "bobbing up and down",  or "bouncing up and down" (a more energetic movement) (from comments)
You mention "when they sing" or "while playing the guitar" so perhaps it would be be better to say "swaying" or "rocking to the music". or "feeling the movement in the music".  The presence of music means that the actual action is not "for fun" so we can refer to the context. Swaying side to side is an action that I'd recognise in singers (some people even recommend it, as a way to relax tension) I don't recognise the action of bobbing while singing.


text:
Q: Nginx proxy pointing to root of node server URL but node responds to full URL? I have an Nginx server running and redirecting proxy to a node server:
  server {
        listen      80 default_server;

        root /usr/share/nginx/html;

        index index.html index.htm;

        location / {
            try_files $uri /index.html;
        }

    location /api {
        proxy_pass http://node_server:9000;
    }

Site URL is example.com, but when you go to example.com/api, it should go to the root of the node server.
When I do app.use('/', indexRouter);, though, it doesn't work.
I have to do app.use('/api', indexRouter);.

A: server {
    listen      80 default_server;

    root /usr/share/nginx/html;

    index index.html index.htm;

    location / {
        try_files $uri /index.html;
    }

    location /api {
        proxy_pass http://node_server:9000/;
        #                                 ^
    }
}

Had to add a forward slash.


text:
Q: Build failing with exception when I run (React-native run-android)  Its gives an error below:
info Starting JS server...
info Installing the app...

Task :app:installDebug FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
27 actionable tasks: 2 executed, 25 up-to-date
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem was found with the configuration of task ':app:installDebug'.

File 'C:\Users\skpul\AppData\Local\Android\platform-tools\adb.exe' specified for property 'adbExe' does not exist.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 20s
error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem was found with the configuration of task ':app:installDebug'.

File 'C:\Users\skpul\AppData\Local\Android\platform-tools\adb.exe' specified for property 'adbExe' does not exist.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 20s
at checkExecSyncError (child_process.js:629:11)
at execFileSync (child_process.js:647:13)
at runOnAllDevices (C:\Users\skpul\MyRe\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:75:39)
at buildAndRun (C:\Users\skpul\MyRe\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:169:41)
at then.result (C:\Users\skpul\MyRe\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12)
at process._tickCallback (internal/process/next_tick.js:68:7)

A: the problem related the emulator,
restart your emulator or device, the problem will solved


text:
Q: How to get two sums from two tables in one output? I have two tables:

*

*Receive_Amount_Details for crediting amount from the construction site owner, and

*SitewiseEmployee for debiting the amount to pay the laborer.

For every single Date, which is present in both tables, I want to:

*

*sum all of the Amount_Received from Receive_Amount_Details as Total_Receive_Amount_from_siteowner, and

*sum all of the Amount from SitewiseEmployee as Total_Amount_Payed_to_Labour
column on output table.

Both tables have the Date column, but I want a single Date column in the output.
If any single day amount is not received and labour was paid, it should be in the output table, and also if any single day amount was received but not paid for labour, then also it needs to be present in the output table.
CREATE TABLE `Receive_Amount_Details` (
    `Id` int(10) NOT NULL AUTO_INCREMENT,
    `SiteId` int(5) NOT NULL,
    `Amount_Received` int(10) NOT NULL,
    `Date` date NOT NULL,
    PRIMARY KEY (`Id`),
    KEY `SiteId` (`SiteId`),
    CONSTRAINT `Receive_Amount_Details_ibfk_1` FOREIGN KEY (`SiteId`)
        REFERENCES `SiteList` (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

and
CREATE TABLE `SitewiseEmployee` (
    `Id` int(10) NOT NULL AUTO_INCREMENT,
    `SiteId` int(5) NOT NULL,
    `EmployeeId` int(10) NOT NULL,
    `Amount` varchar(10) DEFAULT NULL,
    `Date` date NOT NULL,
    PRIMARY KEY (`Id`),
    KEY `SiteId` (`SiteId`),
    KEY `EmployeeId` (`EmployeeId`),
    CONSTRAINT `SitewiseEmployee_ibfk_1` FOREIGN KEY (`SiteId`)
        REFERENCES `SiteList` (`Id`),
    CONSTRAINT `SitewiseEmployee_ibfk_2` FOREIGN KEY (`EmployeeId`)
        REFERENCES `Employee` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

A: Assuming that you may have dates in the one table that are not present in the other, and vice versa, you would need to perform a full outer join. MySql does not have such a join type, but you can achieve it with a union:
select    `Date`,
          sum(Amount_Received) as Sum_Amount_Received,
          sum(Amount) as Sum_Amount
from      (
                select `Date`, Amount_Received, 0 as Amount
                from   Receive_Amount_Details
                union
                select `Date`, 0, Amount
                from   SitewiseEmployee
          ) as dates
group by  `Date`;


text:
Q: Creating vector MbTile file from source of lat / long points? I need to create a vector mbTile, not a raster one, to be compatible with the application that uses it.
I have a postgres database that has many rows, each one representing an item with a lat and long position. Of course I can export that to CSV if required.
What should I use to create the vector mbtile? I have tried with tilemill, but it creates a raster file.

A: I use mapbox tippecanoe takes GEOJSON as input produces mbtiles or folder of PBF
It's a Linux application but runs great in bash for Windows 10
tippecanoe -z5 -o filtered.mbtiles name.geosjon
https://github.com/mapbox/tippecanoe/blob/master/README.md

A: t-rex https://github.com/t-rex-tileserver/t-rex has worked well producing vector tiles for me. There is a way to generate the tiles and looks like an mbtile option too http://t-rex.tileserver.ch/doc/generate/
This links well with postgres/postgis as you noted was your data source.


text:
Q: what does it mean !! (not not) in javascript and when to use it i try to reading code of pandajs game engine and according to this code from github :
playMusic: function(name, loop) {
    var volume = this.musicMuted ? 0 : this.musicVolume;

    if (typeof loop === 'undefined') loop = true;

    if (this.currentMusic) this._stop(this.currentMusic);

    this.currentMusic = this._play(name, !!loop, volume);
    this.currentMusicName = name;

    return !!this.currentMusic;
}

and it's return !!this.currentMusic i try to figure it out but i cant understand why he use it. for example this code :

function a(arg){
  console.log(!!arg);
}

a(true)
a(false)

if i pass true it's print true and if i pass false it's print false , so why not just return this.currentMusic instead of !!this.currentMusic or in my example just console.log(arg) instead of console.log(!!arg)

A: it coerces the object to boolean, if it was null, undefined etc it would be false else true

let x = null;
let y = 1;
console.log(!!x);
console.log(!!y);


text:
Q: If 8 new teachers are to be divided among 4 schools, how many divisions are possible? If 8 new teachers are to be divided among 4 schools, how many divisions are possible?
I understand that in this question you are just solving for the multinomial coefficients of the multinomial theorem.  So x1=x2=x3=x4=1:
(1+1+1+1)^8 = 65,536.
But I thought about this question a different way and don't understand why this solution is not working:
Suppose I have 8 teachers: A B C D E F G H and the '^' symbol represents the dividing line for the school.  Since I have 4 schools, I will have 3 dividers.
So an example division would be as such:  AB^CD^EF^GH.  In this case,
school1=AB,
school2=CD,
school3=EF,
school4=GH.
Another example would be ABC^D^EF^GH:
school1=ABC
school2=D
school3=EF
school4=GH
So how many different ways could I place the divisors?  The answer is 8-1 and I have to choose 3.  Also there are 8! permutations of the teachers.  So I thought if I do:
(7 choose 3) * 8! I would get the answer, but I don't.  Can someone please explain what I am misunderstanding and what I just actually calculated?  Thanks in advance!

A: This does not answer your question, it just comments on the implicit introduction of  multinomial coefficients.
Line up the teachers, say in order of age, or weight, or whatever. The first teacher can be assigned to a school in $4$ ways. For every such way, the second teacher can be assigned to a school in $4$ ways, and so on, for a total of $4^{8}$.
Remark: An approach of the Stars and Bars type runs into difficulties. Like not a few school boards, it starts off by treating new teachers as indistinguishable.
The count we get cannot be easily adjusted to take distinguishability into account. The magic multiplier depends on the structure of the decomposition. For example, the assignment of everybody to school A gives rise to only $1$ decomposition into parts when distinguishability is taken into account, while a distribution of type $2$-$2$-$2$-$2$ gives rise to many decompositions when we consider the teachers distinguishable. In our $8$ teacher $4$ school situation, the multiplier is never $8!$. One can find an expression for the average multiplier, but it is hard to imagine doing so in a way that bypasses the $4^8$ calculation.

A: Your approach overcounts. That is, it counts distributions of teachers more than once. For instance, the distribution that puts all $8$ teachers in the first school is counted once for every permutation of the teachers, as XXXXXXXX^^^, so it's counted $8!$ times. And every distribution is counted at least twice, since you can certainly get it by reversing the entire string of teachers and dividers.


text:
Q: Hibernate second level cache: Hit and miss counts are always 0 I am using hibernate 4.1.7 and ehcache as second level cache
<property name="hibernate.cache.region.factory_class">
          org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>

When I check miss count and hit count before and after DB calls, I get always get 0.
long loadEntityCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xys.Program").getElementCountInMemory();
    long hitCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xys.Program").getHitCount();
    long missCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xys.Program").getMissCount();

List patientPrograms = getProgramsForPatient( r);
loadEntityCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xyz.Program").getElementCountInMemory();
        hitCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xyz.Program").getHitCount();
        missCount = HibernateUtil.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("com.xyz.Program").getMissCount();

I was expecting non zero values for both cases and miss count goes up.
Any help?


text:
Q: How to retrieve all parents with children having many-to-one relationship defined in children entity in JPA? Entity A,
@Entity
class A {
    ...
    private String propertyA;
    private String propertyA1;
}

Entity B
@Entity
class B {
    ...
    @ManyToOne()
    private A a;
    private String propertyB;
    private String propertyB1;
}

Repositories
@Repository
interface A extends CrudRepository<A, Long> {
}

@Repository
interface B extends CrudRepository<B, Long> {
}

How can I retrieve all A(s) with their children. I want a JSON object similar like this.
[
  {
    "propertyA": "..",
    "propertyA1": "..",
    "B": [
      {
        "propertyB": "1B",
        "propertyB1": "1B1"
      },
      {
        "propertyB": "2B",
        "propertyB1": "2B1"
      }
    ]
  },
  {
    "propertyA": "..",
    "propertyA1": "..",
    "B": [
      ...
    ]
  }
]

Is there any way to achieve this in JPA? I am newbie at Springboot and JPA.

A: Just add a @OneToMany(mappedBy = "a") @JsonProperty("B") private Set<B> bs; to A.
For this to work, you'll need to make sure the bs property is fetched while the persistence context is still open. You can do that by either (1) adding fetch = EAGER to @OneToMany, (2) using a query graph with the query to fetch A, or (3) enabling the OpenEntityManagerInViewFilter by setting spring.jpa.open-in-view to true.
(Depending on SB version, spring.jpa.open-in-view may or may not be enabled by default)


text:
Q: Returning the Progress Status How do I return the status of the Progress from the below? Am I using the IProgress status properly? I had assumed there would be a Progress.report() function somewhere but it doesn't seem to be there.
        public static void Main()
    {
        Console.WriteLine("Running Async Methods");
        AsynchronousMethods am = new AsynchronousMethods();

        Progress<int> p = new Progress<int>();
        Task ta = am.asyncMethods(p);

        while (!ta.IsCompleted)
        {
            // report progress
            // I would liek to return the Progress here. I am not sure how?
            // there doesnt seem to be a P.result
        }
        ta.Wait();
    }

    public async Task asyncMethods(IProgress<int> pro)
    {
        await Task.Run(() =>
        {
            for (int i = 0; i < 1999; i++)
            {
                Console.WriteLine("I is {0}", i);
                pro.Report(i * 2);
            }
        });
    }

A: You should handle the ProgressChanged event
Progress<int> p = new Progress<int>();
p.ProgressChanged += p_ProgressChanged;

static void p_ProgressChanged(object sender, int e)
{
    Console.WriteLine("Progress :"+e);
}


text:
Q: Unable to upload password-protected file into R anymore I initially used this code to upload a password-protected Excel spreadsheet into R. It worked completely fine and I was able to read the file.
library("readxl")
library("dplyr")
library("excel.link")
library("tinytex")

new_path = paste0(tempdir(), "\\", "Bone_Dataset_7-13-2022.xlsx")
xl()[["Activeworkbook"]]$saveas(new_path, AccessMode=xl.constants$xlExclusive)
###
xl()[["Activesheet"]]$Unprotect(password = "Password")
bonedata = crc[a1]
xl.workbook.close()
unlink(new_path) # remove temporary Excel File

BoneData <- bonedata
BoneData

However, I am trying to knit my r.markdown file, and the code no longer seems to be working. It uploads a file with only 1 row and one column in it (there should be ~1500 rows).
Description:df [1 × 1]

|      |a              |
| -----| --------------|
| 1    | NA            |

What am I doing wrong here? Why did it work before, but not now??
Thank you so much!


text:
Q: OO Design related questions in technical interviews I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

*

*Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

*I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

*Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *
For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"
I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?
public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}

A: I find these questions rather silly.  The true answer is "what are the use cases?"  Without a use case, there is no need for any design.  For example, here is a perfectly reasonable answer to the parking lot question:
class ParkingLot {
 boolean isFull();
 void carEntered();
 void carExited();
}

It satisfies one obvious use case.

A: You actually demonstrate one use of this question in your edit, where you fail to design a workable model.
public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}

var parkingLot = new ParkingLot();
var v1 = new Vehicle();
v1.Slot = parkingLot.GetEmptySlots()[0];
parkingLot.Vehicle = v1; // WHAT!??

You also mention creating Car and Motorcycle classes, which doesn't make a lot of sense without further consideration. Your design isn't going to benefit any from having subclassed Vehicle. If you introduce Motorcycle without any behavioral differences to Vehicle, I'd consider it a fail.
If you didn't spot the single Vehicle problem, then we'd pretty much be done in a live interview. If you corrected that (possibly by making that a List<IVehicle>), I would use this as a starting point to look at evolution of your design. There's a reason the requirements are basic, and there's no well defined use cases - that's pretty much the way the world works.
I might throw the new requirement at you that "two motorcycles can park in one slot" to see how you'd evolve your design to handle it. Then maybe we have a conversation around concurrency (What if we have two entrances, and two cars pull up simultaneously - will your design fail? How? What can we do to fix it?). Other possible avenues to explore would be how to implement assigned parking, charging for parking, rates per row (maybe closer rows have to pay more), time limited parking and how to find offenders, etc., etc.
I would also consider your thought process around parking lots to be indicative of your general ability to intelligently analyze a problem. If you have to ask me for basic use cases and/or come up with oddball ones (like 2 for 1 specials on parking), I start to get mightily concerned that you've never actually used a parking lot before and that we're going to have a hard time communicating on anything slightly complicated.

A: I used to ask these - back when we created class diagrams for code generation.  I still do on occasion, but not routinely.  I like the question because it lets me see the person think.
It is intended to be open ended.  That's ok.  There isn't one right answer.  I don't have an answer in my mind; I want to see where it leads.  I think it's a better question to ask in person, not "email in answer."  It's about communication, assumptions and interaction; not just an answer!

A: *

*I have seen this type of interviews at least 12 years ago. It is the approach I have used for the last 6 years.  Experience shows that it selects better candidates for the job than the ask 20 questions and give them a score out of 20 approach.

*Again, I would make it very open ended too.  The goal is to provide space for the candidate to demonstrate ability. Having a candidate that asked relevent questions at this stage would be a plus. As is a candidate making good assumptions, but flagging up that they were assumptions, and would need to be reviewed before implementation.

*I do requre all potential employees to demonstrate the skills they need for the job at interview. For programmers, they will need to implement some code, and talk about their design for it. It is very effective for preventing bad hires, but be prepared for a 90% failure rate at interview.

A: Designing a small system is actually a very relevant exercise to ask in an interview. It shows your skills at coming up with a good software solution to a domain problem.
However, I find it strange to just ask to post a class diagram online with no human interaction :

*

*They'll miss the essential - the reasoning behind the diagram and what led you to design things that way.

*There's no "parapet" to stop the applicant from going too far. If you reflect a final implementation in the diagram, you'll probably have dozens of classes and an unreadable schema.

*Being able to draw a UML class diagram is not really an essential skill, it's just one OO notation among others. The ability to create solid designs is.

In a live interview, the ideal steps I'd expect a candidate to take would be :

*

*Talk about the problem with the recruiter and start expressing a basic solution verbally, asking questions and adjusting as the recruiter gives more precise needs.

*Stand up and sketch an overall view of the system and how components could interact together. Might be the purest style of UML, might be just boxes and circles.

*Write a test, either high level acceptance test or unit test for one of the components/classes.

*Start writing the corresponding implementation.

Hopefully at some point the recruiter will have gathered enough information about the candidate's skills and call it a day. The goal is not to implement a full working solution (unless it's one of these unpaid service in disguise interviews).

A: *

*To some degree, yes. Anyone can recite syntax or copy/paste their way through a solution. We want to hire people who can solve problems.

*They expect you to document the design sufficiently that they can understand it (and no more than that).

*I ask people how they would solve XYZ problem, yes. Usually they just describe it verbally. I want to see if they ask questions to clarify requirements. I want to see how they communicate with other programmers. I want to see if they can think on their feet.
It has been helpful for me. I don't want code monkeys, I want software engineers.

A: The OOP questions are open-ended. There is no right or wrong answer, but there are some principles the interviewers expect to see (like using a constructor to initialize variables, keeping your methods small, using encapsulation/composition/polymorphism/inheritance when applicable, etc).
Always expect data structure, OOP, and database related questions in interviews, they are very common. Books like "cracking the coding interview" and "programming interviews exposed" can help you to prepare.

A: I had been asked for coming out a design for a parking lot not too long ago. I wasn't given any use cases in the first place, but mentioned a couple later. I believe my design didn't fit what the interviewer's had in mind. I agree that any software design is only valid for a given use case. Back to this interview question, I believe that my interviewer didn't have any real world design experience. Those people believe that they know what they ask for. It is another story whether that is indeed true or not.


text:
Q: MySQL: Find day with max orders I have a very basic orders table:

+----------+---------+------------+---------+
| order_id | cust_id | order_date | book_id |
+----------+---------+------------+---------+
| 1        | 1       | 10/10/2014 | 1       |
+----------+---------+------------+---------+
| 2        | 1       | 10/10/2014 | 2       |
+----------+---------+------------+---------+
| 3        | 1       | 10/12/2014 | 1       |
+----------+---------+------------+---------+
| 4        | 2       | 10/18/2014 | 6       |
+----------+---------+------------+---------+
| 5        | 2       | 10/18/2014 | 77      |
+----------+---------+------------+---------+
| 6        | 2       | 10/18/2014 | 103     |
+----------+---------+------------+---------+
| 7        | 2       | 10/10/2014 | 13      |
+----------+---------+------------+---------+
| 8        | 3       | 10/09/2014 | 1       |
+----------+---------+------------+---------+
| 9        | 3       | 10/11/2014 | 2       |
+----------+---------+------------+---------+
| 10       | 3       | 10/12/2014 | 3       |
+----------+---------+------------+---------+

The query should:

- For each customer show order_date with Max number of orders. Example: customer 1 had 2 orders on 10/10/2014

- Special case: When customer has multiple days with most orders, show the earliest date. Example: customer 3 had 3 single item orders on different days. Need to show 10/09/2014.

I should be able to solve this without use of temp tables.
Kira

A: You need two clauses: 1) find the max number of orders per customer per day and 2) find the day on which the max number of orders occurred. The second step is needed to eliminate multiple days with same number of orders.

SELECT * FROM
    (SELECT cust_id,
        order_date,
        count() cnt
    FROM
        orders
    GROUP BY cust_id, order_date) x
JOIN
    (SELECT cust_id,
            MAX(cnt) max_cnt
    FROM
        (SELECT cust_id,
                order_date,
                count() AS cnt
         FROM
            orders
        GROUP BY cust_id, order_date) n
GROUP BY cust_id) y
ON
    y.max_cnt = x.cnt
AND
    y.cust_id = x.cust_id

JOIN  (SELECT   x.cust_id,
                min(x.order_date) AS dd
        FROM
            (SELECT cust_id,
                    order_date,
                    count() cnt
            FROM orders
            GROUP BY by cust_id, order_date) x
        JOIN
            (SELECT cust_id,
                    MAX(cnt) max_cnt
            FROM
            (SELECT cust_id,
                    order_date,
                    count() as cnt
            FROM
                orders
            GROUP BY
                cust_id, order_date) n
            GROUP BY cust_id) y
        ON
            y.max_cnt = x.cnt
        AND
            y.cust_id = x.cust_id
        GROUP BY cust_id) AS t2
    ON
        t2.cust_id=x.cust_id
    AND
        t2.dd=x.order_date;


text:
Q: Where are the Windows system menu icons stored? Where are the Windows system menu icons stored?
I'm talking about the icons on the system context menu.

I want to put them in my application.

A: You can get images using the LoadBitmap function.
Example (c#):
namespace GetBitmap
{
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Runtime.InteropServices;

    internal static class Program
    {
        private const long OBM_RESTORED = 32744;

        private static void Main()
        {
            var hBitmap = LoadBitmap(IntPtr.Zero, OBM_RESTORED);
            var image = Image.FromHbitmap(hBitmap);

            image.Save(@"d:\restored.png", ImageFormat.Png);

            DeleteObject(hBitmap);
        }

        [DllImport("user32.dll")]
        private static extern IntPtr LoadBitmap(IntPtr hInstance, long resourceId);

        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DeleteObject([In] IntPtr hObject);
    }
}


text:
Q: Smart way to determine a limit I'm looking for a way to improve the following statement:
var limit = images.length > 15 ? 15 : images.length;

I know about the || operator but I cannot seem to find a good way of using it here.
Is there any way to improve this statement?

A: You can use the function min.
var limit = Math.min(images.length, 15);

A: I think you can logically stretch it only this far -
var limit = (images.length > 15 ? 15 : images.length) || 0;