text:
Q: preg_match('/^\d*$/', $nr_procedimento) ? 'f' : 't'; - o que faz ? php Eu tenho isso (preg_match('/^\d*$/', $nr_procedimento) ? 'f' : 't';) em um código, mas eu não faço idéia do que faz, mais precisamente a parte do preg_match('/^\d*$/'. Alguém sabe?

A: A função preg_match faz um match de uma expressão regular em uma string, retornando 1 em caso match, 0 se não deu match e false em caso algum erro tenha ocorrido.
Você passa dois parâmetros para ela, sendo o primeiro uma expressão regular e o segundo a string a ser veriricada.
No seu caso a regex é /^\d*$/, definindo cada parte:

/ indica o inicio da expressão regular
^ indica que seu padrão inicia da seguinte maneira
\d define que são valores numéricos
* define que o elemento anterior pode ocorrer 0 ou n vezes
$ indica que sua string deve terminar aqui
/ indica o término da expressão regular

Pode ver mais sobre preg_match aqui.

Em seu exemplo completo você possui um ternário.
preg_match('/^\d*$/', $nr_procedimento) ? 'f' : 't';

Neste caso, se o conteúdo da variável $nr_procedimento der match na regex apresentada, o valor f será retornado pelo ternário, caso contrário sera retornado t.

A: É uma expressão regular para buscar uma linha que começe e termine com números.
Os simbolos amontoados são conhecidos como meta caracteres, cada um tem uma função:
^ - siginifica inicio de linha.
\d - é uma abreviação para [0-9] ou seja apenas números.
* - torna a combinação gulosa, caso o maior número de vezes possível o padrão definido.
$ - significa fim de linha


text:
Q: How to apply rowSums() in R to select top n rows on the basis of rowsum value? I am reading my data from a csv file. I want to sum over rows of the read data, then I want to sort them on the basis of rowsum values. Now, I want to select number of rows on the basis of specified threshold on rowsum value. I gave a try on tempdata.csv, which contains following data:
>data <- read.csv("tempdata.csv")
>data

        X Doc1 Doc2 Doc3 Doc4
1    book    2    0    2    1
2   table    0    2    0    1
3    room    0    2    0    0
4   chair    0    0    2    0
5 speaker    0    0    0    0

>m <- data.matrix(data[2:length(data)], rownames.force=NA)
>(dimnames(m)[[1]] <- data[,1])
>rs1 <- rowSums(m, na.rm = FALSE)

Now I don't know how to combine rowsum values to the matrix 'm'. I am very new in R, I am not able write the optimized code to achieve this. Please help me, thanks in advance.

A: This will sort the data.frame or data.matrix by rowSums
m[sort(rowSums(m), index=T, decreasing=TRUE)$ix, ]

If you only want the rows that meet a threshold you don't need to sort
m[rowSums(m) > threshold, ]

If you want to add a column containing the rowSum values
m <- cbind(m, rowSums(m))

A: Thank you @6pool for your answer. I used following code to achieve the goal.
data <- read.csv("tiny.csv")
data2 <- data[, 2:length(data)]
data2 <- transform(data2, sum=rowSums(data2))
(dimnames(data2)[[1]] <- data[,1])
data3 <- data2[order(-data2$sum),]
### specify the threshold to select the number of rows
threshold = 3
(data4 <- data3[data3$sum>= threshold, ])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hibernate - clustered cache and updating class versions We use Ehcache as L2 cache for Hibernate in a cluster. Since we update servers one by one to avoid downtime, at some point it is possible that in the cluster one server is running older version of code, and another the updated version.
I thought the issue was Ehcache, but I narrowed it down to Hibernate. Hibernate does not cache whole entities, but arrays of field values. So if you got entity with different schema replicated into your cache, Bad Things happen on load as the array is blindly copied.
I can't stop this on Ehcache level. I thought of setting serialVersionUID on my entity classes, but that won't work with those lower-level arrays.
How can I indicate to Hibernate that entity version has changed and the value from cache should NOT be loaded?

A: I don't think you can avoid temporary degradation of capacity in this case because what you have here is a system running servers with incompatible codebases.
Even if you could asses the incompatibility of the entity format and it's cached version and not to load it from cache, what you would end up with is  that some machines would be reading from/writing to cache, and some would go straight to the database which will cause inconsistent data access, and so on and so forth. Basically, this approach is a can of worms.
There is a better solution. The steps include:

*

*Disconnect a half of the cluster from the network. You can use switch's or load balancer's management or any other means available.

*Take down that half, upgrade it, bring it up.

*Connect it back.

*Disconnect the second.

*Repeat #2 and #3.

What you get here is temporarily degradation of capacity while still keeping the system available to serve customer requests while upgrading. It can work nicely during off-peak hours. You may enhance it by routing new requests to the upgraded part of the cluster as it becomes increasingly available. There other variations but the idea is the same - divide and conquer.
The only thing that is important that new and old cluster should not be talk to each other. You'll need help of your operations but it's certainly doable.
Hope this helps.
Slava Imeshev
Cacheonix: Reliable Distributed Java Cache


text:
Q: How to create a lookup field from another lookup column I have one lookup column. I need to create another lookup column to look up the existing lookup column in different lists.
I am notable to do this, Could you please suggest some idea to implement the same.

A: There is no direct way to lookup an existing Lookup column in different lists.
As a workaround, I suggest you create another column which is used to store the lookup column's value, you can use a workflow to set the column to the lookup's value and automatically start the workflow when an item is created and changed.
Then in the target list, lookup the new column instead of the existing lookup column.


text:
Q: Meteor: How to bypass update/upgrade Is there a way to bypass the auto update feature of Meteor?
I'm stuck with
   Downloading meteor-tool@1.3.0_3...        \

When I try to run existing project, or create a new one or simply run "meteor list",..It starts updating, downloads meteor-tool@1.3.0_3... which completes 100% and then countdown vanishes & it remains like that with the spindle rotating.
I tried waiting like mentioned at this link
However, nothing happens even after an hour.

A: I've same error. I resolve by following steps, please try

*

*Download meteor installation from https://github.com/meteor/meteor/wiki/Meteor-on-Windows:-Alternate-installation

*Extract zip & Copy all tool from .meteor/packages/meteor-tool directory

*Go To %AppData%/../Local/.meteor/packages/meteor-tool or C:\Users\<your_user_name>\AppData\Local\.meteor\packages\meteor-tool

*Paste inside folder (Note: If you can't copy or gives error of long path, use RoboCopy)
Now, you can create new Meteor app.

A: Go to project > .meteor > release

Change the meteor version to the current one that is installed on your system.
Consider my scenario:
1) System have the Meteor version 1.4.3.1 installed
2) Downloaded the todos(meteor project), developed on version 1.4.2.1
3) On running it gives similar problem
4) Changed the release version to 1.4.3.1
5) Run with command 'meteor'

A: Considering latest Meteor 1.6 you can use below commands for your best needs

*

*meteor create . --release 1.5 --full to create a scaffolded app.

*meteor create . --release 1.5 --bare to create an empty app.

NOTE: Instead of --release 1.5 you could use your version which actually exists.


text:
Q: var in class gives error
Possible Duplicate:
Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?
In function/method, i can declare a var type variable,then why can't, i do it in class ?
Thanks.

A: If you really don't know the type of object your instance variable will hold, use object, not var. var doesn't mean "i don't know", it means "infer the type for me" - this is why it can never be used on class members.

A: Because C# doesn't support this level of type inferencing. Your alternatives are to use a language, such as F#, that does support this level of type inferencing or beg the C# team to implement the feature. I've got a pretty good guess which one you'll have more luck with...

A: var in C# is a implicitly typed local variable used to infer the type from the RHS of the given expression, which needs to be resolved at compile time. When you declare a var with no RHS value in the class definition, there is no way for the compiler to know the type that you are trying to assign to var.
C# doesn't support implicit typing for class variables.

A: // method variable
var X;

is never valid - even inside a method; you need immediate initialization to infer the type:
// method variable
var X = "abc"; // now a string

As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:
private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid

So all in all I'm happy with the current logic.

A: Because the actual type of a var is inferred from the context in which it is used. For fields (class member variables), there is no such context.

