text:
Q: Jquery real time input validation with $.post function Hi Guys:
I am kind of new to Jquery and web development, so please just bear with me.
I want to implement real time input validation with Jquery on my website. Maybe I have some syntax errors in this post, but I am sure I don't have any in my real code.
This is what I have, whenever the user inputs something that's not blank the error() will be called and make a post request to the server (PHP+MySQL) to check if the input value already exists. The error() is also used again when the submit button is pressed.
This works perfectly fine before I press the submit button. If I enter something that already exists, the form will not be submitted. But if I enter something that's new, I will still get the ("exists") text even though the data still gets inserted into the database. I will always get the ("exists") after ("success"). It seems like when I submit, the .post request from the error() is made after the form's .post request. Does anyone how to solve this bug? or another way to construct this type of input validation??
Thanks
$('.unique').change(function(){
    error($(this));
});

function error(obj)
{
    var ok = true;

    if(obj.val().length == 0)
    {
        alert('This field can not be blank');
        ok = false;
    }

    else
    {
        var data = "action=check&input=" + obj.attr('name') + "&value=" + obj.val();
        $.post('database.php',
               data,
               function(reply){
                   if(reply == true)
                   {
                      alert("This " + obj.attr('name') + " already exists");
                      ok = false;
                   }
               });

    }
    return ok;
}

//When the user submits the form
$('#info').submit(function(){
    var ok = true;
    var data = 'action=insert&' + $(this).serialize();

    //Passes each input to the error()
    $('.unique').each(function{
       var temp = error($(this));
       ok = ok && temp;
    });

    if(!ok) return false;

    $.post('database.php',
           data,
           function(reply){
               alert(reply);
           });
});

<form id="info" name="info" action="" method="post">
   <input type ="text" class = "unique" id = "username" name = "username" class = "unique">
   <input type ="text" class = "unique" id = "email"    name = "email"    class = "unique">
</form>

//On the server
if(isset($_POST['action']))
{
    if($_POST['action'] == 'check')
    {
        $query = sprintf("select * from Users where %s = '%s'",
                                                                $_POST['input'],
                                                                $_POST['value']);
        $result = mysql_query($query);
        if(mysql_num_rows($result) > 0)
        { echo true;}

        else
        { echo false;}
    }
    else
    {
        $query = sprintf("insert into Users(username, email) values('%s','%s')",
                    $_POST['username'],
                    $_POST['email']);
        if(!($result = mysql_query($query)))
            die(mysql_error());

        echo 'Success';
    }
}

A: There are a couple issues that stand out immediately.
First error function is always return false.
Second $.post is asynchronous. This means it will continue on with the code execution while waiting for response from the ajax request. You can change that in jquery my using $.ajaxSetup({async:false}); prior to the $.post request.
Here's a code sample that should work correctly:
$('.unique').change(function(){
    error($(this));
});

function error(obj)
{
    var ok = true;

    if(obj.val().length == 0)
    {
        alert('This field can not be blank');
        ok = false;
    }
    else
    {
        var data = {
          action: 'check',
          input: obj.attr('name'),
          value: obj.val()
        };

        $.ajaxSetup({async:false}); // Force program execution to wait for ajax response
        $.post('database.php', data, function (reply) {
          if (reply) {
            alert("This " + obj.attr('name') + " already exists");
            ok = false;
          }
          $.ajaxSetup({async:true}); // Setup ajax to be async again
        });
    }
    return ok;
}

//When the user submits the form
$('#info').live('submit', function(e){
    e.preventDefault();
    var ok = true;

    //Passes each input to the error()
    $('.unique').each(function(){
       ok = ok && error($(this));
    });

    if (!ok) {
      return false;
    }

    $.post('database.php', 'action=insert&' + $(this).serialize(), function(r) {
      alert(reply);
    });
});

A: I had this problem in the past to. You can avoid this to prevent default behavior:
$('#info').submit(function(e){
e.preventDefault();

var ok = true;
var data = 'action=insert&' + $(this).serialize();

//Passes each input to the error()
$('.unique').each(function{
   var temp = err($(this));
   ok = ok && temp;
});

if(!ok) return false;

$.post('database.php',
       data,
       function(reply){
           alert(reply);
       });
});

This will avoid the form actually being submit. If you still want to submit it when the ajax post is okay:
$('#info').submit(function(){
  var theForm = this;
  $.post('database.php',
       data,
       function(reply){
           alert(reply);
           theForm.submit();
       });
});


text:
Q: Calling a super base class method from a derived class C# I am trying to call a Super base class method from a derived class
public class Base
{
    public virtual void TestFun()
    {
        Console.WriteLine("This is Class Base");
    }
}

public class A : Base
{
    public override void TestFun()
    {
        Console.WriteLine("This is Class A");

        base.TestFun();
    }
}

public class B : A
{
    public override void TestFun()
    {
        Console.WriteLine("This is Class B");

        base.TestFun();
    }
}

public class Program
{
    public static void Main()
    {
        Base obj = new B();

        obj.TestFun();
    }
}

I am getting the output as

*

*This is Class B

*This is Class A

*This is Class Base

I want to know how can we skip calling the function in A. That means I want to call class "Base" function from class "B"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infinite-dimensional Hilbert spaces in physical systems Can anyone give an example of when infinite-dimensional Hilbert spaces are required to describe a physical system? The standard answer to this question is yes, and I'm sure some of you will be quick to point out several clear examples:
Ex. 1: Photon number states $\left\{ |0\rangle,|1\rangle,...,|n\rangle \right\}$
Ex. 2: Harmonic oscillator number states (same as above).
Ex. 3: Continuous-variable basis of a single free particle $\left\{ |x\rangle \right\} \forall x \in \mathbb{R}$
From the infinite number of basis vectors in these examples, it is generally concluded that the dimension of the Hilbert space is also infinite.
However, it is clear that a photon number state such as $|\psi\rangle=|100\rangle$ is unphysical (to be clear, this is the Fock number state with $n=100$, not a tripartite state with one photon in one channel). If you dispute this, I would suggest you try preparing such a state in a single-mode fiber in an optics lab. For this reason, we can apply a (somewhat arbitrary) cutoff value of $n$ and recover a finite-dimensional Hilbert space.
Similarly, the cardinality of the basis set for a free particle is actually $\mathbb{N}$, not $\mathbb{R}$ (due to the properties of the function space), and although this set of orthogonal functions is infinite, we can also apply a similar cutoff for any reasonably behaved wavefunction.
Can anyone give an example of a system described by an infinite-dimensional vector space for which such a cutoff cannot be applied?

A: Isn't your Ex 3 such an example?
In any event, you might have trouble producing a pure photon state $\left|\,001\right>$, but you should have no trouble creating a coherent state.  Just turn on your laser pointer.  The coherent state is a superposition of single photon states, summing over all single photon number states.  You can't impose a cutoff.
See this Wikipedia article, in particular search for the phrase "This can be easily seen" and look at the equation that follows.

A: They are much more physical systems than you can imagine that have solutions in a Hilbert space. Most common are physical systems which are classically described by a periodic unknown function. The unknown function is developed in a Fourier series whose members are trigonometric functions that form an orthonormal complete base in a Hilbert space.
Another example is a classical distribution of particles $u(r,\varphi)$ in phase space that has circular symmetry. The dynamics of such a distribution is described by the Vlasov equation. The $\varphi$-dependence can be described by the functions $e^{im\varphi}$ with $m=-\infty,\ldots-1,0,1,\ldots\infty$. The $r$-dependence is non-periodic and a priori unknown, but can be developed in a series of Laguerre-polynomials. A scalar product can be defined. The Laguerre-polynomials form a orthonormal complete infinite basis on a vector space, which has with the scalar product and completeness all characteristics of a Hilbert space.
Such type of problems appear in physics everywhere where there is a differential equation whose solution is not right obvious to be guessed, so that the solution has to be searched in a larger function space, with a scalar product in a Hilbert space. (and the Schroedinger equation is just a example as many other classical examples.)
And in order to have complete and correct description all found modes have to be considered.


text:
Q: Difference between .next and .succ in Ruby What is the difference between Fixnum methods .next and .succ in Ruby?
It seems it works identically:
 1.next
 => 2
 1.succ
 => 2

If there is any difference why there is two method which do the same?

A: They are equivalent. Fixnum#succ is just an synonym for Fixnum#next.
They even share the same block in the reference manual.


text:
Q: Order by in relations PROPEL I have:
# config/schema.yml
propel:
  jobeet_category:
    id:           ~
    name:         { type: varchar(255), required: true, index: unique }

  jobeet_job:
    id:           ~
    category_id:  { type: integer, foreignTable: jobeet_category, foreignReference: id, required: true }
    type:         { type: varchar(255) }
    company:      { type: varchar(255), required: true }

for example:
JobeetCategory:

id | name
1  | first
2  | second

JobeetJob:

id | category_id | name
1  | 1           | bbb
2  | 1           | ccc
3  | 1           | aaa
4  | 2           | zzz
5  | 2           | xxx

and I do:
$c = new Criteria();
$categories = JobeetCategoryPeer::doSelect($c);

and I can:
foreach($categories as $category){

  echo $category->getName();
  foreach ($category->getJobeetJobs() as $job){
          echo '-' . $job->getName();
  }
}

this show me:
 first
 - bbb
 - ccc
 - aaa
 second
 - zzz
 - xxx

but I would like have this sorted ASC by NAME:
 first
 - aaa
 - bbb
 - ccc
 second
 - xxx
 - zzz

how can I make it with PROPEL QUERY?

A: It would have been easier if you had mentioned the version of symfony and propel you're using. But here's something that might work hope it helps.
$categories = JobeetCategoryQuery::create()
                            ->addJoin(JobeetJobPeer::CATEGORY_ID, JobeetCategoryPeer::ID)
                            ->addAscendingOrderByColumn(JobeetJobPeer::NAME)
                            ->find();

Just incase Query doesn't exist, you could use criteria for the purpose.
  $criteria = new Criteria();
  $criteria->addJoin(JobeetJobPeer::CATEGORY_ID, JobeetCategoryPeer::ID)
                        ->addAscendingOrderByColumn(JobeetJobPeer::NAME);
  $categories = JobeetCategoryPeer::doSelect($criteria);

A: I know this is an old question, but wanted to give an updated way to do this. You can pass a query object into your getter:
foreach($categories as $category){
  echo $category->getName();
  $q = JobeetJobQuery::create()->orderByName();
  foreach ($category->getJobeetJobs($q) as $job){
          echo '-' . $job->getName();
  }
}

A: $c = new Criteria();
$c->addJoin(JobeetJobPeer::CATEGORY_ID, JobeetCategoryPeer::ID, Criteria::INNER_JOIN);
$c->addAscendingOrderByColumn(JobeetJobPeer::NAME);

$categories = JobeetCategoryPeer::doSelect($c);

