text:
Q: How to send on a specific day in php? I want to a e-cards or something like that. The user can choose the e-cards, after chosen, he must enter the some fields like name(to and from), email(to and from), message and I want to let user to choose which date to send the e-cards.
How to send the e-cards on specific day? I need to write a script that run every new day? How to do that? Sorry, I am new to php... (but not beginner like not even know how to execute mysql query, get message from url etc)

A: Yes, you need a script that runs every day.  (Barring ridiculous maneuvers like trying to fake this by checking on Web requests.)  The usual way to do this in a Unix context is called a cron job; if your hosting provider is Unix-based, you should look into what they provide for making cron jobs available to you.  On Windows there's a parallel service called Scheduled Tasks.

A: This is for *nix.
Let's say you have a php script that sends email on a specific day called mailer.php
<?php
    //mailer.php
    if (date("m/d/Y") == "06/02/2009") {
        mail("client@email", "Subject", "Body");
    }
?>

We are going to assume that you already have cron daemon running in the background.
If you have root access to your machine, then setting up a cron job is simple as editing a file.
Open up /etc/crontab file and add the following task:
1 14 * * * root php /path/to/your/scrip/mailer.php

This means, as a root, the mailer.php script will be running daily at 02:01PM. You can change the numbers to whatever you desire.

A: A similar question was disscussed here resetting-a-mysql-field-value-without-user-execution
I'll just reiterate: There are web based cron services too. This could come in handy if you only got a shared hosting plan and can't add cron jobs. They will call an URL at a regular interval that you can set. Usually very cheap. (Cheaper than upgrading to a root-access server anyway.)
Just search Google for web based cron
ciao!
/0

A: This is somehow complex. First it depends on your system. If it is Linux/BSD/Unix/Solaris then you have this handy utility as cron. If you are using Windows, you have Scheduled Tasks. Run your script daily (or as you wish) and check what cards you have to send today.


text:
Q: nest client Bypass ssl Certificate error in .netcore application var uris = new[]
                {
                    new Uri("https://10.8.173.179:9200"),
                };

                var connectionPool = new SniffingConnectionPool(uris);
                var settings = new ConnectionConfiguration(connectionPool);
                settings.BasicAuthentication("elastic", "password");
                var lowlevelClient = new ElasticLowLevelClient(settings);
                var health = lowlevelClient.Cluster.Health<StringResponse>();

Getting below :
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

A: Take a look at the working with certificates documentation.
If you're using a self signed cert, you can use either the following on ConnectionSettings.ServerCertificateValidationCallback(...)

*

*CertificateValidations.AllowAll; to allow all certificates

*CertificateValidations.AuthorityIsRoot(cert) and pass it the Certificate Authority (CA) public key to validate that the certificate the server presents is generated with the CA

*CertificateValidations.AuthorityPartOfChain(cert) and pass it the certificate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Cloud Dataflow Python SDK updates On using the Google Cloud Dataflow Python SDK happens that at start reading a lot of data from the Cloud Storage it takes a while and causes the error AssertionError: Job did not reach to a terminal state after waiting indefinitely.
Doing a search we found the open issue BEAM-5529 which refers to the patch #6535 released in version 2.8.0 but not present in the release note.
In the other hand the current published version is google-cloud-dataflow 2.5.0
There is any update policy or is it the individual responsibility to perform the compilation and generation of a new version with the latest releases?
Please any help or comment will be welcome.

A: As per official Google Cloud Platform docs here:

The Cloud Dataflow SDK 2.5.0 is the last Cloud Dataflow SDK release that is separate from the Apache Beam SDK releases. The Cloud Dataflow service fully supports official Apache Beam SDK releases.

So yes, google-cloud-dataflow 2.5.0 is the last release, and from that version on you should use the official apache-beam releases. Bear in mind that you will need to install the library using the extra [gcp]:
pip install apache-beam[gcp]

Finally, the fix in 6535 should be applied already, since I installed the library "pip install apache-beam[gcp]===2.8.0" and I went to the file "apache_beam/runners/dataflow/dataflow_runner.py" and it has the fix applied there.


text:
Q: Understanding the $Z$ production cross section in $e^{+}e^{-}\rightarrow Z\rightarrow \mu^{+}\mu^{-}$ In "Modern Particle Physics", Mark Thomson derives the total cross section for $\sigma\left(e^{+}e^{-}\rightarrow Z^{0}\rightarrow\mu^{+}\mu^{-}\right)$, cf. subchapter 16.1.1 on page 431 ff. He assumes that $\sqrt{s}\sim m_{Z}$, s.t. the QED Feynman diagram is in first approximation negligible.
Now, in the first Eq. on page 431 that does not have a number, i.e. $$\mathcal M_{fi} = - \frac{g_{Z}^{2}g_{\mu\nu}}{\left( s-m_{Z}^{2} + im_{Z}\Gamma_{Z}\right)}\dots,$$ I do not understand the term that Mark Thomson wrote down, which is supposed to be the propagagtor, I assume. Usually, we would write the $W^{\pm}/Z^{0}$ propagator as
$$\frac{-i\left( g_{\mu\nu} - q_{\mu}q_{\nu}/m_{Z}^{2}\right)}{\left(q^{2}-m_{Z}^{2}+im_{Z}\Gamma_{Z}\right)}.$$ In an $s$-channel Feynman diagram, $s = q^{2}$, but what happened to the term $q_{\mu}q_{\nu}/m_{Z}^{2}$? After all, in the following derivation, M. Thomson does not ignore the term $s-m_{Z}^{2}$ in the denominator..


text:
Q: Audio software compressors and audio output filtering I'm going to try to explain this the best I possibly can, but what I want seems feasible.
I have a studio condensor mic that I use as my microphone input to my computer.  When recording I know it is possible to take noise out of the recording by subtracting it from the wavelength.  This is often called noise suppression, reduction, or removal.  I have speakers on my desk, but the microphone sometimes picks the sound up from there.  Is there anyway for my computer to take what is currently being output to the speakers, treat it as noise and remove it from the microphone input in realtime?
I also use the microphone to do voice chat.  I have a large room and like to walk around when I talk.  Is there anyway to apply a compressor effect to the live input, where when the signal falls below a certain threshold it is boosted and when it goes above a threshold it is softened?
I want to see if I can do this with software instead of hardware.
Edit, I already have wireless headphones but I'd rather not use them since they're bulky.

A: Have you considered buying a wireless headset?
I think any solution to this you'd have to write yourself. It's certainly possible, probably a C app with Matlab FFT cleverness.
Tricky problem indeed, good luck with whatever you try, and keep us informed =)

A: Speaker problem: Use headphones. The cleaner the audio to begin with the better it is to work with later. Most audio professionals I know say to avoid any noise reduction as it can and does affect what you want to keep. If you still have noise you need to eliminate after listening via headphones, your best option is to use a noise gate (either hardware or software).
Microphone Compression: Most decent DAW applications (or audio editing) applications can work in a live environment and do similar to what you are talking about in software. However that can only do so much. Mic technique is critical for good sounding audio. If you need to move around the room invest in either a wireless mic/headphone combo or a very long cord for a wired headset.
To me, it sounds like based on what you are saying you need to invest in a headset of some sort.


text:
Q: Brace range expansion of three variables I'm not sure if I've used the correct terminology in the title and in this question so please edit it if it's incorrect.
In a bash script I have three arrays, dirs, files, and extensions. How can I make all combinations of strings that contain a value from dirs, then files, and then extensions?
I'm not experienced with Bash at all, but I did try this to see if I could achieve this with just two arrays:
$ echo ${dirs[@]}
a b
$ echo ${files[@]}
c d
$ echo ${dirs[@]}{${files[@]}}
a bc d

The output I want from this example is ac bc ad bd
EDIT: I completely screwed up the example and just fixed it, in case you were wondering what happened.

A: You can't do this with {foo,bar} syntax; bash only expands that if it sees literal commas between the braces.  (I suppose you could use eval, but that brings its own mess.)
Just use loops:
for dir in "${dirs[@]}"; do
    for file in "${files[@]}"; do
        for ext in "${extensions[@]}"; do
            echo "$dir$file$ext"
        done
    done
done

A: The following will work in all conditions where brace expansion conditions are satisfied
$ dirs=(a b)
$ files=(c d)