A: You can argue that the intent is quite obvious if you would write var _users = new List<User>() as a field declaration.
The problem is that not all field declarations contains an assignment which is required to infer the type. (You might want to initialize a field through the constructor)
Mixing both var and normal type declarations would look like a nasty soup. Therefore it's not possible.
(at least that's my guess)

A: Yes, the var keyword is only allowed for local variables.
It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var keyword in a local scope.
Additionally, it never works to use the var keyword without specifying a value, as that is used to infer the data type:
var x = "asdf"; // works

var x; // doesn't work

The normal way of declaring a variable is using a specific data type. Use the var keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:
var x = new { Key = 42, Name = "asdf" };

var y = new System.Text.StringBuilder();

A: It is all because of the Build order. You can declare var in only methods. Compiler builds everything but methods first and thats why the type of the object will be clear to the compiler if you use it inside of a method. Jon had a great answer about this but can't seem to find.


text:
Q: Curl error does not resolve my host but it does it with google I'm having an issue with curl, right now I'm running to dedicated servers with proxmox on them. in the first dedicated server I got my website and doing CURL from it (from the vps) does resolve google.es but it does not resolve my domain (panel.roozservers.com) the error that I'm getting it is Could not resolve host: panel.roozservers.com; UInknow error

Doing curl from an online curl tool will give the correct results so I figured out that its a problem on my machine.
My /etc/resolv.conf file it is
# --- BEGIN PVE ---
search ip-54-39-131.net
nameserver 127.0.0.1
nameserver 213.186.33.99
# --- END PVE ---

My /etc/hosts file it is
127.0.1.1       LXC_NAME
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
# --- BEGIN PVE ---
51.161.31.150 RSWeb.ip-54-39-131.net RSWeb
# --- END PVE ---

A: Sometimes there's issues curling or resolving a link to the machine your trying to resolve it from.
I can curl the domain just fine with a status code 200.
Try to curl from another machine or when not connected via ssh.
EDIT:
Open your hosts file with
nano /etc/hosts

Append this line:
127.0.0.1 localhost panel.roozservers.com

Check if loopback ping works with:
ping "$(hostname)"

Try again to curl your domain from the same machine:
curl panel.roozservers.com

A: Fixed it creating a new instance (VM).


text:
Q: Git I changed the HEAD by mistake, and don't know what to do My project has 2 branches main and feature1. I merged them and then I tried to delete feature1 I thought the command was git checkout -d feature1, but it wasn't and now it says HEAD is now at 71bgr8p (My latest commit message). And it shows that I'm in a branch ((71bgr8p...)). When I type git branch it says that the current branch I'm on is HEAD detached at refs/heads/feature1
How can I undo this?

A: You are currently in the detached HEAD state.  The fix is easy, just checkout another branch, e.g. to return to the main branch do:
git checkout main

As for deleting the feature1 branch, use the following:
git branch -d feature1        # to delete the local branch
git push -d origin feature 1  # to delete the remote branch


text:
Q: Xamarin.Forms Entry with auto thousand and decimal separator I have a Xamarin.Forms entry with numeric keyboard that will represent a pt-BR REAL currency (999.999,99). When I type numbers in the numeric keyboard, the comma(representing decimal) and dot(representind thousand) needs to be added automatically while I am typing.
To achieve this goal, what is the best practice/design pattern in Xamarin.Forms to work in all platforms?

A: The trick is to use a TextChanged event.  The first step I removed the $ from the string so that I could parse the new text value.  If it fails to parse, that means that the user added a non-digit character and we just revert to whatever the old text was.
Next, we detect if user ADDED a new digit and its to the RIGHT of the decimal (example 1.532).  If so we, we move the decimal to the right by * 10.   Do the opposite for a DELETION.
OH, and almost forgot about when we initialize the number! The first digit we enter will be a whole number so we * 100 to make sure the first digit we enter starts as fraction.
Once we got our decimal correct, we display it using num.ToString("C");
Working Example:

xaml:
<Entry
    Keyboard="Numeric"
    TextChanged="OnFinancialTextChanged"
    Placeholder="$10.00"
    Text="{Binding RetailPrice}"/>

Then in the cs
.cs:
private void OnFinancialTextChanged(object sender, TextChangedEventArgs e)
{
    var entry = (Entry)sender;

    var amt = e.NewTextValue.Replace("$", "");

    if (decimal.TryParse(amt, out decimal num))
    {
        // Init our number
        if(string.IsNullOrEmpty(e.OldTextValue))
        {
            num = num / 100;
        }
        // Shift decimal to right if added a decimal digit
        else if (num.DecimalDigits() > 2 && !e.IsDeletion())
        {
            num = num * 10;
        }
        // Shift decimal to left if deleted a decimal digit
        else if(num.DecimalDigits() < 2 && e.IsDeletion())
        {
            num = num / 10;
        }

        entry.Text = num.ToString("C");
    }
    else
    {
        entry.Text = e.OldTextValue;
    }
}

I created these Extension methods to help with the logic
public static class ExtensionMethods
{
    public static int DecimalDigits(this decimal n)
    {
        return n.ToString(System.Globalization.CultureInfo.InvariantCulture)
                .SkipWhile(c => c != '.')
                .Skip(1)
                .Count();
    }

    public static bool IsDeletion(this TextChangedEventArgs e)
    {
        return !string.IsNullOrEmpty(e.OldTextValue) && e.OldTextValue.Length > e.NewTextValue.Length;
    }
}

A: No need to create a custom renderer.
I recommend to subclass Entry and subscribe to the TextChanged event.
In there you would parse and reformat the current text and update the Text property.


text:
Q: Collision Check GMS2 I have written a collision check code and ran it, works perfectly but it is working for just one layer. e.g My code is getting layer id and gets tiles in that layer and giving them a number between 1 and 0. If it is 1 there is a collision, else (0) there is no obstacle. My problem is I have more than one layer like objects and objects2. But I can't choose the "objects2" layer to get the id. I can just choose the "objects" layer. This is my code:
"CREATE" EVENT IN COLLISION OBJECT "obj_collision"

var lay_id = layer_get_id("Objeler");
var lay_id2 = layer_get_id("Objeler2");
var map_id = layer_tilemap_get_id(lay_id);
var map_id2 = layer_tilemap_get_id(lay_id2);

hcells = room_width / 16;
vcells = room_height / 16;

for (var yy = 0; yy < vcells; yy ++){
    for (var xx = 0; xx < hcells; xx ++){
            //Bu kod tile'ın integer değerini veriyor.
            tile = tilemap_get(map_id, xx, yy);

            if (tile <= 6){
                //Hareket edebilir.
                a_grid[xx,yy] = 0;
            }else{
                //Hareket edemez.
                a_grid[xx,yy] = 1;
            }
        }
    }

    for (var yy = 0; yy < vcells; yy ++){
    for (var xx = 0; xx < hcells; xx ++){
            //Bu kod tile'ın integer değerini veriyor.
            tile2 = tilemap_get(map_id2, xx, yy);

            if (tile2 <= 6){
                //Hareket edebilir.
                a_grid2[xx,yy] = 0;
            }else{
                //Hareket edemez.
                a_grid2[xx,yy] = 1;
            }
        }
    }

STEP EVENT IN CHARACTER OBJECT "obj_karakter"

#region MOVEMENT

gridX = floor(x/16);
gridY = floor(y/16);

if (canMove){
    if (keyboard_check(vk_up)){
        if (gridY > 0) && (obj_collision.a_grid[gridX, gridY - 1] == 0){
            targetX = x;
            targetY = y - 16;
            sprite_index = spr_yukarikarakter;
            canMove = false;
        }
    }
    if (keyboard_check(vk_down)){
        if (gridY < (obj_collision.vcells - 1)) && (obj_collision.a_grid[gridX, gridY + 1] == 0){
            targetX = x;
            targetY = y + 16;
            sprite_index = spr_asagikarakter;
            canMove = false;
        }
    }

    if (keyboard_check(vk_left)){
        if (gridX > 0) && (obj_collision.a_grid[gridX - 1, gridY] == 0){
            targetX = x - 16;
            targetY = y;
            sprite_index = spr_solakarakter;
            canMove = false;
        }
    }

    if (keyboard_check(vk_right)){
        if (gridY < (obj_collision.hcells - 1)) && (obj_collision.a_grid[gridX + 1, gridY] == 0){
            targetX = x + 16;
            targetY = y;
            sprite_index = spr_sagakarakter;
            canMove = false;
        }
    }
}
    if (x != targetX) || (y != targetY){
        if (x < targetX) x += stepSpeed;
        if (x > targetX) x -= stepSpeed;
        if (y < targetY) y += stepSpeed;
        if (y > targetY) y -= stepSpeed;
    }else{
    if (x == targetX) || (y == targetY){
        canMove = true;
        if (sprite_index == spr_yukarikarakter) sprite_index = spr_bostayukari
        if (sprite_index == spr_asagikarakter) sprite_index = spr_bostaasagi
        if (sprite_index == spr_solakarakter) sprite_index = spr_bostasola;
        if (sprite_index == spr_sagakarakter) sprite_index = spr_bostasaga;
       }
    }

#endregion

A: I've learned this method in one of Heartbeast tutorials:
I've using one invisible objects layer for object collisions, and used another objects layer purely for visuals, to draw over the collisions.
My collision objects are transparent squares, that way it's easy to tell where the collision is. Once I'm done with the collision layer, I can either hide it with the eye symbol, or hide the layers in code. (May provide examples later)
That way collisions are not related to which tile you use, and you only have to use one layer for collisions.


text:
Q: CARTO Analytics Toolbox for Snowflake - Functions disappeared I have been using CARTO Analytics Toolbox for Snowflake for quite some time but all of a sudden all the functions have disappeared.

What should I do in order to bring them back?
Kind Regards

A: This is javier from CARTO.
SOrry for the inconvenience. We have been reorganizing data shares and we don't know if we might have affected something. Can you tell us the region your snowflake account is?
Also you can reach us at support@carto.com


text:
Q: OpenCL variables or array in kernel cost memory? I am trying to run the following code about OpenCL. In kernel function, I will define an array int arr[1000] = {0};
kernel void test()
{
    int arr[1000] = {0};
}

Then I will create N threads to run the kernel.
cl::CommandQueue cmdQueue;
cmdQueue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(N), cl::NullRange); // kernel here is the one running test()

My question is, since we know that OpenCL will parallel run the threads, does it mean that, the peak memory will be N * 1000 * sizeof(int)?