But jobeet_job do not have a column name. Are you using a custom getter for $job->getName() ?


text:
Q: "DenseToSparseBatchDataset" device_type: "CPU" for unknown op: DenseToSparseBatchDataset After a lot of fiddling, tensorflow built from sources and installed into Python 3.5 (it didn't seem to like 3.6) and now a Keras program runs in the notebook without any complaining from tensorflow as before, something was not installed to standards. But, it does seem to use the CPU heavily:

and the GPU lightly:
$ nvidia-smi
Fri Nov 10 18:13:11 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.26                 Driver Version: 375.26                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 105...  Off  | 0000:01:00.0      On |                  N/A |
|  0%   49C    P0    36W /  72W |   3740MiB /  4030MiB |     28%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      2283    G   /usr/lib/xorg/Xorg                             273MiB |
|    0      3411    G   cinnamon                                       155MiB |
|    0     14388    C   /storageHDD/tensorflow/bin/python3            3307MiB |
+-----------------------------------------------------------------------------+

From the messages in the output of the jupyter kernel it looks like it has made a conscious decision to use the CPU rather than the GPU:
[I 17:20:45.588 NotebookApp] Adapting to protocol v5.1 for kernel a3c0afcc-e525-48e5-8f54-75a349214f96
2017-11-10 17:20:50.857309: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-11-10 17:20:50.857625: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1061] Found device 0 with properties:
name: GeForce GTX 1050 Ti major: 6 minor: 1 memoryClockRate(GHz): 1.43
pciBusID: 0000:01:00.0
totalMemory: 3.94GiB freeMemory: 3.45GiB
2017-11-10 17:20:50.857643: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1151] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
2017-11-10 17:21:43.862726: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DenseToSparseBatchDataset" device_type: "CPU"') for unknown op: DenseToSparseBatchDataset
2017-11-10 17:21:43.862770: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "GroupByWindowDataset" device_type: "CPU"') for unknown op: GroupByWindowDataset
2017-11-10 17:21:43.862783: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "IgnoreErrorsDataset" device_type: "CPU"') for unknown op: IgnoreErrorsDataset
2017-11-10 17:21:43.862803: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DatasetToSingleElement" device_type: "CPU"') for unknown op: DatasetToSingleElement
2017-11-10 17:21:43.862817: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "SerializeIterator" device_type: "CPU"') for unknown op: SerializeIterator
2017-11-10 17:21:43.862836: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DeserializeIterator" device_type: "CPU"') for unknown op: DeserializeIterator
2017-11-10 17:21:43.862845: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "MapAndBatchDataset" device_type: "CPU"') for unknown op: MapAndBatchDataset
2017-11-10 17:21:43.862867: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "ParallelInterleaveDataset" device_type: "CPU"') for unknown op: ParallelInterleaveDataset
2017-11-10 17:21:43.862891: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "ScanDataset" device_type: "CPU"') for unknown op: ScanDataset
2017-11-10 17:21:43.862910: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "SqlDataset" device_type: "CPU"') for unknown op: SqlDataset
2017-11-10 17:21:45.342326: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1151] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
2017-11-10 17:21:45.621793: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/batchnorm/add_grad/BroadcastGradientArgs-0 is not in the graph.
2017-11-10 17:21:45.621852: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/batchnorm/add_grad/BroadcastGradientArgs-1 is not in the graph.
2017-11-10 17:21:45.622311: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/cond/batchnorm/sub_grad/BroadcastGradientArgs-0 is not in the graph.
2017-11-10 17:21:45.622332: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/cond/batchnorm/sub_grad/BroadcastGradientArgs-1 is not in the graph.
2017-11-10 17:21:45.622394: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/batchnorm/sub_grad/BroadcastGradientArgs-0 is not in the graph.
2017-11-10 17:21:45.622411: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_1/batchnorm/sub_grad/BroadcastGradientArgs-1 is not in the graph.
2017-11-10 17:21:45.622470: W tensorflow/core/grappler/utils.cc:48] Node ConstantFolding/training/Adam/gradients/batch_normalization_2/batchnorm/add_grad/BroadcastGradientArgs-0 is not in the graph.

What is the meaning of all those lines containing device_type: "CPU" ?
Does anyone know if that is normal or if it is perhaps a sign that a dependency is missing somewhere?

A: The following lines containing warning messages were accidentally added by a recent change:
2017-11-10 17:21:43.862726: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DenseToSparseBatchDataset" device_type: "CPU"') for unknown op: DenseToSparseBatchDataset
2017-11-10 17:21:43.862770: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "GroupByWindowDataset" device_type: "CPU"') for unknown op: GroupByWindowDataset
2017-11-10 17:21:43.862783: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "IgnoreErrorsDataset" device_type: "CPU"') for unknown op: IgnoreErrorsDataset
2017-11-10 17:21:43.862803: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DatasetToSingleElement" device_type: "CPU"') for unknown op: DatasetToSingleElement
2017-11-10 17:21:43.862817: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "SerializeIterator" device_type: "CPU"') for unknown op: SerializeIterator
2017-11-10 17:21:43.862836: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "DeserializeIterator" device_type: "CPU"') for unknown op: DeserializeIterator
2017-11-10 17:21:43.862845: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "MapAndBatchDataset" device_type: "CPU"') for unknown op: MapAndBatchDataset
2017-11-10 17:21:43.862867: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "ParallelInterleaveDataset" device_type: "CPU"') for unknown op: ParallelInterleaveDataset
2017-11-10 17:21:43.862891: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "ScanDataset" device_type: "CPU"') for unknown op: ScanDataset
2017-11-10 17:21:43.862910: E tensorflow/core/framework/op_kernel.cc:1142] OpKernel ('op: "SqlDataset" device_type: "CPU"') for unknown op: SqlDataset

That change has since been reverted, and the warning messages should no longer be printed.


text:
Q: Stopping a request in Tornado I have a method for signing up a user, basically if the user fails
validation I want the request to stop processing so the user isn't
signed up.
def post(self):
       #[...]
       if isvalid(username) == False:
           print "Invalid Username"
           self.redirect("/badusername")

       print "User Is OK"

If I enter a valid username, 'User Is OK' is printed to the console
and everything is dandy, but if I use an invalid username, 'Invalid
Username' AND 'User Is OK' is printed to the console, the page re-
directs correctly though. How do I stop the request after
self.redirect so print "User Is OK" is never called?

A: def post(self):
       #[...]
       if isvalid(username) == False:
           print "Invalid Username"
           self.redirect("/badusername")
       else:
           print "User Is OK"

A: Just do a return, like this:
def post(self):
       #[...]
       if not isvalid(username):
           print "Invalid Username"
           return self.redirect("/badusername")

       print "User Is OK"

A: def post(self):
   #[...]
   if isvalid(username) == False:
       print "Invalid Username"
       self.redirect("/badusername")
       return

   print "User Is OK"


text:
Q: Generated resource output not found in test classpath in gradle build I am attempting to configure a gradle (version 4.6) build (as a part of a multi-module project) that uses a Java "script" to generate resources into the main sourceSet, which are then referenced in my test configuration. The idea is that I'd ultimately like to create a jar that is simply a resource bundle for inclusion in another module of my build, but I have java files both to generate these resources and to execute verification tests on them before packaging.
I currently have three sourceSets configured: the standard "main" and "test", and a custom sourceSet "generator" which holds resources used as inputs to the generator "script" and the source for the generator script itself. I've registered a main output directory according to this documentation (see "working with generated resources"), pointing to a JavaExec class that runs the generator with the "generator" sourceSet runtime classpath to output resources into the main classpath.
All of this appears to work- I can find the output in the correct directory when running :<module>:build, showing that the script is both running properly and that it is done as a dependency to the main compile task. However, when I try to reference the generated output in the tests with getClass().getClassLoader().getResource("<baseGeneratedOutputDirectory>"), I get a null value back, suggesting that my generated output is not being included in the test runtime classpath. The documentation clearly states that the...

Java plugin will use those dirs in calculating class paths and for jarring the content

...so I'm not sure why my files aren't getting picked up. Below is my abridged build.gradle file. Note that I'm overriding the generator task type in order to set it up with build caching, but I still see this bug with caching turned off.
apply plugin: 'java-library'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    generator {
        java.srcDirs = ['src/generator/java']
        resources.srcDirs = ['src/generator/resources']
    }
    main {
        java
        resources
        output.dir("$buildDir/generated-files/main", builtBy: 'generateConfig')
    }
    test {
        java
        resources
    }
}

dependencies {
    api project(':server:server_protobuf_classes');
    api project(':common:game-config-util')
    api 'com.google.protobuf:protobuf-java:3.5.1'

    generatorImplementation project(':common:game-config-util')
    generatorImplementation project(':server:server_protobuf_classes');
    generatorImplementation group: 'commons-io', name: 'commons-io', version: '2.5'
    // ...

    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'
    testCompile group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
    // ...
}

task generateConfig(type: GenerateConfig) {
    outputs.dir("$buildDir/generated-files/main")

    classpath sourceSets.generator.runtimeClasspath
    main = "com.project.ProtobufConfigurationProcessor"
}

@CacheableTask
class GenerateConfig extends JavaExec {
}

EDIT: Adding the following makes the tests pass, but I'm confused why I'd need to manually configure the test resource directory like this. Shouldn't the test task pick up build output from the main source set by default?
sourceSets {
    test {
        resources.srcDirs = ["$buildDir/generated-files/main"]
    }
}


text:
Q: Not able to load keras model on nodejs platform I am trying to create a simple web app that contains my trained model on mnist dataset and it predicts the number that is drawn on the canvas but I am not able to load the model, I have converted the model into json format .
My directory for the project is like this :
./Project
    local-server/
      -server.js
    static/
       model/
         -model.json
       predict-with-tfjs.html
       predict.js

server.js
const express = require("express");
const app = express();
const port = 3000;
const tf=require('@tensorflow/tfjs')

app.use(express.static("../static"));

app.set("view engine", "html");
app.get("/", function (req, res) {
  res.sendFile(__dirname+'predict-with-tfjs.html')
});

app.get("/dog", (req, res) => res.send("This is a dog page"));
app.listen(3000, () => console.log(`App listening at http://localhost:3000`));

predict.js

let model;
(async function () {
    model = await tf.loadModel("http://localhost:3000/predict-with-tfjs.html/model/model.json");
    console.log(model)
})();
console.log(model)

The model is not able to load and I have searched every possible solution.

A: You should probably use __dirname and path.join
app.use(express.static(path.join(__dirname, '../static')));

A: 1.require '@tensorflow/tfjs-node' -> require('@tensorflow/tfjs-node')

*if it still doesnt work, you can try 'file://' protocol

*assuming you created model.json using tensorflowjs_converter , Use tf.loadGraphModel('file://.....')
Hope it helps.