$ eval echo {${dirs[0]}..${dirs[$((${#dirs[@]}-1))]}}{${files[0]}..${files[$((${#files[@]}-1))]}}
ac ad bc bd

For your more understanding:
$ A=`echo {${dirs[0]}..${dirs[$((${#dirs[@]}-1))]}}`
$ B=`echo {${files[0]}..${files[$((${#files[@]}-1))]}}`
$ echo $A$B
{a..b}{c..d}
$ eval echo $A$B
ac ad bc bd

A: This is inspired by @Suku's answer, but uses {a,b,c}-style expansion instead of {a..c}:
$ dirs=(this/ that/)
$ files=(a b c)
$ extensions=(.c .h)
$ saveIFS=$IFS
$ IFS=,
$ eval echo "{${dirs[*]}}{${files[*]}}{${extensions[*]}}"
this/a.c this/a.h this/b.c this/b.h this/c.c this/c.h that/a.c that/a.h that/b.c that/b.h that/c.c that/c.h
$ IFS=$saveIFS

Note that as with almost anything involving eval, this can fail catastrophically if any of the array values have the wrong metacharacters. If this is a concern, use @Eevee's answer instead.


text:
Q: Solve Query Failures Regarding ONLY_FULL_GROUP_BY SQL Mode From https://www.percona.com/blog/2019/05/13/solve-query-failures-regarding-only_full_group_by-sql-mode/

"Hey, what's going on with my applications? I installed a newer version of MySQL. I have queries that perfectly run with the older version and now I have a lot of errors."
This is a question some customers have asked me after upgrading MySQL. In this article, we'll see what one of the most frequent causes of this issue is, and how to solve it.
We are talking about this error:

My error is the same:

In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'ebenlizy_inventorycontrol.sales_orders.orderId'; this is incompatible with sql_mode=only_full_group_by

my query is
$query=mysqli_query($conn,"
  SELECT
     Sum(sales_order_details.quantity) AS Quantity,
     (SELECT buyingPrice from items INNER JOIN sales_order_details ON items.stockId = sales_order_details.stockId WHERE sales_order_details.orderId = sales_orders.orderId) AS buyingPrice,
 sales_order_details.price
  FROM sales_orders
  JOIN sales_order_details ON sales_orders.orderId = sales_order_details.orderId
  WHERE MONTH(sales_orders.orderDate)='$month'
    and YEAR(sales_orders.orderDate)='$year'
    AND sales_orders.branchId =$id
    AND salesStatus=1")
or die(mysqli_error($conn));


text:
Q: ElectronJS: Uncaught TypeError: ipcRenderer.on is not a function Using: Electron v15.2.0 using the Electron Quick Start
I know this is a very simple problem, but I can't seem to find a solution for it. Here's the code.
main.js:
// Get Tasks
ipcMain.on('json:get', (event, dataset) => {

  // Read the JSON file
  fs.readFile('./data/data.json', 'utf8', (err, jsonString) => {

    // Throw error to console if there is one
    if (err) {
      console.log("File read failed:", err)
      return
    }

    console.log(`JSON Data: ${jsonString}`)

    // Send returned JSON data to mainWindow
    mainWindow.webContents.send('tasks.return', jsonString)

  })
})

preload.js:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('ipcRenderer', ipcRenderer)

renderer.js
document.getElementById('test').addEventListener('click', () => {
    ipcRenderer.send('json:get', 'tasks')
})

ipcRenderer.on('tasks.return', (event, json) => {
    console.log(json)
})

What's happening is that the event listener is firing correctly, I know that because the JSON will dump into the console from the main.js code, but it's not firing from the renderer.js code. And I'm getting the error: Uncaught TypeError: ipcRenderer.on is not a function, but it's being called on:
ipcRenderer.on('tasks.return', (event, json) => {
    console.log(json)
})

But, it's not being called with the event listener fires.
I tried adding:
const electron = require('electron')
const { ipcRenderer } = electron

To renderer.js, but then I get this error: Uncaught SyntaxError: Identifier 'ipcRenderer' has already been declared and neither work.
I know that I need to shorten the scope of the contextBridge and ipcRenderer in the preload.js file, and I will, but the issue is that I can't get the Electron app to send messages back to the mainWindow.
Thanks in advance!

A: I believe you're seeing this issue. ipcRenderer does not have an on method when in a (context-isolation-enabled?) renderer.
The solution is to move the ipcRenderer.on logic inside of the preload script like so (full code example here):
contextBridge.exposeInMainWorld("api", {
    onResponse: (fn) => {
        ipcRenderer.on("tasks.return", (event, ...args) => fn(...args));
    }
});

And then your renderer can do:
window.api.onResponse((json) => console.log(json));

(keep in mind the memory leak for which a solution is mentioned here)


text:
Q: Testing a entry_point contribution I am writing a Python module that specifies a set of entry_points, so other host modules can discover a new piece of functionality. I am following the setuptools approach specified at the official documentation.
As an example, the snippet below shows a contribution through sample.contribution named hello-world which points to timmins.hello_world attribute.
[options.entry_points]
sample.contribution =
    hello-world = timmins:hello_world

Let's suppose the host plugin defines a method like the following for loading sample.contributions extensions.
def load_contributions():
   ...

What I want to do is to write a test that ensures the entry_point is properly loaded by the host module. At this moment, the only way of testing such entry_point loading is through building a wheel and pip-install it. Once installed, the entry_point can be loaded sucessfully.
So, my question is ... Is there any way of adding the specified entry_points at setup.py (or setup.cfg) so they can be loaded during the tests execution? That is, a test for the module that defines the entry_point that returns the contributions when calling the load_contributions method

A: Maybe using tox for executing a set of test commands is the right choice.
This approach installs the developed module into a virtual environment, and so its entry_points are loaded when invoking a command.


text:
Q: Get broadcast address or subnet mask in flutter I need to get the broadcast address of the local network the device (smartphone, tablet, desktop) is in. While Flutter lets you retrieve the network interfaces with the dart:io package and its NetworkInterface.list() method, the info seem to lack the broadcast address or subnet mask. (Documentation: NetworkInterface, InternetAddress).
I did find a "Flutter Interfaces Plus" plug-in, which should do the trick. Unfortunately it only supports Android at this point and the last commit is 2 years old. So chances that iOS support is added any time soon seem slim.
Is there a way to get the broadcast address or subnet mask that I missed?


text:
Q: ContextPath and autocompletion with subpackages I'm developing a larger package which includes several subpackages. My problem is, that I can't introduce the symbols in the subpackages to the autocompletion by loading the main package, but by calling a subpackage.
Let's explain this with an example: I have a main package, called main which loads the subpackages sub1, sub2 and sub3. The directory should look like
main
├── Kernel
│   └── init.m
├── main.m
├── sub1.m
├── sub2.m
└── sub3.m

The package main loads all three subpackages in its BeginPackage statement, while the package sub1 loads sub2 and sub3. The respective init.m looks like:
Get["main`sub3`"]
Get["main`sub2`"]
Get["main`sub1`"]
Get["main`main`"]

The big problem I have is, that by calling
Needs["main`"]

I can see all symbols in main, but not those in the subpackages (though, they are usable).
By calling
Needs["main`sub1`"]

I can see all symbols in the subpackages without any problems but can't load main anymore, because then some definitions are redone, which leads to error messages about protected symbols. The most interesting thing is, that the $ContextPath includes the subpackages in both cases.
Is there a nice possibility to get the symbols of the subpackages into the autocompletion?

Update: By prepending the path of a subpackage to the $ContextPath, I can load the corresponding symbols of that package into the autocompletion.
$ContextPath = Prepend[$ContextPath, "main`sub1`"]

Unfortunately, this is not very nice and yields duplicates in the $ContextPath.
Is there a better, automatic way to achieve this?

A: Just to give additional information, what I found, at least in Mathematica version 9, is that one must load the subpackages after the main package in order to have autocompletion for the subpackages symbols. When we do this the subpackages appear before the main package in the $ContextPath, so when you have a init.m like this:
Get["main`main`"]
Get["main`sub1`"]
Get["main`sub2`"]
Get["main`sub3`"]

you have $ContextPath = {main`sub3`, main`sub2`, main`sub1`, main`main`, ...}, and voilà, we have autocompletion.
I don't understand why Mathematica "shadows" the subpackage symbols when they appear after the main package in the $ContextPath, but this is the solution I found.

A: I think you have deal with Mathematica application.
I know 2 way for solv this problem
1) Add path to your application in variable $Path. And then load with Get
AppendTo[$Path,"C:\\path\\to\\your\\application"];
<<main`

This code try to find init.m in your application and evaluate it.
2) Save your application in directory $UserBaseDirectory <> "\\Autoload" and it will load with mathematica start (withe the way described in previous way).


text:
Q: Android setWallpaper deprecated I want to create an Application that allows me to set my phone's wallpaper, but i have a problem with : getApplicationContext().setWallpaper(bm).
It says that setWallpaper is deprecated and i should use another method, but i have no idea what method to use.
This is my code so far:
   package com.example.asus.incercare_proiect;

/**
 * Created by Asus on 29-Apr-15.
 */
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

 class bakapp extends Activity implements OnClickListener {
    ImageView display;
    int tophone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        // activitatea noastra sa acopere intreg ecranul
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.backapp);
        Button but = (Button) findViewById(R.id.setwallpaper);
        tophone = R.drawable.image4;
        but.setOnClickListener(this);
        display = (ImageView) findViewById(R.id.ivdisplay);
        ImageView image1 = (ImageView) findViewById(R.id.IVimage1);
        ImageView image2 = (ImageView) findViewById(R.id.IVimage2);
        ImageView image3 = (ImageView) findViewById(R.id.IVimage3);
        ImageView image4 = (ImageView) findViewById(R.id.image4);
        ImageView image5 = (ImageView) findViewById(R.id.IVimage5);

        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
        image4.setOnClickListener(this);
        image5.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast var;
        switch (v.getId()) {
            case R.id.IVimage1:
                display.setImageResource(R.drawable.image4);
                var = Toast.makeText(bakapp.this, "image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                tophone = R.drawable.image4;
                break;
            case R.id.IVimage2:
                display.setImageResource(R.drawable.image5);
                var = Toast.makeText(bakapp.this, "image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                tophone = R.drawable.image5;
                break;
            case R.id.IVimage3:
                display.setImageResource(R.drawable.image6);
                var = Toast.makeText(bakapp.this, "image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                tophone = R.drawable.image6;
                break;
            case R.id.image4:
                display.setImageResource(R.drawable.image7);
                var = Toast.makeText(bakapp.this, "image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                tophone = R.drawable.image7;
                break;
            case R.id.IVimage5:
                display.setImageResource(R.drawable.image8);
                var = Toast.makeText(bakapp.this, "image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                tophone = R.drawable.image8;
                break;
            case R.id.setwallpaper:
                // trebuie folosit bitmap
                InputStream is = getResources().openRawResource(tophone);

                Bitmap bm = BitmapFactory.decodeStream(is);

                try {
                    getApplicationContext().setWallpaper(bm);

                // trebuie sa cerem permisiune pentru a seta Wallpaperul

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
           var = Toast.makeText(bakapp.this, "Wallpaper image changed",
                        Toast.LENGTH_SHORT);

                var.show();

                break;
        }
    }

}

Could anyone help me out?

A: If you take a look at the official docs, you will find, that this method is deprecated since API 5 and you should use WallpaperManager.setBitmap() instead.

A: First you set the permission in your Menifest file
 <uses-permission android:name="android.permission.SET_WALLPAPER"/>

and then use WallpaperManager to set the wallpaper .
WallpaperManager myWallpaperManager
        = WallpaperManager.getInstance(getApplicationContext());
        try {
            myWallpaperManager.setResource(R.drawable.five);


text:
Q: Jaspersoft : Extra space at the end of table in detail band I am using jaspersoft studio 5.6. I created a table in detail band to display data from database (it expands to many pages). And when in the new page, at some point, it generates extra space at the end. You can see in the image I uploaded here, when in record 23rd, it generates extra space below, but from 25th it not. Can someone help me on this problem? It make me confuse.
jrxml file

A: Ok, this is what happens according to me (can't test but you can)

*

*Your detail band is height=65

*Your table is at y=15 height=50

If you do not have enough rows your table will never arrive to height=50, so since detail band is 65 you will have the space below the table, hence table starts at 15, runs for 2 rows give height=40, there will be 10 space until detail band ends.
Solution:
Make the height of your table as 1 row in it 20!, and reduce the detail band to fit height=35
The tag you need to change on the table is:
<componentElement>
   <reportElement x="0" y="15" width="511" height="20" uuid="b3d3ccdb-1d82-4bb3-81f6-e0690e70519b">

*

*tag on detail band
<detail>
 <band height="35" splitType="Stretch">


text:
Q: AngularJS animation card flip I am trying to use the new AngularJS way of doing animations between page transitions and would like to incorporate a card flip (like http://jsfiddle.net/nicooprat/GDdtS/)
body {
 background: #ccc;
}
.flip {
-webkit-perspective: 800;
width: 400px;
height: 200px;
position: relative;
margin: 50px auto;
}
.flip .card.flipped {
-webkit-transform: rotatex(-180deg);
}
.flip .card {
width: 100%;
height: 100%;
-webkit-transform-style: preserve-3d;
-webkit-transition: 0.5s;
}
.flip .card .face {
 width: 100%;
 height: 100%;
 position: absolute;
 -webkit-backface-visibility: hidden ;
 z-index: 2;
 font-family: Georgia;
 font-size: 3em;
 text-align: center;
 line-height: 200px;
}
.flip .card .front {
 position: absolute;
 z-index: 1;
 background: black;
 color: white;
 cursor: pointer;
}
.flip .card .back {
 -webkit-transform: rotatex(-180deg);
  background: blue;
  background: white;
  color: black;
  cursor: pointer;
}

I am just a bit unsure how to update that code to make it work with AngularJS for a page transition.
Any thoughts?

A: I realize this was a long time ago, but I was just doing this, and it took zero javascript. The key is ng-class. Here is a JSFIDDLE.
The key is this line

It will assign the class 'flipped' to the card when $scope.isFlipped is true. Here is a little NFL flash cards game I put together for fun. Check out the source code (which isn't super pretty), it should be helpful if you are doing something like this.
NFL Flash Cards

A: Here is an alternate solution where it's more clear from the html what's happening. Specifically, the flip mechanism is in angularjs rather than buried in css magic. Perhaps easier to follow for anyone who's not a css expert:

        Front

        Back


text:
Q: How to return an object from a function that contains a Promise and a .then and how to get the returned value in another function? how can i return an object from a function that contains a Promise and a .then; and how can i get the returned value from that function, in another function? Here is the function that contains the Promise and the object that i want to return is obj:
function searchdb(user, key){
    var ok;
    const list = new Promise(function (resolve, reject) {
        MongoClient.connect(uri, function(err, db) {
            var dbc = db.db("chat");
            dbc.collection("chat_messages").find({$or: [ {user1: key, user2: user}, {user1: user, user2: key} ]}).toArray(function (err, result){
                if(err) {
                    reject(err);
                } else {
                    resolve(result);
                }
                if(result[0].user1 == key){
                    ok = 1;
                }
                else{
                    ok = 2;
                }
            });
        db.close();

        });

    });
    var obj = {};

        list.then(result => {
        if (ok == 1){
            obj[result[0].user1] = result[0].user2_seen;
        }else{
            obj[result[0].user2] =result[0].user1_seen;
        }
        console.log(obj);              <--------------- here its working
        }).catch(err => console.log(err.message));

        return obj;
}

And here is the function where i want to get the return:
function get(data){
    suser = data[0]
    obj = data[1];

    for (var i in obj){
        var key = Object.keys(obj[i])[0];

        var a = searchdb(suser, key);
        console.log(a);       <-------------- here its not working
    }
}

I just can't return and get the return from that function, everything else its working fine. Please help

A: In your main function at the top level return new promise and resolve it whenever obj promise is solved and store it in newVarible.
Then Use promise.all("newVarible") after that you'll be able to get values of obj after the promise is being resolved anywhere.


text:
Q: How can I customize the AuditingHandler injected by Spring-Data when using Auditing? I'm using Spring Data 1.5 and Auditing.  Part of the AuditingEntityListener has a setAuditingHandler method.
How can I customize the AuditingHandler and instruct Spring-Data to inject my custom handler instead of the default org.springframework.data.auditing.AuditingHandler?
I've tried instantiating my own AuditingEntityListener in which I inject my own Handler, but that is not doing the job.  The default handler is still being injected.  I've tried both via XML configuration and JavaConfig to see if one worked better than the other, but neither way works.
JavaConfig:
@Configuration
@EnableJpaAuditing(auditorAwareRef="auditorProvider")
public class AppConfig {

    @Bean
    public AuditorAware<User> auditorProvider(){
        return new SpringSecurityAuditorAware();
    }

    @Bean
    public AuditingEntityListener auditingEntityListener(){
        AuditingEntityListener listener = new AuditingEntityListener();
        listener.setAuditingHandler(new com.ia.persistence.AuditingHandler());
        return listener;
    }
}

My custom handler:
@Component
public class AuditingHandler extends  org.springframework.data.auditing.AuditingHandler {

    // SLF4J logger
    private static final Logger logger = LoggerFactory.getLogger(AuditingHandler.class);

    /* (non-Javadoc)
     * @see org.springframework.data.auditing.AuditingHandler#markCreated(java.lang.Object)
     */
    @Override
    public void markCreated(Object source) {
        logger.info("Custom handler");
        super.markCreated(source);
    }

    /* (non-Javadoc)
     * @see org.springframework.data.auditing.AuditingHandler#markModified(java.lang.Object)
     */
    @Override
    public void markModified(Object source) {
        logger.info("Custom handler");
        super.markModified(source);
    }
}

What am I doing wrong?  With my JavaConfig, I do not even see Spring instantiating the listener using my configuration.  Alternatively, I've tried using XML configuration to configure the listener, but the default listener is still the one that is used.
    <!-- enable Spring data-JPA repositories -->
    <jpa:repositories base-package="com.ia" />

    <bean id="auditingEntityListener" class="org.springframework.data.jpa.domain.support.AuditingEntityListener">
        <property name="auditingHandler" ref="auditingHandler"/>
    </bean>

Any suggestions would be helpful.

A: I met the same question.
The short version
You have to register jpaAuditingHandler bean definition using BeanDefinitionRegistry.
The long version
the org.springframework.data.jpa.domain.support.AuditingEntityListener is a special class which mixed in with aspectj when compiling. see here
It need a bean definition to work. see the spring framework document.
the org.springframework.data.jpa.repository.config.EnableJpaAuditing you are using will register the bean definition with auditingHandler bind to a jpaAuditingHandler bean. It also will register the jpaAuditingHandler bean definition.
If you add a jpaAuditingHandler using @Component, it won't work because Spring prefer another one. see org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader#loadBeanDefinitionsForConfigurationClass
So you have to register your bean definition using BeanDefinitionRegistry.
public class jpaAuditingHandlerRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("jpaAuditingHandler", BeanDefinitionBuilder
                .rootBeanDefinition(JpaAuditingHandler.class)
                .addConstructorArgReference("jpaMappingContext")
                .getBeanDefinition());
    }
}

and add @Import(JpaAuditingHandlerRegistrar.class) to your Configuration class
@SpringBootApplication
@EnableJpaAuditing
@Import(JpaAuditingHandlerRegistrar.class)
public class Application {

I put sample code https://github.com/macdao/customize-auditing-handler


text:
Q: GEO Datasets in Orange I am a new user to the Orange Data Mining and I was taking the BioInformatics tutorial as a means to do some initial exploring on the platform.
Going directly to the problem at hand when I put the GEO Datasets widget into my Canvas I apparently get an error downloading the datasets that is described as the following Python errors :

ValueError                                    Traceback (most recent
  call last):   File
  "C:\Python27\lib\site-packages\orange_bioinformatics-2.6.1-py2.7.egg\orangecontrib\bio\widgets\OWGEODatasets.py",
  line 518, in _on_dataready
      data = self._datatask.result()   File "C:\Python27\lib\site-packages\Orange\OrangeWidgets\OWConcurrent.py",
  line 315, in result
      return self._future.result(timeout)   File "C:\Python27\lib\site-packages\Orange\OrangeWidgets\OWConcurrent.py",
  line 432, in result
      return self._get_result()   File "C:\Python27\lib\site-packages\Orange\OrangeWidgets\OWConcurrent.py",
  line 420, in _get_result
      raise self._exception ValueError: Invalid mode ('rtb')

I have tried to find solutions online to no end and because of this I have not been able to advance with my Orange exploration. I have to clarify I'm not familiar with Python to understand what exactly those errors mean and how to fix them.

A: Update Orange-Bioinformatics add-on to the latest version.


text:
Q: Competing risks with left-truncation and right-censoring Reading a paper "Cause-Specific Cumulative Incidence Estimation and the Fine and
Gray Model Under Both Left Truncation and Right Censoring" Geskus (2011).
I'm trying to implement the method and was wondering if anyone had any experience with it.
I was wondering how the weight values in Table 1 were calculated? I can't seem to figure it out.
As far as I can tell, once I have these weights then calculating the cumulative incidence functions is straightforward in R.
EDIT
I understand that there is a function in R called finegray. However, in its current form it cannot handle left-truncation?
EDIT2
I have discovered the R function crprep in package mstate. This calculates the weights in the presence of right-censoring and left-truncation.
However, I'm still having trouble recreating Table 1 from Geskus (2011). I don't seem to get all the weights for id=3 that appear in Table 1. Any help would be greatly appreciated.


text:
Q: Http Post not working (Android) My code works fine on android 2.2 but doesn't work on Android 4+.Does anybody know what's the problem.I tried it on the android simulator and my phone.P.S I have put the internet permission.
      protected void postData2(){

    HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;
            String response = null;
            String parameters = "Post Data Here";

            try
            {

                url = new URL ("URL");

                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();
               String line = "";
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }
                // Response from server after login process will be stored in response variable.
                response = sb.toString();
                // You can perform UI operations here
                Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
                isr.close();
                reader.close();

            }
            catch(IOException e)
            {
                // Error
            }
                }

A:     public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

              InputStream is = httpResponse.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
String json = sb.toString();///HERE IS WHAT YOU NEED

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

A: i am using for posts requests the followig code which works for me perfectly:
private String sendPostRequest(String restPath, String param1,String param2) {
        String response = "ERROR";
        try {
            data = URLEncoder.encode("param1Key", "UTF-8") + "="
                        + URLEncoder.encode(param1, "UTF-8");
                data += "&" + URLEncoder.encode("param2Key", "UTF-8") + "="
                        + URLEncoder.encode(param2, "UTF-8");

                        URL url = new URL(SERVER_ADRRESS + restPath);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            String answer = "";
            while ((line = rd.readLine()) != null) {

                Log.i("sendPostRequest, " + restPath + ":", line);
                answer += line;

            }
            wr.close();
            rd.close();
            response = answer;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            return response;
        }

        return response;
    }

I hope it helps
Cheers!

A: Use aysnctask
http://developer.android.com/reference/android/os/AsyncTask.html
or
use this in you code
       if (Build.VERSION.SDK_INT>= 10) {
        ThreadPolicy tp = ThreadPolicy.LAX;
        StrictMode.setThreadPolicy(tp);
        }

android does not allow network operation on main thread for > API 9


text:
Q: Increasing network range for new VOIP users Our office using 192.168.1.0 /24 for DHCP 120 users and reserved 20 IP for servers and 10 IP for network printers.
Now management decided to upgrade to VOIP phones for all users so I need to make some changes on network. But, all the users desk will have only one data point so both VOIP phone and PC need to share which means desk Cat 6 cable will connect to VOIP phone port and Phone's PC port is connect to PC Ethernet port. I have 3 options to choose so please correct me which is the best for me?
Option 1: Shall I increase network to /22? I will move VOIP phones and PC to 192.168.2.0/22 and all servers and network printers will remain the same static IP address range 192.168.1.0/22 . Now all the PCs are grabbing IP address from DHCP server so after changing network to /22 so I strongly believe that I need to change new subnet on DHCP. Can I disable the existing scope since I am going to use static IP address (192.168.1.x) for servers and Printers and shall I create New Scope (192.168.2.1-192.168.2.250) for new VOIP Phones and PCs? Or remain the existing scope (192.168.1.0/22) and just add a new scope (192.168.2.0/22) ?
Option 2: Shall I use VLAN for PCs and Phones so I don't need to change new subnet on all servers? But, I am not sure how to configure on 3Com VLAN supported managed switch and I am not sure whether this VLAN can use for one Ethernet cable sharing for VOIP+PCs with two ip addresses?
Option 3: I will just change /22 subnet and all the PCs will remain the same ip address (192.168.1.0) which will grab IP from DHCP server and I will use static IP address for VOIP Phones (192.168.2.0). I am not sure whether I can use two different segments for one data point which mean VOIP phone will use .2 and Servers/Pcs/Netowrk printers will remain .1 network?
Please advice me. Thanks a lot. It's a hard time for me.

A: 192.168.1.0/22 and 192.168.2.0/22 are the same thing.  Actually, they are both part of 192.168.0.0/22 which covers all addresses from 192.168.0.0 through 192.168.3.255
Consult a Variable-Length Subnetting Chart ("VLSM chart") for easy visual assistance on understanding how one subnet contains the same addresses of multiple other subnets.
Basically, a /24 contains 256 addresses.  A /23 contains twice what a /24 has, and a /22 contains twice what a /23 has.
You can have two DHCP scopes simultaneously.  If the devices (e.g., PCs) don't need to communicate with each other, that may even be the smoothest way to introduce a transition.  e.g.: place new equipment on 192.168.4.0/22 (192.168.4.0 through 192.168.7.255), which means subnet mask "255.255.252.0".  For critical equipment like the routers, place them on 192.168.0.0/21 (subnet mask 255.255.248.0, so they can communicate with 192.168.0.0 through 192.168.7.255) during the time of the transition; then you can move them to 192.168.4.0/22 (subnet mask 255.255.252.0) after the transition is done.  Devices on the old subnet ought to work until they renew their DHCP lease; they can renew their release (often by restarting the device) if you want them on the new subnet sooner.

A: You really don't want VoIP phones sharing a layer-2 domain with your regular data traffic. A common solution for what you have is to create separate VoIP and data VLANs, each with their own network addressing. This prevents all the PC/Server/Printer traffic from hindering the VoIP traffic which is particularly sensitive to jitter. It also makes it easier to build your QoS policies, which are particularly important to have if you are using VoIP.
Most VoIP phones which have data ports for connecting PCs are really switches internally. This allows them to trunk to the switch and connect separate data and VoIP VLANs. Many switches can use LLDP or CDP to automatically negotiate this trunk, or you can configure the trunk on the switch port.


text:
Q: Is this correct way to implement MVVM? I'm creating an application that enables a user to insert, update and delete data that has been entered and then shown in a data-grid (CRUD operations).
In my View Model, it contains properties which are bound to the xaml (Firstname for example). It also contains a navigation property as well as validation attributes.
      [Required(ErrorMessage = "First Name is a required field")]
      [RegularExpression(@"^[a-zA-Z''-'\s]{1,20}$", ErrorMessage = "First Name must       contain no more then 20 characters and contain no digits.")]
      public string FirstName
      {
        get { return _FirstName; }
        set
        {
            if (_FirstName == value)
                return;

            _FirstName = value;
            OnPropertyChanged("FirstName");
        }
    }

Furthermore, it contains commands for the xaml to execute, which creates an instance of the CRUD operation;
    private void UpdateFormExecute()
    {
        var org = new OrganisationTypeDetail();
        UpdateOrganisationTypeDetail(org);
    }

And lastly, it contains the CRUD operations as well. Such as the Insert, Update and Delete.
Which leads me to my question. if I want to implement the correct MVVM way, is all this code too much for the view model to contain?
Should I use the model and create a collection within my View-model and bound that to my xaml? Would this be the correct way of doing it?
Should I use a Repository system for the CRUD operations? If so, how would I pass the data from the text fields through to the model to get updated?
Im new to WPF, MVVM and finding it hard to adapt without proper guidance.

A: I would say that this is a correct way to implement MVVM, but not the correct way to implement MVVM.
What I mean by this is that there is no one correct way to implement this pattern. if you have created a ViewModel that can be bound to your View, without having any extra logic within your View (i.e. code-behind) then you have captured the essence of MVVM.
Whether or not you add more patterns and structure to your code is entirely up to you. If this is a simple application, I would keep the patterns light. Go ahead and have your ViewModel talk directly with a repository. You current code looks just fine to me in that respect.
If this is a large application, you might want to add further layers, like a service layer, data access layer. You might want to think about dependency injection.
But don't just adopt a pattern, or add an extra layer just because you think you should. Dependency Injection sounds cool, but in many cases it is more hassle than it is worth!

A: For me it's not the correct way, I think defining the properties like FirstName in view model is not good idea. view should contain model only and your view model should be wrap the model which should be bounded to XAML(if required).
Also model object creation should be completely independent of view model. View model should know only about unit operations on models and validations should be inside the model e.g in your case FirstName validations are in ViewModel means you are only limiting GUI to validate the FirstName property, but what if someone set it from other place.


text:
Q: condicional executar query mongo Tengo el siguiente código, y quiero saber si hay alguna función de mongodb que devuelva true o false dependiendo de si la query se ha ejecutado correctamente o no.
public function removepopup($id){
    $collection = $this->connect()->deleteOne(['_id' => new MongoDB\BSON\ObjectID( $id )]);
}

A: El método deleteOne(), por lo que he leido en la documentación te devuelve un Objeto del tipo MongoDB\DeleteResult,  https://docs.mongodb.com/php-library/v1.2/reference/write-result-classes/#phpclass.MongoDB\DeleteResult . Se utiliza para encapsular en objeto PHP http://php.net/class.mongodb-driver-writeresult . Bien, el objeto php tiene unos métodos, escribiré un código a ver si te sirve, basandome en el método: http://php.net/manual/es/mongodb-driver-writeresult.getdeletedcount.php
public function removepopup($id){
    $collection = $this->connect()->deleteOne(['_id' => new MongoDB\BSON\ObjectID( $id )]);
     if($collection->getDeletedCount() == 0){
          //No se ha eliminado ninguna fila
          return false;
     }
     return true;
}


text:
Q: ipython notebook config options ignored unless placed in regular config file OS X 10.6.8, ipython upgraded from 1.something (from fink) to 3.0.0 (using pip). Everything seems to work fine, except an issue with configuration.
From the documentation and my own testing, I am having trouble understanding the expected behavior of config options in my .ipython/profile_default/ipython_config.py versus the ipython_notebook_config.py.
I want to auto-load a couple of extensions and modules for my notebooks but not for my regular ipython sessions (partly because those loads create warnings, but it just seems that I'm supposed to be able to keep these configurations separate). It seemed to make sense that config options that apply only to the notebook go in the notebook config. But I can only get the notebook to honour my choices when I put the options in ipython_config.py. It seems to ignore the notebook config, and I am stuck with non-notebook ipython also loading these modules. Am I doing something wrong?
The documentation does not explicitly address the distinctions, and the inline comments in these files do not make reference to the distinction between these two config files, only to inheritance of TerminalIPythonApp from Application and InteractiveShellApp (but same class names in both config files). What is the rule for notebook config reading? Does ipython read from one first, then the other? Currently, it seems to ignore the ipython_notebook_config.py altogether, so why is it there?
Maybe it's related to this from 2013: http://mail.scipy.org/pipermail/ipython-user/2013-February/012170.html
But the commit that fixed his problem is surely in the master repo by this point, so maybe not...
The result of ipython notebook --debug is
[D 10:37:52.595 NotebookApp] Config changed:
[D 10:37:52.595 NotebookApp] {'NotebookApp': {'log_level': 10}}
[D 10:37:52.596 NotebookApp] IPYTHONDIR set to: /Users/robclewley/.ipython
[I 10:37:52.598 NotebookApp] Using existing profile dir: u'/Users/robclewley/.ipython/profile_default'
[D 10:37:52.598 NotebookApp] Searching path [u'/Users/robclewley/Work/literate_modeling/scenario-local-linear/notebook/project', u'/Users/robclewley/.ipython/profile_default', '/usr/local/etc/ipython', '/etc/ipython'] for config files
[D 10:37:52.598 NotebookApp] Attempting to load config file: ipython_config.py
[D 10:37:52.600 NotebookApp] Loaded config file: /Users/robclewley/.ipython/profile_default/ipython_config.py
[D 10:37:52.601 NotebookApp] Config changed:
[D 10:37:52.601 NotebookApp] {'TerminalInteractiveShell': {'logstart': True}, 'NotebookApp': {'log_level': 10}, 'TerminalIPythonApp': {'matplotlib': 'osx'}}
[D 10:37:52.602 NotebookApp] Attempting to load config file: ipython_notebook_config.py
[D 10:37:52.604 NotebookApp] Loaded config file: /Users/robclewley/.ipython/profile_default/ipython_notebook_config.py
[D 10:37:52.605 NotebookApp] Config changed:
[D 10:37:52.605 NotebookApp] {'TerminalInteractiveShell': {'logstart': True}, 'NotebookApp': {'log_level': 10}, 'InteractiveShellApp': {'exec_lines': ['import notebook_importing'], 'gui': 'osx', 'pylab': 'osx', 'matplotlib': 'osx', 'extensions': ['yaml_magic', 'autoreload'], 'extra_extension': 'yaml_magic'}, 'TerminalIPythonApp': {'extra_extension': 'yaml_magic', 'extensions': ['yaml_magic'], 'matplotlib': 'osx'}}
[D 10:37:52.611 NotebookApp] searching for local mathjax in [u'/Users/robclewley/.ipython/nbextensions', '/sw/share/jupyter/nbextensions', '/usr/local/share/jupyter/nbextensions', '/usr/share/jupyter/nbextensions']
[D 10:37:52.613 NotebookApp] searching for local mathjax in [u'/Users/robclewley/.ipython/profile_default/static', '/sw/lib/python2.7/site-packages/IPython/html/static']
[I 10:37:52.613 NotebookApp] Using MathJax from CDN: https://cdn.mathjax.org/mathjax/latest/MathJax.js

For instance, invoking the magic command %%yaml (from my custom extension) in the notebook results in a complaint that the command is not recognized. If, instead, I set these extensions to be loaded in ipython_config.py, then the notebook accepts %%yaml immediately. In this case, the debug output is:
[D 10:46:50.330 NotebookApp] Config changed:
[D 10:46:50.330 NotebookApp] {'NotebookApp': {'log_level': 10}}
[D 10:46:50.331 NotebookApp] IPYTHONDIR set to: /Users/robclewley/.ipython
[I 10:46:50.332 NotebookApp] Using existing profile dir: u'/Users/robclewley/.ipython/profile_default'
[D 10:46:50.332 NotebookApp] Searching path [u'/Users/robclewley/Work/literate_modeling/scenario-local-linear/notebook/project', u'/Users/robclewley/.ipython/profile_default', '/usr/local/etc/ipython', '/etc/ipython'] for config files
[D 10:46:50.332 NotebookApp] Attempting to load config file: ipython_config.py
[D 10:46:50.335 NotebookApp] Loaded config file: /Users/robclewley/.ipython/profile_default/ipython_config.py
[D 10:46:50.336 NotebookApp] Config changed:
[D 10:46:50.337 NotebookApp] {'TerminalInteractiveShell': {'logstart': True}, 'NotebookApp': {'log_level': 10}, 'InteractiveShellApp': {'extensions': ['yaml_magic', 'autoreload']}, 'TerminalIPythonApp': {'matplotlib': 'osx'}}
[D 10:46:50.337 NotebookApp] Attempting to load config file: ipython_notebook_config.py
[D 10:46:50.338 NotebookApp] Loaded config file: /Users/robclewley/.ipython/profile_default/ipython_notebook_config.py
[D 10:46:50.339 NotebookApp] Config changed:
[D 10:46:50.340 NotebookApp] {'TerminalInteractiveShell': {'logstart': True}, 'NotebookApp': {'log_level': 10}, 'InteractiveShellApp': {'extra_extension': 'yaml_magic', 'extensions': ['yaml_magic', 'autoreload'], 'exec_lines': ['import notebook_importing'], 'gui': 'osx', 'pylab': 'osx', 'matplotlib': 'osx'}, 'TerminalIPythonApp': {'extra_extension': 'yaml_magic', 'extensions': ['yaml_magic'], 'matplotlib': 'osx'}}
[D 10:46:50.345 NotebookApp] searching for local mathjax in [u'/Users/robclewley/.ipython/nbextensions', '/sw/share/jupyter/nbextensions', '/usr/local/share/jupyter/nbextensions', '/usr/share/jupyter/nbextensions']
[D 10:46:50.345 NotebookApp] searching for local mathjax in [u'/Users/robclewley/.ipython/profile_default/static', '/sw/lib/python2.7/site-packages/IPython/html/static']

Thanks.

A: In the meantime, this was answered here:
http://comments.gmane.org/gmane.comp.python.ipython.user/11941
Essentially, the kernel and notebook server are different. The kernel's config file (missing by default on my system) is where the root, global config options go. From the forum thread, clearer documentation about this structure will be forthcoming.


text:
Q: Find specific data from a text file in VBA I want to fetch the data from a text file which starts with arrUserActivity in VBA. I'm able to fetch if there is no break line i.e Sample 1 but not for Sample 2.
Sample 1 :
var arrUserActivity = [['9/13/2022 8:49:00 AM','MOA_S10EST','Firoj  Aga','Remote Desktop using VNC 2.0 ','CBM'],['9/13/2022 1:54:00 PM','MOA_S10EST','Aux Tech2','Remote Desktop using VNC 2.0','Routine']];
Sample 2 :
var arrUserActivity = [
['9/13/2022 8:49:00 AM','MOA_S10EST','Firoj  Aga','Remote Desktop using VNC 2.0 ','CBM'],
['9/13/2022 1:54:00 PM','MOA_S10EST','Aux Tech2','Remote Desktop using VNC 2.0 ','Routine']];
My code is  :
 WhatToFind = "var arrUserActivity"
    FromFile1 = Path + "\02-Text_Files\" + Site_Name + ".txt"
    FileNum = FreeFile()
    Open FromFile1 For Input As #FileNum
    Do While Not EOF(FileNum)
    lngCount = lngCount + 1    'increment a counter'
    Line Input #FileNum, DataLine    ' read in data 1 line at a time'
    If InStr(1, DataLine, WhatToFind) > 0 Then    'the string is found'
    bFound = True    'set a boolean value to true'
    Exit Do    'and stop the loop'
    End If
    Loop

I'm able to fetch data if there is no line break.

A: This will do
WhatToFindStart = "var arrUserActivity"
 WhatToFindEnd = "];"
    FromFile1 = Path + "\02-Text_Files\" + Site_Name + ".txt"
    FileNum = FreeFile()
    Open FromFile1 For Input As #FileNum
    Do While Not EOF(FileNum)
        lngCount = lngCount + 1    'increment a counter'
        Line Input #FileNum, DataLine    ' read in data 1 line at a time'
        If InStr(1, DataLine, WhatToFindStart) > 0 Then    'the string is found'
            bFoundStart = True    'set a boolean value to true'
        End If
        If bFoundStart Then
            Data = Data & DataLine
            Data2 = Data2 & Trim(Replace(DataLine, " ", ""))
            If Right(Data2, 2) = WhatToFindEnd Then
                bFound = True
                Debug.Print (Data) 'Here yo have the data in one line
                Exit Do
            End If
        End If
    Loop
    Close


text:
Q: Optional arguments for newtcblisting? Is it possible to have optional arguments for newtcblisting?
Do I use \ifthenelse?

A: Edit: added the solution suggested by @cmhughes in his comment using the xparse library.
Here is an example of the tcolorbox manual section 4.13 p 302, the argument in square brackets [ ] is optional :
\documentclass{article}
\usepackage[most]{tcolorbox}

\newtcblisting{mybox}[2][]{%
colback=red!5!white,
colframe=red!75!black,
fonttitle=\bfseries,
title=#2,#1}

\begin{document}
\begin{mybox}%[listing only]
{Listing Box}
This is my \LaTeX\ box.
\end{mybox}
\bigskip

\begin{mybox}[listing only]
{Listing Box}
This is my \LaTeX\ box.
\end{mybox}
\bigskip

\begin{mybox}[listing side text]
{Listing Box}
This is my
\LaTeX\ box.
\end{mybox}

\end{document}

Output:

Second solution with the xparse library
The format is \DeclareTCBListing[init options]{name}{specification}{options}
where {specifications} are those of the xparse package.
In the example, from page 441 of manual 4.13 the specifications are { s O{} m } where :

*

*"s" is an optional star, which will result in a value \BooleanTrue if a star is present and \BooleanFalse otherwise (as described later).

*O{} is  as for "o", but returns hdefaulti if no value is given. Should be given as O{hdefaulti}.

*m is a standard mandatory argument, which can either be a single token alone or multiple tokens surrounded by curly braces. Regardless of the input, the argument will be passed to the internal code surrounded by a brace pair. This is the xparse type specifier for a normal T E X argument

See the xparse package documentation for more information: xparse
\documentclass{article}
\usepackage[most]{tcolorbox}

\DeclareTCBListing{mybox}{ s O{} m }{%
colback=red!5!white,
colframe=red!75!black,
fonttitle=\bfseries,
IfBooleanTF={#1}
{listing side text}
{text side listing},
title=#3,#2}

\begin{document}

\begin{mybox}{Listing Box}
This is my
\LaTeX\ box.
\end{mybox}
\bigskip
\begin{mybox}*{Listing Box}
This is my
\LaTeX\ box.
\end{mybox}
\bigskip
\begin{mybox}[colback=yellow]
{Listing Box}
This is my
\LaTeX\ box.
\end{mybox}

\end{document}


text:
Q: Uncaught ReferenceError: $hxClasses is not defined in Haxe js project I am having an issue that I discussed on the Haxe IRC channel but was unable to come up with a fix. It seems to be a bug with the compiler.
Here is the Haxe code:
package;

import js.Lib;
import js.three.Three;
import haxe.Timer;

class Main {

    public var timer:Timer;
    public var renderer:WebGLRenderer;
    public var scene:Scene;
    public var camera:PerspectiveCamera;

    public function new() {

        timer = new Timer(30);

        var w = Lib.window.innerWidth;
        var h = Lib.window.innerHeight;

        scene = new Scene();

        // create a red cube
        var material = new MeshLambertMaterial({color:0xff0000});
        var geometry = new CubeGeometry(50, 50, 50, 1, 1, 1, material, null);
        var cube = new Mesh(geometry, new MeshFaceMaterial());
        cube.position.set(0, 100, 0);
        scene.add(cube);
        // add some light
        var pointLight = new PointLight(0xffffff, 1, 0);
        pointLight.position.set(10, 50, 130);
        scene.add(pointLight);
        // and a camera
        camera = new PerspectiveCamera(70, w/h, 1, 1000);
        camera.position.z = 500;
        scene.add(camera);
        // setup renderer in the document
        renderer = new WebGLRenderer(null);
        renderer.setSize(w, h);

        Lib.document.body.appendChild(renderer.domElement);

        untyped Lib.window.onload = onLoad;
    }

    public function onLoad() {

        timer.run = function(){

            renderer.render(scene, camera, null, null);
        }
    }

    public static function main() {
        new Main();
    }

}

The solution is to get the compiler to add the following to the beginning of the JS file that it creates.
var $_, $hxClasses = $hxClasses || {},

As it stands right now the first line in the JS file looks like this
$estr = function() { return js.Boot.__string_rec(this,''); }

Not sure what needs to be done to fix this or a possible work around other than adding in that line by hand after compilation ?

A: Found the issue - three.js has Date.hx and Timer.hx files in it (older versions) delete them and it works (on my win install it's in c:\Motion-Twin\haxe\lib\three,js\0,2,46\ and c:\Motion-Twin\haxe\lib\three,js\0,2,46\haxe)


text:
Q: Auto-COmmit of DDL I read that "CREATE TABLE" and "DROP TABLE" statements are auto-commit. I am trying to understand their behaviour for the below scenario:
conn.setAutoCommit(false);
stmt = conn.createStatement("CREATE TABLE ...");

conn.commit();

In the above case, would setting autoCommit to false would have any impact on CREATE TABLE auto-commiting. If conn.setAutoCommit(false) does override DDL auto-commit property, then whats the entire point, because by default a new connection is in auto-commit mode.
I believe except MySQL and older versions of ORacle, most major RDBMS allow DDL rollback. My questions concerns If in MySQL DDL rollback is not allowed, what is point of setting auto-commit of connection to false for DDL operations?
I will really appreciate your opinion in clarifying my doubts.

A: Executing a DDL statement causes an "implicit commit".  But the statement has to be executed.
The scenario you give doesn't make sense to me, the createStatement method doesn't take a string as an argument, does it?
We typically see
stmt = conn.createStatement();
stmt.execute("CREATE TABLE ... ");

If you actually execute a DDL statement, it causes an implicit commit, as if you had run a COMMIT; statement immediately before you ran the DDL statement.
But don't take my word for it, try it yourself, and consult the appropriate section of the MySQL Reference Manual for whichever version of MySQL you are running.
Reference: https://dev.mysql.com/doc/refman/5.6/en/implicit-commit.html


text:
Q: Websocket connection failed - Jhipster Vue for production with secure connection My build version is Jhipster 7.9.3, monolith, with Vue and websocket. I want to run my application in secure connection via SSL/https.
I had run the server (backend) using gradlew -Pprod -x webapp --spring.profiles.active=prod,tls and for the front-end using nginx reverse proxy with a secure connection https (ssl/letsencrypt).
Now the problem is, there is error with websocket connection; WebSocket connection to 'wss://localhost:9060/ws' failed, as according to the documentation when the frontend is secure, it also the same with the backend. The backend is also secured, but it seems the WSS is not accessible
console log;
Production log:

GET https://app.mydomain.com/api/account 401
(Unauthorized) (anonymous) @ xhr.js:220 t.exports @ xhr.js:16
tracker.service.ts:39 Tue Sep 20 2022 19:37:41 GMT+0800 (
Time) 'Opening Web Socket...' abstract-xhr.js:132          POST
https://app.mydomain.com/websocket/tracker/692/aruisji5/xhr?access_token=bla bla bla
405 (Not Allowed)
Uncaught SyntaxError: Unexpected token '<' (at
jsonp?access_token=ebla bla bla
tracker.service.ts:39 Tue Sep 20 2022 19:37:43 GMT+0800 (
Time) 'Connection closed to undefined' tracker.service.ts:39 Tue Sep
20 2022 19:37:43 GMT+0800 (Time) 'STOMP: scheduling
reconnection in 5000ms' tracker.service.ts:39 Tue Sep 20 2022 19:37:48
GMT+0800 (Time) 'Opening Web Socket...' websocket.js:6
WebSocket connection to
'wss://app.mydomain.com/websocket/tracker/629/qbujjtrn/websocket?access_token=bla bla bla token bla bla failed:
POST https://app.mydomain.com/websocket/tracker/629/xqnxz0w0/xhr_streaming?access_token=bla
bla bla token bla bla bla 405 (Not Allowed)

Dev console log:

xhr.js:220          GET https://localhost:9000/management/info 502
(Bad Gateway) WebSocketClient.js:16 WebSocket connection to
'wss://localhost:9060/ws' failed:  WebSocketClient @
WebSocketClient.js:16 initSocket @ socket.js:24 (anonymous) @
socket.js:48 index.js:561 [webpack-dev-server] Event {isTrusted: true,
type: 'error', target: WebSocket, currentTarget: WebSocket,
eventPhase: 2, …}

For now, I run my production build using a secure connection for the frontend and backend but with websocket error still there.
EDIT:
The error from console in production is the same with dev build, So I am using example from the dev console.

A: I am updating this post with the current solution I have right now. The first problem I have is to use NGINX server and secure connection using SSL/TLS. I am using AWS amazon ec2 ubuntu and reconfigured the nginx block like this and it is working. The websocket is working now, just to make sure to set up the proxy;
server {
    listen      [::]:80;
    listen      80;
    server_name test.yourserver.com;

    root /var/www/test.yourserver.com/html;
    index index.html index.htm index.nginx-debian.html;

    access_log  /var/log/nginx/test.yourserver.com-access.log;
    error_log   /var/log/nginx/test.yourserver.com-error.log;

    location /api {
        proxy_pass https://localhost:8080/api;
    }

    location /i18n {
        proxy_pass https://localhost:8080/i18n;
    }

    location /content {
        proxy_pass https://localhost:8080/content;
    }

    location /app {
        proxy_pass https://localhost:8080/app;
    }

    location /swagger-ui {
        proxy_pass https://localhost:8080/swagger-ui;
    }

    location /test {
        proxy_pass https://localhost:8080/test;
    }

    location /management {
        proxy_pass https://localhost:8080/management;
    }

    location /swagger-resources {
        proxy_pass https://localhost:8080/swagger-resources;
    }

    location /v2 {
        proxy_pass https://localhost:8080/v2;
    }

    location /auth {
        proxy_pass https://localhost:8080/auth;
    }

    location /websocket {
        proxy_pass https://localhost:8080/websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass_header X-XSRF-TOKEN;
        proxy_set_header X-NginX-Proxy true;
    }

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


text:
Q: Tmux colors lost I've got two very similar Linux installations (Manjaro). On one of them the basic output is colored out of the box (no ~/.tmux.conf yet). On another it's black an white. Adding
~/.tmux.conf:
set -g default-terminal "screen-256color"

makes no difference. Different console applications make no difference, too. What should I check?


text:
Q: Singleton array deallocated? EXC_BAD_ACCESS Ok, so I have this singleton object and in it is an array that needs to be shown in a tableview.
The thing is that it deallocates and after the first show, i get EXC_BAD_ACCESS in cellForRowAtIndexPath
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 return [[dataBase shareddataBase].dateActive count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"celula"];
 int i;
 i=indexPath.row;
 if (cell==nil) {
  cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"celula"];
 }

count sent to dealocated instance of CFArray .. in cellForRowAtIndexPath..
WHAT is deallocating it? why?
it's declarea as an NSMutableArray and has a (nonatomic,retain) property defined ..
 if ((i<[[dataBase shareddataBase].dateActive count])&&(i>=0)) {
  NSDictionary *d=[[dataBase shareddataBase].dateActive objectAtIndex:i];
  cell.textLabel.text=[d objectForKey:@"detaliu"];
 }

  return cell;
}

A: Most likely you never retained shareddatabase when you set it.


text:
Q: How to map fields by stream api I have a simple class:
class Note {
    public int id;
    public String status;
    // some other fields....
}

and I'm want to map fields of this class by the stream api. I have a simple implementation of method, that do what I'm want:
public function(int externalId) {
    Set<Note> notes = getFromRepository(); // simple method for getting all Note from repository
    for (Note note : notes){
        note.setId(externalId);
        note.setStatus("Open");
    }
}

How I can do it with Stream api?

A: Map is not really appropriate here because

*

*setters don't typically return a value (although you can fudge it), and

*map is not a terminal operation so you would need some unnecessary terminal operation to trigger the stream.

But there is nothing gained by using a stream here.  And since getFromRespository returns a set you can use the Set interface's forEach method directly.
public void function(int externalId) {
     getFromRespository().forEach(note->{
                     note.setID(externalId);
                     note.setStatus("Open");
    });
}

BTW, there is nothing wrong with your existing implementation.  As you said, it is "simple", and therefore is easy to understand.


text:
Q: How to group properties into a sub-object when serializing to JSON Given this class:
public class Thing
{
    public string Alpha { get; set; }
    public string Beta { get; set; }
}

I need to serialize arbitrary subclasses of Thing which subclasses may themselves add Thing properties.  For example...
public class SomeThing : Thing
{
  public string Delta {get; set; }

  public Thing ThisThing { get; set; }
  public Thing ThatThing { get; set; }
}

It is easy, using Newtonsoft Json.NET to serialize a SomeThing class to this:
{
  alpha: "x",
  beta: "x",
  delta: "x",

  thisThing: {
    alpha: "y",
    beta: "y"
  },
  thatThing: {
    alpha: "z",
    beta: "z"
  }
}

What I want to do, though, is this (without changing the Thing or SomeThing classes):
{
  alpha: "x",
  beta: "x",
  delta: "x",

  things: {
    thisThing: {
      alpha: "y",
      beta: "y"
    },
    thatThing: {
      alpha: "z",
      beta: "z"
  }
}

That is, I want to collect any Thing properties into a sub-object named things.
Another example:
public class SomeThingElse : Thing
{
  public int Gamma {get; set; }

  public Thing Epsilon { get; set; }
}

...would serialize to
{
  alpha: "x",
  beta: "x",
  gamma: 42,

  things: {
    epsilon: {
      alpha: "y",
      beta: "y"
    }
  }
}

By creating a contract resolver I can easily peel out the individual thing properties and leave the non-things to serialize themselves.  But I don't know how to create the things property and stuff back in the properties I peeled out:
public class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        // grab the properties that are NOT a Thing
        var toCreate = properties.Where(p => !typeof(Thing).IsAssignableFrom(p.PropertyType)).ToList();

        // grab the properties that ARE a Thing
        var toGroup = properties.Where(p => typeof(Thing).IsAssignableFrom(p.PropertyType)).ToList();

        // create the new things property to stuff toGroup into
        var things = new JsonProperty
        {
            PropertyName = "things"
        };

        // THIS IS WHERE I'M STUCK...
        // TODO: somehow stuff toGroup into "things"

        // put the group back along with the non-thing properties
        toCreate.Add(things);

        // return the re-combined set of properties
        return toCreate;
    }
}

I use this resolver as follows (simplified for this question):
static void Main(string[] args)
{
    var st = new SomeThing
    {
        Alpha = "x",
        Beta = "x",
        Delta = "x",
        ThisThing = new Thing() {Alpha = "y", Beta = "y"},
        ThatThing = new Thing() {Alpha = "z", Beta = "z"}
    };

    var settings = new JsonSerializerSettings
    {
        ContractResolver = new MyContractResolver(),
        Formatting = Formatting.Indented
    };

    var result = JsonConvert.SerializeObject(st, settings);

    Console.WriteLine(result);
}

Which produces
{
  alpha: "x",
  beta: "x",
  delta: "x"
}

Notice that even though I've created and added a JsonProperty with the name of "things" it does not appear.  My hope is I just need to fill in the blanks near the TODO in the contract resolver.
Or maybe I'm going in the wrong direction.  Can you help me?

A: It is possible to do what you want using a custom IContractResolver in combination with a custom IValueProvider.  Try this:
public class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        // if the type is a Thing and has child properties that are things...
        if (typeof(Thing).IsAssignableFrom(type) &&
            properties.Any(p => typeof(Thing).IsAssignableFrom(p.PropertyType)))
        {
            // grab only the properties that are NOT a Thing
            properties = properties
                .Where(p => !typeof(Thing).IsAssignableFrom(p.PropertyType))
                .ToList();

            // Create a virtual "things" property to group the remaining properties
            // into; associate the new property with a ValueProvider that will do
            // the actual grouping when the containing object is serialized
            properties.Add(new JsonProperty
            {
                DeclaringType = type,
                PropertyType = typeof(Dictionary<string, object>),
                PropertyName = "things",
                ValueProvider = new ThingValueProvider(),
                Readable = true,
                Writable = false
            });
        }

        return properties;
    }

    private class ThingValueProvider : IValueProvider
    {
        public object GetValue(object target)
        {
            // target should be a Thing; we want to get its Thing properties
            // and group them into a Dictionary.
            return target.GetType().GetProperties()
                         .Where(p => typeof(Thing).IsAssignableFrom(p.PropertyType))
                         .ToDictionary(p => p.Name, p => p.GetValue(target));
        }

        public void SetValue(object target, object value)
        {
            throw new NotImplementedException();
        }
    }
}

Demo:
class Program
{
    static void Main(string[] args)
    {
        SomeThing st = new SomeThing
        {
            Alpha = "x.a",
            Beta = "x.b",
            ThisThing = new Thing { Alpha = "y.a", Beta = "y.b" },
            ThatThing = new SomeThingElse
            {
                Alpha = "z.a",
                Beta = "z.b",
                Delta = 42,
                Epsilon = new Thing { Alpha = "e.a", Beta = "e.b" }
            }
        };

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.ContractResolver = new MyContractResolver();
        settings.Formatting = Formatting.Indented;

        string json = JsonConvert.SerializeObject(st, settings);

        Console.WriteLine(json);
    }
}

public class Thing
{
    public string Alpha { get; set; }
    public string Beta { get; set; }
}

public class SomeThing : Thing
{
    public Thing ThisThing { get; set; }
    public Thing ThatThing { get; set; }
}

public class SomeThingElse : Thing
{
    public int Delta { get; set; }
    public Thing Epsilon { get; set; }
}

Output:
{
  "alpha": "x.a",
  "beta": "x.b",
  "things": {
    "thisThing": {
      "alpha": "y.a",
      "beta": "y.b"
    },
    "thatThing": {
      "delta": 42,
      "alpha": "z.a",
      "beta": "z.b",
      "things": {
        "epsilon": {
          "alpha": "e.a",
          "beta": "e.b"
        }
      }
    }
  }
}

A: Here's another converter that uses reflection to get the Things:
public class MyConverter : JsonConverter
{
    public override bool CanRead { get { return false; } }

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        var someThing = (SomeThing)value;

        var things = typeof(SomeThing).GetProperties()
            .Where(pr => pr.PropertyType.IsAssignableFrom(typeof(Thing)))
            .ToDictionary (pr => pr.Name, pr => pr.GetValue(someThing));

        var nonThings = typeof(SomeThing).GetProperties()
            .Where(pr => !pr.PropertyType.IsAssignableFrom(typeof(Thing)));

        writer.WriteStartObject();
        writer.WritePropertyName("things");
        serializer.Serialize(writer, things);

        foreach (var nonThing in nonThings)
        {
            writer.WritePropertyName(nonThing.Name);
            serializer.Serialize(writer, nonThing.GetValue(someThing));
        }

        writer.WriteEndObject();
    }

    public override bool CanConvert(Type type)
    {
        return type == typeof(SomeThing);
    }
}

I am having trouble figuring out how to respect the CamelCasePropertyNamesContractResolver and use the converter though.

A: I think you may be going in the wrong direction.
If contained Thing objects are zero to many you could define your property
List<Thing> Things;

I believe at this point json.Net would serialize how you want without a Contract resolver.

A: Use C# JsonSerializer or NewtonSoft.Json. Examples available at: http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx and http://www.c-sharpcorner.com/UploadFile/dacca2/json-serialization-using-newtonsoft-json-serialize/


text:
Q: How to mesh an ASCII text file from pixel data - MATLAB I have been trying to import data from a .txt file (ASCII text file) into Matlab to then mesh is to have a map of what is happening at each pixel (each pixel have a row and column # and corresponding value).
It is supposed to be a colormap of different air pressures are specific points of an image.
I cannot figure out how to make this happen. The txt file has 1200 rows and 1600 columns.

A: Question is a bit ambiguous. But here's how you read an ASCII file of a matrix and then plot the value of each cell as a colour.
rows = 1200;
cols = 1600;
fid = fopen('file.txt', 'r');
A = fscanf(fid, '%f', [cols rows])'; % transpose so rows of matrix correspond to rows in text
fclose(fid)

imagesc(A)
shading interp


text:
Q: Modificar "NLS_NUMERIC_CHARACTERS" Tengo una bbdd en Oracle 12 con este parámetro:
NLS_NUMERIC_CHARACTERS = '.,';

Necesitaría que quedase al revés ',.'. La única opción que encuentro es:
alter session set NLS_NUMERIC_CHARACTERS = ',.';

Pero esto solo lo cambia a nivel de sesión y necesitaría que la bbdd esté con este formato.
¿Podríais ayudarme?
Gracias.

A:
Pero esto solo lo cambia a nivel de sesión y necesitaría que la bbdd
  esté con este formato.

Los parámetros de lenguaje, regularmente son establecidos a nivel de cliente, cuya configuración ignora la del servidor.
El servidor almacena los datos en formato binario (no se almacenan separadores, es decir, puntos o comas). Lectura recomendada (en inglés): Format models
Dicho esto, puedes establecer el default de la base de datos en el archivo de parámetros de inicialización de tu instancia de Oracle.
NLS_NUMERIC_CHARACTERS = ',.';

Aunque estos son derivados del territorio, por lo que si tu base de datos es para un territorio específico, debiera quedar ya bien configurado al inicializar el mismo, por ejemplo:
NLS_TERRITORY = 'GUATEMALA'

Lista completa de territorios y lenguajes(para oracle 10g)
Finalmente, aunque hagas esto, cada cliente puede elegir sus propios parámetros de formato, por lo que nada de esto será "mandatorio", esto es parte del Soporte para la globalización del motor de base de datos.


text:
Q: Typescript: do I have to check for array to get rid of TS7053 (string index to possible array element) I have run into a situation where I believe obeying typescript checks produces slower code.
So, here's my (oversimplified) function:
function test(data: { [key: string]: any } | any[]) {
  const x = Object.keys(data).reduce((res: { [key: string]: any }, name: string) => {
    const item = data[name];
    const key = item?.name || name;
    ...
  });
}

basically just converts either array or object into an object - when looked simplified like this. In reality it also makes sure that items are of correct class type.
Anyway, the data[name] line produces a TS7053, because - if data is the array - accessor should be a Number.
The solution to typescript warning is to rewrite the line like this:
const item = data instanceof Array ? data[Number(name)] : data[name];

However, I believe this solution is slower than implicit type coercion that happened before for instances where the parameter was an array. It first checks for type, branches and only then does the explicit type conversion and finally accesses the item.
I realize that in case of array, a much more proper solution would be to simply use Array.forEach, but that would require a function extraction to not duplicate the code in question, which is only three lines in its entirety. The intent is just to index the items by their name property for faster access.
Is there a better way to make TypeScript checker happy?

A: An array is also an object, so you can simply omit that from the type signature:
function test(data: { [key: string]: any }) {
  const x = Object.keys(data).reduce((res: { [key: string]: any }, name: string) => {
    const item = data[name];
    const key = item?.name || name;
    res[key] = item;
    return res;
  }, {});
  console.log(x);
}

test([1, 2, 3]);               // { "0": 1, "1": 2, "2": 3 }
test({a: 'Alice', b: 'Bob'});  // { "a": "Alice", "b": "Bob" }

Playground link
This works because Object.keys always returns keys as strings, even if they are numeric array keys, and because you can also use numeric strings to index arrays.
I also had to add an empty object {} as the initial value for reduce, otherwise it will take the first key, which is a string instead of an object.

A: You could use Object.entries() instead of Object.keys(). This saves you from having to do the value lookup and fixes your type problem at the same time:
function test(data: { [key: string]: any } | any[]) {
  return Object.entries(data).reduce((a: { [key: string]: any }, [k, v]) => {
    a[v?.name || k] = v;
    return a;
  }, {});
}

Playground link


text:
Q: VB .Net Can i manage all events from inside a groupbox in an efficient way? I have a groupbox containing a lot of Checkboxes - only Checkboxes.
Is there a simple/fast way to handle the same event coming from different controls?
I know I can write a single sub and let it handle all the Events, but it's really time-consuming to write.
Using Visual Studio 2012

A: If your time concern is about writing and managing a large Handles clause, you can simply loop through the GroupBox's Controls collection upon construction of your UserControl/Form and wire up each event on each CheckBox, like so:
Imports System.Linq

Public Sub New()
    InitializeComponent()

    For Each chkBox As CheckBox In yourGroupBoxVariable.Controls.OfType(Of CheckBox)()
        AddHandler chkBox.CheckStateChanged, AddressOf YourCheckStateChangedHandlerMethod
    Next
End Sub

Private Sub YourCheckStateChangedHandlerMethod(ByVal sender As Object, ByVal e As EventArgs)
    ' Your handler code for the checkboxes
End Sub

This leverages LINQ's OfType Enumerable extension to filter down all child controls of the GroupBox to those of type CheckBox.

A: Another possibility is to create a custom GroupBox, i.e. deriving from GroupBox and exposing the event yourself:
Public Class CheckboxGroup
  Inherits GroupBox

  Public Event CheckboxChanged(source As CheckBox, e As EventArgs)

  Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
    ' this method is called everytime a checkbox is added
    If TypeOf e.Control Is CheckBox Then
      Dim chk As CheckBox = DirectCast(e.Control, CheckBox)
      AddHandler chk.CheckedChanged, AddressOf AllCheckedChange
    End If
  End Sub

  Private Sub AllCheckedChange(source As Object, e As EventArgs)
    If TypeOf source Is CheckBox Then
      Dim chk As CheckBox = DirectCast(source, CheckBox)
      RaiseEvent CheckboxChanged(chk, e)
    End If
  End Sub

End Class

You can then attach to the event in the Form like:
  Private Sub CheckboxChanged(source As CheckBox, e As EventArgs) Handles gb.CheckboxChanged
    MsgBox(source.Text & " to " & source.Checked)
  End Sub

Advantage: you can never miss to add an event handler to a CheckBox, even if it is created dynamically.


text:
Q: How can I set a string from variable as a key in existing object in mongodb I know that this is working:
db.users.update({_id: "1234"}, {$set: {"conversations.partId": id}});

In result I've got: conversations:{"partId":2345}
but I would like to set partId as a variable. And to have structure like this:
conversations:{"3456":"2345"}
I have tried:
db.users.update({_id: "someid"}, {$set: {"conversations".partId: id}});
or
db.users.update({_id: "someid"}, {$set: {"conversations"+partId: id}});

But this is of course not working
Can anyone help me?

A: Try creating the document you need to update via the bracket notation, i.e.
var obj = {};
obj[partId] = id;

You can then use that as a new embedded document to add to the conversations field with the $set operator expression as follows:
db.users.update(
    {_id: "someid"},
    {
        $set: {
            "conversations": obj
        }
    }
);


text:
Q: How to make an Email link in html I want to make an Email link which direct to my Email.
code:
Email

Screenshot

I want to direct to Gmail.com and ready to send Email with my Email address.

A: Email


text:
Q: passing numpy arrays through multiprocessing.Queue I'm using multiprocessing.Queue to pass numpy arrays of float64 between python processes. This is working fine, but I'm worried it may not be as efficient as it could be.
According to the documentation of multiprocessing, objects placed on the Queue will be pickled. calling pickle on a numpy array results in a text representation of the data, so null bytes get replaced by the string "\\x00".
>>> pickle.dumps(numpy.zeros(10))
"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I10\ntp6\ncnumpy\ndtype\np7\n(S'f8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\np13\ntp14\nb."
I'm concerned that this means my arrays are being expensively converted into something 4x the original size and then converted back in the other process.
Is there a way to pass the data through the queue in a raw unaltered form?
I know about shared memory, but if that is the correct solution, I'm not sure how to build a queue on top of it.
Thanks!

A: The issue isn't with numpy, but the default settings for how pickle represents data (as strings so the output is human readable).  You can change the default settings for pickle to produce binary data instead.
import numpy
import cPickle as pickle

N = 1000
a0 = pickle.dumps(numpy.zeros(N))
a1 = pickle.dumps(numpy.zeros(N), protocol=-1)

print "a0", len(a0)   # 32155
print "a1", len(a1)   #  8133

Also, note, that if you want to decrease processor work and time, you should probably use cPickle instead of pickle (but the space savings due to using the binary protocol work regardless of pickle version).
On shared memory:
On the question of shared memory, there are a few things to consider.  Shared data typically adds a significant amount of complexity to code.  Basically, for every line of code that uses that data, you will need to worry about whether some other line of code in another process is simultaneously using that data.  How hard this will be will depend on what you're doing.  The advantages are that you save time sending the data back and forth.  The question that Eelco cites is for a 60GB array, and for this there's really no choice, it has to be shared.  On the other hand, for most reasonably complex code, deciding to share data simply to save a few microseconds or bytes would probably be one of the worst premature optimizations one could make.

A: Share Large, Read-Only Numpy Array Between Multiprocessing Processes
That should cover it all. Pickling of uncompressible binary data is a pain regardless of the protocol used, so this solution is much to be preferred.


text:
Q: Can't pass value from a button into timer function I am trying to pass the variable time from the easy_click into the RunTimer_tick. This is what I have done, but it doesn't work:
public void RunTimer_Tick(object sender, EventArgs e, int time )
{
    RunTimer.Interval = time;
    target();
}

private void Target_Click(object sender, EventArgs e)
{
    scoring();
}

public int easy_Click(object sender, EventArgs e)
{
    int time = 2000;
    return time;
}

A: You can't change the signature of the timer tick method. You have to stick with the signature expected by the timer, and that's without the additional int time argument.
The same applies for the button click event handler. The event handler expects a given signature and you must not change it, so you can't change the return value to int.
If I get the intent of the code right, you just want to change the timer interval when clicking the "easy" button. This could be written like so:
public void easy_Click(object sender, EventArgs e)
{
    RunTimer.Interval = 2000;
}

You would then remove the time parameter from the timer's tick method:
public void RunTimer_Tick(object sender, EventArgs e)
{
    target();
}


text:
Q: Class diagram for object-orientated card game to deal cards up to 21 points I have been asked to create a class diagram for a simple card game - 21 (aka Black Jack). The game doesn't need to take into consideration of suits and there is no Kings, Queens or Jacks. The Ace is just a 1. So the Ace doesn't count as 11 or 1, instead there is no Ace just a 1.
I am horrible at designing class diagrams and I do not have a lot of experience. But considering that this is StackOverflow, I recognise that I have to research and attempt to complete this task prior to posting this question. So this is all I could conjure up, as follows:

The criteria for the class diagram is as follows:
The Language being used is Java (no that it really matters),
The class diagram needs to show the members of the class for both the individual cards and how they fit together as part of a deck of cards (as I have attempted above).


text:
Q: Div overlapping Bootstrap Column I'm just starting to use Bootstrap.  Building my own page from scratch with it.
The problem I have is a div is overflowing a bootstrap container.
I don't know if I am designing this well in terms of how many columns I should be using or using a column instead of a div in some cases, I don't really understand the fine line yet between adding plain html inside columns and if I need nested Bootstrap columns, or if I'm going way overboard or not with columns and rows or if I dno't have enough...trying to understand that.  Because I could put a ton in ONE column but does one wanna do that, probably not and I'm trying to understand why or why not.
So obviously this is not fully responsive.
Anyway here is my code, and an image showing the overflow.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>A Title</title>

    <link href="../../../content/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../../content/bootstrap/css/sticky-footer.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                </button>

Dashboard

Settings

Profile

Help

Donate!

Profile

Help

                Getting Around

Authors (current)

Recent shows

Popular shiows

About

                                    The Title

                                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor.

2/17/2015

Author: Some Dude

                                More details about this episode

                                Watch this episode

Footer

A: In my opinion, you are going a bit overboard with the columns. I couldn't reproduce your particular issue on Firefox but I did see other layout issues. Most issues were caused by your heavy mixing of different column sizes. In each row you should aim to make sure your col-* combinations add up to 12 at each size. You had huge numbers of different values for each of the size levels, when really you could have just made it simpler by only defining the sizes you needed.
I have created a Bootply that simplifies your code quite a bit. Instead of defining sizes for every single size breakpoint I only use the col-sm size. This means it will use the size you define until it hits the 'small' size, at which point it will break to full width. You'll find it much simpler to start with this kind of simple approach and only overlay more column sizes as and when you need them.
http://www.bootply.com/c8VpkBzHiI#
This is by no means a finished article. I've messed around with your Title section and turned it into a Bootstrap media object, but it didn't go responsive, but this can be a challenge for you to fix!
I hope this helps get you back in the right direction, and if you can tell us which browser you were having trouble with the overflowing text in and whether it still occurs with my code that would be helpful.