A: This is not the way to OpenCL (yes, that's what I meant :).
The kernel function operates on kernel operands passed in from the host (CPU) - so you'd allocate your array on the host using clCreateBuffer and set the arg using clSetKernelArg. Your kernel does not declare/allocate the device memory, but simply receives it as an __global argument. Now when you run the kernel using clEnqueueNDRangeKernel, the OpenCL implementation will allocate 1000 ints and run a thread on each of those ints.
If, on the other hand you meant to allocate 1000 ints per work-item (device thread), your calculation is right (yes, they cost memory from the local pool) but it probably won't work. OpenCL work-items have access to only local memory (see here on how to check this for your device) which is severely limited.


text:
Q: How can I check for a file existence in XSLT? I would like to check in XSLT whether an HTML file exists or not.
How can I do this?
I have already tried the file-exists.xsl from here https://gist.github.com/emth/4531924 but it doesn't work for me. I've been trying to get it running for over 2 hours now, but I am stuck.
Here's my ant snippet:
<target name="transform">
    <xslt in="/tmp/sample.xml" out="/tmp/out.html" style="/tmp/sample.xsl" />
</target>

and this is my xslt file:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:java="http://www.java.com/">
<xsl:import href="file-exists.xsl"/>
...
<xsl:if test="java:file-exists('myfile.html', base-uri())">
    <!-- do something here... -->
</xsl:if>
....

Running this with ant I will get the following error:
[xslt] Processing /tmp/sample.xml to /tmp/out.html
[xslt] Loading stylesheet /tmp/sample.xsl
[xslt] : Error! The first argument to the non-static Java function 'fileExists' is not a valid object reference.
[xslt] : Error! Cannot convert data-type 'void' to 'boolean'.
[xslt] : Fatal Error! Could not compile stylesheet
[xslt] Failed to process /tmp/sample.xml

Can anybody provide me a running example or is there any other alternative? Thanks!

A: I've found a solution:
<xsl:when test="fs:exists(fs:new('myfile.html'))" xmlns:fs="java.io.File">
    <!-- do something here... -->
</xsl:when>

and it works independently of XSLT 1.0 or 2.0

A: If the file is a text file, you can use the XSLT 2.0 function:
fn:func-unparsed-text-available()
The fn:unparsed-text-available function determines whether a call on the fn:unparsed-text function with identical arguments would return a string. The function will attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no invalid characters.
This is similar to fn:doc-available() which works on XML documents instead.


text:
Q: Regular Expressions in Python for dissecting IP I am currently trying to script a task for my Bind9 server. The goal is to have the user input an IP address in the following format:
192.168.90.150

I would then like Python to take that IP address and dissect it into 4 different groupings in 4 different variables
192.168.90.150 would become...

first  = 192
second = 168
third  = 90
fourth = 150

I assume the "industry standard" way of doing this would be with regular expressions. I have tried to use the following search strings to identify groupings of 1-3 numeric characters separated by periods. The following didn't work.
ipaddy = raw_input('Enter IP address: ')

failsearch1 = re.search(r'\d+\.')
failsearch2 = re.search(r'\d\.')
failsearch3 = re.search(r'(\d)+\.')

for x in ipaddy:
    a = search.failsearch1(x)
    b = search.failsearch2(x)
    c = search.failsearch3(x)
    if a or b or c:
        print('Search found')

The output of the code above is nothing.
I've also tried several other variants of these search strings. Does anyone have any ideas how I can turn a typical IP address (192.168.10.10) into 4 different groupings based on separation between periods?
Any advice would be appreciated. Thanks.

A: Validation:
How to validate IP address in Python?
+plus

first, second, third, fourth = str(ipaddy).split('.')

A: If you are reasonably sure the input is going to be an IPv4 in dotted form, you don't even need a regular expression:
assert possible_ip.count(".") == 3
ip_parts = possible_ip.split(".")
ip_parts = [int(part) for part in ip_parts]
first, second, third, fourth = ip_parts

A: You can just use the builtin str functions.
try:
    first, second, third, fourth = [int(s) for s in some_text.split('.')]
except ValueError as e:
    print 'Not 4 integers delimited by .'
if not all (0 <= i <= 254 for i in (first, second, third, fourth)):
    print 'Syntax valid, but out of range value: {} in "{}"'.format(i, some_text)

A: def validate_and_split_ip(ip):
    parts = ip.split('.')
    if len(parts) != 4:
        return None

    for part in parts:
        if not part.isdigit() or not 0<=int(part)<=255:
            return None
    return [int(part) for part in parts]

Test:
>>> validate_and_split_ip('123.123.0.255')
[123, 123, 0, 255]
>>> validate_and_split_ip('123.123.0.256') # Returns None
>>> validate_and_split_ip('123.123.123.a') # Returns None

You then have a list rather than 4 variables, which is more Pythonic and cleaner.

A:
Make a list of bytes:
>>> [ byte for byte in '192.168.90.150'.split('.') ]
['192', '168', '90', '150']


text:
Q: I can't connect to phpmyadmin using php I'm obviously new to PHP, and I've been asked by a friend to create a dynamic blog that could use continuously. I wanted it to connect to phpMyAdmin so it would be easier, but when I try to connect with it to my web page, it always fails and my set error appears. I don't know what to look up to help me. I'm sorry if I'm not clear. Post if you want me to go more into detail.
Here's my code:
<?php

$dbhost = 'localhost';

$dbuser = ' root';

$dbpass = '';

$dbname = 'blog1';

$connect = mysqli_connect($dbname, $dbuser, $dbhost, $dbpass) or die ('Cannot connect to database.');

echo "Succesfully connected to database!";

?>

A: Test This
<?php
$dbhost = 'localhost';

$dbuser = ' root';

$dbpass = '';

$dbname = 'blog1';

$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ('Cannot connect to database.');

echo "Succesfully connected to database!";

The mysqli_connect() was called in wrong way.

A: $dbhost = 'localhost';

    $dbuser = 'root';

    $dbpass = 'root123';

    $dbname = 'mydb';

    $connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ('Cannot connect to database.');

If you run PHPMyAdmin on localhost uncomment in file:
sudo gedit /etc/php5/apache2/php.ini

this line:  mysqli.allow_local_infile = On
Restart Apache:
sudo /etc/init.d/apache2 restart or   sudo service apache2 restart


text:
Q: Asyncio.sleep blocking the rest of the function Function cant pass to next line because of asyncio.sleep. There is rest of the code but i will share just 3 lines. It explains everything. Console doesnt print 0 to console. If i move print(0) above of asyncio.sleep it prints to console.
async def getHistory(self):
    logging.info(f"Getting history for {self.parite}...")
    await asyncio.sleep(1)
    print(0)

async def get_histories():
    for parite in parite_list:
        asyncio.create_task(parite.getHistory())

asyncio.run(get_histories())

A: It looks like you created the tasks but did not execute them. Try this with asyncio.gather:
import asyncio
import logging

async def getHistory(num):
    print(f"Getting history for {num}...")
    await asyncio.sleep(1)
    print(num)

async def get_histories():
    await asyncio.gather(
        asyncio.create_task(getHistory(1)),
        asyncio.create_task(getHistory(2)),
        asyncio.create_task(getHistory(3))
    )

asyncio.run(get_histories())

Result:
% python asdf.py
Getting history for 1...
Getting history for 2...
Getting history for 3...
1
2
3


text:
Q: java.lang.NoClassDefFoundError: com.ibm.ws.xd.container.state.config.CellSensor$CellConsumer I have a problem, WAS failed initialization since I rename com.ibm.ws.security.crypto.jar at /opt/was_D85/AppServer/plugins to other name.
I already renamed the jar to it's original name but still failed initialization.
My environment is:
OS: AIX
WebSphere 8.5
The error I'm getting:
[12-01-2015 13:13:50:057 WET] 00000001 WsServerImpl  E   WSVR0100W: An error occurred initializing, server1 [class com.ibm.ws.runtime.component.ServerImpl]
java.lang.NoClassDefFoundError: com.ibm.ws.xd.container.state.config.CellSensor$CellConsumer
                at java.lang.ClassLoader.defineClassImpl(Native Method)
                at java.lang.ClassLoader.defineClass(ClassLoader.java:264)
                at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:188)
                at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:580)
                at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:550)
                at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:490)
                at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassName(ClasspathManager.java:460)
                at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:447)
                at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:216)
                at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:393)
                at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:469)
                at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
                at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
                at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
                at java.lang.ClassLoader.loadClass(ClassLoader.java:650)
                at java.lang.J9VMInternals.verifyImpl(Native Method)
                at java.lang.J9VMInternals.verify(J9VMInternals.java:93)
                at java.lang.J9VMInternals.initialize(J9VMInternals.java:170)
                at java.lang.J9VMInternals.newInstanceImpl(Native Method)
                at java.lang.Class.newInstance(Class.java:1564)
                at com.ibm.ws.runtime.component.ContainerHelper.initializeComponent(ContainerHelper.java:1060)
                at com.ibm.ws.runtime.component.ContainerHelper.initializeComponents(ContainerHelper.java:901)
                at com.ibm.ws.runtime.component.ContainerImpl.initializeComponents(ContainerImpl.java:776)
                at com.ibm.ws.runtime.component.ContainerImpl.initializeComponents(ContainerImpl.java:750)
                at com.ibm.ws.runtime.component.ServerImpl.initialize(ServerImpl.java:333)
                at com.ibm.ws.runtime.WsServerImpl.bootServerContainer(WsServerImpl.java:336)
                at com.ibm.ws.runtime.WsServerImpl.start(WsServerImpl.java:267)
                at com.ibm.ws.runtime.WsServerImpl.main(WsServerImpl.java:730)
                at com.ibm.ws.runtime.WsServer.main(WsServer.java:59)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
                at java.lang.reflect.Method.invoke(Method.java:611)
                at com.ibm.wsspi.bootstrap.WSLauncher.launchMain(WSLauncher.java:234)
                at com.ibm.wsspi.bootstrap.WSLauncher.main(WSLauncher.java:96)
                at com.ibm.wsspi.bootstrap.WSLauncher.run(WSLauncher.java:77)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
                at java.lang.reflect.Method.invoke(Method.java:611)
                at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:587)
                at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:198)
                at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
                at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
                at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
                at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
                at java.lang.reflect.Method.invoke(Method.java:611)
                at org.eclipse.core.launcher.Main.invokeFramework(Main.java:340)
                at org.eclipse.core.launcher.Main.basicRun(Main.java:282)
                at org.eclipse.core.launcher.Main.run(Main.java:981)
                at com.ibm.wsspi.bootstrap.WSPreLauncher.launchEclipse(WSPreLauncher.java:379)
                at com.ibm.wsspi.bootstrap.WSPreLauncher.main(WSPreLauncher.java:150)
Caused by: java.lang.ClassNotFoundException: com.ibm.ws.xd.container.state.config.CellSensor$CellConsumer
                at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
                at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
                at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
                at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
                at java.lang.ClassLoader.loadClass(ClassLoader.java:650)
                ... 55 more
Can somebody help?
Thank you.

A: Problem solved by cleaning the WAS caches.


text:
Q: Высокая нагрузка на Angular.js На предприятии сделал справочник телефонный на yii2 и angularjs. Народу до 100 человек. Работает быстро, всем нравится. Тут решил потестить и залить 50000 пользователей. Результат - страница грузится минуту и потом жутко тормозит. Снизил до 5000 - чуть лучше но тоже не идеал. Вообщем пока считаю, что справочнику оптимально не более 1000 записей.
Вопрос в следующем - angular вообще для такого годится?
Вывожу записи вот так

Где search
<input ng-model="search" class="form-control input-lg" type="text" placeholder="Именя, фамилию или номер">

Список такого типа
    {
"id":"2",
"name":"_administraciya_",
"description":"Администрация",
"mans":[
{
"name":"Всеволод",
"surname":"Кравчук",
"phone":"102",
"email":"skyq@skyq.ru",
"dep_id":"2"
},
{
"name":"Захар",
"surname":"Любимцев",
"phone":"115",
"email":"skyq@skyq.ru",
"dep_id":"2"
}]
},
{
"id":"2",
"name":"_administraciya2_",
"description":"Администрация2",
"mans":[
{
"name":"Всеволод1",
"surname":"Кравчук1",
"phone":"102",
"dep_id":"2"
},
{
"name":"Захар",
"surname":"Любимцев",
"phone":"115",
"dep_id":"2"
}]
}

phones.skyq.ru

A: Стоит делать пагинацию или бесконечный скролл. Выводить 50000 сразу на страницу нельзя, потому что из-за большого количества вотчеров страница начинает есть много ОЗУ.


text:
Q: How to seal an overridden property Suppose I have a pair of obviously contrived C# classes like this:
public abstract class Foo {
    public abstract int[] LegalValues { get; }
    public virtual bool IsValueLegal(int val) {
        return Array.IndexOf(LegalValues, val) >= 0;
    }
}

and this:
public class Bar : Foo {
    static int[] _legalValues = new int[] { 0, 1 }; // whatever
    public sealed override int[] LegalValues
        { get { return _legalValues; } }
    public sealed override bool IsValueLegal(int val)
        { return base.IsValueLegal(val); }
}

How do I do this in F#?  The obvious code for the properties:
[<Sealed>]
override this.LegalValues with get() = // ...

[<Sealed>]
override this.IsValueLegal value = // ...

Triggers an error because the SealedAttribute apparently can't be applied to members.
I can, of course, seal the entire class and thereby seal all members, but (and this is a really important but) is that I have a goal of matching an existing class signature exactly and the base class has other virtual/abstract members that should, ideally, remain overridable.

A: Looks like F# defines the Sealed Attribute is defined with its AttributeTargets property set to Class only, its probably not possible to seal members.
This is probably ok, since inheritance and overriding functions is generally less idiomatic in F# than C#. I don't think you can really get what you want without rewriting in more F# idioms. Start with this:
type foo =
    | Bar
    | Baz
    | Qux
        with
            member this.LegalValues =
                match this with
                | Bar -> [0; 1]
                | Qux -> [-1; 0; 1]
                | Baz -> [0 .. 10 ]
            member this.IsValueLegal value =
                match this with
                | Baz -> value >= 0 && value <= 10
                | _ -> List.exists (fun x -> x = value) (this.LegalValues)