text:
Q: How can I set the each line color or width in SVG path I use the path to crate a Triangle,
svg.append("path").attr("d","M " + x(0) + "," + y(0) + " L " + x(1) + "," + y(1) + " " + x(-1) + "," + y(1) + " " + x(0) + "," + y(0) ).style({
    stroke: 'black',
    'stroke-width': 1,
    fill: 'red'
});

How can I set the stroke color or width for each line?
thanks.

A: As @Lars said, you need to use separate path elements. Also, you could use a line generator so you don't have to create the path strings by hand.
var data = [
    {p: [{x: 100, y: 100}, {x: 200, y: 100}], w: 2, c: 'red'},
    {p: [{x: 100, y: 100}, {x: 150, y: 200}], w: 3, c: 'blue'},
    {p: [{x: 150, y: 200}, {x: 200, y: 100}], w: 1, c: 'green'}
];

// Line generator
var line = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

svg.selectAll('path')
   .data(data)
   .enter().append('path')
   .attr('d', function(d) { return line(d.p); })
   .attr('stroke-width', function(d) { return d.w; })
   .attr('stroke', function(d) { return d.c; });

I wrote a small fiddle here: http://jsfiddle.net/pnavarrc/9Qqy8/


text:
Q: PostgreSQL: How to return multiple row in subquery and find percentage for each individual row? This query is supposed to find the percentage of error occured on particular  date but i am getting same percentage for all dates. Is there any way to return multiple rows from subquery.
select date(time) as day , ((select date(time) as day, from
 log where status != '200 OK')/(select date(time) as day from log )) as views from
 log group by day;

A: Try this:
select
  date(time) as day,
  ((count(*) filter(where status!=200)) /
  count(*)::decimal(5,2))::decimal(5,2)
from log
group by day

A: Try this
select date(time) as day , count(1) / tot_err as views
From log, (Select count(1) as tot_err from log where status != '200 OK')
Where status != '200 OK'
group by day;


text:
Q: How to declare new generic within a parameter of a TypeScript function? Essentially, I want to remap an object using Record, but I'm not sure how I can access the type of the value. For example, I want something like this:
const testFunc = <S>(mappedObj: Record<A extends keyof S, S[A]>) => { ... }

The problem is I can't declare a new generic (A) inside of a parameter. But I need some way to know the type of the key so I can determine the type of the value.

A: You have to use mapped type directly in this case.
const testFunc = <S>(mappedObj: { [P in keyof S]: S[P] }) => { ... }


text:
Q: Jenkins Email policy setup Jenkins newbie here.
I am using editable email plugin for emails being sent out of jenkins jobs.
The policy is:

*

*Always send an email to admin irrespective of job status

*Send email to anyone who breaks the build (can be someone outside the team)

*Send email to whole team when build breaks or gets fixed

Is there a way to achieve this?

A: Install Email Extension Plugin.
On the Job configuration page
Add post-build action "Editable Email Notification"
Add Trigger "Always" and in advanced section set you email address in Recipient List - this will send you an email all always
Add Trigger "Failure - Any", "Fixed", "Success", "Unstable" - this will send email to people in the default Recipient list
Hope this helps!


text:
Q: Azure Functions Dependency Injection - Registering Custom Services I'm trying to do DI in Azure Functions V2 with my service but even after reading the documentation I'm not understanding how to register a service with parameters.
In the example below I want to use the built-in Logger and the DB context within CustomService and the CustomService within SpecialService. These are in the constructors of the respective services, i.e. CustomService(IMyContext context, ILogger logger) and SpecialService(ICustomService customService).
Startup.cs:
[assembly: FunctionsStartup(typeof(Startup))]
namespace AzFunction.IoC
{
    class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddLogging();

            var connectionString = "test-conn-string";
            var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            builder.Services.AddDbContext<MyDbContext>(
                options => options.UseSqlServer(connectionString));

            builder.Services.AddScoped<ICustomService, CustomService>();

            builder.Services.AddScoped<ISpecialSerivce, SpecialService>();
        }
    }
}

It compiles and and hits the breakpoints with in startup.cs but does not seem to be able to find the services that are registered.
The error:

Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'customService' to type ICustomService. Make sure the parameter Type is supported by the binding.

A: I was trying to inject into the Azure functions parameters instead of the constructor, here is the correct way:
public class GreatClass
    {
        private ICustomService _customService;

        public GreatClass(ICustomService customService)
        {
            _customService = customService;
        }

        [FunctionName("MyFunc")]
        public async Task Run([TimerTrigger("%RunFrequency%", RunOnStartup = true)]TimerInfo myTimer,
            // ICustomService customService, // Incorrect!
            ILogger log)
        {
            //Logic
        }
    }


text:
Q: Javascript - getImageData on canvas always returns alpha 255 I am trying to read the alpha values in an image with javascript and canvas, but the alpha part of the ImageData returned by getImageData is always 255 even if the processed image only consists of transparent pixels. This is what i did:
var img = new Image();
img.src = "url/to/an/image/with/transparency";
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var data = context.getImageData(0, 0, img.width, img.height).data;
for(var i = 0; i<data.length; i+=4){
    console.log(data[i+3]);
}

This always outputs 255. I already found this, but it didn't really help me:
newbie keeps losing alpha values in canvas
No matter what i try, it wont work.
EDIT: This is my full code: http://pastebin.com/3giQCWvP
The mistakes occur inside the generateCollisionGrid() function. I found out that red and green are also always 255.
This is the image i used for testing: https://addons.opera.com/media/extensions/03/1303/1.4-rev1/icons/icon_64x64.png

A: I had the same issue and found that I needed to set the context.globalCompositeOperation = "copy" to ensure that the alpha overrode the destination data.

A: There are several possible issues with your code:

*

*The image might not really be transparent.

*The image might not be fully loaded when you try to draw it. Use img.onload to wait until the img is fully loaded before trying to draw it.

*When you createElement('canvas') the default size of the canvas is 300x150 so your image is probably larger or smaller than the default canvas size. Use canvas.width=img.width & canvas.height=img.height to set the canvas size to the img size.

*If the image URL is from a different domain than the web page then a security error will be raised. This error condition will prevent .getImageData from returning data.

Here's your code refactored to avoid those issues:

var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/icon_64x64.png";
function start(){

    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    canvas.width=img.width;
    canvas.height=img.height;
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0);
    var data = context.getImageData(0, 0, img.width, img.height).data;
    var alphas=''; // demo purposes
    for(var i = 0; i<data.length; i+=4){
        console.log(data[i+3]);
        if(i<200){alphas+=data[i+3]+',';} // demo purposes
    }

    alert(alphas); // demo purposes
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }


text:
Q: Hide the tab bar in a tab bar application I have created a new project from the template:
IPhoneOS>Application>Tab Bar Application.
I get two tabs.
How can I make the second become a full screen hiding the tab bar and even the status bar?
I tried to check the "Wants Full screen" - but it didn't help.
(Much less important... When I do get a full screen I do I get back?)
Please give me a simple code/guidelines or a reference to them, cause I'm a beginner - and Me and the compiler got too many issues to make things worse
Thanks
Asaf

A: To hide the tab bar you can use hidesBottomBarWhenPushed. For instance:
MyController *myController = [[MyController alloc]init];
myController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:myController animated:YES];
[myController release];

To hide the status bar you can use:
[[UIApplication sharedApplication] setStatusBarHidden:YES];

To hide the nav bar you can use:
self.navigationController.navigationBarHidden = YES;

A: You can just use:
//Navigation bar:
self.navigationController.navigationBarHidden = YES;

//Statusbar:
[[UIApplication sharedApplication] setStatusBarHidden:YES];

//Tabbar:
self.tabBarController.tabBar.hidden = YES;

A: Have you checked Modal View Controllers out?
http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/ModalViewControllers/ModalViewControllers.html
Try the presentModalViewController:animated: method on your navigationController (instead of pushing a view controller)
[self.navigationController presentModalViewController:foo animated:YES];

A: Another way to accomplish this is by making the UITabBarController the rootViewController of a UINavigationController.  Then when you pushViewControllerAnimated: the tab bar will slide away with the root view controller.


text:
Q: Dimension formula for exact sequence of finite dimensional k-vector space I have two questions regarding the following problem and the solution to it.

Let $k$ be a field and $0 \to M_0 \to ... \to M_n \to 0$ be an exact sequence of finite dimensional $k$-vector spaces and $k$-linear maps. Prove that $\sum_{i=0}^n (-1)^i \dim_k(M_i)=0$.
Solution: Denote $d_i$ for the map $d_i: M_i \to M_{i+1}$. The long exact sequence splits into short exact sequences $0 \to \ker(d_i) \to M_i \to \operatorname{im}(d_i) \to 0$. By using the dimension formula for linear maps of finite dimensional vector spaces and the fact $\ker(d_{i+1})= \operatorname{im} (d_i)$, we conclude that $\dim(\ker(d_{i+1}))+\dim(\ker(d_{i}))=\dim(M_i).$
Thus, $\sum_{i=0}^n (-1)^i \dim_k(M_i)=\dim(\ker(d_{0}))+\dim(\ker(d_{n+1})=0$.

1.) How do they come to the short exact sequence above in the solution? Shouldn't the short exact sequence be $0 \to \ker(d_{i-1}) \to M_i \to \operatorname{im}(d_i)$?
2.) Why is $\dim(\ker(d_{0}))+\dim(\ker(d_{n+1}))=0$
Everything else I have understood, so far, but I don't get these two points.
It would be great if someone could explain this to me.
Thanks!

A: 1) No. It comes from the canonical decomposition of a homomorphism:
$$\begin{matrix}\ker d_i\hookrightarrow M_i&\xrightarrow[\qquad\quad]{d_i}&M_{i+1}\\[-21ex]
&\searrow\qquad\nearrow\\
&\operatorname{im}d_i
\end{matrix}$$
2) Simply because $\ker d_0=\{0\}$, and $d_{n+1}$ doesn't really exist: its domain would be $\{0\}$, hence if we take it to have codomain any vector space, say $\{0\}$ to make it simple, anyway its kernel has dimension $0$.


text:
Q: elasticsearch nested document query I'm new to elasticsearch, well have some idea on how to go about doing filters, queries, and aggregation but not sure how to solve this following problem below.
I'm want to be able to query only the most recent deliveries (date and crate_quantity) of companies from the document shown below. I'm not sure how to go about doing it. Is there a way to use max aggregation to pull only the most recent deliveries from each document?
POST /sanfrancisco/devlivery
{
"company1": {
    "delivery": [
        {
            "date": "01/01/2013",
            "crate_quantity": 5
        },
        {
            "date": "01/12/2013",
            "crate_quantity": 3
        },
        {
            "date": "01/24/2013",
            "crate_quantity": 2
        }
    ]
}
}

POST /sanfrancisco/devlivery
{
"company2": {
    "delivery": [
        {
            "date": "01/01/2015",
            "crate_quantity": 14
        },
        {
            "date": "12/31/2014",
            "crate_quantity": 20
        },
        {
            "date": "11/24/2014",
            "crate_quantity": 13
        }
    ]
}
}

A: If you want the latest delivery for one company at a time, I would probably set it up using a parent/child relationship. I used company as the parent and delivery as the child.
I also added a custom date format so that your dates will be sorted the way you're expecting.
I set up the index like this:
DELETE /test_index

PUT /test_index
{
   "settings": {
      "number_of_shards": 1,
      "number_of_replicas": 0
   },
   "mappings": {
      "company": {
         "properties": {
            "name": {
               "type": "string",
               "index": "not_analyzed"
            }
         }
      },
      "delivery": {
         "_parent": {
            "type": "company"
         },
         "properties": {
            "crate_quantity": {
               "type": "long"
            },
            "date": {
               "type": "date",
               "format": "MM/dd/yyyy"
            }
         }
      }
   }
}

then indexed the documents using the bulk api:
PUT /test_index/_bulk
{"index": {"_index":"test_index", "_type":"company", "_id":1}}
{"name":"company1"}
{"index": {"_index":"test_index", "_type":"delivery", "_id":1, "_parent":1}}
{"date": "01/01/2013", "crate_quantity": 5}
{"index": {"_index":"test_index", "_type":"delivery", "_id":2, "_parent":1}}
{"date": "01/12/2013", "crate_quantity": 3}
{"index": {"_index":"test_index", "_type":"delivery", "_id":3, "_parent":1}}
{"date": "01/24/2013",  "crate_quantity": 2}
{"index": {"_index":"test_index", "_type":"company", "_id":2}}
{"name":"company2"}
{"index": {"_index":"test_index", "_type":"delivery", "_id":4, "_parent":2}}
{"date": "01/01/2015", "crate_quantity": 14}
{"index": {"_index":"test_index", "_type":"delivery", "_id":5, "_parent":2}}
{"date": "12/31/2014",  "crate_quantity": 20}
{"index": {"_index":"test_index", "_type":"delivery", "_id":6, "_parent":2}}
{"date": "11/24/2014",  "crate_quantity": 13 }

Now I can query for the latest delivery for a particular company by using a has_parent filter, sorting on date, and only accepting a single result, as follows:
POST /test_index/delivery/_search
{
   "size": 1,
   "sort": [
      {
         "date": {
            "order": "desc"
         }
      }
   ],
   "filter": {
      "has_parent": {
         "type": "company",
         "query": {
            "term": {
               "name": {
                  "value": "company1"
               }
            }
         }
      }
   }
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": null,
      "hits": [
         {
            "_index": "test_index",
            "_type": "delivery",
            "_id": "3",
            "_score": null,
            "_source": {
               "date": "01/24/2013",
               "crate_quantity": 2
            },
            "sort": [
               1358985600000
            ]
         }
      ]
   }
}

Here is the code I used while experimenting with this:
http://sense.qbox.io/gist/c519b0654448c8b7b0c7c85d613f1e88c0ad1d19


text:
Q: Understanding FeathersJS hooks I'm following the tutorial. In Asynchronous hooks, there's a snippet like this:
todoService.before({
  find(hook) {
    return this.find().then(data => {
      hook.params.message = 'Ran through promise hook';
      hook.data.result = data;
      // Always return the hook object
      return hook;
    });
  }
});

Would you please let me know what this.find() is supposed to do?

A: find is a Feathers service method and this is the service the hook is running on.


text:
Q: Recaptcha enterprise - key for mobile - waiting for security review we already have a reCAPTCHA Enterprise key for the web app.  Now we need to create a reCAPTCHA key for our mobile app.   We applied for security review many days ago... how long does it take for google to contact us and to perform a security review?   We need to launch our app very shortly, but still waiting for Google.
Thank you!


text:
Q: Eclipse - error executable jar file When I use the eclipse function export - executable jar etc ...
I get a message when It's making the jar
JAR export finished with warning. See details ...
Details : Could not read JAR file '.classpath'. Reason : error in opening zip file.
I have no idea what this means and what I need to do to solve this ...
Anyone an idea?
thx all

A: When you are packaging your application with the Runnable Jar File, this message is usually associated with some kind of permission issue on a %TEMP% directory.

Check also if the option to generate a script display the same behavior when executed.


text:
Q: Detect mouse click on circle that is on different surface How can I check if circle on separate surface is clicked?
from pygame.locals import *
import pygame, sys, math

pygame.init()
screen = pygame.display.set_mode((640, 480))

s = pygame.Surface((100, 100))
s.fill((255, 0, 0))
s_rect = s.get_rect(center = (300, 300))

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:

            x = pygame.mouse.get_pos()[0]
            y = pygame.mouse.get_pos()[1]

            sqx = (x - 20)**2
            sqy = (y - 20)**2

            if math.sqrt(sqx + sqy) < 20:
                print ('inside')

    screen.fill((200, 200, 255))
    screen.blit(s, s_rect)
    pygame.draw.circle(s, (0, 0, 0), (20, 20), 20) # this doesn't work

    pygame.draw.circle(screen, (0, 0, 0), (20, 20), 20) # this works

    pygame.display.update()

pygame.quit()

Nothing happens when I run this code. However if I draw the circle on the main screen it works!!!

A: You have to compute the mouse position relative to the Surface.
You have 2 possibilities. Either subtract the (top left) position of the Surface on the screen from the mouse position:
x = event.pos[0] - s_rect.left
y = event.pos[1] - s_rect.top

Or add the (top left) position of the Surface on the screen to the center point of the circle:
sqx = (x - (s_rect.left + 20))**2
sqy = (y - (s_rect.top + 20))**2

Complete example

from pygame.locals import *
import pygame, math

pygame.init()
screen = pygame.display.set_mode((640, 480))

s = pygame.Surface((100, 100))
s.fill((255, 0, 0))
s_rect = s.get_rect(center = (300, 300))
clicked = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:

            x = event.pos[0]
            y = event.pos[1]

            sqx = (x - (s_rect.left + 20))**2
            sqy = (y - (s_rect.top + 20))**2

            if math.sqrt(sqx + sqy) < 20:
                clicked = not clicked
                print ('inside')

    screen.fill((200, 200, 255))
    color = (255, 255, 255) if clicked else (0, 0, 0)
    pygame.draw.circle(s, color, (20, 20), 20)
    screen.blit(s, s_rect)
    pygame.display.update()

pygame.quit()


text:
Q: How to make an inside div with text to be responsive I have a parent div with a responsive background image. Inside the parent div I have a child div with some text in it. I want the text inside the child div, and the child div itself, to be responsive too.
Don't want to do that with the table attribute.
Is there any other solution?
here is an example

A: demo - http://jsfiddle.net/victor_007/xb548oqt/2/
use  instead of background-image

.parent {
  position: absolute;
  width: 100%;
  height: auto;
}
.parent img {
  width: 100%;
  height: auto;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 0;
  transform: translate(-50%, -50%);
  background-color: orange;
  padding: 1.2em;
  font-size: .5em;
}

some text

A: I am not quite sure, what your issue is, but as long as you don't use anything like white-space: nowrap; a DIV with some text should be responsive by default. Just set the DIV to width: 100%; (which is the default) and you should be fine.

A: I'm not sure what you mean by responsive here, but looking at your example I think you may be looking for background-size: cover;. Something like this: http://jsfiddle.net/xb548oqt/1/


text:
Q: Flutter firebase version solving failed in flutter 2.8.1 Because firebase_auth 0.16.0 depends on firebase_auth_web ^0.1.1 which depends on http_parser ^3.1.3, firebase_auth 0.16.0 requires http_parser ^3.1.3.
And because flutter_paystack >=1.0.5+1 depends on http ^0.13.1 which depends on http_parser ^4.0.0, firebase_auth 0.16.0 is incompatible with flutter_paystack >=1.0.5+1.
So, because flutter_sell_app depends on both firebase_auth 0.16.0 and flutter_paystack ^1.0.5+1, version solving failed.
My pubspec.yaml
  cupertino_icons: ^1.0.0
  country_list_pick: ^1.0.1+2
  bottom_navy_bar: ^5.4.0
  cached_network_image: ^2.4.1
  carousel_slider: ^3.0.0
  flutter_html: 0.11.1
  flutter_rating_bar: ^3.2.0+1
  another_flushbar: ^1.10.10
  image_picker:
  shared_preferences: ^0.5.4+6
  carousel_pro: ^1.0.0
  flutter_staggered_animations: ^1.0.0
  flutter_credit_card: ^0.1.3
  mask_text_input_formatter: ^1.0.5
  progress_dialog: ^1.2.1
  rxdart: ^0.25.0
  # stripe_payment: ^1.1.4
  # flutter_facebook_login: ^3.0.0
  google_sign_in: ^4.5.1
  multi_image_picker: ^4.8.0
  flutter_absolute_path:
    git:
      url: https://github.com/canewsin/flutter_absolute_path.git
  #path_provider: ^2.0.1
  fluttertoast: ^7.1.8
  flutter_staggered_grid_view: ^0.3.3
  transparent_image: ^1.0.0
  google_fonts:
  webview_flutter: ^2.0.2
  toast: ^0.1.5
  cloud_firestore: any
  firebase_auth: 0.16.0
  firebase_database: ^3.0.7
  firebase_storage: ^3.1.3
  firebase_messaging: 6.0.13
  photo_view: ^0.9.2
  place_picker:
  geolocator: ^5.1.5
  google_maps_flutter:
  permission_handler:
  timeago: ^2.0.26
  flutter_paystack: ^1.0.5+1
  sign_in_with_apple: ^3.0.0
  flutter_image_compress: ^1.0.0
  flutter_countdown_timer: ^4.1.0
  dio:
  flutter_datetime_picker: ^1.5.1
  maps_launcher: ^2.0.1
  readmore: ^2.1.0
  like_button: ^2.0.2
  clay_containers: ^0.3.2
  country_code_picker: ^2.0.2

A: Please use the older version of flutter_paystack as ^1.0.5+1 version of ^1.0.5+1 depends on latest version of http_parser and firebase_auth: 0.16.0 depends on older version of http_parser. You can use ^1.0.0 or older version of flutter_paystack to solve your issue


text:
Q: what's wrong with this simple bash command? $i is not working... it's making me crazy!
for i in {1..200};
do echo "/scratch/inputTest/prob/timit.test.pg.list_10_$i_prob.bin" >> longProbList;
done

in the file there is just
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin
/scratch/inputTest/prob/timit.test.pg.list_10_.bin

A: It thinks your variable name is $i_prob since an underscore is a valid character for a variable name. Use ${i} to fix this:
for i in {1..200};
do echo "/scratch/inputTest/prob/timit.test.pg.list_10_${i}_prob.bin" >> longProbList;
done