You can say that Baz "overrides" the foo.IsValueLegal member, all other types use the "base" function.

A: There are currently several limitations to F#'s support for OO, so you should not generally expect to be able to produce an F# class hierarchy which is identical to an arbitrary C# class hierarchy.  As far as I know, there is no way to override and seal a virtual method.


text:
Q: Update password with php/mysql Yesterday I have posted some code asking how the user can update a password through a form. Look here
However after updating the password, I couldn't login though my android app. So I decided to change a bit the forgotpassword.php file.
<?php
session_start();
require "../init.php";
ini_set('display_errors', 1);

if(isset($_POST['update'])){

    $email = $_POST['email'];
    $user_name = $_POST['user_name'];
    $password = $_POST['user_pass'];
    $passwordEncrypted = sha1($user_pass);

    $confpassword = $_POST['confirm_pass'];
    $confPasswordEncrypted = sha1($confirmPass);

    if($password !== $confpassword){
       echo "<script>alert('Passwords are not equal')</script>";
    }else{
        $select_query = "SELECT * FROM user_info";

        $run_select_query = mysqli_query($con,$select_query);

        while ($row_post=mysqli_fetch_array($run_select_query)){

              $_SESSION['id'] = $row_post['id'];
              $user_id = $_SESSION['id'];
              $useremail = $row_post['email'];
              $username = $row_post['user_name'];

              var_dump($user_id);

            if($useremail == $email AND $username == $user_name){
                //echo "<script>alert('$useremail')</script>";
                //echo "<script>alert('$username')</script>";
                echo "<script>alert('$id')</script>";
                $update_posts = "UPDATE user_info SET user_pass='$passwordEncrypted',confirm_pass ='$confPasswordEncrypted'
                WHERE $id='$_userid'";

                $run_update = mysqli_query($con,$update_posts);
                //var_dump($user_name);
            echo "<script>alert('Password Has been Updated!')</script>";
            }else{
             echo "<script>alert('No email or username was found')</script>";
            }

        }

    }

}
?>

But now the password is not updated as it was before. There is something wrong in the update statement or a line before that. The $_SESSION['id'] is not null so the select query works fine.
Any ideas?
Thanks.

A: typo in where clause. WHERE $id='$_userid'";
change update query's where clause to this: WHERE $id='$user_id'";

A: Update your select query:
$select_query = "SELECT * FROM user_info where email = '".$email."' and user_name = '".$username."' ";

and then check if mysqli_num_rows(). If it > 0 then only execute the update query & put the data in the session.
Also your update query is not proper.It should be :
$update_posts = "UPDATE user_info SET user_pass='$passwordEncrypted',confirm_pass ='$confPasswordEncrypted'
                WHERE $id='$userid'";

A: Your update query should be like this :
$update_posts = "UPDATE user_info
    SET
           user_pass='$passwordEncrypted',
           confirm_pass ='$confPasswordEncrypted'
    WHERE id = $user_id";

A: Ok. I have changed the code and made it work. So this is what I am doing.
1) I run a select query to check if the user is already registered. If yes then update the password and send a new one in his email.
2) If not then you get a json response in my android app saying that the user email is not found.
3) And finally the user can login with his updated  5 digit password:).
<?php
 require "init.php";
 $email = $_POST['email'];

  if($email){
        $select_query = "SELECT * FROM user_info";

        $run_select_query = mysqli_query($con,$select_query);

        while ($row_post=mysqli_fetch_array($run_select_query)){

            $id = $row['id'];
            $usermail = $row_post['email'];
            $username = $row_post['user_name'];

        }
            if($usermail == $email){
                $don = array('result' =>"success","message"=>"user mail found.");

                $random = rand(72891, 92729);
                $new_pass = $random;

                $email_password = $new_pass;
                $new_pass = sha1($new_pass);

                $update_pass = "update user_info set user_pass='$new_pass',confirm_pass='$new_pass' where user_name='$username'";

                $run_update = mysqli_query($con,$update_pass);

                    $subject = "Login information";

                    $message = "Your password has been changed to $email_password";

                    $from = "From: example@example.com";

                    mail($email,$subject,$message,$from);

                $don = array('result' =>"success","message"=>"your password has been updated. Please check your email");

            }else{
                $don = array('result' =>"fail","message"=>"user mail not found.");
            }
        }else{
            $don = array('result' =>"fail","message"=>"please enter your email");
        }

   echo json_encode($don);
?>


text:
Q: How to use Excel VBA to click a web CSS button? I am creating a macro with Excel VBA that will submit an entry into an online database using information from an Excel spreadsheet. During this entry process, the macro needs to click on a CSS button. It isn't a form button, does not have an input type, no name, no id, and no source image except for a background image. I think my only hopes are either to click on the button based on the div class. Can anyone help?
The button is here :

    By Ankit

                By LOT

A: Thanks to Remou's answer on this thread: Use VBA code to click on a button on webpage
Here is a first stab in your issue, you could try this:
Set tags = wb.Document.GetElementsByTagname("div")

For Each tagx In tags
    If tagx.class = "v-caption-clearelem" Then
        tagx.Click
    End If
Next

Yet, I've never tried to use the Click method on a div.


text:
Q: Conditional view contribution with vscode extension api I am trying to show my view contribution only when the editor has an HTML file. According to this issue on GitHub, I can use the when clause. I found in the docs an example for a file type based condition. It's used on a command and not on a view contribution though.
I am trying with the below config, the view contribution is hidden but doesn't show up when I open an HTML file. If I remove the when clause, the view contribution shows fine but of course all the time.
"activationEvents": [
    "onLanguage:html"
],
"contributes": {
    "views": {
    "explorer": [
        {
          "id": "documentOutline",
          "name": "Document Outline",
          "when": "editorLangId == html"
        }
      ]
    }
}

A: According to the contributes.views documentation the when depends on context values.
And according to the npm extension it can also contain config settings.
    "views": {
      "explorer": [{
        "id": "npm",
        "name": "%view.name%",
        "when": "npm:showScriptExplorer || config.npm.enableScriptExplorer"
      }]
    },

The npm extension sets a context value in the activation function
    if (await hasPackageJson()) {
        vscode.commands.executeCommand('setContext', 'npm:showScriptExplorer', true);
    }

You might try the following:
In your extension define an event handler to get called when the editor changes (onDidChangeActiveTextEditor).
In the event handler set the context value based on the langugeId of the document.
Edit
It works with the following code
  const setContext = () => {
      vscode.commands.executeCommand('setContext', 'documentOutline:fileIsHTML',
          vscode.window.activeTextEditor.document.languageId == 'html'); };
  vscode.window.onDidChangeActiveTextEditor(setContext, null, context.subscriptions);
  setContext();

And in the package.json
"activationEvents": [
    "onLanguage:html"
],
"contributes": {
    "views": {
    "explorer": [
        {
          "id": "documentOutline",
          "name": "Document Outline",
          "when": "documentOutline:fileIsHTML"
        }
      ]
    }
}

Or looking at this issue conditional visibility for custom views it might be even simpler. See Weinands example: add quotes in the == compare.
"activationEvents": [
    "onLanguage:html"
],
"contributes": {
    "views": {
    "explorer": [
        {
          "id": "documentOutline",
          "name": "Document Outline",
          "when": "editorLangId == 'html'"
        }
      ]
    }
}

Edit
Tried this and it does not work, maybe editorLangId is not a context variable.


text:
Q: Sum of Möbius function multiplied by a character I am trying to understand whether some non trivial explicit estimate is known about the following
$$\sum_{n \leq x} \mu(n) \chi(n)$$
as a function of $x$.
Here $\chi$ is a Dirichlet character modulo $q$ and $q > (\log x)^2$ (for example).

A: Explicit estimates for the Moebius function are much harder than for the prime counting function. Ramare (From explicit estimates for the primes to explicit estimates for the Moebius function, Acta Arithmetica 157, (2013), 365-379) has shown how to translate estimates for primes to estimates for the Moebius function, as far as I know this approach is superior to a direct estimate using complex integration. It should be possible without too much work to change Sections 4, 5, 6 of that paper to the character case, as there is a lot of literature on various sums involving primes in arithmetic progressions (see the work of Rosser, Schoenfeld, McCurley, Rumely, Ramare). I would be worried about Lemma 9.1, but this is not necessary for your question.

A: Estimating this sum is much the same as estimating the error term in the prime number theorem for arithmetic progressions. See Exercises 7-8 in Section 11.3 of Montgomery-Vaughan: Multiplicative number theory I (Cambridge University Press, 2006). (Your sum is denoted by $M(X,\chi)$ in this book, as introduced by (11.39) there.)
In particular, there is a constant $c>0$ such that for any $A>0$ we have
$$ \sum_{n \leq X} \mu(n) \chi(n)\ll_A x\exp(-c\sqrt{\log x})$$
as long as $q\leq(\log x)^A$ .

A: There is an equivalent of the Riemann explicit formula for those :
If all the zeros
of $L(s,\chi) = \sum_{n=1}^\infty \chi(n) n^{-s}$ are simple,
then $\displaystyle\frac{1}{L(s,\chi)} = \sum_{n=1}^\infty \mu(n)\chi(n) n^{-s}= s\int_1^\infty (\sum_{n < x}\mu(n) \chi(n))x^{-s-1}dx$ leads to $$\sum_{n < x} \mu(n) \chi(n) = \frac{1}{2i\pi}\int_{\sigma-i\infty}^{\sigma+i\infty}\frac{1}{L(s,\chi)}\frac{x^s}{s}ds = \frac{1}{L(0,\chi)} + \sum_\beta \frac{x^{\beta}}{\beta L'(\beta,\chi)}$$
by Mellin inverse transform and the residue theorem, where $\sigma > 1$,
$\beta$ are the zeros (trivial and non-trivial) of $L(s,\chi)$,
and $\sum_\beta$ is convergent only when grouping the terms correctly.
(note if some zeros are of order $k$, it is not so different except you'll get some additional terms $x^\beta (\ln x)^{m}, m < k$)


text:
Q: Is there any mathematical work on formalizing problems and their solutions as mathematical objects? Problems (tasks?) are an important part of life, science, math, basically everything. Do people study them as mathematical objects? Theorem proving seems close, however, I'm interested more in the taxonomy and ontology of problems and operations on them, like combining several problems or reducing one problem to another.
We, humans, use different heuristics to solve the problems, but how does the problem space look like? What is a structure of the solutions space? How to find a good heuristic for a particular problem? What kind of problems are most prevalent in our universe?
The question is probably a bit vague, I'm sorry. What I want is to reason formally about the problems, problem-solving heuristics, and intelligence as an ability to solve problems.

A: Part of what you seem to be talking about is either computability theory (also called recursion theory) or complexity theory, depending on whether or not the problems you're interested in are solvable by a computer. If you're primarily interested in solvable problems, complexity theory considers which problems can be used to efficiently solve other problems. Computability theory, by contrast, considers which non-solvable problems we could solve if we had access to the solution to certain other non-solvable problems. In both, there is a notion of combining multiple problems or reducing problems.
On the other hand, there's no good mathematical notion of a "heuristic", so far as I know, simply because "heuristic" is not really a well-defined notion - it just means "general strategy which has generally been right in practice". Numerical analysis considers methods of approximating a solution to a mathematical problem, but I don't think that's what you're looking for.
Questions about the "structure" of the problem space or solution space depends on what you mean by "structure" - both computability and complexity theory have a notion of the structure of the space of problems (neither makes a distinction between the problem and its solution, though).
Finding a heuristic for a problem is computer science's job, though again a numerical analyst might be interested.
Your last question, what kind of problems are most prevalent in our universe, isn't really a theory question at all - it's something that would be determined by experiment. For that, you're looking for something like physics, but don't get your hopes up.


text:
Q: How to convert MySQL Seb-Select to Join I am trying to write a SELECT in mySQL (and PHP) that will retrieve all the rows in "Images" table that were not ranked yet by a certain user.
Those are my tables:
Table: Images
+-----------+----------+-----------+----------+------------+
| Index     | Rank_Good| Rank_OK   | Rank_Bad | Is_Allowed |
+-----------+----------+-----------+----------+------------+
| 201       | 2        | 9         | 28       | true       |
| 202       | 11       | 20        | 39       | false      |
| 203       | 36       | 14        | 7        | true       |
+-----------+----------+-----------+----------+------------+

Table2: WhoAlreadyClickedImg (has no index)
+------------+-----------------+-----------+
| ImageIndex | UserWhoRankedIt | RankGiven |
+------------+-----------------+-----------+
| 202        | 87              | OK        |
+------------+-----------------+-----------+
| 202        | 93              | Bad       |
+------------+-----------------+-----------+
| 204        | 93              | Good      |
+------------+-----------------+-----------+
| 203        | 94              | Bad       |
+------------+-----------------+-----------+

my logic:
when a user is ranking an image, I add to the "WhoAlreadyClickedImg" table a row with the id of the user who has just ranked it, and the image id (and the rank).
(This creates thousands of rows per each image in this table and its growing fast.)
Then, when a user wants to rank an image, I am looking in the "WhoAlreadyClickedImg" table to see which images were not already ranked by him and I add to the query the parameter Images.Is_Allowed from the "Images" table (so I will show him only an image that can be ranked).
first I did it with sub-select, but it turns out it calles the subselect for every row it checks and it is very very slow.
SELECT Images.Index
FROM Images
WHERE Images.Index NOT IN
         (
            SELECT WhoAlreadyClickedImg.ImageIndex
                 FROM WhoAlreadyClickedImg
                 WHERE WhoAlreadyClickedImg.UserWhoRankedIt = 93
         );
AND Images.Is_Allowed = 1
ORDER BY RAND()
LIMIT 1

I have no idea how to do it with JOIN (never did it and not familiar with what will be best - Left join/inner or right)

A: SELECT Images.Index
FROM Images
LEFT JOIN WhoAlreadyClickedImg
  ON WhoAlreadyClickedImg.ImageIndex = Images.Index
  AND WhoAlreadyClickedImg.UserWhoRankedIt = 93
WHERE Images.Is_Allowed = 1
AND WhoAlreadyClickedImg.ImageIndex IS NULL
ORDER BY RAND()
LIMIT 1

That should do it. You just make a left join with that table and if there's no corresponding value on that table based on these conditions, a row will be brought back as a NULL and then you can check for this condition in WHERE clause.
Although, if your tables are properly indexed, there should be no real difference in both queries, MySQL should be smart enough to figure out the right plan.


text:
Q: How to use RocksDB after installation? How to read from RocksDB from KSQL? I have installed RocksDB using the command "sudo apt-get install librocksdb-dev". How can I use the DB? How can I read and write data using KSQL?

A: What is it you're trying to do?
KSQL is part of Confluent Platform, built on top of Kafka Streams which uses RocksDB under the covers.
You don't interface with RocksDB directly through KSQL, it is abstracted.
To get started with KSQL see https://www.confluent.io/ksql


text:
Q: 'OraOLEDB.Oracle' provider is not registered on the local machine - Oracle Database Client 12C I have some problem with connect to the Oracle Database by Oracle Client. I installed on laptop oracle client - version 32 bit. I can connect to the database from laptop when i use 64 bit applications, but when i will use 32 bit application i get following error:
 ERROR System.InvalidOperationException: The 'OraOLEDB.Oracle' provider is not registered on the local machine.
   at System.Data.OleDb.OleDbServicesWrapper.GetDataSource(OleDbConnectionString constr, DataSourceWrapper& datasrcWrapper)
   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
   at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.OleDb.OleDbConnection.Open()
   at EconLib.Utility.SqlDataAccess.OpenConnection(String host, String database, String user, String pass)

i have seen this question 'https://stackoverflow.com/questions/12903366/oraoledb-oracle-provider-is-not-registered-on-the-local-machine', but i can't find oraOLEDBXX.dll on my laptop. Any idea what can i do ?

A: From comment by Wernfried Domscheit:

Have a look at this instruction to install both 32 bit and 64 bit on one machine: stackoverflow.com/questions/24104210/…. Note Oracle OLEDB provider is not included in Oracle Instant client, you have to install it separately or enable the corresponding option in Oracle Universal Installer.


text:
Q: WP update_user_meta() is not working My goal is to create a plugin for counting the number of times a user logs in. But for now, it seems the update_user_meta() is not working or I'm not using it properly. I'm just trying to update a custom variable with the user_id value, so that I can know that I am storing a value in the user_meta.
<?php
function user_login_count2($redirect_to, $request, $user) {
    global $user;
    global $current_user;
    get_currentuserinfo();
    $user_id = $current_user->ID;

    if (isset($user_id)) {
      if ( get_user_meta($user_id, 'login_count2', true) ){
        //$login_count2 = get_user_meta($user_id, 'login_count2', true);
        //$login_count2++;
        //update_user_meta($user_id, 'login_count2', $login_count2);
        $user_id_test = get_user_meta($user_id, 'user_id_test', true);
        update_user_meta($user_id, 'user_id_test', $user_id);

      }else{
          add_user_meta($user_id, 'login_count2', '1');
      }
    }else{
        return $redirect_to;
    }
}
add_filter('login_redirect', 'user_login_count2', 10, 3);

function show_login_counts() {
    global $current_user;
    get_currentuserinfo();
    $user_id = $current_user->ID;

    $user_id_test = get_user_meta($user_id, 'user_id_test', true);
    if(isset($_GET['ict']) && $_GET['ict'] == 1){
        echo $user_id;
        echo $user_id_test;
    }
}
add_action('wp_footer', 'show_login_counts');
?>

A: It's a little hard to follow your code with all the commented out code, and I'm not sure what the purpose of the calls to the various user functions are variables are.
Here's how I would do it:
    add_action('wp_login', 'record_user_login', 10, 2);

    function record_user_login($user_login, $user){

        // Get current user ID from the user object
        $user_id = $user->ID;

        // Get previous login count
        $login_count = get_user_meta($user_id, 'login_count', true);

        // Increment login count if it exists, or set it to 1
        if (int_var($login_count)){
            $new_count = $login_count++;
        }
        else {
            $new_count = 1;
        }

        // Update login count in user meta
        update_user_meta($user_id, 'login_count', $new_count);

    }


text:
Q: Normal distribution and two tailed tests do we have to assume normal distribution in order for two tailed tests?
Eg: According to the Australian Bureau of Statistics, the quantity of waste ending up in municipal landfills amounts to 0.80 kg per person per day. Some claim that because of recycling and greater emphasis on the environment, this figure is now lower. Others contend that constant increases in packaging and other life-style developments have pushed this figure higher in spite of recycling efforts. To test whether the amount of garbage per person has changed, a random sample of 54 Australians was taken and they were asked to keep a log of their garbage for a day. The sample mean was 0.92 kg.
Population standard deviation is 0.5 kg, and that the amount of garbage per person per day is normally distributed, use the sample data to determine whether there is sufficient evidence at the 5% level of significance to assert that the amount of garbage per person per day has changed.
Q)Is the assumption that the amount of garbage is normally distributed necessary in order to perform this test?

A: Because you're looking at the mean, you can rely on the central limit theorem that says that the distribution of the mean is Normally distributed. The strength of the central limit theorem is that it works for most underlying distributions; thye don't have to be Normal. It is, however, an approximation that gets better as the sample size increases. How large your sample size needs to be depends on the kind of underlying distribution you have. As the comment says, there are some underlying distributions for which the central limit theorem doesn't work.


text:
Q: Where is Windows getting it's proxy settings from? I've been configuring the proxy settings on a Win10 image that users will launch instances of. I initially configured the settings in the Internet Options tool and then used netsh winhttp import proxy source=ie to pull them into that system.
I needed to amend the bypass list. I tried to do this by adding the entry in Internet Options, but it didn't persist. Each time I closed the tool and reopened it, the entry was gone. I ran netsh winhttp reset proxy in case that configuration was overwriting the other.
Why I'm really confused, though, is that I am using the local group policy option Make proxy settings per-machine (rather than per-user). When it is enabled, the proxy settings are configured using the previous settings including the bypass list. I've tried to modify the list again, but again, the entry doesn't persist. When I disable the per-machine policy the proxy settings disappear from Internet Options. Enable it again and they reappear.
I've gone through the registry and removed every entry for the proxy server. I'm certain all entries are gone based on the searches I've done for "proxy", the IP address of the proxy, the port number of the proxy, "bypass", etc.
So I'm befuddled. Where is the proxy configuration coming from when I enable Make proxy settings per-machine (rather than per-user)?

A: I was clued into the solution to this when an unrelated post mentioned the DefaultConnectionSettings registry value. I looked into it and sure enough, there it was in the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\InternetSettings\Connection key.
I deleted it under both HKLM and HKCU, System and SysWOW64, and probably a few other places it popped up including ControlSet01.
Once I was sure the registry was devoid of any possible values that could affect the proxy configuration, I then set the local GPO to make the proxy configuration per-machine rather than per-user. Then I deleted everything again.
Only after I had the per-machine policy enabled and the registry again free of the value, did I add the configuration to the Proxy Settings interface. The configuration was written to the registry as the DefaultConnectionSettings value which persisted across reboots.
I confirmed it was correct by disabling the per-machine policy and verifying that the proxy configuration was removed for the user. Then I re-enabled the policy and verified that the configuration was again in place.


text:
Q: BibLaTeX adds incorrect letter after year in incollection entry i'm facing a problem with my modified authoryear-icomp style.
See screenshot below:

BibLaTeX adds a letter after the year (2017b), even though it's the only publication with that editor in that particular year. Is there any way to circumvent this?
I want it to display like so:

Krajewski, C. (2017b): "Städtetourismus und Stadtkultur". In: Heineberg, H. (Hrsg.) (2017): Stadtgeographie. 5. Aufl. Paderborn, S. 413–421 (=UTB 2166).

MWE:
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[ngerman]{babel}
\usepackage[babel]{csquotes}
\usepackage{xpatch}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}