A: You've forgotten the " " around $i
for i in {1..200};
do echo "/scratch/inputTest/prob/timit.test.pg.list_10_"$i"_prob.bin" >> longProbList;
done


text:
Q: Exploding multiple array columns in spark for a changing input schema in PySpark I have the same situation as stated in this question.
df = spark.createDataFrame(
    [(1, "xx", [10, 20], ["a", "b"], ["p", "q"]),
     (2, "yy", [30, 40], ["c", "d"], ["r", "s"]),
     (3, "zz",     None, ["f", "g"], ["e", "k"])],
    ["c1", "c2", "a1", "a2", "a3"])
df.show()
# +---+---+--------+------+------+
# | c1| c2|      a1|    a2|    a3|
# +---+---+--------+------+------+
# |  1| xx|[10, 20]|[a, b]|[p, q]|
# |  2| yy|[30, 40]|[c, d]|[r, s]|
# |  3| zz|    null|[f, g]|[e, k]|
# +---+---+--------+------+------+

I can't figure out a way to explode it correctly in PySpark. How I can achieve this result?
+---+---+----+---+---+
| c1| c2|  a1| a2| a3|
+---+---+----+---+---+
|  1| xx|  10|  a|  p|
|  1| xx|  20|  b|  q|
|  2| yy|  30|  c|  r|
|  2| yy|  40|  d|  s|
|  3| zz|null|  f|  e|
|  3| zz|null|  g|  k|
+---+---+----+---+---+

A: The following should do it for dynamic number of array columns.
Spark 3:
from pyspark.sql import functions as F

arr_cols = [c[0] for c in df.dtypes if c[1][:5] == "array"]
df = df.withColumn(
    "arr_of_struct",
    F.arrays_zip(*[F.coalesce(c, F.array(F.lit(None))).alias(c) for c in arr_cols])
).select(
    *[c for c in df.columns if c not in arr_cols],
    F.expr("inline(arr_of_struct)")
)

df.show()
# +---+---+----+---+---+
# | c1| c2|  a1| a2| a3|
# +---+---+----+---+---+
# |  1| xx|  10|  a|  p|
# |  1| xx|  20|  b|  q|
# |  2| yy|  30|  c|  r|
# |  2| yy|  40|  d|  s|
# |  3| zz|null|  f|  e|
# |  3| zz|null|  g|  k|
# +---+---+----+---+---+

Spark 2:
from pyspark.sql import functions as F

arr_cols = [c[0] for c in df.dtypes if c[1][:5] == "array"]
df = df.withColumn(
    "my_struct",
    F.explode(F.arrays_zip(*[F.coalesce(c, F.array(F.lit(None))) for c in arr_cols]))
).select(
    *[c for c in df.columns if c not in arr_cols],
    *[F.col(f"my_struct.{i}").alias(c) for i, c in enumerate(arr_cols)]
)


text:
Q: Finding the percentage in my while loop isn't working correctly. Is nested while loop ok? I am trying to learn java while loops. I'm trying to make a program that will count passing test scores from a group of students and output the total number of scores inputted, the number of passing tests with a score above 69, and display the percentage of tests that passed.
The problem I am running into is I can't seem to get the percentage to output correctly. It keeps displaying 0.0. The following is the best code I came up with so far.
Is it good coding style to have a nested while loop? Is there a simpler way to shorten my program? Thanks
    import java.util.Scanner;
    import java.text.DecimalFormat;

    public class CountPassingScores {

     public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // Formats the percentage output to one decimal place.
        DecimalFormat df = new DecimalFormat("###,##0.0");

        // counts how many times a score is entered. Passing score is not
        // considered here.
        int count = 0;
        // The score the user enters.
        int score = 0;
        // percent of the class that passed the test. Passing score is 70 and
        // above.
        double percentOfClassPassed = 0.0;
        // total number of tests passed. Passing score is 70 and above.
        int numberOfTestsPassed = 0;

        System.out.println("This program counts the number of passing "
                + "test scores. (-1 to quit)\n");

        while (score != -1) {
            System.out.print("Enter the first test score:  ");
            score = scan.nextInt();

            while (count != -1 && score > 0) {
                System.out.print("Enter the next test score:  ");
                score = scan.nextInt();
                count++;

                if (count == -1)
                    break;
                else if (score > 69)
                    numberOfTestsPassed++;
                percentOfClassPassed = (numberOfTestsPassed / count);
            }

        }

        System.out.println("\nYou entered " + count + " scores.");
        System.out.println("The number of passing test scores is "
                + numberOfTestsPassed + ".");
        System.out.println(df.format(percentOfClassPassed)
                + "% of the class passed the test.");
    }
}

A: That's because you are dividing an int from an int. Which will result in an int only.
To get proper result, cast any one to double.
percentOfClassPassed = ((double) numberOfTestsPassed / count);

A: Your code doesn't consider 92 as a test passed score as you haven't incremented the value of numberOfTestsPassed in your first while loop. Hereby are a few changes I made in your code snippet:
    while (score != -1) {
        System.out.print("Enter the first test score:  ");
        score = scan.nextInt();
        if(score > 69)
        numberOfTestsPassed++;
        while (count != -1 && score > 0) {
            System.out.print("Enter the next test score:  ");
            score = scan.nextInt();
            count++;
            if (score == -1)
                break;
            else if (score > 69)
                numberOfTestsPassed++;
        }
         percentOfClassPassed = ((double)numberOfTestsPassed * 100 / count);
    }

It gives the correct output for all inputs.


text:
Q: Is there any way that we can use Kafka streams for loading file to database? It can be any file. I just wanna know whether it's possible using Kafka stream.

A: Use Kafka Connect's JDBC Sink connector to stream data from Kafka to a database.
Here's an example of it in use: https://rmoff.dev/kafka-jdbc-video