@article{KrajewskiMetropoleRuhrWandel2017,
  langid = {german},
  title = {Metropole Ruhr – Wandel durch Freizeit, Kultur und Tourismus},
  number = {2},
  journaltitle = {Praxis Geographie},
  author = {Krajewski, Christian},
  date = {2017},
  pages = {36--41}
}

@incollection{KrajewskiStadtetourismusundStadtkultur2017,
  langid = {german},
  location = {{Paderborn}},
  edition = {5},
  title = {Städtetourismus und Stadtkultur},
  isbn = {978-3-8252-4708-9},
  number = {2166},
  booktitle = {Stadtgeographie},
  series = {UTB},
  author = {Krajewski, Christian},
  editor = {Heineberg, Heinz},
  date = {2017-10-10},
  pages = {413--421}
}
\end{filecontents*}

\usepackage[%
    backend=biber,
    style=authoryear-icomp,
    autopunct=true,
    giveninits=true,
    uniquename=mininit,
    maxcitenames=2,
    maxbibnames=10,
    isbn=false,
    % url=false,
    doi=false,
    eprint=false,
    dashed=false,
]{biblatex}
\addbibresource{\jobname.bib}

% colon after year
\renewcommand{\labelnamepunct}{\addcolon\space}

% editor in parentheses
\DeclareFieldFormat{editortype}{\mkbibparens{#1}}

% no comma before editor
\renewbibmacro*{bbx:editor}[1]{%
  \ifboolexpr{
    test \ifuseeditor
    and
    not test {\ifnameundef{editor}}
  }
    {\usebibmacro{bbx:dashcheck}
       {\bibnamedash}
       {\printnames{editor}%
        \setunit{\addspace}%
        \usebibmacro{bbx:savehash}}%
     \usebibmacro{#1}%
     \clearname{editor}%
     \setunit{\printdelim{nameyeardelim}}}%
    {\global\undef\bbx@lasthash
     \usebibmacro{labeltitle}%
     \setunit*{\printdelim{nonameyeardelim}}}%
  \usebibmacro{date+extrayear}}

% change order of incollection
\DeclareBibliographyDriver{incollection}{%
  \usebibmacro{bibindex}%
  \usebibmacro{begentry}%
  \usebibmacro{author/translator+others}%
  \setunit{\printdelim{nametitledelim}}\newblock
  \usebibmacro{title}%
  \newunit
  \printlist{language}%
  \newunit\newblock
  \usebibmacro{byauthor}%
  \newunit\newblock
  \usebibmacro{in:}%
  \usebibmacro{editor+others}% %instead of byeditor+others
  \setunit{\printdelim{nametitledelim}}\newblock%
  \usebibmacro{maintitle+booktitle}%
  \newunit\newblock
  \printfield{edition}%
  \newunit
  \iffieldundef{maintitle}
    {\printfield{volume}%
     \printfield{part}}
    {}%
  \newunit
  \printfield{volumes}%
  \newunit\newblock
  \usebibmacro{series+number}%
  \newunit\newblock
  \printfield{note}%
  \newunit\newblock
  \usebibmacro{publisher+location+date}%
  \newunit\newblock
  \usebibmacro{chapter+pages}%
  \newunit\newblock
  \iftoggle{bbx:isbn}
    {\printfield{isbn}}
    {}%
  \newunit\newblock
  \usebibmacro{doi+eprint+url}%
  \newunit\newblock
  \usebibmacro{addendum+pubstate}%
  \setunit{\bibpagerefpunct}\newblock
  \usebibmacro{pageref}%
  \newunit\newblock
  \iftoggle{bbx:related}
    {\usebibmacro{related:init}%
     \usebibmacro{related}}
    {}%
  \usebibmacro{finentry}}

% Series & number at the end in parentheses
\renewbibmacro*{series+number}{%
  \iffieldundef{series}
    {}
    {\printtext[parens]{%
       \printtext{=\addnbthinspace}%
       \printfield{series}%
       \setunit*{\addspace}%
       \printfield{number}%
       \newunit}}}

\newcommand*\patchseries[1]{%
  \xpatchbibdriver{#1}
    {\usebibmacro{series+number}}
    {}
    {}
    {\typeout{Warning: Failed to remove series+number from driver #1.}}
  \xpatchbibdriver{#1}
    {\usebibmacro{chapter+pages}}
    {\usebibmacro{chapter+pages}%
     \setunit{\addspace}%
     \usebibmacro{series+number}}
    {}
    {\typeout{Warning: Failed to add series+number to driver #1.}}}

\patchseries{collection}\patchseries{incollection}

\begin{document}

\nocite{*}
\printbibliography

\end{document}

A: The extrayear is called by your redefinition of the driver for incollection, in particular by the line:
\usebibmacro{editor+others}% %instead of byeditor+others

By substituting it with:
\printnames{editor}%
\setunit{\space}%
\usebibmacro{editor+othersstrg}%
\setunit{\space}%
\printfield[parens]{labelyear}%

in your bibliography driver for incollection you can get the desired result.


text:
Q: Will the use of count(distinct depositor.account_number) make a difference here Given Database Schema:
[The primary key for the tables is mentioned in bold)
account(account_no , branch_name,balance)
depositor(customer_name,account_number)  {No key was stated here}
customer(customer_name,customer_street,customer_city)
The question required to write the SQL query for - Find average balance for each customer who lives in Harrison and has atleast 3 accounts.
I wrote the following SQL query:
select depositor.customer_name,avg(balance)
from depositor,account,customer
where depositor.account_number=account.account_number and
          depositor.customer_name=customer.customer_name  and
          customer_city='Harrison'
group by depositor.customer_name
having count(depositor.account_number) >=3

My textbook mentions of the query as:
select depositor.customer_name,avg(balance)
from depositor,account,customer
where depositor.account_number=account.account_number and
          depositor.customer_name=customer.customer_name  and
          customer_city='Harrison'
group by depositor.customer_name
having count( distinct depositor.account_number) >=3

Would placing distinct here lead to a change in result ?
  According to my analysis, The cross-product of the resultant relation (depositoraccountcustomer) will have the candidate key as
 customer_name account_number so distinct would not add any value here.

A: It seems that depositor table stores unique combinations of customer_name and account_number, meaning that adding DISTINCT in the count should not make a difference.
But if the table was a fact table which had repeating instances of the same account_number you wouldn't want to count the same account number twice and in that case, it would have made a difference.
But in your case, it should not make a difference since the other two tables also seem to contain unique combinations of their respective fields.

A: Since the depositor table doesn't have a primary key constraint it would be possible to duplicate a name-account pairing. Your textbook likely hasn't discussed composite keys so this was possibly intended as a way to catch that scenario. Unfortunately the extra row(s) would still throw off the average   calculation though getting the three accounts qualification correct.


text:
Q: Why is this wrapper for SynchronizedList thread safe? I am reading "Java Concurrency in Practice" and this case is a little bit unclear to me. Why is this code ThreadSafe?
@ThreadSafe
public class ListHelper<E> {
    public List<E> list =
        Collections.synchronizedList(new ArrayList<E>());
    ...
    public boolean putIfAbsent(E x) {
        synchronized (list)  {
            boolean absent = !list.contains(x);
            if (absent)
} }
}

we lock instance of  SynchronizedList  list but inside that used inner object
final Object mutex;     // Object on which to synchronize
  public void add(int index, E element) {
            synchronized (mutex) {list.add(index, element);}
        }

We still have locks on two different objects. Why is it safe?

A: Good question.
You have to follow the whole chain of when mutex is assigned.
If not specified explicitly when calling Collections.synchronizedList as a second argument it will be the list itself.
Deep down you eventully find this:
mutex = this;


text:
Q: Finding time differences between each row in a specific column in SQL Server Still learning SQL, but I'm trying to see if there are any Customers that have a time frame within 24 hours of each other.  So in this example ID 1 and 4 meet this criteria.
CustID Date
1   2018-04-10 11:21:00.000
1   2018-03-05 18:14:00.000
1   2018-03-05 22:53:00.000
2   2018-04-10 11:21:00.000
2   2018-03-27 14:57:00.000
2   2018-04-04 20:00:00.000
3   2018-04-10 11:21:00.000
3   2018-02-10 11:21:00.000
3   2018-04-24 11:29:00.000
4   2018-04-10 11:21:00.000
4   2018-04-10 11:20:00.000
4   2018-04-24 11:29:00.000

I'm thinking about doing something like
 SELECT CustId
    From Cars c
    CROSS APPLY(
    SELECT Date
    FROM Cars
    Where Date != c.Date)
WHERE Date - c.Date < 24 hours

A: Use lag():
select distinct custid
from (select c.*,
             lag(c.date) over (partition by c.custid order by c.date) as prev_date
      from cars c
     ) c
where date < dateadd(hour, 24, prev_date);

A: This answer is based on sql-server, but you should be able to translate as needed.  I also assumed you had a requirement where the same datetime between two customers can't be the same.  If that's a false assumption, remove the where clause.  A simple self-join should get you there.
declare @t table (id int, dt datetime)

insert into @t values ('1','2018-04-10 11:21:00.000')
insert into @t values ('1','2018-03-05 18:14:00.000')
insert into @t values ('1','2018-03-05 22:53:00.000')
insert into @t values ('2','2018-04-10 11:21:00.000')
insert into @t values ('2','2018-03-27 14:57:00.000')
insert into @t values ('2','2018-04-04 20:00:00.000')
insert into @t values ('3','2018-04-10 11:21:00.000')
insert into @t values ('3','2018-02-10 11:21:00.000')
insert into @t values ('3','2018-04-24 11:29:00.000')
insert into @t values ('4','2018-04-10 11:21:00.000')
insert into @t values ('4','2018-04-10 11:20:00.000')
insert into @t values ('4','2018-04-24 11:29:00.000')

select
 t1.id, t2.id
from @t t1
join @t t2 on t2.dt between dateadd(hh, -24,t1.dt) and t1.dt and t1.id<>t2.id
where t1.dt<>t2.dt


text:
Q: Image inserted via Macro is moving when clicking in to another cell Please note that while I am quite proficient in Excel, I have almost no knowledge of VBA and Macros. A friend wrote this code for me, but it doesn't work exactly as I need, so am looking for help.
I have a Macro that pulls the file path of an image and inserts the image into a cell when the data in a cell is changed.
The data being changed is in cell C3, which changes the image file path, which is stored in I2, and the image should be displayed in cell I4, which is the top left most cell of a larger merged cell.
There is also a bit of code that deletes the old image when changing information so it doesn't keep adding an image on top of the old image.
Everything works fine apart from when clicking into any cell to edit the data, once I click out, the image moves to where clicked out. I just need the image to stay in I4
Here is the current code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ProdCell As Range
Dim PicPath As String, Pic As Picture, ImageCell As Range

Set ProdCell = Range("C3")

If Not Application.Intersect(ProdCell, Range("C3")) _
    Is Nothing Then

    Shapes(1).Delete
    On Error GoTo 0

    PicPath = Range("I2").Value
    Set ImageCell = Range("I4").MergeArea

    Set Pic = ActiveSheet.Pictures.Insert(PicPath)
    With Pic
        .ShapeRange.LockAspectRatio = msoFalse
        .Left = ImageCell.Left
        .Top = ImageCell.Top
        .Width = ImageCell.Width
        .Height = ImageCell.Height
    End With
End If

End Sub


text:
Q: How do i send azure pipeline artifacts ( in my case .apk ) to MsTeam i created an zure build pipeline and i want to publish my artifacts to Microsoft-teams Channel so my teasting team can get it .

A:
How do i send azure pipeline artifacts ( in my case .apk ) to MsTeam

I am afraid there is a way to achieve this.
According to the document Azure Pipelines with Microsoft Teams:

Azure Pipelines app on Microsoft Teams enables you to monitor the
events for your pipelines. You can set up and manage subscriptions for
releases, pending approvals, completed builds etc. and get
notifications right into your Teams channel for these updates. You can
also approve releases from within your Teams channel.

So, we could only send the notification about the build pieline, not share the build artufact to teams.
In other words, using Teams to transfer files inherently degrades Teams' service and introduces additional risks.


text:
Q: url setting for directry I want to make a setting for the url. If a user entered url in address bar like this "folder.mysitedomain.com"
   then it should be open files from second layer directory named 'folder' of the 'mysitedomain.com'(root directory) at server.
   A user can also put url just like this "mysitedomain.com/folder" then it also done as above.
   Url will show as well as user entered.
   This should be dynamically, for example directories are creating accrording to separate user accounts, so the name of the directory may be anything as dynamically.
I think it is for .htaccess  files setting. is there ?
   I have no idea about this that what i should to do and how to search this in Google and any searching site.
Help should be happily.

A: I'm not completely sure what you're trying to do but I think you should check out glob
http://php.net/manual/en/function.glob.php
That should get you started anyway.


text:
Q: sha256sum: /path/filename: No such file or directory I'm trying to install anaconda. I'm following the official instructions but when I get to the second step, I run the following command:
$ sha256sum /path/filename
sha256sum: /path/filename: No such file or directory

A: It seems OP didn't adapt the command to his computer.
In the command sha256sum /path/filename, there is 3 parts :

*

*sha256sum is the command to show the file hash value

*path is the path to reach the Anaconda installer, so it's the Download file in the OP case

*filename is the name of the Anaconda installer, the current name is Anaconda3-2019.10-Linux-x86_64.sh
So the command would be :
sha256sum ~/Downloads/Anaconda3-2019.10-Linux-x86_64.sh

It would return the hash of the file, which you have to compare on the link where you donwload it; if it's NOT the same, don't use it, it could be a malware or just the file corrupt itself during download.
Hash list of Anaconda installer : https://docs.anaconda.com/anaconda/install/hashes/all/
As you can see in the screenshot below, I use your hash result and find that you download a good installer, not corrupted nor malware :


text:
Q: VBA: Using WithEvents on UserForms I have a Word userform with 60+ controls of varying types. I would like to evaluate the form every time a control_change event is triggered and change the enabled state of the form's submit button. However, I really don't want to write and maintain 60 on change event handlers.

A: You can create an event-sink class that will contain the event-handling code for all of your controls of a particular type.
For example, create the a class called TextBoxEventHandler as follows:
Private WithEvents m_oTextBox as MSForms.TextBox

Public Property Set TextBox(ByVal oTextBox as MSForms.TextBox)
    Set m_oTextBox = oTextBox
End Property

Private Sub m_oTextBox_Change()
    ' Do something
End Sub

Now you need to create & hook up an instance of that class for each control of the appropriate type on your form:
Private m_oCollectionOfEventHandlers As Collection

Private Sub UserForm_Initialise()

    Set m_oCollectionOfEventHandlers = New Collection

    Dim oControl As Control
    For Each oControl In Me.Controls

        If TypeName(oControl) = "TextBox" Then

            Dim oEventHandler As TextBoxEventHandler
            Set oEventHandler = New TextBoxEventHandler

            Set oEventHandler.TextBox = oControl

            m_oCollectionOfEventHandlers.Add oEventHandler

        End If

    Next oControl

End Sub

Note that the reason you need to add the event handler instances to a collection is simply to ensure that they remain referenced and thus don't get discarded by the garbage collector before you're finished with them.
Clearly this technique can be extended to deal with other types of control. You could either have separate event handler classes for each type, or you could use a single class that has a member variable (and associated property & event handler) for each of the control types you need to handle.

A: In that case you have few options, because event handlers cannot be shared in VBA/VB6
Option 1: Use a central handling function which is called from every event handler.
Sub Control1_ChangeEvent()
  CommonChangeEvent // Just call the common handler, parameters as needed
End Sub

Sub Control2_ChangeEvent()
  CommonChangeEvent
End Sub
...
Sub CommonChangeEvent(/* Add necessary parameters */)
  //Do the heavy lifting here
End Sub

Option 2: Organize your controls in control arrays.
Sub TextBox_ChangeEvent(Index As Integer)
  CommonChangeEvent
End Sub

Sub OtherControlType_ChangeEvent(Index As Integer)
  CommonChangeEvent
End Sub

Combining both options your total event handler count will shrink considerably and the remaining handlers are just brainless stubs for the one true event handler.


text:
Q: Export to JSON format I have the following 2 tables. Actually I need to sync all table related and non related table to another database. Am using SQL Server 2017.

 CREATE TABLE EmailAddresses (
        ID int,
        EmailAddress varchar(255),
         StartDate datetime,
        EndDate datetime,
    );

 CREATE TABLE Cards (
        ID int,
        CardNumber varchar(255),
        ValidFrom datetime,
        ValidTo datetime,
        CVC  varchar(255),
    );

I need all the records of 2 table in single json file ( format is as below) .
{
    "Sync By" : "XYZ",
    "Sync Date" : "2021-10-16",
    "EmailAddresses" : [
        {
            "EmailAddress" : "Aisha@AEL.com",
            "StartDate" : "2015-11-12",
            "EndDate" : "2019-06-21"
        },
        {
            "EmailAddress" : "Elsie@Livulook.co.wm",
            "StartDate" : "2014-02-09",
            "EndDate" : "2015-12-23"
        },
        {
            "EmailAddress" : "Harriet23@Zaha.com",
            "StartDate" : "2013-07-26",
            "EndDate" : "2018-04-16"
        }
    ],
    "Cards" : [
        {
            "CardNumber" : "340365242116610",
            "ValidFrom" : "2015-07-28",
            "ValidTo" : "2021-10-16",
            "CVC" : "205"
        }

    ]
}

A: You could achieve that with the for json.
https://learn.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-2017
These two will produce two json arrays which if combined together will give you the desired format.
These two properties:
Sync By and Sync Date do not exist in database hence they need to be adjusted manually at the export time.
 select 'XYZ' as 'Sync By',
 select '2021-10-16' as 'Sync Date',

 (select ID, EmailAddress, StartDate, EndDate,
         from table EmailAddresses
         for json path) EmailAddresses,

 (select Id, CardNumber, ValidFrom, ValidTo, CVC
         from table Cards
         for json path) Cards

  for json path

A: One possible approach is to export the data from the two tables using FOR JSON AUTO and then generate the final output using FOR JSON PATH with WITHOUT_ARRAY_WRAPPER option:
Tables:
CREATE TABLE EmailAddresses (
        ID int,
        EmailAddress varchar(255),
        StartDate datetime,
        EndDate datetime,
    );

CREATE TABLE Cards (
        ID int,
        CardNumber varchar(255),
        ValidFrom datetime,
        ValidTo datetime,
        CVC  varchar(255),
);
INSERT INTO EmailAddresses
   (ID, EmailAddress, StartDate, EndDate)
VALUES
   (1, 'Aish"a@AEL.com', '2015-11-12', '2019-06-21'),
   (2, 'Aisha@AEL.com', '2015-11-12', '2019-06-21'),
   (3, 'Aisha@AEL.com', '2015-11-12', '2019-06-21')
INSERT INTO Cards
   (ID, CardNumber, ValidFrom, ValidTo, CVC)
VALUES
   (1, '340365242116610', '2015-07-28', '2021-10-16', '205')

Statement:
SELECT
   [Sync By] = 'XYZ',
   [Sync Date] = '2021-10-16',
   [EmailAddresses] = (
      SELECT EmailAddress, StartDate, EndDate
      FROM EmailAddresses
      FOR JSON AUTO
   ),
   [Cards] = (
       SELECT CardNumber, ValidFrom, ValidTo, CVC
       FROM Cards
       FOR JSON AUTO
   )
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER


text:
Q: How to set navigator.webdriver to false in selenium chrome by using python I am trying to set this argument to false in chrome. IN firefox we can do this profile.set_preference("dom.webdriver.enabled", False)
How can i perform this on chrome.
Any help would be appreciated.


text:
Q: How does SSD Wear Leveling work? Is ssd wear leveling built into the hardware or the software? Does ide mode (since I cloned my data from a hdd with ide mode, I cannot set it to ahci because it results in a BSOD) have any disadvantages in terms of the longevity of the drive (does it not allow for wear leveling).
The ssd is an intel series 335 with 250 gigs of storage

A: The controller mode has no effect on wear leveling. It will, however, affect trim.


text:
Q: Bulk geocoding for associating addresses to shapefiles [here-api] I was wondering if I can use the here-api to geocode addresses (bulk way) and store the results. I need to store them on a python data frame to afterwards merge them with a shape file. However, in the TOS HERE says that you cannot store the results from geocoding.

A: I've been in your situation. Let me list the options that we've considered.

*

*You could fetch address information dynamically using their Geocoding API. Advantage is that you'll always have up-to-date information, and you don't need to query places that you'll never use anyway.

*I'm assuming that your shape file is based on HERE data. You could still try to use OpenStreetMaps. You'll get some inaccuracies if the map data differs, but it's free, and not as restrictive as HERE.

*You could opt to buy the HERE map data, to work around the TOS restrictions
By the way, we went for an option 4: switching to OpenStreetMaps entirely, but it sounds like you don't have that luxery, because you have to work with existing shapefiles that you want to "enrich".


text:
Q: Is there a way to lock the difficulty setting in minecraft? In minecraft, difficulty settings can be changed anytime, and this is in fact (normally) a great feature. Yet, for some reasons given below, I am looking for an option to disable this feature, may it be by a mod or whatever. Does anybody know a way to lock the difficulty setting once a game is created? Or even better (for my purposes): How can I enforce that new games will always use a predetermined, fixed difficulty that cannot be changed?
Some explanation: I have seen many discussions of such a question in the web being stalled by comments like "Aww, man, just show some willpower and don't switch the setting!" In the problem at hand, I am preparing a (single-player) installation of Minecraft for my niece and nephew. They love the game, but they are quite young, and being attacked by a bunch of scary spiders will most certainly lead to severe nightmares, that much I am sure. Hence, I want to technically prevent them from changing the difficulty (either on purpose or by accident) to something other than "peaceful". So please, consider this question as valid.

A: A slight work around, that would probably be better as it will turn of mobs but keep health regen off, would be to run the game on a server. You would not need a spare computer as you can run it off the same PC as the game. All you need to do is change:

spawn-monsters=true

To:

spawn-monsters=false

In the server's server.properties file. If you are worried about them purposely changing it back you can lock the file to admin access, although if you do this they will not be able to change map.

A: After they start a level, immediately ask them to say:
/gamerule doMobSpawn false

or set their difficulty to Peaceful. Only hard can be locked, which cannot be simple and is only locked automatically on Hardcore.


text:
Q: How to re-use a variable without getting error C2371 (Redefinition), for var with different types? In VBA I simply would use a variant-Type for this, but how can I reduce this somewhat repetitive code to get to a better switch case block?
switch(command){
case CMD1:
    RESPONSE1 rsp1;
    memcpy(&rsp1,pPkt,sizeof(rsp1));
    break;
case CMD2:
    RESPONSE2 rsp2;
    memcpy(&rsp2,pPkt,sizeof(rsp2));
    break;
case CMD3:
    RESPONSE3 rsp3;
    memcpy(&rsp3,pPkt,sizeof(rsp3));
    break;
case CMD4:
    RESPONSE4 rsp4;
    memcpy(&rsp4,pPkt,sizeof(rsp4));
case CMD5:
    RESPONSE5 rsp5;
    memcpy(&rsp5,pPkt,sizeof(rsp5));
default:
    break;
}

My goal would be to eliminate those 5 response variables and use only one - however, I need the 5 different types because of the memcpy.
I am aware, that there is something like cast, but I think this is more problematic, because these RESPONSE# are structs of different size - wouldn't I have to reallocate memory for that?
Edit:
Thanks to mux, I found, that there is already a union for that in my code (adapting something from someone else)!
typedef union
{
  RESPONSE1 rsp1;
  RESPONSE2 rsp2;
  RESPONSE3 rsp3;
  RESPONSE4 rsp4;
  RESPONSE5 rsp5;
}
RESPONSE_UNION;

And this is what I am using now:
RESPONSE_UNION ru;

switch(command){
    case CMD1:
        memcpy(&ru.rsp1,pPkt,sizeof(ru.rsp1));
        break;
    case CMD2:
        memcpy(&ru.rsp2,pPkt,sizeof(ru.rsp2));
        break;
...

Really a great help!

A: You could use a union and you might also want to define an enum for the response type:
typedef enum {
    RESPONSE_1,
    RESPONSE_2,
    RESPONSE_3,
    RESPONSE_4
} ResponseType;

typedef struct {
    ResponseType type;
    union {
        RESPONSE1 rsp1;
        RESPONSE2 rsp2;
        RESPONSE3 rsp3;
        RESPONSE4 rsp4;
    };
} Response;

In your code you use it like this:
Response r;
switch (command) {
    case CMD1:
        r.type = RESPONSE_1;
        memcpy(&r.rsp1, pPkt, sizeof(r.resp1));
        break;
    case CMD2:
    ...
}


text:
Q: missing "System" reference on ubuntu and .net core 3.0 I'm trying to develop a simple web app using .Net Core 3.0 on an Ubuntu machine.
I setup the .Net Core SDK and the runtime from this link. I setup VS Code and then I create a project using the following commands dotnet new webapp -o RazorPagesMovie code -r RazorPagesMovie
I built the project and it is working. But in VS Code, it shows the following error:
The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)

screenshot of vs code

A: Regarding your problem, there are multiple open issues on omnisharp-vscode (e.g. 3289, 3290) GitHub repository. A few workarounds are available as follows:

*

*For Windows: install Visual Studio 2019 Community Edition, or MsBuild Tools 2019

*For Linux/MacOS: install Mono 6.0.0 or newer

Or uninstall the previous versions of .NET Core. If you don't like these workarounds, the best solution to fix the issue is that installing the new (beta) OmniSharp build for the time being.
You can install this build by adding the following line into your VS Code settings.json:
"omnisharp.path": "1.34.4-beta.7"

Once you save the settings, the new build of omnisharp-vscode with fix will be installed. After the installation, restart IDE if required. I can confirm that the fix works for Windows.

A: I often get a similar message on .net core 2.x and I find that you have to add the reference to netstandard into the project file to fix as below:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    ..
  </PropertyGroup>
  <ItemGroup>
    ..
  </ItemGroup>

  <ItemGroup> <Reference Include="netstandard" /> </ItemGroup>
</Project>

A: On Mac I tried removing old dot net runtimes and sdks, using the preview version of omnisharp and verifying mono version above 6.0.0
I also deleted project bin and obj dirs, recompiled, deleted nuget cache dirs and restored.
Then I ran across this in related post:
ACK! Upgrading to Mono 6.4 solves problem under Linux!
(Under Mono 6.0 problem occurs as I have had this version before)
Not 6.0 necessarily....


text:
Q: Animate Pseudo-Class with @keyframes I have the following code:

.link {
  font-family: 'Arial';
  text-transform: Uppercase;
  color: #000;
  text-decoration: none;
  display: inline-block;
}

.link:after {
  content: "";
  display: block;
  padding-top: 3px;
  border-bottom: 2px solid black;
  transform: scaleX(1);
  transition: transform 250ms ease-in-out;
  transform-origin: 0% 50%
}

.link:hover:after {
  transform: scaleX(0);
  transform-origin: 100% 50%;
}
Some Random Link

I have a simple Animation when I hover over my Link. Basically the Underline slides out to the right, when I hover over the element and slides in from the left when I leave the element.
What I want to have is, that it plays the whole Animation when I'm hovering over the Element. I tried creating an Animation with @keyframes but couldn't get it work, because I don't know how to animate only the Pseudo-Class ::after and not the whole element.
Here's also a JSFiddle to better explain what I'm trying to do: JSFiddle


text:
Q: -bash: /Users/[me]/.rvm/scripts/initialize: No such file or directory I was in a directory where I had a ~ and I went to remove it by doing
rm -f ~
for which it said it was a directory. So I made the really silly move of doing
rm -rf ~
and suddenly I get the error
-bash: /Users/brent/.rvm/scripts/initialize: No such file or directory

See out put
cd ..
-bash: /Users/brent/.rvm/scripts/initialize: No such file or directory
-bash: /Users/brent/.rvm/scripts/hook: No such file or directory

Can I restore these?


text:
Q: How to use xarray's 'where' masking feature with a multidimensional dataset? I am looking for a way to use .where to mask data in a 3D array, such that if any of the values within the 2nd and 3rd dimension are true, it returns the entire 2nd and 3rd dimension matrix, instead of only the ones that are true.
I am using xarray with a dataset that contains 200+ variables. Many of these variables are multidimensional arrays. One array in particular has a 110x16x6 shape. I want to mask my dataset so that if any of the 16x6 values are above a certain number, the whole 16x6 matrix at that index is returned.
I have tried using .where with drop=True, but it returns all false values along all 3 dimensions of my data array. I only want values dropped if the entire 16x6 matrix doesn't have any of the values I am looking for.
In: DS.cloud_layer_top_level_height.shape

Out: (110, 16, 6)

In: DS.cloud_layer_top_level_height[0]

Out: <xarray.DataArray 'cloud_layer_top_level_height' (Cloud groups: 16,
Cloud
Layers: 6)>
array([[2.801278,      nan,      nan,      nan,      nan,      nan],
      [3.37    ,      nan,      nan,      nan,      nan,      nan],
      [2.861235,      nan,      nan,      nan,      nan,      nan],
      [2.981151,      nan,      nan,      nan,      nan,      nan],
      [2.981151,      nan,      nan,      nan,      nan,      nan],
      [2.711341,      nan,      nan,      nan,      nan,      nan],
      [2.861235,      nan,      nan,      nan,      nan,      nan],
      [2.801278,      nan,      nan,      nan,      nan,      nan],
      [2.981151,      nan,      nan,      nan,      nan,      nan],
      [2.981151,      nan,      nan,      nan,      nan,      nan],
      [2.711341,      nan,      nan,      nan,      nan,      nan],
      [2.711341,      nan,      nan,      nan,      nan,      nan],
      [2.711341, 1.362293,      nan,      nan,      nan,      nan],
      [2.711341, 1.272357,      nan,      nan,      nan,      nan],
      [2.681362,      nan,      nan,      nan,      nan,      nan],
      [2.681362,      nan,      nan,      nan,      nan,      nan]],
  dtype=float32)
Dimensions without coordinates: Cloud groups, Cloud Layers
Attributes:
units:        kilometers
format:       F18.9
valid_range:  [-0.5 30. ]

In: DS=DS.where(DS.cloud_layer_top_level_height>3,drop=True)

Out: DS.cloud_layer_top_level_height[0]
<xarray.DataArray 'cloud_layer_top_level_height' (Cloud groups: 16, Cloud
Layers: 4)>
array([[ nan,  nan,  nan,  nan],
      [3.37,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan],
      [ nan,  nan,  nan,  nan]], dtype=float32)
Dimensions without coordinates: Cloud groups, Cloud Layers
Attributes:
units:        kilometers
format:       F18.9
valid_range:  [-0.5 30. ]

Ideally, since that first index contains one value larger than 3, I would like all of the values inside that matrix to be returned instead of just the single one greater than 3. Also, if a first dimension index contained no values greater than 3 (in the 16x6 matrix), I would like it to be dropped.


text:
Q: Как запустить программу C++, которая была скомпилирована в другой Linux ОС Есть программа написанная на С++, скомпилированная в другой Linux ОС.
(Ubuntu BusinessPack 18.04 UALinux Release: 18.04):
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

int main()
{
   std::cout << "TEST BUILDS" << std::endl;
   return 0;
}

Компиляцию делал так:
Среда разработки: Code Blocks 16.01 , компилятор: GNU GCC Compiler - без флагов.
Настройки компиляции в Code Blocks
После компиляции, исполняемый файл был перенесен на другую Linux ОС.
(CentOS Linux release 7.6.1810 (Core) Kernel Version): 3.10.0-957.1.3.el7.x86_64)
При запуске ничего не выводит, ошибок нету. Выставление прав на бинарник не помогло.
Как скомпилировать, чтобы при переносе исполняемого файла на другую Linux ОС программа работала.
Желательно без использования сторонних библиотек и без работы с API ОС.

A: Для сборки переносимого приложения лучше всего использовать -static. Приложение будет включать все зависимости внутри одного файла.
Динамическая сборка будет работать на более новых линуксах, на которых версия glibc выше или совпадает. Остальные зависимости можно положить рядом с исполняемым файлом. Проверить зависимости можно через программу ldd.
Для питона есть проект manylinux - это набор докер образов с допиленной glibc, Собранный в контейнере код запустится почти везде. Тут несложно войти в контейнер и запустить сборку-ликовку сишного кода в нем