text:
Q: Windows Forms Browser Skeleton (C#/.NET) I was wondering if anyone knows of an existing sample or an approach to achieve the desired functionality.
Basically, what I'm looking for is a web browser like skeleton. The idea is that the main screen of my application is shown in the left tab.  This tab can never be closed.  On this screen is an overview of various application components such as activities, events, contacts, etc.
When the user clicks on a specific contact/event/activity a new tab is created and auto-focused.  The user can view and edit the information.  When they are done they can close the tab.
The ability to have multiple tabs open is important.
Also, keyboard shortcuts to easily navigate between tabs would be great, but not absolutely essential at this point.
Note: I don't need to access any web content.
Really what I'm looking for, at least what I think I'm looking for, is a shell of a modern web browser.  Does something like this exist?  Is there a good approach to building such an application?
Note: I'm new to Windows GUI development, so I apologize if this is a rudimentary question.  I was unable to find anything meaningful while searching MSDN and other resources.
Thanks!

A: What it sounds like is not really a Web Browser shell at all, simply the relative appearance of one functionality-wise.
What you can do is use a TabControl control. This can be altered to suit your needs quite perfectly in my view.
An example of a modified TabControl is as follows: [ From here ]

There are a number of things that can be done with a TabControl (as with any other component) to make it suit what you need.
Here are some links that you may find helpful:

*

*Flat Tab Control - As per the picture

*MSDN

*Video on using a Tab Control

*C# Corner


text:
Q: How can I refer to the Winter Bash event in a shorter and more descriptive way? I am writing an essay about Winter Bash, and I want to find a shorter way to say that Winter Bash is an event that repeats annually during Winters.
I have already thought about several ways to call this event, but I think they are not good.

*

*Temporary event (It does not show reoccurrence)

*Seasonal event (It seems as if the Winter Bash is reoccurring every season, but it only happens in Winter)

*Annual event (It again may cause confusion)

Do you have any suggestions to help me shorten and convey my message (bolded above) in a better way? What do you think about my own thoughts?
===
I know I can always just say Winter Bash, but I look for a way to generalize and indicate the nature of the event in a more descriptive manner.

A: brumal: 'indicative of or occurring in the winter' (Merriam-Webster)
No subject has more engaged the naturalist in all ages than the brumal retreat of the swallow. (source)
The wind was whipping the snow into a flurry fury, bruiting the eddies about like brumal rumors. (Joan Connor, 'The Folly of Being Comforted'. TriQuarterly,  Fall, Iss. 123; pg. 169, 2005)
Examples from the OED (which defines it as 'ff, belonging to, or characteristic of winter; wintry'):

1813  Belfast Monthly Mag. 31 Jan. 47/1        Dark indeed are the brumal days that have no sun shine.
1870  J. R. Lowell My Study Windows 32        What cheerfulness there was in brumal verse was that of Horace's.
1934  E. Linklater Magnus Merriman vii. 84        That brumal solitude derived from knowledge of hunger in December and thrashing gales in March.
1983  M. O'Donoghue Jedder's Land (1984) 41        Clumps of snowdrops..had magically withstood the brumal cold of the past week.
2001  P. Ball Bright Earth viii. 205        Here is a very different kind of atmospheric lighting: cold and brumal, veiled in the shadows of a low sun.


text:
Q: Read MySql sequentially on primary key Is there any way to read a MySql database sequentially on the primary key? The file contains about 1.5M rows. I do not want to read all of them and ORDER them, just so I can get the first 100 records.
I tried this code but it seems to start at some random location in the middle of the key range:
  $query = "SELECT main_key FROM mytable LIMIT 100";
  $table = mysql_query($query) or die(mysql_error());
  while ($rec = mysql_fetch_row($table))
      echo $rec[0].'<br>';

A: SQL doesn't guarantee an order unless you specify the required order in an ORDER BY clause. To get the first 100 records do this:
$query = "SELECT main_key FROM mytable order by main_key LIMIT 100";

The database is very good at optimising queries, and will use an index if it estimates it is the fastest way to complete the query. Don't try to second guess it: it's probably better at it than you or me.

A: If you want them ordered, then use the ORDER BY clause:
SELECT main_key FROM mytable ORDER BY main_key LIMIT 100

A:
"I tried this code but it seems to start at some random location in the middle of the key range"
  SELECT main_key FROM mytable LIMIT 100

I wonder if main_key is PRIMARY KEY of mytable. I guess MySQL Optimizer choose non-PK index scan.
IMHO you have two possible choices.
USING FORCE INDEX
I think FORCE INDEX forces always use PRIMARY KEY.
mysql> EXPLAIN SELECT main_key FROM tab_name FORCE INDEX(PRIMARY) LIMIT 10;
+----+-------------+-----------+-------+---------------+---------+---------+------+----------+-------------+
| id | select_type | table     | type  | possible_keys | key     | key_len | ref  | rows     | Extra       |
+----+-------------+-----------+-------+---------------+---------+---------+------+----------+-------------+
|  1 | SIMPLE      | tab_name | index  | NULL          | PRIMARY | 8       | NULL | 13427712 | Using index |
+----+-------------+-----------+-------+---------------+---------+---------+------+----------+-------------+

Using HANDLER
MySQL has interesting functionality called HANDLER. With HANDLER you could open certain INDEX (of course PRIMARY supported), and you can get

*

*N rows from start of table

*and next M rows from Nth position

*or K rows from end of table.

So, you don't need to sort, fetching order is guaranteed.
-- OPEN HANDLER
HANDLER tab_name OPEN;

-- get first 100 records from PK
HANDLER tab_name READ `PRIMARY` FIRST LIMIT 100;

-- get next 100 records
HANDLER tab_name READ `PRIMARY` NEXT LIMIT 100;

-- get 100 records from End of Table
HANDLER tab_name READ `PRIMARY` LAST LIMIT 100;

-- CLOSE
HANDLER tab_name CLOSE;

*

*pros

*

*very fast

*cons

*

*This is not ANSI standard

*You can't specify which columns are retrieved.

*all columns of table are returned.


text:
Q: Where should CakePHP webroot be from apache configuration? I've noticed that there is an index.php file on the root of the cakePHP folder, underapp/, and under app/webroot.
My understanding is that the apache configuration should point to app/webroot as the site root, because otherwise I may be exposing my code and other sensitive data (database connection credentials etc). In my testing environment, I used to point it to the root folder of my cakePHP folder and it worked as expected(!) and I successfully completed the Blog tutorial.
Then I realized that I may be doing a mistake and I pointed apache to app/webroot and it still works as intended.
If this is the case, why doesn't cakePHP make it more clear by not having multiple index.php files and clearly stating that the site's root location should be pointed to app/webroot ?

A:
If this is the case, what doesn't cakePHP make it more clear by not
  having multiple index.php files and clearly stating that the site's
  root location should be pointed to app/webroot ?

Guess  because it was thought to be newbie friendly but this makes it easy to configure it wrong and expose the whole app to the public which is not a good idea.
See http://book.cakephp.org/3.0/en/installation.html#production
But yes, I agree to some extend, this could be a little more clear about the reason.
You should always use the webroot folder and nothing except your tmp folder of the app should be writeable by the webserver user of your system.

A: With some hosting providers it is not possible to put anything "below" public_html. In these cases CakePHP provides both an index.php and .htaccess in both root, app and webroot dir. This is there to have it working in several different hosting environments without the user having to change anything.
If at all possible you should only expose the webroot dir


text:
Q: Cannot catch a click on Chosen close button I am using the Chosen plugin and want to catch the event when clicking on the "X" or close buttom of an li item. But, the event does not seem to be fired or caught.
$(document).on('click', 'a.search-choice-close', function(e){
    alert('asd');
  });

This is the HTML:

a

asd

<input value="Choose Stamps" class="" autocomplete="off" style="width: 25px;" type="text">

A: The chosen documentation describes the Triggered Events
To catch the event on "search-choice-close", you can try the following:
$('#selectID').on('change', function(change, deselected) {
    //do something
    console.log('Value Deselected');
  });

A: To catch any change in the selection use the code
$("#selectId").on('change', function () {

    if ($("#selectId").val() === "") {

        //your code in case "X" button was pressed
        alert('asd');
    } else {

        //your code in case an option was selected
    }
});

when you press the "X" button on a select the same event of select change will be triggered but the select's value  $("#selectId").val() will be empty

A: I would try two things.

*

*Check that selector is correct.
document.querySelector("a.search-choice-close");

*check that element exist in the time when handler is registered.
Edit:
I also see that you are using jQuery. Check you don't have any jQuery error in console.


text:
Q: ksql query array of structs by value in the struct I have an array of structs. The array is an output of delta processing, thats why the count of structs differ (and the struct B sometimes have the position 1, but also can have the position 5).
A struct in the array looks like this:
{
val:{
asString:"12345"
},
position:"1200"
}
Another Example:
{
val:{
asString:"12927"
},
position:"1120"
}
I want to query the Value as String by using the position-key. I know which position keys to query, but i dont know how to get the value, because the position-Value is part of the struct.
The whole object has a key to identify a object
I thought of exploding the array and create a new event with the object identifying key.
The object itself has about 6000 lines, which would return a huge amount of events (which i am trying to avoid).
Maybe an switch to kafka streams is necessary?

A: I found a good working solution:
In my case I knew which keys (or position-attributes in the structs) I was searching for.
Therefore you can use the FILTER Method of Arrays to filter the struct, which has the specific value in the position-attribute, i was searching for.
You can do this for all the values you are searching for (if the position key is missing, you just get a null value, but in my case that was totally alright)
That's a good way to implement it in ksql without using Kafka Streams.
(FYI I am trying to avoid Kafka Streams, because it is not a confluent cloud nativ product and requires deeper java knowledge)


text:
Q: terraform script to create mysql schema and load data I created the RDS Aurora database in AWS management console. I have the sql script on mysql schema and insert statement.
I created the terraform script on the database creation, and next is to use terraform to create mysql schema and load data. My question is do I use terraform script to create mysql schema and load data? I am not clear on that.

A: You can try to use terraform to create your mysql schema, and load data, by leveraging terraform provisioniner: https://www.terraform.io/docs/provisioners/index.html
For example, you can execute remote scripts with remote-exec. This
You should be aware that terraform core capabilities is to provision infrastructure. Configuring and managing services is better achieved with specialized tools.


text:
Q: Comparison of Multiple column of single row in Informatica I have a requirement in Informatica powercenter development, where I need to populate a column after multiple column Compaeisons
Like for ex - we have Brand name in 30 Columns of same row, I have to populate a field in target table based on all these 30 Columns, if all the 30 Brands are equal then only we have to populate the Brand name else I have to populate Brand do not match.
also there may be case that some brands fields are  are null but we do not have to compare that with not null Brands.

A: Either use a DECODE function with OR, or do an MD5 on concatenation of all your columns and compare the result.


text:
Q: Error when trying to use go mod download on docker I'm making an app using docker and Postgres and gorm (go ORM library)
I have this Error (some kind of EOF?) while I want to build my docker image

My code is so simple and runs correctly without docker.
package main

import (
    "fmt"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable TimeZone=Asia/Shanghai"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        fmt.Println("Error connecting to postgres", err)
    }

    fmt.Printf("%+v\n", db)
}

Also, it's my Dockerfile:
FROM golang:1.16.4-alpine3.13 AS build
RUN mkdir /app
COPY src/go.mod /app
COPY src/go.sum /app
WORKDIR /app

RUN go mod download

COPY src /app
RUN go build -o main .

FROM alpine AS final
COPY --from=build /app /app
ENTRYPOINT ["/app/main"]

A: This looks like a networking issue.
When you are running outside of Docker, it is likely that you don't see these errors because the affected modules are already in your local module cache from a previous build, whereas your Dockerfile is starting from a clean cache and redownloading the module source every time.


text:
Q: wordpress container works in docker but fails to load in kubernetes This docker command is working as expected.
docker run -p 8084:80 -e WORDPRESS_DB_HOST=mydb.cd8nudnovwjha.us-east-1.rds.amazonaws.com -e WORDPRESS_DB_NAME=wp -e WORDPRESS_DB_USER=root -e WORDPRESS_DB_PASSWORD=abcd -d wordpress

But how to use it in kubernetes environment?
/usr/local/bin/kubectl  --kubeconfig="k8s-1-14-2-do-0-blr1-1558866674146-kubeconfig.yaml" run mywordpress2 --image=wordpress  --port=80 --env="WORDPRESS_DB_HOST=mydb.cd8nudnovwjha.us-east-1.rds.amazonaws.com" --env="WORDPRESS_DB_USER=root" --env="WORDPRESS_DB_PASSWORD=abcd"

I tried the above command but it does not start the wordpress like the docker command. I am using Amazon RDS if that matters.

Update:
I followed all the instructions found here...
https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/
And I am still not able to install wordpress on the published wordpress IP.
# /usr/local/bin/kubectl --kubeconfig="testme2-kubeconfig.yaml" get services
NAME              TYPE           CLUSTER-IP       EXTERNAL-IP    PORT(S)        AGE
kubernetes        ClusterIP      10.245.0.1       <none>         443/TCP        13m
wordpress         LoadBalancer   10.245.216.246   139.59.51.65   80:30784/TCP   9m2s
wordpress-mysql   ClusterIP      None             <none>         3306/TCP       9m3s

Do I need to make some changes to yaml config file to suit digital ocean nodes? I am asking this because official digital ocean repo is working correctly as expected.
https://github.com/digitalocean/doks-example


text:
Q: Capitalization of each sentence in a string in Python 3 This should be easy but somehow I'm not quite getting it.
My assignment is:

Write a function sentenceCapitalizer that has one parameter of type string. The function returns a
  copy of the string with the first character of each sentence capitalized. The function should return
  "Hello. My name is Joe. What is your name?" if the argument to the function is "hello. my name is
  Joe. what is your name?" Assume a sentence is separated by a period followed by a space."

What I have so far is:
def sentenceCapitalizer (string1: str):
    words = string1.split(". ")
    words2=words.capitalize()
    string2=words2.join()
    return (string2)

print (sentenceCapitalizer("hello. my name is Joe. what is your name?"))

Upon execution I get the error:
Traceback (most recent call last):
  File "C:\Users\Andrew\Desktop\lab3.py", line 83, in <module>
    print (sentenceCapitalizer("hello. my name is Joe. what is your name?"))
  File "C:\Users\Andrew\Desktop\lab3.py", line 79, in sentenceCapitalizer
    words2=words.capitalize()
AttributeError: 'list' object has no attribute 'capitalize'"

What is that telling me and how do I fix this? I tried following instructions found on a page listed as the python software foundation so I thought I'd have this.

A: You are trying to use a string method on the wrong object; words is list object containing strings. Use the method on each individual element instead:
words2 = [word.capitalize() for word in words]

But this would be applying the wrong transformation; you don't want to capitalise the whole sentence, but just the first letter. str.capitalize() would lowercase everything else, including the J in Joe:
>>> 'my name is Joe'.capitalize()
'My name is joe'

Limit yourself to the first letter only, and then add back the rest of the string unchanged:
words2 = [word[0].capitalize() + word[1:] for word in words]

Next, a list object has no .join() method either; that too is a string method:
string2 = '. '.join(words2)

This'll join the strings in words2 with the '. ' (full stop and space) joiner.
You'll probably want to use better variable names here; your strings are sentences, not words, so your code could do better reflecting that.
Together that makes your function:
def sentenceCapitalizer (string1: str):
    sentences = string1.split(". ")
    sentences2 = [sentence[0].capitalize() + sentence[1:] for sentence in sentences]
    string2 = '. '.join(sentences2)
    return string2

Demo:
>>> def sentenceCapitalizer (string1: str):
...     sentences = string1.split(". ")
...     sentences2 = [sentence[0].capitalize() + sentence[1:] for sentence in sentences]
...     string2 = '. '.join(sentences2)
...     return string2
...
>>> print (sentenceCapitalizer("hello. my name is Joe. what is your name?"))
Hello. My name is Joe. What is your name?

A: This does the job. Since it extracts all sentences including their trailing whitespace, this also works if you have multiple paragraphs, where there are line breaks between sentences.
import re

def sentence_case(text):
    # Split into sentences. Therefore, find all text that ends
    # with punctuation followed by white space or end of string.
    sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)

    # Capitalize the first letter of each sentence
    sentences = [x[0].upper() + x[1:] for x in sentences]

    # Combine sentences
    return ''.join(sentences)

Here is a working example.

A: To allow arbitrary whitespace after the dot. Or to capitalize the full words (It might make the difference for a Unicode text), you could use regular expressions -- re module:
#!/usr/bin/env python3
import re

def sentenceCapitalizer(text):
    return re.sub(r"(\.\s+|^)(\w+)",
                  lambda m: m.group(1) + m.group(2).capitalize(),
                  text)

s = "hEllo. my name is Joe. what is your name?"
print(sentenceCapitalizer(s))
# -> 'Hello. My name is Joe. What is your name?'

Note: pep8 recommends lowercase names for functions e.g., capitalize_sentence() instead of sentenceCapitalizer().
To accept  a larger variaty of texts, you could use nltk package:
# $ pip install nltk
from nltk.tokenize import sent_tokenize, word_tokenize

def sent_capitalize(sentence):
    """Capitalize the first word in the *sentence*."""
    words = word_tokenize(sentence)
    if words:
       words[0] = words[0].capitalize()
    return " ".join(words[:-1]) + "".join(words[-1:]) # dot

text = "hEllo. my name is Joe. what is your name?"
# split the text into a list of sentences
sentences = sent_tokenize(text)
print(" ".join(map(sent_capitalize, sentences)))
# -> Hello. My name is Joe. What is your name?

A: Just because I couldn't find this solution here.
You can use 'sent_tokenize' method from nltk.
import nltk
string = "hello. my name is Joe. what is your name?"
sentences = nltk.sent_tokenize(string)
print (' '.join([s.replace(s[0],s[0].capitalize(),1) for s in sentences]) )

And the output
Hello. My name is Joe. What is your name?

A: try:
    import textwrap
except ImportError:
    print("textwrap library module error")
try:
    import re
except ImportError:
    print("re library module errror")

txt = "what ever you want. this will format it nicely. it makes me happy"

txt = '.'.join(map(lambda s: s.strip().capitalize(), txt.split('. ')))

user = "Joe"
prefix = user + ":\t"
preferredWidth = 79

wrapper = textwrap.TextWrapper(initial_indent=prefix,
width=preferredWidth, subsequent_indent=' ' * len(prefix) + " ")

print(wrapper.fill(txt))

I try to use as little amount of internet dependent functions as possible. I found this works for me, hope this is of some use to someone

A: I did not use 'split' but just while loop instead. Here is my code.
my_string = input('Enter a string: ')
new_string = ''
new_string += my_string[0].upper()
i = 1

while i < len(my_string)-2:
    new_string += my_string[i]
    if my_string[i] == '.' or my_string[i] == '?' or my_string[i] == '!':
        new_string += ' '
        new_string += my_string[i+2].upper()
        i = i+3
    else:
        if i == len(my_string)-3:
            new_string += my_string[len(my_string)-2:len(my_string)]
        i = i+1

print(new_string)

Here is how it works:
Enter a string: hello. my name is Joe. what is your name?
Hello. My name is Joe. What is your name


text:
Q: Properties that hold when $f = \mathcal{O}(g)$ This is a homework problem. There are two questions where the answers seem intuitive, but even if I were correct in assuming they were true, I'd still need to provide a proof:
When $f(n) = \mathcal{O}(g(n))$, do these two statements hold true:
$$2^{f(n)} = \mathcal{O}(2^{g(n)})$$
and
$$f(n)^2 = \mathcal{O}(g(n)^2)$$
Both answers seem intuitive: if $f$ grows faster than $g$, then increasing the rate at which the functions increase wouldn't seem to change the relationship. Am I correct, and if so, how does one go about proving something like this?

A: For the first problem, let $f(n)=2n$ and $g(n)=n$. Then certainly $f(n)=O(g(n))$. But $2^{f(n)}$ is not $O(2^{g(n)})$: it grows far faster.
For a proof, it is enough  to show that $\frac{2^{2n}}{2^n}$ blows up as $n\to\infty$.  This is not hard. The counterexample shows that $f(n)=O(g(n))$ does not imply that $2^{f(n)}=O(2^{g(n)})$.
For the second problem, you know that there is a positive constant $k$ such that for large enough $n$, we have $f(n)\lt kg(n)$. Now you need to show that there is a positive constant $l$ such that for large enough $n$, we have $(f(n))^2 \lt l(g(n))^2$. This should not be difficult.

A: As Andre points out, the first statement is certainly untrue.  As another counterexample, consider
$$
f(n)=2\log_2(n) = \log_2(n^2), \quad g(n) = \log_2(n), \quad
$$
Here, we note $2^{f(n)} = n^2$ is not $O(2^{g(n)}) = O(n)$.
As for proving that second statement, use the definition:
Suppose that $f(n) = O(g(n))$.  That is, there is a $K>0$ so that
$$
|f(n)| \leq K|g(n)|
$$
Whenever $n$ is bigger than some $n_0$.  Squaring both sides, it follows that
$$
|f(n)^2| \leq K^2|g(n)|^2
$$
Whenever $n$ is bigger than that same $n_0$.  Why does this show that $[f(n)]^2 = O([g(n)]^2)$?


text:
Q: File Not Found after throws IOException I get this exception when I try to read from a file:
ERROR:
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.util.Scanner.<init>(Scanner.java:611)
    at Postal.main(Postal.java:19)

import java.util.Scanner;
import java.io.*;

public class Postal   {

    public static void main(String[] args) throws Exception   {
        /*** Local Variables ***/
        String line;
        Scanner filescan;
        File file = new File("newfile.txt");
        filescan = new Scanner(file);
        userInfo book = new userInfo();

        /*** Loop through newfile.txt ***/
        while (filescan.hasNext())   {
          line = filescan.nextLine();
          book.addNew(line);
        }

        book.print(0);
    }

}

A: The class Scanner uses a FileInputStream to read the content of the file.
But it can't find the file so a exception is thrown.
You are using a relative path to the file, try out an absolute one.

A: Use this instead:
File file = new File(getClass().getResource("newfile.txt"));

A: Provide an absolute path the location where you want to create the file. And check that user has rights to create file there. One way to find the path is:
File f = new File("NewFile.txt");
if (!f.exists()) {
    throw new FileNotFoundException("Failed to find file: " +
        f.getAbsolutePath());
}

Try this to open file:
File f = new File("/path-to-file/NewFile.txt");


text:
Q: PHPUNIT weird error In my application I have this weird error when testing only, I am not testing any classes in my Repo folder yet but have this:
Call to undefined method Application_Model_Cache::getInstance() in C:\wamp\www\truCrowd_dev\application\models\Repo\User.php on line 12

My user Repo is:
class Application_Model_Repo_User
{
    private $_database;
    private $_cache   ;

    public function __construct()
    {

        $this->_database   = Application_Model_Database::getInstance();
        $this->_cache      = Application_Model_Cache::getInstance();
        $this->_longCache  = Application_Model_Cache::getInstance(604800);
    }

My cache class is:
class Application_Model_Cache
{
    public static function getInstance($_expiration = 7200)
    {
        $frontend= array(
        'lifetime' => $_expiration,
        'automatic_serialization' => true
        );

        $backend= array(
        'cache_dir' => './cache/',
        );

        $cache = Zend_Cache::factory('Output',
            'File',
            $frontend,
            $backend
        );
        return $cache;
    }
}

My testing bootstrap is:
<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV') || define('APPLICATION_ENV', 'production');

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

I Have tried to change the Cache class by having to instantiate it but I get the same result...
My Database class has the exact structure but I haven`t gotten this in the past, now that I advanced in development I wanted to make tests and the error appeared

A: You should check whether Application_Model_Cache class is being mocked in any of your tests, and if the mock is not being used when calling the non existent method.


text:
Q: A road map through group cohomology I am a PhD student in algebraic topology, and I would like to learn something about group cohomology.
The final goal would be to present one or two seminars on this topic, in order to give my mates a gently introduction to this subject and at the same time showing them some striking result/application of this theory. Ideally, my plan for the seminar is:

*

*Introduce group cohomology, with a lot of motivations and examples

*Explain what makes group cohomology awesome

*Focus on a specific result, and showing some pretty applications of it (something that could be interesting to an algebraic topologist if possible) in order to strenghthen point 2

I am not looking for books, which are already given in these questions:
https://math.stackexchange.com/questions/2697778/reference-for-group-cohomology
https://math.stackexchange.com/questions/695613/reference-request-introduction-to-finite-group-cohomology?rq=1
So my questions are:

*

*Does anyone know any introductory papers/lecture notes where I can find a concise introduction to group cohomology? I am looking for something which do not contains all the details but which gives me a general view of the main results and applications of the theory. Youtube videos/lecture series are also very welcome. Of course if you want to mention book that are not in the previous answers it is fine aswell.

*Are there any suggestions about results/applications that I can put in points 2 and 3 of the seminar? As I said before the idea is to present this material to other students of algebraic topology, so I would prefer theorems/applications that will appeal to this kind of audience.

EDIT: an answer of this kind References and resources for (learning) chromatic homotopy theory and related areas is also very welcome and pertinent!
Thank you in advance,
Tommaso

A: Brown: Lectures on the cohomology of groups.
Adem: Lectures on the cohomology of finite groups.
Carlson: The cohomology of groups (from Handbook of Algebra, Vol.1, 1996).
Rotman: Homology of groups (chapter 9 from one of his algebra books that I forget the name).

A: Chapter 2 of these notes by Milne have been helpful to me.


text:
Q: Unit testing with inject annotation How do I unit test a class that uses @inject annotation:class A{
@inject
private B b;

void foo(){
    b.funcInClassB();
}

I am new to unit testing and having troubles testing this function because when calling b.funcInClassB() it throws NullPointerException because b is null.
I wrote the following test:
class Atest{
   @MockBean
   private B b;
   @Test
   void foo(){
     when(b.funcInClassB()).willReturn("something");
      A a = new A();
      a.foo();
   }
}

A: I figured it out:
class Atest{
   @MockBean
   private B b;

   @Autowired
   A a;

   @Test
   void foo(){
     when(b.funcInClassB()).willReturn("something");
      // A a = new A();
      a.foo();
   }
}


text:
Q: Can I have a method argument typed "this class"? I want to have an argument of type "this class" in an interface's method signature, so that any class, for example MyClass, implementing it will have that method with an argument of type MyClass.public interface MyInterface {
    public thisClass myMethod(thisClass other);
    ...
}public class MyClass implements MyInterface {
    // has to reference this class in the implementation
    public MyClass myMethod(MyClass other){
        ...
    }
}
Is this possible, or should I just bind the argument with the interface and have each implementation check for it?

A: public interface MyInterface<T> {
   public T myMethod(T other);
   ...
}

public class MyClass implements MyInterface<MyClass> {
   // has to reference this class in the implementation
   public MyClass myMethod(MyClass other){
      ...
   }
}

A: This somewhat enforces that T is the class that implements the interface:
public interface MyInterface<T extends MyInterface<T>> {
   public T myMethod(T other);
   ...
}


text:
Q: Including many files or just one file Setting up a project structure; I am thinking is it better to have somewhat of a "bootstrap.php" file that include and setup everything such as database connection, session management, libraries, error handling. Or just singulary include the file needed for the moment? (Which would need to prior the order of including, etcetera).
Alternative 1:
index.php
<?php

include 'bootstrap.php';

//session... database up and ready to be used...

Alternative 2:
index.php
    <?php
include 'session.php';
include 'database.php';
include 'errorhandling.php';
//now use database...

A: Include only files that are required for a particular page. For example, if a page doesn't require database connection, you would not include it. So latter approach is better to selectively include needed files unless you have some common stuff to import on every page.

A: In addition, PHP-Autoloading could be interesting for you: http://php.net/manual/de/language.oop5.autoload.php


text:
Q: Bulk upserting with $addToSet in mongo Good Afternoon Everyone,
I have a question regarding upserting arrays to Mongo.
Let's use the following data as an example:
[{
  name: 'Charlie Brown',
  companies: ['xyz', 'abc'],
  data: {
    City: 'PHOENIX'
  }
},
{
  name: 'Alex Brown',
  companies: ['xyz', 'ghj'],
  data: {
    State: 'GA'
  }
},
{
  name: 'Charlie Brown',
  companies: ['abc', 'yui'],
  data: {
    City: 'FLINT',
    State: 'GA'
  }
}]

The actual records are a bit more complex and more numerous than 3, but I hope this will serve sufficiently.
I want to insert/update/upsert these records into a mongoDB where matches (updates) do not overwrite the properties, but instead use $addToSet.
The end result should look like this:
[{
  name: 'Charlie Brown',
  companies: ['xyz', 'abc', 'yui'],
  data: {
    City: ['PHOENIX', 'FLINT'],
    STATE: 'GA'
  }
},
{
  name: 'Alex Brown',
  companies: ['xyz', 'ghj'],
  data: {
    State: 'GA'
  }
}]

I'm having a bit of trouble figuring out the correct mongo syntax for this. I know there is an upsert option on update, but how do I supply an array of records I would like to update, and then update individual records in the array?
I thought maybe the idea is to gather a set of names from the records, so
['Charlie Brown', 'Alex Brown']

and then use that set as a query field,
mongo.collection.update({
    ['Charlie Brown', 'Alex Brown'],
    {$addToSet:{companies: ??? what do I put here??}},
    {upsert: true}
})

What is the correct syntax (or correct method, perhaps using aggregations) to insert/update these records into Mongo?
Thank you!
Note: this question has similarities to Bulk upsert in MongoDB using mongoose
, but the key here is also using the modifier $addToSet. Also, those solutions place the DB operation within a loop, is this normal with mongo?


text:
Q: Informative censoring caused by cesarean section I study labor and delivery as an epidemiologist. It is well established that a large fetus has a higher risk of causing maternal birth trauma.  But a large baby is also likely to be delivered by cesarean section due to difficult labor.  Those delivered by cesarean section will not have any risk for maternal birth trauma and, therefore, excluded from an analysis using trauma as the outcome.  Thus, informative censoring is a real issue to estimate an unbiased relative risk, particularly when the cesarean rate is high.  Are there any methods to adjust for such a bias?

A: When I initially wrote the comments below I had assumed that the Heckman estimator could be used for dichotomous outcomes, but the second paper I cite says there is no direct analog. Hopefully someone can point to different and more applicable resources. I still leave my initial comment up as I still feel those papers are helpful. I'm not sure how acceptable it would be viewed to use OLS (as oppossed to logistic regression) simply so you can incorporate the Heckman correction estimate.

The work of James Heckman would be applicable to your problem, especially if you have an instrument with which you can estimate the probability of being chosen for a C-section independent of trauma risk.
Sample Selection Bias as a Specification Error
by: James J. Heckman
Econometrica, Vol. 47, No. 1. (1979), pp. 153-161.
PDF version
Also as an intro into the logic of the Heckman selection estimator intended for a largely non-technical audience, I enjoy this paper
Is the Magic Still There? The Use of the Heckman Two-Step Correction for Selection Bias in Criminology
by: Shawn Bushway, Brian Johnson, Lee Slocum
Journal of Quantitative Criminology, Vol. 23, No. 2. (1 June 2007), pp. 151-178.
PDF version

A: As another option here, how about using a multinomial logistic regression (with the outcomes being trauma, [non-elective] caesarean, and no trauma?)
I'm not entirely sure if this approach will fully address the issue of bias, but one would get some measures of association about the associations between e.g. fetus size and having a non-elective caesarean section, and could see these side by side with the associations between the same exposure and trauma, and at the least make some qualitative comparisons about magnitudes of effect.
[This question was bumped by an answer edit, with an inactive original questioner, so I'm really just floating another idea here (plus I'm interested in this kind of question)]


text:
Q: RBAC in Jenkins: How to create custom permission for only users and groups management I installed Role-based authorization strategy plugin in Jenkins LTS. Please can you give me feedback about "RBAC: How to create custom permission for only users and groups management" I see the "Credentials section" (inside Manage Roles) has the following permissions: Create /Delete /ManageDomains/Update /View. So, is possible to create similar permissions for only users and groups management?
Additionally, can you confirm if in Jenkins LTS or in CloudBees Jenkins Disstribution is possible to create groups ? Or in which versions can I do that?
Best Regards!


text:
Q: What is considered 100% efficiency when talking about photovoltaic cells? I was reading this article in Popular Science and figured that I actually don't know what is considered 100% efficiency.
Is it when every photon that hits the cell kicks out an electron that is excited enough to become free? Not every photon in the spectrum has enough energy to do that, does it?

A: Have a look at the Wikipedia article on Solar cell efficiency. The efficiency is the electrical power output divided by the total energy received across all wavelengths. As you say, this would be unlikely ever to reach 100% as some of the energy is at long wavelengths.


text:
Q: add values into section in recyclerView i followed this question's answer for adding sections in my  recyclerView
for adding the sections we have to provide the index for section like this :
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Section 1"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Section 2"));

so the section 1 will be at index 0 and section 2 will be at index 5
now i have dataset of ChannelsInformation and channelInformation class is :
public class ChannelsInformation {
String id,channelName;
boolean isSelected , isfavorite;
}

so my question is that what i have to do for adding my dataSet into different sections ?  suppose i have a data
<id = 1 , channelName = channelName1 , isSelcted = false , isfavorite = true >
2 , channelName2 , false , false
3 , channelName3 , false , true
4 , channelName4 , false , false

so the above is a demo of some data now i want to add that data into my recyclerView according two isFavorite field , after adding the data in recylerView it should look like this :
section 1
1 - channelName1
3 - channelName3
section 2
2 - channelName2
4 - channelName4

any idea what i have to do for adding my data in a form so that it'll organise as the above example ?
this is how am populating the data into my recyclerView (on my fragment class) :
    public static List<ChannelsInformation> getData(){

    List<ChannelsInformation> data = new ArrayList<>();

    for (int i = 0 ; i<channelsArray.size() && i<channelsIDArray.size() ; i++ ){

        ChannelsInformation current  = new ChannelsInformation();
        current.channelName = channelsArray.get(i);
        current.id = channelsIDArray.get(i);
        current.isFavorite = channelIsFavoriteArray.get(i);

        data.add(current);
    }

    return  data;

}

any idea how am gonna do that ? any hint or guidance will be highly appreciated
if code is not sufficient then please let me know i'll update it

A: you can sort your list on the basis of boolean "isfavorite" as follows:
public class ChannelsInformation implements Comparable<ChannelsInformation> {
    String id, channelName;
    boolean isSelected, isfavorite;

    @Override
    public int compareTo(ChannelsInformation o) {
        int b1 = this.isfavorite ? 1 : 0;
        int b2 = o.isfavorite ? 1 : 0;

        return b2 - b1;
    }

}

And then call Collections.sort(data); after setting your arraylist.


text:
Q: what's the difference between these two command in R?(levels of factor variable) I'm new to R, I was trying to figure out what is the difference between the last two commands?Are they the same?Because the output are exact the same.
yesno <- sample(c("yes", "no"),size = 10, replace = TRUE);yesno
> yesno
[1] "yes" "yes" "no"  "yes" "yes" "yes" "no"  "yes" "no"  "yes"

yesnofac <- factor(yesno, levels = c("yes", "no"));yesnofac
[1] yes yes no  yes yes yes no  yes no  yes
Levels: yes no

relevel(yesnofac, ref = "yes")   #Reorder Levels of Factor
[1] yes yes no  yes yes yes no  yes no  yes
Levels: yes no

A: In the above example, there is no difference as the first level is 'yes'.  But, if we change the order of levels, then the relevel willl make the 'yes' as the first level
yesnofac <- factor(yesno, levels = c("no", "yes"))
yesnofac
#[1] yes no  yes yes yes yes yes no  yes yes
# Levels: no yes

relyesnofac <- relevel(yesnofac, ref = "yes")
relyesnofac
#[1] yes no  yes yes yes yes yes no  yes yes
# Levels: yes no'

Check the levels, it is now different in order
levels(relyesnofac)
#[1] "yes" "no"
levels(yesnofac)
#[1] "no"  "yes"


text:
Q: can not send a post request using postman
I am trying to sand post request using postman.
for some reason i am getting 400 Bad Request - Required request body is missing.
My controller is in spring boot environment.

My controller:

    @RestController
    public class HagarController {

      @PostMapping(value = "/hagar")
      @ResponseStatus(HttpStatus.OK)
      public void hagar(@RequestBody String name, @RequestBody String id)
      throws Exception{
          System.out.println("my name is: " + name +" id: " + id);
      }
    }

The postman request img
Thanks!!

A: This is how I do it, I hope it will help you:
@RestController
public class HagarController {

  @ResponseMapping(value = "/add", method = RequestMethod.POST)
  public void hagar(@RequestBody String name, @RequestBody String id)
      System.out.println("my name is: " + name +" id: " + id);
}

and in postman you probably added in Headers:
see image:
enter image description here