text:
Q: Select one number at a time between 0 & 10 billion in random order Problem
I have a need to pick one unique random number at a time between 0 and 10,000,000,000 and do it till all numbers are selected. Essentially the behavior I need is a pre-built stack/queue with 10 billion numbers in random order, with no ability to push new items into it.
Not so good ways to solve:
There's no shortage of inefficient ways in my brain. Such as,

*

*persist generated numbers and check newly generated random number is already used, at some point this gets us into indefinite wait before a usable number is produced.

*Persist all possible numbers in a table and pop a random row and maintain new row count for next pick etc. Not sure if this is good or bad.

Questions:

*

*Are there other deterministic ways besides storing all possible combinations and using random?

*

*Like maintaining windows of available numbers and randomly select a window first and randomly select a number within that window etc. eg: like this

*If not, what is the best type to store numbers in reasonably small amount of space?

*

*50+% of numbers wont fit in a 32 bit (int), 64 bit (long) is waste. Cos largest number fits in 34 bits, wasting 30 bits per number (>37GB total).

If this problem hasn't been solved already.

*What is a good data structure for storing & picking a random spot and quickly adjust the structure for next pick to be fast?

***Sorry for the ambiguity. The largest selectable number is 9,999,999,999 and smallest selectable is 1.

A: You ask: "Are there other deterministic ways besides storing all possible combinations and using random?"
Yes there is: Encryption.  Encryption with a given key guarantees a unique result for unique inputs since it is reversible.  Each key defines a one-to-one permutation of the possible inputs.  You need an encryption of inputs in the range [1..10e9].  To deal with something that big you need 34 bit numbers, which go up to 17,179,869,183.
There is no standard 34 bit encryption.  Depending on how much security you need, and how fast you need the numbers, you can either write your own simple, fast, insecure four-round Feistel Cipher or else for something slower and more secure use Hasty Pudding cipher in 34 bit mode.
With either solution, if the first encryption gives a result outside the range, just encrypt the result again until the new result is within the range you want.  The one-to-one property ensures that the final result of the chain of encryptions will be unique.
To generate a sequence of unique random-seeming numbers just encrypt 0, 1, 2, 3, 4, ... in order with the same key.  Encryption guarantees that the results will be unique for that key.  If you record how far you have got, then you can generate more unique numbers later, up to your 10 billion limit.

A: As mentioned by AChampion in the comments, you could use a Linear Congruential generator.
Your modulo (m) value will be 10 billion. In order to get a full period (all values in the range appear before the series repeats) you need to choose the a and c constants to satisfy certain criteria. m and c need to be relatively prime and a - 1 needs to be divisible by the prime factors of m (which are just 2 and 5) and also by 4 (since 10 billion is divisible by 4).
If you just come up with a single set of constants, you will only have one possible series and the numbers will always occur in the same order. However you can easily randomly generate constants that satisfy the criteria. To test for relative primality of c and m, just test if c is divisible by 2 and 5, since these are the only prime factors of m (see first condition of coprimality test here)
Simple sketch in Python:
import random

m = 10000000000
a = 0
c = 0
r = 0

def setupLCG():
    global a, c, r
    # choose value of c that is 0 < c < m and relatively prime to m
    c = 5
    while ((c % 5 == 0) or (c % 2 == 0)):
        c = random.randint(1, m - 1)
    # choose value of a that is 0 < a <= m and a - 1 is divisible by
    # prime factors of m, and 4
    a = 4
    while ((((a - 1) % 4) != 0) or (((a - 1) % 5) != 0)):
        a = random.randint(1, m)
    r = random.randint(0, m - 1)

def rand():
    global m, a, c, r
    r = (a*r + c) % m
    return r

random.seed()
setupLCG()
for i in range(1000):
    print rand() + 1

This approach won't give the full possibility of 10000000000! possible combinations, but it will still be on the order of 1019, which is quite a lot. It does have a few other issues (e.g. alternates even and odd values). You could mix it up a bit by having a small pool of numbers, adding a number from the sequence to it each time and randomly drawing one out.

A: Similar to what rossum has suggested, you can use invertible integer hash function, which uniquely maps an integer in [0,2^k) to another integer in the same range. For your particular problem, you choose k=34 (2^34=16 billion) and reject any number above 10 billion. Here is a complete implementation:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

uint64_t hash_64(uint64_t key, uint64_t mask)
{
    key = (~key + (key << 21)) & mask; // key = (key << 21) - key - 1;
    key = key ^ key >> 24;
    key = ((key + (key << 3)) + (key << 8)) & mask; // key * 265
    key = key ^ key >> 14;
    key = ((key + (key << 2)) + (key << 4)) & mask; // key * 21
    key = key ^ key >> 28;
    key = (key + (key << 31)) & mask;
    return key;
}

int main(int argc, char *argv[])
{
    uint64_t i, shift, mask, max = 10000ULL;
    char *dummy;
    if (argc > 1) max = strtol(argv[1], &dummy, 10);
    for (shift = 0; 1ULL<<shift <= max; ++shift) {}
    mask = (1ULL<<shift) - 1;
    for (i = 0; i <= mask; ++i) {
        uint64_t x = hash_64(i, mask);
        x = hash_64(x, mask);
        x = hash_64(x, mask); // apply multiple times to increase randomness
        if (x > max || x == 0) continue;
        printf("%llu\n", x);
    }
    return 0;
}

This should give you number [0,10000000000] in random order.

A: For the range 1-999,999,999,999 is equivalent 0-999,999,999,998 (just add 1). Given the definition of LCG then you can implement this:
import functools as ft
import itertools as it
import operator as op
from sympy import primefactors, nextprime

def LCG(m, seed=0):
    factors = set(primefactors(m))
    a = ft.reduce(op.mul, factors)+1
    assert(m%4 != 0 or (m%4 == 0 and (a-1)%m == 0))
    c = nextprime(max(factors)+1)
    assert(c < m)
    x = seed
    while True:
        x = (a * x + c) % m
        yield x

# Check the first 10,000,000 for duplicates
>>> x = list(it.islice(LCG(999999999999), 10000000))
>>> len(x) == len(set(x))
True
# Last 10 numbers
>>> x[-10:]
[99069910838, 876847698522, 765736597318, 99069940559, 210181061577,
 432403293706, 99069970280, 543514424631, 99069990094, 99070000001]

I've taken a couple of shortcuts for the context of this question as the asserts should be replaced with handling code, currently it would just fail if those asserts were False

A: I'm not aware of any truly random methods of picking the numbers without storing a list of the numbers already picked.   You could do some sort of linear hashing algorithm, and then pass the numbers 0 to n through it (repeating when your hash returns a value above 10000000000), but this wouldn't be truly random.
If you are to store the numbers, you might consider doing it via a bitmask.   To pick quickly in the bitmask, you would likely keep a tree, where each leaf would represent the number of free bits in the corresponding 32 bytes, the branches above that would list the number of free bits in the corresponding 2K entries, and so forth.  You then have O(log(n)) time to find your next entry, and O(log(n)) time to claim a bit (as you have to update the tree).   It would require something to the order of 2n bits to store as well.

A: If predictability is not a concern, you can generate quickly using XOR operations. Suppose you want to generate a random sequence of unique numbers with n bits (34 in your case):
1- take a seed number on n bits. This number, K, can be considered as a seed that you can change each time you run a new experiment.
2- Use a counter from 0 upward
3- Each time XOR the counter with K :  next = counter xor K; counter++;
To limit the range to 10 Billion, which is not a power of two, you will need to do rejection.
The obvious drawback is predictability. In step 3, you can do a prior transposition on the bytes of the counter, for example inverse the order of the bytes (like when you transform from little-endian to big endian). This would yield some improvement concerning the predictability of the next number.
Finally I have to admit that this answer can be considered as a particular implementation of encryption which was mentioned in the answer of @rossum, but it's more specific and probably fastest.

A: You definitely don't need to store all the numbers.
If you want a perfect set of the numbers from 1 to 10B each exactly once, there are two options that I see: as hinted at by the others, use a 34-bit LCG or Galois LFSR or XOR-shift that generates a sequence of numbers from 1 to 17B or so, then throw out the ones over 10B. I am not aware of any specifically 34-bit functions for this, but I'm sure someone is.
Option 2, if you can spare 1.25 GB of memory, is to create a bitmap that stores only the information that a certain number has been chosen, then use Floyd's Algorithm to get the numbers, which would be fast and give you much better quality numbers (in fact, it would work just fine with hardware RNGs).
Option 3, if you can live with a rare but occasional mistake (duplicate or never-selected number), replace the bitmap with a Bloom filter and save memory.

A: Incredibly slow but it should work. Completely random
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static Random random = new Random();
        static void Main()
        {
            const long start = 1;
            const long NumData = 10000000000;
            const long RandomNess = NumData;
            var sz = Marshal.SizeOf(typeof(long));
            var numBytes = NumData * sz;

            var filePath = Path.GetTempFileName();
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                // create file with numbers in order
                stream.Seek(0, SeekOrigin.Begin);
                for (var index = start; index < NumData; index++)
                {
                    var bytes = BitConverter.GetBytes(index);
                    stream.Write(bytes, 0, sz);
                }

                for (var iteration = 0L; iteration < RandomNess; iteration++)
                {

                    // get 2 random longs
                    var item1Index = LongRandom(0, NumData - 1, random);
                    var item2Index = LongRandom(0, NumData - 1, random);

                    // allocate room for data
                    var data1ByteArray = new byte[sz];
                    var data2ByteArray = new byte[sz];

                    // read the first value
                    stream.Seek(item1Index * sz, SeekOrigin.Begin);
                    stream.Read(data1ByteArray, 0, sz);

                    // read the second value
                    stream.Seek(item2Index * sz, SeekOrigin.Begin);
                    stream.Read(data2ByteArray, 0, sz);

                    var item1 = BitConverter.ToInt64(data1ByteArray, 0);
                    var item2 = BitConverter.ToInt64(data2ByteArray, 0);

                    Debug.Assert(item1 < NumData);
                    Debug.Assert(item2 < NumData);

                    // swap the values
                    stream.Seek(item1Index * sz, SeekOrigin.Begin);
                    stream.Write(data2ByteArray, 0, sz);

                    stream.Seek(item2Index * sz, SeekOrigin.Begin);
                    stream.Write(data1ByteArray, 0, sz);
                }

            }
            File.Delete(filePath);

            Console.WriteLine($"{numBytes}");

        }

        static long LongRandom(long min, long max, Random rand)
        {
            long result = rand.Next((int)(min >> 32), (int)(max >> 32));
            result = (result << 32);
            result = result | rand.Next((int)min, (int)max);
            return result;
        }
    }
}


text:
Q: Common database in LAN I'm making system like client-server. There's two possibilities: to log in as user or admin. On one of the machines, e.g. superadmin's machine is storing main database. There's option to log in as administrator from any machine and to get datas from this main database.
But I've problem - what if this machine'll be broke? This db should be available all the time, but putting the db with the same datas on each machine it doesn't make sense.
I think about chosing proportional amounts of machines that will be store copies of main database: e.g. 2 on 10 computers in LAN.
Is there any better idea? Or better proportions?

A: This machine is commonly called server, made of server HW (more reliable and performant, and of course expensive) and certainly not "superadmin's machine".
There are ways to have more than one server, but I think this would just add unnecessary complexity to your application.

A: SQL Server supports both failover clustering which it sounds like you want here and replication  which you could also use to maintain multiple instances.
in a failover cluster if one instance goes down the clients won't notice it, in a replication scenario you have multiple sql servers, each client is tied to one sql server, if one goes down then all the clients using that server will have a problem (of course, you could go ahead and custom make your own failover implementation on top of replicated sql servers, but I would highly recommend you to use the technology provided by Microsoft instead)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Measuring degrees of randomness Imagine, for simplicity's sake, that we have a set of numbers, each equal to either 0 or 1. Let's call each a bit. Rationally, if the set is completely random, and reasonably large, the probability should be quite high that each possible value (0 or 1) is equally represented, and this probability should grow with increasing size of the set, until, with infinite bits in the set, the chance each possible value is equally represented should be exactly 1.
However, with my current knowledge of set theory and statistics, I cannot think of a way to measure this probability, given a set size and number of contained values. Also, assuming we have found this function, it implicitly defines the set as perfectly random. If that were not so, how could one factor in "degree of randomness?" How is degree of randomness measured?

A: The question came up while the first answer is perfect
I'll add a complement to the answer of this question : How is degree of randomness measured?
Instead of computing the variance of all the datas, that is in some cases intrinsically difficult, one can pick random samples, compute their variances and the variance of the sampled variances. In some cases when speed is critical, simply counting the number of bits up in small samples may give accurate informations on the quality of the whole set of the random datas.
This method may be used dynamically to build a confidence(time) curve that may be used in the real time ( or not ) analyses.

A: You are interested in the proportion of $1$s in the set, that is $n/N$ where $N$ is the size of the set, and $n$ is the random number of $1$s.
Now $n$ is sum of independant Bernoulli variables $x_i$ with parameter $(p=1/2)$ and you are interested in the deviations from the mean $1/2$.
From the CLT the size of the deviations is $\sqrt{N}$ for the number of $1$s, that is $\frac 1{\sqrt{N}}$ for the ratio:
$$
P\left(\left|\frac nN - \frac 12\right|>\frac a{\sqrt{N}}\right)=
P\left( \sqrt{N}\left|\frac 1N \sum x_i - Ex_1 \right|>a\right)\to
\int_{-a}^a \exp{-\frac{u^2}{2V}}\frac{du}{\sqrt{2\pi V}}
$$where $V=p(1-p)=1/4$ is the variance of the $x$ variable.


text:
Q: Uninstall package locally installed with checkinstall OS: Ubuntu 18.04
I wanted to install vim from source, using checkinstall. So I ran this:
$ git clone https://github.com/vim/vim.git
$ cd vim/src

Here, I edited the Makefile so vim would be installed in the $HOME directory, instead of the default location that requires sudo privileges (I do have sudo privileges, but wanted to install vim locally). I also edited some other lines, like uncommenting the Python lines, or choosing the normal size of vim; but I think those are not too relevant to this post. I then ran:
$ make
$ checkinstall

Notice that I ran checkinstall without sudo. When checkinstall was done "installing", I got the following result:
Building file list...OK
Building Debian package...OK
Installing Debian package... FAILED!

However, I can now use vim in the command line and $ vim --version returns the corresponding lines, including compiled <date-of-today>. And $ which vim returns:
/path/to/home/bin/vim

I now want to uninstall vim and just install it using apt-get, even though it will install it globally.
So, what is the right way to uninstall vim in this case?
Also, other than building a deb package, what are the steps or actions that checkinstall does but make install does not?

Edit:
When checkinstall asked "Do you want to see the log file?", I typed y and the output was something like (I don remember it exactly): dpkg error: sudo privileges are required.
Later on, trying my luck (coincidentally one of the answers to this post suggested the same), I ran:
$ make uninstall

That successfully (as far as I can tell) uninstalled vim and removed the vim files from my $HOME directory. I then ran:
$ sudo apt-get install vim-gtk3

because I wanted to install a version with xterm_clipboard enabled. Then, as requested in a comment here (I read the comment after I installed vim-gtk3), I ran some commands, and the results were:
$ type -a vim
vim is /usr/bin/vim
$ dpkg -S /usr/bin/vim
dpkg-query: no path found matching pattern /usr/bin/vim

A: You didn't read man checkinstall and didn't save any data from it.
To uninstall software that was installed via make, thusly:
cd vim/src
make uninstall


text:
Q: Solve for quadrilateral with minimal difference between interior angles Given an arbitrary quadrilateral with known side lengths and one input angle (the single degree of freedom), I am trying to pick the input angle that minimizes the difference between the resulting other 3 angles.
I want each of the calculated angles to be as close to each other as possible: for example some configurations result in one angle being 180° while another is 90°.  My goal  in this case would be to choose an input angle such that these two angles are more "evenly spaced", like 135° and 135° for example.  I'm not sure what relations or equations I would need to figure this out, but any direction would be helpful!
Some Clarification:
Let the quadrilateral have sides $a, b, c, d$ where all sides have known lengths and fixed order.  Let $\theta$ be the input angle between $a$ and $b$.  Let $\phi$ be the angle between $b$ and $c$, and $\gamma$ be the angle between $c$ and $d$.   I would like to find a value for $\theta$ such that $\phi - \gamma$ is minimal.

A: So as @saulspatz intuited, treating the quadrilateral as cyclic gives the best solution with the given restrictions.  The input angle $\theta$ can be calculated as follows:
$$cos(\theta) = \frac{(a^2 + d^2 - b^2 - c^2)}{2(ad + bc)}$$
Then the rest of the angles can be calculated using the law of cosines.  Since all vertices of the quadrilateral will lay on the perimeter of a circle, the internal angles end up being relatively evenly distributed!
Thanks for the help guys!


text:
Q: UnresolvedException: Invalid call to dataType on unresolved object when using DataSet constructed from Seq.empty (since Spark 2.3.0) The following snippet works fine in Spark 2.2.1 but gives a rather cryptic runtime exception in Spark 2.3.0:
import sparkSession.implicits._
import org.apache.spark.sql.functions._

case class X(xid: Long, yid: Int)
case class Y(yid: Int, zid: Long)
case class Z(zid: Long, b: Boolean)

val xs = Seq(X(1L, 10)).toDS()
val ys = Seq(Y(10, 100L)).toDS()
val zs = Seq.empty[Z].toDS()

val j = xs
  .join(ys, "yid")
  .join(zs, Seq("zid"), "left")
  .withColumn("BAM", when('b, "B").otherwise("NB"))

j.show()

In Spark 2.2.1 it prints to the console
+---+---+---+----+---+
|zid|yid|xid|   b|BAM|
+---+---+---+----+---+
|100| 10|  1|null| NB|
+---+---+---+----+---+

In Spark 2.3.0 it results in:
org.apache.spark.sql.catalyst.analysis.UnresolvedException: Invalid call to dataType on unresolved object, tree: 'BAM
  at org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute.dataType(unresolved.scala:105)
  at org.apache.spark.sql.types.StructType$$anonfun$fromAttributes$1.apply(StructType.scala:435)
  at org.apache.spark.sql.types.StructType$$anonfun$fromAttributes$1.apply(StructType.scala:435)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
  at scala.collection.immutable.List.foreach(List.scala:392)
  at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
  at scala.collection.immutable.List.map(List.scala:296)
  at org.apache.spark.sql.types.StructType$.fromAttributes(StructType.scala:435)
  at org.apache.spark.sql.catalyst.plans.QueryPlan.schema$lzycompute(QueryPlan.scala:157)
  ...

The culprit really seems to be Dataset being created from an empty Seq[Z]. When you change that to something that will also result in an empty Dataset[Z] it works as in Spark 2.2.1, e.g.
val zs = Seq(Z(10L, true)).toDS().filter('zid === 999L)

In the migration guide from 2.2 to 2.3 is mentioned:

Since Spark 2.3, the Join/Filter's deterministic predicates that are after the first non-deterministic predicates are also pushed down/through the child operators, if possible. In prior Spark versions, these filters are not eligible for predicate pushdown.

Is this related, or a (known) bug?

A: @user9613318 there is a bug create by the OP but it is closed as "Cannot Reproduce" because the dev says that

I am not able to reproduce on current master. This must have been fixed.

but there is no reference to another underlying issue so it might remain a mystery.

A: I have worked this around on 2.3.0 by issuing someEmptyDataset.cache() right after the empty Dataset was created. OP's example didn't fail anymore like that (with zs.cache()), also the actual problem at work went away with this trick.
(As a side note, OP-s code doesn't fail for me on Spark 2.3.2 run locally. Though I don't see the related fix in 2.3.2 change log, so it's maybe due to some other differences in the environment...)


text:
Q: Why is keras tokenizer applying lowercase() to it's own tokens? I am running my first cnn text-classifier using the IMDB dataset with the in-built
tf.keras.datasets.imdb.load_data()
I understand the AttributeError: 'int' object has no attribute 'lower' error indicates that a lowercase function is being applied to int objects (seems to be from the tokenizer). However, I don't know why it is throwing this in this case as I am loading it directly though the in-built tf.keras.datasets.imdb.load_data().
I am not experienced with using embedding in text-classification.
The code excluding the CNN model is:
import tensorflow as tf
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding, LSTM
from keras.layers import Conv1D, Flatten, MaxPooling1D
from keras.datasets import imdb
import wandb
from wandb.keras import WandbCallback
import numpy as np
from keras.preprocessing import text

import imdb

wandb.init(mode="disabled") # disabled for debugging
config = wandb.config

# set parameters:
config.vocab_size = 1000
config.maxlen = 1000
config.batch_size = 32
config.embedding_dims = 10
config.filters = 16
config.kernel_size = 3
config.hidden_dims = 250
config.epochs = 10

(X_train, y_train), (X_test, y_test) = tf.keras.datasets.imdb.load_data()

tokenizer = text.Tokenizer(num_words=config.vocab_size)
tokenizer.fit_on_texts(X_train)
X_train = tokenizer.texts_to_matrix(X_train)
X_test = tokenizer.texts_to_matrix(X_test)

X_train = sequence.pad_sequences(X_train, maxlen=config.maxlen)
X_test = sequence.pad_sequences(X_test, maxlen=config.maxlen)

Line 34 referred to in the error is tokenizer = text.Tokenizer(num_words=config.vocab_size)
The exact error thrown (includes Deprecation warnings) is:
C:\Users\Keegan\anaconda3\envs\oldK\lib\site-
packages\tensorflow_core\python\keras\datasets\imdb.py:129:
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-
or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If
you meant to do this, you must specify 'dtype=object' when creating the ndarray.
 x_train, y_train = np.array(xs[:idx]), np.array(labels[:idx])

C:\Users\Keegan\anaconda3\envs\oldK\lib\site-
packages\tensorflow_core\python\keras\datasets\imdb.py:130: VisibleDeprecationWarning: Creating
an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or
ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must
specify 'dtype=object' when creating the ndarray.
x_test, y_test = np.array(xs[idx:]), np.array(labels[idx:])
Traceback (most recent call last):
  File "imdb-cnn.py", line 34, in <module>
tokenizer.fit_on_texts(X_train)
  File "C:\Users\Keegan\anaconda3\envs\oldK\lib\site-packages\keras_preprocessing\text.py",
line 217, in fit_on_texts
     text = [text_elem.lower() for text_elem in text]
  File "C:\Users\Keegan\anaconda3\envs\oldK\lib\site-packages\keras_preprocessing\text.py", line 217, in <listcomp>
     text = [text_elem.lower() for text_elem in text]

AttributeError: 'int' object has no attribute 'lower'

The Anaconda venv has Python 3.7.1, Tensorflow 2.1.0 and Keras 2.3.1

A: The Keras tokenizer has an attribute lower which can be set either to True or False.
I guess the reason why the pre-packaged IMDB data is by default lower-cased is that the dataset is pretty small. If you did not lower-case it the capitalized and lower-cased words would get different embeddings, but the capitalized forms probably are not frequently enough in the training data to train the embeddings appropriately. This of course changes, once you use pre-trained embeddings or pre-trained contextualized models such as BERT which were pre-trained on large data.


text:
Q: Why doesn't my copy constructor work? This is probably a no-brainer, but I'm a little stumped. I've had some trouble with my vectors not behaving nicely, and now it looks like I've found the culprit. Here's a watered down version of my Player class.
class Player {
private:
    std::string _firstName;
    std::string _lastName;
public:
    Player(std::string firstName, std::string lastName) {
        _firstName = firstName;
        _lastName = lastName;
    };
    Player(const Player& otherPlayer) {
        _firstName = otherPlayer._firstName.c_str();
        _lastName = otherPlayer._lastName.c_str();
        std::cout << "Created " << _firstName << " " << _lastName << std::endl; // Why doesn't _firstName and _lastName contain anything?
    };
    std::string GetName() { return _firstName + " " + _lastName; };
};

int main(int argc, const char * argv[])
{

    Player player1 = Player("Bill", "Clinton");
    Player player2 = Player(player1);

    std::cout << "Player: " << player2.GetName() << std::endl;

    return 0;
}

The output is a meager Player:. I'm not sure why my copy constructor doesn't do what I want it to do, in particular in light of advice such as this (Zac Howland's comment accounts for the c_str();-part). Am I violating the rule of three (which, btw, I still haven't totally gotten my head around)? I'd be really grateful if anyone could point me in the right direction!

A: It works for me : http://ideone.com/aenViu
I just addded :
#include <iostream>
#include <string>

But there is something I don't understand :
_firstName = otherPlayer._firstName.c_str();
_lastName = otherPlayer._lastName.c_str();

Why the .c_str() ? You convert the string to char* to assign it to a new string?
EDIT : From the comment, Zac Howland pointed : "Prior to C++11, if you wanted to ensure your string was copied (instead of reference counted), you had to use the c_str() method to force it to copy the string. The new standard eliminates that, but if he's using an older compiler, or one that hasn't fully implemented C++11 yet, it will ensure a deep copy."
Just do :
_firstName = otherPlayer._firstName;
_lastName = otherPlayer._lastName;

And, do you really need this copy constructor ? The default would do what you want I think...

Also, instead of assigning the members :
Player(std::string firstName, std::string lastName) {
    _firstName = firstName;
    _lastName = lastName;
}

use the member-initialization-list instead :
Player(std::string firstName, std::string lastName) :
    _firstName( std::move(firstName) ),
    _lastName( std::move(lastName) )
{}

In the first case the string's default constructor is called and then string's copy-assignment operator, there could definitely be (minor) efficiency losses compared to the second case, which directly calls the copy-constructor.
Last thing, when it is possible, does not pass values as method arguments, pass references and even const references when they don't need to be modified :
Player( const std::string& firstName, const std::string& lastName )
//      ^^^^^            ^            ^^^^^            ^
    : _firstName( firstName )  // no move here, since args are constant references
    , _lastName( lastName )
{}

Working live example of all the modifications.


text:
Q: How to store webcam captured image path in mysql database I've tried the following code for capture a image, it stores image in specified folder but the path of image which i want to store in database doesn't work.The execution of code stops after Uploding... message.Please help me,whats going wrong with my code.

<?php
session_start();
include 'connection.php';
$name = date('YmdHis');
$newname=mysql_real_escape_string("images/".$name.".jpg");
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
 print "ERROR: Failed to write data to $filename, check permissions\n";
 exit();
}
else
{
    $sql="Insert into entry(images) values('$newname')";
    $result=mysql_query($con,$sql)
            or die("Error in query");
    $value=mysql_insert_id($con);
    $_SESSION["myvalue"]=$value;
}

$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";

?>

<?php
session_start();
if(isset ($_POST["send"]))
{
    $getname=$_POST["myname"];
    include 'connection.php';
    $idvalue=$_SESSION["myvalue"];
    $sql="update entry set name='$getname' where id='$idvalue'";
    $result=mysql_query($sql)
            or die(mysql_error());
    if($result)
    {
        echo "Uploaded $_SESSION[myvalue] re ..... ";
    }
    else
    {
        echo "$_SESSION[myvalue] nahi hua";
    }
}
?>

<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <input type="text" name="myname" id="myname">
    <input type="submit" name="send" id="send">
</form>

<form>
  <input type=button value="Configure..." onClick="webcam.configure()">

  <input type=button value="Take Snapshot" onClick="take_snapshot()">
 </form>

A: instead of giving relative path in the file_get_contents() give full path/actual path.
Hope this might help you.


text:
Q: Executing code every time a laptop is plugged into, or unplugged from power I'm looking to run some code every time my laptop is plugged into, or unplugged from power. I know this can be done; for example, GNOME hooks into this functionality (somehow) to update the battery indicator in my toolbar. The code I want to execute is a simple shell script which switches between the integrated and discrete GPU depending on whether external power is available (a wrapper around gpu-switch).
I'm specifically interested in knowing about ways to do this other than polling and parsing the output of e.g. acpi -V to determine whether the battery is charging or not.

A: Create a udev rule that runs a script when the AC adapter is plugged and unplugged:
/etc/udev/rules.d/powersave.rules
SUBSYSTEM=="power_supply", ATTR{online}=="0", RUN+="/path/to/your/script true"
SUBSYSTEM=="power_supply", ATTR{online}=="1", RUN+="/path/to/your/script false"


text:
Q: Where is most appropriate for Cloudfoundry server admin questions? This question is probably a server administration question than a development one.  Would ServerFault be more appropriate (as I have suggested to the OP), given the current lack of any kind of cloud.stackexchange.com?
If there is a more appropriate location than stackoverflow.com, Cloud Foundry should get a heads-up, as they currently push all questions to either Twitter or the main SO site.  Maybe them adding a second link to a cloudfoundry tag on ServerFault (or wherever is more appropriate) would be advisable.

A: I would post such a question on Server Fault as you already suggest. From their FAQ:

What kind of questions can I ask here?
Server Fault is for Information Technology Professionals needing expert answers related to managing computer systems in a professional capacity.
If your question is about…

*

*Server and Business Workstation operating systems, hardware, software and virtualization

*Enterprise storage, backup, and disaster recovery

*Network routing, switches, and firewalls

*Operations, maintenance, and monitoring


text:
Q: Python 3 dis.distb() assembly language code on interactive promt - Python Bytecode Disassembler I am running code on my command-line interface with python 3. However, I am confused about why dis.distb() does not give me an assembly language code for an error in print("Hello World) with missing quotes.
C:\Users\jarvis>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> print("Hello World)
  File "<stdin>", line 1
    print("Hello World)
                  ^
SyntaxError: EOL while scanning string literal
>>> dis.distb()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\jarvis\AppData\Local\Programs\Python\Python37-32\lib\dis.py", line 86, in distb
    while tb.tb_next: tb = tb.tb_next
AttributeError: 'NoneType' object has no attribute 'tb_next'

This code gives me an assembly code for the print function that misses the letter 't'
>>> prin("Hello World")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'prin' is not defined
>>> dis.distb()
  1 -->       0 LOAD_NAME                0 (prin)
              2 LOAD_CONST               0 ('Hello World')
              4 CALL_FUNCTION            1
              6 PRINT_EXPR
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE

 >>>

What is the difference in the error types above? I am trying to understand how python works in this situation.

A: The reason you are not getting a dissasembly of bytecode is simply because there is none: the Python interpreter hit a serious error before it could create any bytecode.
Here is an all-too-common analog, but it is useable hee. Suppose I want to translate:
"Whose woods these are, I think I know"
into Spanish. Basically you'd understand the words (or if someone speaks the words instead, in your head you might break up the sounds into phonemes and figure out words).
Then you'd piece together the words into a sentence, and then after that you might parse the sentence into a subject-phrase and and object phrase.) With all of this you are in a good position to make a translation. If you can't hear or don't understand one word you might be able to figure out what was meant, but that's extra work, and you might guess the wrong word or meaning.
Now, if instead I were to ask you to translate:
"fafdsasdSFEFafef094qt43qtu08rpiekjsfdrshgoirtfhejtr4qr5841u0toiqjhwekfnsajf"
There are no descernable words there that make up a reasonabe sentence and that you could parse. The best you could do is spit out the same thing which is what, for example, google translate does.
When it comes to real-world production compilers or interpreters, these programs are pretty exacting. (In the olden days there were special compilers for languages that were targeted for beginners who would make mistakes, and the compiler might try to fill in the details).
But in CPython, if one double quote is missing, as in your situation, CPython gives you a message about the invalid syntax with a pointer of where the problem is and what might be done about it. But it won't try to go further and create bytecode. It's missin unlike google translate is not about trying to figure out what you might have meant given partial information.

A: The cause maybe be is calling values or types in the Python interpreter's stack or perhaps memory management. On the other hand, it shows that dis.py cannot handle the SyntaxError exception in such cases as the one that occurred here (EOL while scanning string literal). Deep diving goes back to the sys.last_traceback, which traces the previous exception if it happened in an interactive environment to do some post mortem debugging.
One of the parameters of the method distb() is the variable tb, but the default value of this parameter is None. On the other side, when the tb is None, the method will raise an AttributeError. So, this process indicates that in the case of your problem, in the CMD or terminal, tb will be None, but not in jupyter notebook.
For example, if you do the same thing in jupyter notebook, dis.distb() works appropriately in both cases. Bot in command prompt not.
I ran both cases in jupyter notebook and I've got the following result.
print("Hello World)

# result:
  File "C:\Users\itpro\AppData\Local\Temp/ipykernel_21836/2771583741.py", line 1
    print("Hello World)
                       ^
SyntaxError: EOL while scanning string literal
# ---

dis.distb()

# result:
101           0 LOAD_GLOBAL              0 (compile)
              2 LOAD_FAST                1 (source)
              4 LOAD_FAST                2 (filename)
              6 LOAD_FAST                3 (symbol)
              8 LOAD_FAST                0 (self)
             10 LOAD_ATTR                1 (flags)
             12 LOAD_GLOBAL              2 (PyCF_ONLY_AST)
             14 BINARY_OR
             16 LOAD_CONST               1 (1)
    -->      18 CALL_FUNCTION            5
             20 RETURN_VALUE

And for the second case:
prin("Hello World")

# result:
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21836/2802362923.py in <module>
----> 1 prin("Hello World")

NameError: name 'prin' is not defined

# ---

dis.distb()

# result:

  1 -->       0 LOAD_NAME                0 (prin)
              2 LOAD_CONST               0 ('Hello World')
              4 CALL_FUNCTION            1
              6 PRINT_EXPR
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE


text:
Q: Integral of smooth function with compact support is also smooth In Ronkin's Теория аналитических функций нескольких переменных he introduces an integral
$$f(z)=-\frac1\pi\int_0^\infty\int_0^{2\pi}\varphi\left(z+t\mathrm{e}^{-i\theta}\right)\mathrm d\theta\mathrm dt$$
where $z\in\mathbb{C}$, $\varphi\in C^k(\mathbb{R}^2)$ is a complex function that is $C^k$ as a function of two real variables, and $\mathrm{supp}\,\varphi$ is compact.
He says the function $\varphi(z+t\mathrm e^{i\theta})$ treated as a function of parameter $z$ is $C^k$ (which again is to be understood as a function of two real variables).
He then says the integral, or the function $f$ is also $C^k(\mathbb{R}^2)$ because the support of $\varphi$ is compact.
I don't understand the latter statement, why is it $C^k(\mathbb{R}^2)$? Where do we need the compactness of $\mathrm{supp}\,\varphi$?

A: To verify the smoothness, you just need to ascertain that it is "ok to differentiate under the integral symbol"; i.e., that doing something like this (if we put $z = x + i y$), for example,
$$
{\partial \over \partial x} f(z) = -{1 \over \pi} \int_{t = 0}^{t = \infty} \int_{\theta = 0}^{\theta = 2\pi} \; {\partial \over \partial x} \phi \left(z + e^{-t \theta}\right) \; d\theta \; dt
$$
is legitimate.
Why do we need the compactness of support?  To make sure that the integration over the unbounded domain $0 \leq t < \infty$ converges.  Without this compactness, if we took $\phi$ to be constantly equal to $1$, the double integral would not exist.
Zorich's Математический анализ (Mathematical Analysis) may give a cleaner, more detailed and better paced explanation of differentiation under the integral.


text:
Q: Using a VPN only for a specific mail account or app On my iPhone, I know I can set up a VPN. But if I understand it correctly, it is a global setting. How can I use a VPN only when checking a specific IMAP account?
Alternatively, can it be activated on an app-by-app basis? It would be ok if every mail account used the VPN.


text:
Q: An altitude or the altitude? Here are two questions from Quora:

1) How fast does an airliner reach an altitude of 500m after it starts to take off?
2) What is the average time for an airplane to reach the altitude of 30,000 feet?

What is the correct usage? Is there any difference? Why not use "zero article"?

A: Is there something special about the altitude of 500m, that the listener/reader should already know?
For example:

This audio enconding standard doesn't allow frequencies at the 20KHz limit.

20KHz is the upper limit of human hearing, it's special and the writer/speaker expects the listener/reader to already know that.
If there isn't anything special about that altitude, then an should be used.
30,000 feet might be where the sky turns into space or something like that, or the writer/speaker may be referring to a line on a diagram.

A: 1) How fast does an airliner reach an altitude of 500m after it starts to take off?
2) What is the average time for an airplane to reach the altitude of 30,000 feet?
Both are right.
The second one uses "the" if that altitude has particular significance to the writer in the text. The second one suggests that altitude may be relevant in the text, in which case, the "the" is used to make that fact salient.

A: 1)  In this instance, the word 'fast' is incorrectly used because it is an adjective, which can only describe the plane.  What is needed instead is an adverb to modify the verb 'does', such as 'quickly' or 'soon'.  The second problem with this sentence is 'after it starts to take off?'  An airliner doesn't typically 'start to take off', it simply 'lifts-off', unless you wish to count also the time it spends accelerating down the runway.  Typically, people mean to start counting time beginning with liff-off.  This sentence might have been rewritten:

How soon does an airliner reach an altitude of 500m after it lifts-off?

2)The only problem I identify with this sentence is the misuse of the article 'the'.  'The' implies there is something special about an altitude of 30,000 feet.  So in this case, I might rewrite the sentence on one of two ways:

What is the average time for an airplane to reach the cruising altitude of 30,000 feet?

since 30,000 feet is often the cruising altitude for planes.  Or,

What is the average time for an airplane to reach an altitude of 30,000 feet?

in this case changing the definite article 'the' to the indefinite article 'an'.
The zero article typically is only used with proper nouns and prepositional phrases.
The English language has many subtleties that many native English-speakers often don't observe in its common usage, so despite these errors, most people will parse the meaning of either of these sentences without raising any objection.  What this implies is that you too may relax from strict usage of the rules in common speech, but not so much in academic writing.


text:
Q: Unattended upgrades suddenly not working? Security updates not installing I have a server running Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-147-generic x86_64).
After initial setup, I installed and enabled Unattended Upgrades.
For about 9 months Unattended Upgrades worked fine.
However, it seems that about 8 weeks ago it stopped working. On login I now see the notification "79 packages can be updated. 9 updates are security updates."
At this stage I am only concerned about the security updates.
I have tried re-installing Unattended Upgrades. I have also checked the settings which seemed to be most relevant after investigating this matter online. However, nothing seems to work.
I have also tried to upgrade manually using "sudo unattended-upgrade -d". Again, it does not work. It gives the output (here abbreviated):
Initial blacklisted packages:
Starting unattended upgrades script
Allowed origins are: ['o=Ubuntu,a=trusty-security', 'o=UbuntuESM,a=trusty']
...
pkgs that look like they should be upgraded:
Fetched 0 B in 0s (0 B/s)
fetch.run() result: 0
blacklist: []
Packages that will be upgraded:
InstCount=0 DelCount=0 BrokenCount=0

Can someone help me with this, please?


text:
Q: laravel livewire breaks styling (@push script) I applied livewire on top of an already made laravel project.
It's simply applying wire:model to select like below.
 <select wire:model="wired" id="#selector-01" >
  <option>1</option>
  <option>1</option>
 </select>

and using the wire variable(wired) in if statement in for loop.
<select id="#selector-02">
   @foreach($numbers in $number)
     @if($some_id == $wired)
        <option> some_id </option>
     @endif
   @endforeach
</select>

I use it only as a component.
all the data is controlled in the original laravel controller.
livewire component is called by @livewire('component-name')
and everything works, as I thought it would, except styling.
I think it has to do with using SlimSelect
At the end of livewire component-name.blade.php, I have SlimSelect styling just like the below.
 @push('js')
        <script>
            new SlimSelect({
                select: '#selector-01'
            })
            new SlimSelect({
                select: '#selector-02'
            })
        </script>
 @endpush

I tried moving the codes to

*

*original.blade.php with @push and @stack

*app.blade.php without @push

but still styling breaks.
I am thinking a solution might be adding few lines in  update() in live wire controller to reinject the styling script.
am I going in the right direction?
Please help.

A: adding the below code fixed the problem.
<script>
        document.addEventListener('livewire:update', function () {
            // Your JS here.
            new SlimSelect({
                select: '#selector-01'
            })
            new SlimSelect({
                select: '#selector-01'
            })
        })
</script>

you can also use livewire:onload instead of @stack and @push for loading styling onload
Reference to livewire doc


text:
Q: How to expose windows file share via HTTPS and NTLM authentication? I want to be able to expose the contents of a windows file share via HTTP, so a file can be linked to using http:// rather than file:// which doesnt work in all popular browsers.
I want to be able to authenticate the user hitting the http:// url using NTLM (their credentials from their logged-in Windows session at their computer) and then "pass through" this authentication to the server to ensure that they are allowed to access the file share.
Have tried to set up IIS + WebDAV however I get this error:
Error: {Access Denied}
A process has requested access to an object, but has not been granted those access rights.

Can what I want to do be done? Any guidance on the error I am running into?

A: Hallo the computer or network service (depending the IIS user) needs read access at filesystem. Please check the security tab of our fo9lder which you want to access.


text:
Q: IKImageView choppy? I have an IKImageView, and I'm putting CGImages (That I make out of NSImages) onto it. However, a normal 200DPI 8.5/11 page takes like 3 seconds to come up, appearing in rectangles about 2inches (screen) on a side at a time. This is really annoying. Is there a way around this?
Alternatively, is there a way to double buffer the view? To have 2 IKImageViews and draw into one, and then display it?
ETA:
doubling my scrollviews (with ikimageviews inside) and then drawing into them, and then unhiding them, doesn't seem to help... or, maybe it helps a  little, but not much
I did a little poking around with instruments, and found that a lot of work seems to be being done in memcopy:
  22 commpage [libSystem.B.dylib] 78.0  __memcpy
  21 ImageIO 37.0  CGImageReadGetBytesAtOffset
  20 ImageIO 37.0  CGImageReadSessionGetBytes
  19 ImageIO 37.0  myTIFFReadProc
  18 libTIFF.dylib 37.0  TIFFReadRawStrip1
  17 libTIFF.dylib 37.0  TIFFFillStrip
  16 libTIFF.dylib 37.0  _cg_TIFFReadEncodedStrip
  15 ImageIO 37.0  copyImageBlockSetTIFF
  14 ImageIO 37.0  ImageProviderCopyImageBlockSetCallback
  13 CoreGraphics 37.0  CGImageProviderCopyImageBlockSet
  12 CoreGraphics 37.0  img_blocks_create
  11 CoreGraphics 37.0  img_blocks_extent
  10 CoreGraphics 37.0  img_interpolate_extent
   9 CoreGraphics 37.0  img_data_lock
   8 CoreGraphics 37.0  CGSImageDataLock
   7 libRIP.A.dylib 37.0  ripc_AcquireImage
   6 libRIP.A.dylib 37.0  ripc_DrawImage
   5 CoreGraphics 37.0  CGContextDrawImage
   4 ImageKit 37.0  -[IKImageLayer drawInContext:]
   3 QuartzCore 37.0  tiled_layer_render(_CAImageProvider*, unsigned int, unsigned int, unsigned int, unsigned int, void*)
   2 QuartzCore 37.0  CAImageProviderThread(void*)
   1 libSystem.B.dylib 37.0  _pthread_wqthread
   0 libSystem.B.dylib 37.0  start_wqthread

I'm not sure what that tells me though...
EDIT: For the record, the problem is NOT data size. I have an old version of the program, that uses deprecated quickdraw method calls. When I zoom the image up to 300%, so that one screen pixel = one image pixel, so it needs to be using the whole image, it STILL zips right along page after page.
I'm being ridiculed by the guy who wrote this originally, because his version moves faster on his ancient 10.3 G5 than it does on my up-to-date Intel box. faster by at least a factor of 10.

A:
200DPI 8.5/11 page

Assuming those are in RGB color, that's 11.22 megabytes of pixels per image. Your application uses a lot of memory, and drawing 3.74 megapixels (regardless of color space) is going to be slow.

2 inches (screen) on a side

Make use of that. Figure out how many screen pixels 2 inches is, using the 72 dpi constant and the window's user-space scale factor, and rasterize your pages to that size. Currently, those rectangles will be 144 points on a side, and a 144×144 image is very efficient to have in memory and to draw.
If you have a zoom setting, you'll want to invalidate your cache of these images when it changes, and re-compute each image no earlier than when your view gets told to draw.


text:
Q: How to join two tables in mysql with matching data and group in array I need to join two tables (products and orders) in mysql with a matching data (order id) and different data (products ids) that should be in a array.
I tried with a simple JOIN but data are not being grouped. Does anyone can give me a light?
SELECT Order.id, Order.userId, Product.id AS productsIds
FROM Orders AS Order
JOIN Products AS Product
ON Order.id = Product.orderId

Result:
[
  {
    "id": 1,
    "userId": 1,
    "productsIds": 2
  },
  {
    "id": 1,
    "userId": 1,
    "productsIds": 5
  },
  {
    "id": 1,
    "userId": 1,
    "productsIds": 6
  },
  {
    "id": 3,
    "userId": 2,
    "productsIds": 4
  },
  {
    "id": 2,
    "userId": 3,
    "productsIds": 3
  }
]

Expected:
[
  {
    "id": 1,
    "userId": 1,
    "productsIds": [2, 5, 6]
  },
  {
    "id": 3,
    "userId": 2,
    "productsIds": 4
  },
  {
    "id": 2,
    "userId": 3,
    "productsIds": 3
  }
]

A: You need to use GROUP BY clause and GROUP_CONCAT in select statement, will give the expected result.
Following is the query.
SELECT Order.id, Order.userId, GROUP_CONCAT(Product.id) AS productsIds FROM Orders AS Order JOIN Products AS Product ON Order.id = Product.orderId GROUP BY Order.id, Order.userId ;


text:
Q: Tracking a change of web directory in Google Analytics We recently changed the directory structure for our website.  For example the following page was listed changed as follows:

Previous: /degrees/msm-technology/
Current: /degrees/masters/ms-management/technology/

They are the same directory with the same pages just listed differently.
I'm attempting to do a custom filter Search and Replace to update the previous page so that there is not an interruption in data when tracking the pages.  However it doesn't seem to be working.
Filter Field Request URI -

Search string ^/degrees/msm-technology/
Replace string:  /degrees/masters/ms-management/technology/

The data for the previous page listed ends this week, while the other begins.

A: You need to escape the hyphen like this
Search string: ^/degrees/msm\-technology/

because GA filters use POSIX Regex.
[source: https://support.google.com/analytics/answer/1034836?hl=en]
Hope this helps.


text:
Q: Single Row Sub query return more than one row I wrote a SQL query which updates the record, in most cases it runs fine, but from yesterday it fails to update the row.I am currently working on Spring MVC based Web application, in which I need to perform the DML operation by calling update()method.
I am using JDBC template and in my update method i wrote this query.
It fetches the 947 records for January month 2018 and I already checked all records are unique.
I am here stuck, i am not able to find the duplication of record.I thought this exception occurred because of multiple record, but I think i am wrong, there is something which i am not able to identify.
Here is the query:
    UPDATE SALARY_DETAIL_REPORT_012018 sd
SET sd.EMP_ID =
(SELECT e.emp_id from EMPLOYEE e
WHERE e.VERIFY_STATUS = 1
AND e.RELIEF_TYPE IS NULL
AND e.emp_code = to_char(sd.emp_code)
AND e.EMP_TYPE_ID!=03)
WHERE EXISTS
(SELECT e.emp_id from EMPLOYEE e
WHERE e.VERIFY_STATUS = 1
AND e.emp_code = to_char(sd.emp_code)
AND e.EMP_TYPE_ID!=03 AND e.RELIEF_TYPE IS NULL)
AND sd.EMP_ID IS NULL
AND sd.REFERENCE_ID LIKE '203-%'

and HERE is Java Code in my DAOImpl class
 public void update(String tableSuffix, String regionId, String circleId) {
        String tabName = "SALARY_DETAIL_REPORT_" + tableSuffix;
            String q = "UPDATE " + tabName + " sd"
                    + "         SET sd.EMP_ID = (SELECT e.emp_id "
                    + "                                  from EMPLOYEE e WHERE e.VERIFY_STATUS = 1 AND e.RELIEF_TYPE IS NULL "
                    + "                                  AND e.emp_code = to_char(sd.emp_code) AND e.EMP_TYPE_ID!=03) "
                    + "                                  WHERE "
                    + "         EXISTS (SELECT e.emp_id from EMPLOYEE e WHERE e.VERIFY_STATUS = 1 "
                    + "                          AND e.emp_code = to_char(sd.emp_code) AND e.EMP_TYPE_ID!=03 AND e.RELIEF_TYPE IS NULL) "
                    + "          AND sd.EMP_ID IS NULL";
            if (circleId != null && !circleId.trim().equals("")) {
                q += "      AND sd.REFERENCE_ID LIKE '" + circleId + "-%' ";
            } else {
                q += "      AND sd.REFERENCE_ID LIKE '" + regionId + "-%' ";
            }

            //   System.out.println("q " + q);
            MapSqlParameterSource param = new MapSqlParameterSource();
            getNamedParameterJdbcTemplate().update(q, param);

    }

Please suggest me the best solution

A: You need to find the rows that prevent your query from running.
Run this query:
SELECT sd.emp_code, COUNT(*) as cnt
FROM EMPLOYEE e
WHERE e.VERIFY_STATUS = 1 AND
      e.RELIEF_TYPE IS NULL  AND
      e.emp_code = to_char(sd.emp_code) AND
      e.EMP_TYPE_ID <> 03
GROUP BY sd.emp_code
HAVING COUNT(*) > 1;

This has the candidate problems.  What can you do?  The simplest thing is one of the problems:

*

*Change the SELECT to SELECT MAX(sd.emp_code)

*Change the WHERE with AND rownum = 1


text:
Q: How to solve 'Cannot retrieve length of file, path (OS Error: No such file or directory, errno = 2) ' in flutter I am building a simple music player app in which I want to fetch all songs available on the users device. I am doing this with my custom method in java
private static List<Map<String, String>> getAllSongs(Context context) {
    List<Map<String, String>> songs = new ArrayList<>();

    // Set up query to get all audio files
    String[] projection = new String[] {
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM_ID
    };
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

    // Execute query
    Cursor cursor = context.getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            sortOrder
    );

    // Extract metadata from query result
    if (cursor != null && cursor.moveToFirst()) {
        int idColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
        int titleColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int albumColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
        int durationColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
        int pathColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        int albumIdColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);

        do {
            Map<String, String> song = new HashMap<>();

            song.put("id", cursor.getString(idColumnIndex));
            song.put("title", cursor.getString(titleColumnIndex));
            song.put("artist", cursor.getString(artistColumnIndex));
            song.put("album", cursor.getString(albumColumnIndex));
            song.put("duration", cursor.getString(durationColumnIndex));
            song.put("path", cursor.getString(pathColumnIndex));

            long albumId = cursor.getLong(albumIdColumnIndex);
            Uri albumArtUri = Uri.withAppendedPath(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, Long.toString(albumId));
            song.put("albumArt", albumArtUri.toString());

            songs.add(song);
        } while (cursor.moveToNext());

        cursor.close();
    }

    return songs;
}

This is then handled in flutter by ->
class Song {
  String id;
  String title;
  String artist;
  String album;
  String path;
  String albumArt;

  Song(
      {required this.id,
      required this.title,
      required this.artist,
      required this.album,
      required this.path,
      required this.albumArt});
}

class MusicService {
  static const MethodChannel _channel = const MethodChannel('com.mybea.ah');

  static Future<List<Song>> getAllSongs() async {
    List<Song> songs = [];

    try {
      final List<dynamic> result = await _channel.invokeMethod('getAllSongs');
      if (result.isNotEmpty) {
        for (int i = 0; i < result.length; i++) {
          songs.add(Song(
            id: result[i]['id'],
            title: result[i]['title'],
            artist: result[i]['artist'],
            album: result[i]['album'],
            path: result[i]['path'],
            albumArt: result[i]['albumArt'],
          ));
        }
      }
    } on PlatformException catch (e) {
      print("Failed to get all songs: '${e.message}'.");
    }

    return songs;
  }
}

When I fetch the songs from the method all is fetched properly but when I try to display the artwork I get the following error->

════════ Exception caught by image resource service
════════════════════════════ Cannot retrieve length of file, path =
'content://media/external/audio/albums/89' (OS Error: No such file or
directory, errno = 2)
This is the code where I try to use the method ->

      Future<void> _loadSongs() async {
        if (await Permission.storage.request().isGranted) {
          List<Song> songs = await MusicService.getAllSongs();
          setState(() {
            _songs = songs;
        } else {
          return;
        }
      }
_songs.length == 0
          ? Center(
              child: Text("No Songs Found"),
            )
          : ListView.builder(
              itemCount: _songs.length,
              itemBuilder: (context, index) {
                Song song = _songs[index];
                return ListTile(
                  onTap: () {
                    debugPrint(song.path);
                  },
                  leading: CircleAvatar(
                    backgroundImage: FileImage(File(song.albumArt)),
                  ),
                  title: Text(song.title),
                  subtitle: Text(song.artist),
                  trailing: Icon(Icons.play_arrow),
                );
              },
            ),

I tried displaying the image by Image.file() and Image.network() but nothing seemed to work and gave the same error.
Please Help


text:
Q: how to select all fields in SYMFONY 3.x I select from DB only nameSurname:
$em = $this->getContainer()->get('doctrine')->getManager();
$users = $em->createQuery('SELECT u.nameSurname FROM MyBundle:User u')
            ->getResult();

var_dump($users);
exit;

But how to select all fields in SYMFONY 3.x like simple sql query?
       select * from table

UPD that not work, work but show much more and not users information i think
$users = $em->createQuery('SELECT u FROM MyBundle:User u')
            ->getResult();

A: This should return all your User Entities:
$users = $em->createQuery('SELECT u FROM MyBundle:User u')
            ->getResult();

Now $users contains all the users information.

A: Why not to do this way?
to select specific user:
$user = $this->getDoctrine()->getRepository('MyBundle:User')->find($userId);
$userName = $user->getName();
$userEmail = $user->getEmail();
etc...

to select all users:
$users = $this->getDoctrine()->getRepository('MyBundle:User')->findAll();


text:
Q: How do I increase each new line by 1 or more in a for loop? Trying to print a number triangle that does the following:
numTri(6)
1
23
456

Edit:(all new line)
What I have so far:
def numTri(n):
  a = 0
  for x in range(1,n+1):
    a = 10*a + x
    print a

Any hints? I don't want the answer. Some guidance would be well appreciated.

A: Woot this is my first post! (Edit: I posted the python code since someone else had posted the complete answer already).
The following approaches this problem from a different perspective and needs only one loop. Hope this helps.
def numTri(n):
    x = list(range(1,n+1)) #creates a list of numbers ([1],[2],...,[n])
    i = 0
    ln = 1
    while i < n+1:
        print(x[i:i+ln])   #prints a partition of the list of numbers
        i += ln
        ln += 1

NB: you may need to adjust the print function, I was using python 3.5

A: As you have said guidance.
Python code
def numTri(n):
    a=1
    col_per_row=1
    while a<=n:
        s=""
        for y in range(1,col_per_row+1):
            s+=str(a)
            a=a+1
        col_per_row=col_per_row+1
        if(a==n+1):
            print(s),
        else:
            print(s)

*

*The comma after print statement is for avoiding the newline in Python-2

*In Python-3 you can use print(s,end="")

1.How to print in python without newline or space?


text:
Q: How to create a new array from current, with changed "id" of all single item I have array
const arr = [
  { id: 31241, title: "Campfire Story" },
  { id: 31242, title: "Booting Up" },
  { id: 31243, title: "Hey Boys" },
.......
];

How can I create a new array from the current one so that id and index are the same:
  const newArr = [
      { id: 0, title: "Campfire Story" },
      { id: 1, title: "Booting Up" },
      { id: 2, title: "Hey Boys" },
    .......
    ];

A: You can use map() and replace the id with the index of the element in array.

const arr = [
  { id: 31241, title: "Campfire Story" },
  { id: 31242, title: "Booting Up" },
  { id: 31243, title: "Hey Boys" },
];
const res = arr.map((x, i) => ({...x, id: i}))
console.log(res)


text:
Q: Can I make git-svn import a Subversion repository which itself contains git repositories I have a project in SVN which has a plugins folder.  Several of the plugins folders are git repositories -- I added them to my plugins folder using git clone.
This has been working well for me but now I'm looking to migrate my SVN repository to git using git-svn:
git svn init http://path/to/my/repo --no-metadata
git config svn.authorsfile ~/authors.txt
git svn fetch

This works fine for all my early revisions which didn't have the git repos in my plugins folder, but when it hits the first revision containing a git repository it fails with the following error:
trunk/plugins/my_plugin/.git/HEAD was not found in commit
ae9ad0ab7cebd144c823d90d43cdab2b30d13f9e (r2259)

Is there a way around this to allow me to fully import my repository, perhaps by excluding any .git folders which reside in the SVN repository?

A: It turns out that I was using git-svn 1.5 on Ubuntu which didn't support the --ignore-paths flag on git-svn fetch.  After building git 1.6 from source I can now run:
git svn fetch --ignore-paths='\.git'

The fetch now ignores all .git folders and successfully imports all the SVN history to my new git repository.

A: You could dump the current svn repo, filter out the .git directories, and create another svn repo based on this filtered dump, and use this new one as a basis for the git repo.
Parallel use of git and svn would probably be interesting - you'd have to replace the existing repo with new gitless one, and the missing .git directories could cause some hassles.
I have not tried this, so you're going to want to be careful, and have backups.

A: Due to the way Git works, having more than 1 .git folder will cause you problems (well, you already know that hehe).
You have 2 options:
- if you don't care about story, do it the easy way: remove the .git folders from svn and move to git the full project

*

*if you care about story, do it the hard way: check this link and follow the steps

I know my team leader had some issues with that, but it works.
EDIT: I forgot to mention another way: you might use Bazaar to pull the project, as it interacts with both. Not sure if that would be easier though


text:
Q: Can't attach custom layout to Activity dynamically When I create Activity and set new RelativeLayout right in onCreate(), all works fine.
But I think it's more convenient to create a class MView that extends RelativeLayout and do all the settings there. And if I do this, Activity stays empty. What should I change in MView (or shall I need to use RelativeLayout without extension)?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

RelativeLayout mLayout = new RelativeLayout(this);//Change this to MView mLayout=new MView(this);
//I've been trying to move text from here...
TextView tv = new TextView(this);
tv.setText("TestText");
tv.setTextAppearance(this, android.R.attr.textAppearanceSmall);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);

tv.setLayoutParams(lp);

mLayout.addView(tv);
//... to here to MView class that extends RelativeLayout

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.MATCH_PARENT);

setContentView(mLayout, rlp);
}

So, code for MView constructor is:
public MView(Context context) {
    super(context);
    TextView tv = new TextView(context);
    tv.setText("TestText");
    tv.setTextAppearance(context, android.R.attr.textAppearanceLarge);

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT);

    tv.setLayoutParams(lp);

    this.addView(tv);
}

And onCreate becomes this:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MView mLayout = new MView(this);

    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);

    setContentView(mLayout, rlp);
}

A: *

*It is better to set layout parmas to direct view rather than when you add another layout.

*In your case, set wrong add rules for text now.

Corrected code:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        RelativeLayout mLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);

        mLayout.setLayoutParams(rlp);
        TextView tv = new TextView(this);
        tv.setText("TestText");
        tv.setTextAppearance(this, android.R.attr.textAppearanceSmall);
        RelativeLayout.LayoutParams rlt = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rlt.addRule(RelativeLayout.CENTER_IN_PARENT);
        tv.setLayoutParams(rlt);

        mLayout.addView(tv);
        setContentView(mLayout);
}

A: It was VERY simple. When I created MView, my implementation of onLayout was empty. Obviously, I had to write
super.onLayout(arg0, arg1, arg2, arg3, arg4);

And it worked fine. Thanks for helping :)


text:
Q: How can i use array of undefiend length? public static void main(String[] args) {
   int[] arr;

}

//I'm new to java and getting problem for initializing and getting inputs from user.

A: Most  likely what you want is an ArrayList
List<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(3);
int i = ints.get(0); // == 1
for (int x : ints) {
    System.out.println(x); // print out all values
}

A: You cannot to create an array of undefined length.
If you need to store a number of elements, where you don't know in advance how many elements to store. Ideally, you will need to use a List. For example,
List<Integer> intList = new ArrayList<>();


text:
Q: attach image_field to entity in drupal 7 I use drupal 7, and Entity API to develope a module.  I have an entity to record client information.  I wish to use image_field to let client upload their logo.  So I have this function:
    function silver_client_enable()
{
  field_cache_clear();
  field_associate_fields("silver_client");

  if(field_info_field('logo'))
    return;

  $field = array(
    'field_name' => 'logo',
    'cadinality' => 1,
    'type' => 'image',
    );

    field_create_field($field);

  $instance = array(
    'field_name' => 'logo',
    'entity_type' => 'silver_client',
    'bundle' => 'silver_client',
    'label' => 'Logo',
    'description' => 'Logo',
    'display' => array(
      'default' => array('label' => 'hidden')
    ),
    'settings' => array(
      'file_directory' => '/logo',
    ),
    'widget' => array(
      'type' => 'image_image',
     ),
  );

  field_create_instance($instance);
}

In the entity creation/edit form, I use :
field_attach_form('silver_client', $client, $form, $form_state);

to attch the field.
When I called up this form, the image upload field was corrected displayed.  An i can use it to uplod file to serve.
In the form submit function, I save the entity as:
entity_save('silver_client', $client);

However, after I press the save button, the entity table is correctly saved.  Field table is not.  Both field_data_logo and field_revision_logo are empty.
I believer Entity API looks after the retrieving and saving of attached fields.  Can someone tell me what is wrong with my code?  Thank you.

A: You have to write the values back into your entity:
field_attach_submit('silver_client', $client, $form, $form_state);
entity_save('silver_client', $client);

http://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_submit/7
And you should validate the field values:
field_attach_validate('silver_client', $client, $form, $form_state);

http://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_validate/7
Furthermore if you don't want to declare your entity and fields by yourself you might checkout the EntityConstructionKit : http://drupal.org/project/eck which allows to export entity structures with Features just like Views.


text:
Q: Pueden muchos Tablespaces compartir entre ellos un solo datafile? Entiendo que un Tablespace puede tener muchos datafiles pero mi duda es si entre los Tablespace pueden compartir solo un datafile. Gracias

A: No, Un datafile, solo puede pertenecer a un tablespace exclusivamente. Y un tablespace puede tener uno o varios datafiles, pero no compartirlos entre tablespaces.
Aqui puedes leer un poco acerca de la estructura de oracle.
https://docs.oracle.com/database/121/CNCPT/physical.htm#CNCPT1112


text:
Q: Convex Polygon Inscribed in a Circle Consider a convex polygon with $n$ sides inscribed in a circle. We denote $P$ its perimeter and $e^{ia_1},\ldots, e^{ia_n}$ its vertices with $0<a_1<a_2<\ldots<2\pi$.
Show that
this polygon perimeter equation
holds.
I understand how to do this for a regular polygon (drawing a line from the center of the circle to each vertex and then calculating the circumference from the side length of each triangle), but how would you do this with a convex polygon?


text:
Q: MySQL join with conditional "on" statement Say I have the below 2 tables:
text

id

text_lang

id
media_id
lang
text

(these are not the actual table structures - but I just have 2 tables with one containing all the localized strings that "belong" to the first table)
I want to join the tables, with a "preferred" language. So basically:
SELECT text.id, text_lang.text
FROM text
         LEFT JOIN text_lang ON text.id = text_lang.text_id
                             AND (only a single row, and if there's a row with lang="en", pick that,
                             otherwise just pick any language)

The part I'm having trouble with is the "only a single row, and if there's a row with lang="en" pick that, otherwise just pick any language".
I think this does what I'm looking for:
SELECT text.id, text_lang.text
FROM text
         JOIN text_lang ON text_lang.text_id = text.id AND
                           text_lang.lang = (select lang
                                             FROM text_lang sub_text_lang
                                             WHERE sub_text_lang.text_id = text.id
                                             ORDER BY text_lang.lang = "en" DESC
                                             limit 1)

... but I'd like to avoid a sub-query if possible, as I assume that would be quite a hit to the query performance.

A: I can think of a few ways but since you're trying to avoid subquery, perhaps you can do something like this:
SELECT t.id,
       SUBSTRING_INDEX(
          GROUP_CONCAT(text ORDER BY CASE WHEN lang='en' THEN 0 ELSE RAND() END),',',1)
          AS extracted_text
       FROM
       text t
       LEFT JOIN text_lang tl ON tl.text_id=t.id
 GROUP BY t.id;

Use GROUP_CONCAT() with a customized ORDER BY then use SUBTRING_INDEX() to get the first value using comma (the default GROUP_CONCAT() separator) as the delimiter.
I've made a fiddle with sample data here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0d0501f36af1ba4e181856f761dbd5f7 . You can run the fiddle a few times to see that the text value other than 'en' change.


text:
Q: Infinite sets closed under some binary operation, their subsets and question of cardinality Can it be that there exists some infinite set $S$ and some binary operation $b: S \times S \to S$ such that cardinality of subsets of $S$ which are closed under $b$ is greater than the cardinality of $S$?
Edit:  Since edit was requested, I would like to mention that I wanted $b$ to include both of the variables in its definition and that it is almost-everywhere non-constant (in other words, it is possibly constant only on finite number of pairs) so that binary operations such as $b(s_1,s_2)=s_1$ and $b(s_1,s_2)=s_*$ are not allowed.

A: Without restrictions on the binary operation, this is not difficult.
For instance, all subsets of $S$ are closed under  $$b_1:S\times S\to S$$ $$(s_1,s_2)\mapsto s_1$$
Or, if $s_*\in S$ is some element in $S$, we could consider the constant operation $$b_2:S\times S\to S$$ $$(s_1,s_2)\mapsto s_*$$
under which every subset which contains $s_*$ is closed.
If you had some restrictions on the nature of the binary operation, please edit your question accordingly.

A: You can even find abelian groups with this property.
For example, consider the free abelian group on a countably infinite set of  generators. Another name for this group is $\bigoplus_{i\in \mathbb{N}} \mathbb{Z}$, the group of all infinite integer sequences with all but finitely many terms equal to $0$, with pointwise addition.
This group is countably infinite, but it has uncountably many subgroups. For example, for any set $S\subseteq \mathbb{N}$, the set $G_S = \{(n_i)_{i\in \mathbb{N}}\mid n_i = 0 \text{ for all }i\in S\}$, consisting of all integer sequences which are $0$ at all coordinates in $S$, is a subgroup, and $G_S\neq G_T$ when $S\neq T$.


text:
Q: JavaScript: Changing Language Without Page Reload I am implementing multilingual support into my webpage. I would like to minimize the page blinking caused from page reload, and I came to the idea to change page language without forcing the whole page to reload. To achieve this, the only possible way that comes to my mind is with the use of JavaScript:

*

*I dynamically load appropriate language .js file with appropriate translations

*I manually go through every text object on the page and update it by re-sending the appropriate new text value

To provide you with example code, I paste a code that will update just submit buttons. On the language change, I call a function that loads appropriate .js language file dynamically.
var fileRef = LoadJsCssFile("Language/svk.js", "js", UpdateLanguage);

After the language .js file is fully loaded, I call the function that updates every element containing text on the webpage:
function UpdateLanguage()
{
    var buttons = document.getElementsByClassName("submit_button");
    for (buttonID in buttons)
    {
            buttons[buttonID].innerHTML = lang.SUBMIT;
    }
};

Manually updating every text object in the webpage is complex and error prone. As I am not very experienced with JavaScript yet, I was thinking, if there is a way to simply refresh the all key elements in the webpage with one JavaScript command without casing the webpage blink?
If you have any other idea, how to effectively implement language change without page blink, I am interested to know. :-)

A: I found a solution on my own:

*

*I prepare several javascript language files containing strings per every keyword

*On language selection button, I import appropriate language file for the language I wish to use

*I manually update every text on the webpage through javascript.

The above solution is suitable for smaller sites. for large ones, that would be a lot of work, to update every single text string through javascript.


text:
Q: How to implement factory pattern with dagger using annotation What I have done currently is
Created an abstract class
public interface AbstractRawPathStrategy {
    String getRouteKey();

    void processRequest();
}

Implemented the classes
public class GetDocumentImpl implements AbstractRawPathStrategy {
    @Override
    public String getRouteKey() {
        return "GET_DOCUMENT";
    }

    @Override
    public void processRequest() {
        log.info("Inside get document");
    }
}

Created a routing factory
public class RawPathStrategyFactory {
    private final Map<String, AbstractRawPathStrategy> dictionary;

    @Inject
    public RawPathStrategyFactory(final Set<AbstractRawPathStrategy> abstractRawPathStrategySet) {
        dictionary = new HashMap<>();
        for (AbstractRawPathStrategy abstractRawPathStrategy : abstractRawPathStrategySet) {
            dictionary.put(abstractRawPathStrategy.getRouteKey(), abstractRawPathStrategy);
        }
    }

    public AbstractRawPathStrategy getByRouteKey(final String rawPath) {
        return dictionary.get(rawPath);
    }
}

Instantiated the factory
@Module
public class AppModule {
    @Provides
    @Singleton
    public RawPathStrategyFactory getRouteKeyStrategyFactory() {
        Set<AbstractRawPathStrategy> abstractRouteKeyStrategies = new HashSet<>();
        abstractRouteKeyStrategies.add(new GetDocumentImpl());
        abstractRouteKeyStrategies.add(new GetUserRightsImpl());
        return new RawPathStrategyFactory(abstractRouteKeyStrategies);
    }

What I want is to go to respective class based on the route key (String). How can this be done without instantiating each class with new in AppModule. Any cleaner way to do this?

A: Try to use multibindings when create RawPathStrategyFactory
https://dagger.dev/dev-guide/multibindings.html

A: The easy, boring, way would be to use some static identifier which you'll have to set for each distinct subtype of your abstract class, and subsequent subtype thereof.
The more complicated, albeit fun, way to do this would be to use reflection.


text:
Q: What's the difference between unset () and unlink ()? I watch tutorial but i can't understand directly the discussion
can anyone help me?

A: In PHP unlink() is a function for file system handling, unlink() is used to delete files. Suppose you have uploaded a file and wants to delete this file through the coding then unlink() function is used to delete the file.
unset() is a function for variable management. It will make a variable undefined. Or we can say that unset() is used to null out the value of a given variable. OR Unset () is used to destroy a variable in PHP. In can be used to remove a single variable, multiple variables, or an element from an array.


text:
Q: Active directory user alias Do you know if exists something like "alias" for domain users? On my domain I have a short username (ex. n.surname) and i would like users could login with extended name (es. name.surname) to the same profile. Is it possibile?
Thanks

A: There is no such concept as an "alias", but you could use the UPN (User Principal Name) as login. The UPN is structured like an E-Mail address (name.surname@domain.com) and you can set/change it on the same tab as you can change the login name. Maybe that helps.


text:
Q: Duration of a LDR instruction on STM32H7 depending on memory I'm doing some evaluations on STM32H7, on the STM32H753I-EVAL2 board. I used STMicro example code to configure, write and read the QSPI Flash in memory mapped mode.
I was surprised by some figures regarding duration of LDR instruction:

*

*I measure the number of cycles of instructions using the SysTick (connected on CPU clock). As far as I understood: one cycle of SysTick = one cycle of CPU.

*I measured two instructions exactly identical ldrb.w Rn, [Rp, Rq] except that Rp is in one case an address in DTC-RAM and in the other case an address
in QSPI Flash.
The results are (code executed from internal flash): 15 cycles from DCTM-RAM, 12 cycles from QSPI.
I'm surprised by the results, I guess the QSPI content if cached so it might explain the figures ?
Also I find that 15 cycles for a single LDR instruction seems quite a lot, what do you think ? Is there something wrong in my procedure ?

A: If the internal flash is not cached, or the cache is invalid, or the pipeline was flushed or ... (many many other)s it may take more time than the QSPI Flash located instruction.
To measure execution time you have special registers.


text:
Q: C# Entity Framework Property is (Sometimes) Null So I am having a very weird issue when using EF where sometimes property of a class is null and sometimes it is not. In this case ParentType is often null, when it should have a value
With the following code is DOES have a value:
        using (Context context = new Context())
        {
            checkedListBox_SubTypes.DataSource = context.Types.Where(x => x.ParentType != null && x.ParentType.TypeID == _selectedType.TypeID).ToList();
        }

However with this line of code, where i try to get the same object back out of a listbox, it ParentType becomes null
Below are my classes and DB diagram for how things are set up:
public class Type
{
    #region Fields
    #endregion Fields

    #region Constructor
    public Type()
    {

    }
    #endregion Constructor

    #region Properties
    public int? TypeID { get; set; }

    [DisplayName("Type")]
    public string TypeName { get; set; }

    public Type ParentType { get; set; }

    /// <summary>
    /// List of Types this Type is associated with (Parent / Sub)
    /// </summary>
    public virtual ICollection<Type> Types { get; set; }

    public virtual ICollection<Object> Objects { get; set; }
    #endregion Properties

Context:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        //Set Many-To-Many relationship Mapping between Object & Type
        modelBuilder.Entity<ObjectType>()
            .HasMany(x => x.Objects)
            .WithMany(x => x.Types)
            .Map(m => m.ToTable("ObjectType")
            .MapLeftKey("TypeID")
            .MapRightKey("ObjectNumber"));

        //Set One-To-Many relationship Mapping between Type &(Parent)Type
        modelBuilder.Entity<Type>()
            .HasMany(x => x.Types)
            .WithOptional(x => x.ParentType)
            .Map(m => m.ToTable("Type")
            .MapKey("ParentTypeID"));

}

A: I'm pretty sure that in your first code fragment ParentMatterType is null too. Let's change it a little bit:
using (LitTrackContext context = new LitTrackContext())
{
    var types = context.MatterTypes
                       .Where(x => x.ParentMatterType != null
                                && x.ParentMatterType.MatterTypeID == _selectedMatterType.MatterTypeID)
                       .ToList();
    checkedListBox_MatterSubTypes.DataSource = types;
}

If you inspect types in the debugger you'll see that there are no ParentMatterTypes in there. That's because the property isn't virtual, so it isn't loaded lazily (which would happen if you inspect it in the debugger).
Even if you make the property virtual you won't be able to see its content later, because the context is disposed immediately (which is good, by the way). If you would try to access ParentMatterType afterwards, EF would throw an exception.
You should instead Include the property in your query, by changing the first part:
var types = context.MatterTypes.Include(m => m.ParentMatterType)
...

A: I have the same issue retrieving datasources once it has been bounded onto a control, in my case DataGrids. I have never figured out why this is or investigated further. To work around this problem, what I would normally do is keep a reference of the object in a Session or ViewState, or a class level variable just before I assign it to the control. So later on, I would still have a reference to the object If I need so.


text:
Q: Can I use glm algorithms to do a multinomial logistic regression? I am using spotfire (S++) for statistical analysis in my project and I have to run multinomial logistic regression for a large data set. I know best algorithm would have been mlogit, but unfortunately that is not available in s++. However, I have an option of using glm algorithm for this regression. I want to clarify two things here:
1.Is my understanding correct that glm also can be used to run Multinomial Logistic Regression?

*

*If answer to previous question is yes, then what parameters should be used in glm algo?

Thanks,

A: Yes you can, and in fact this is precisely what the R package GLMNET does for multinomial logistic regression.  Writing the log-likelihood function as:
$$LogL=\sum_i\sum_cn_{ic}\log(p_{ic})$$
Where $i$ denotes observations and $c$ denotes the multinomial categories $n_{ic}$ is the observed count for observation $i$ in category $c$.  The observations are defined by their unique covariate combinations - or alternatively we can allow duplicates and set each $n_{ic}=1$ so that we have categorical "binary" data (....don't know what the plural of binary is....).  For logistic regression the probabilities are defined as:
$$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\sum_{c'}\exp\left(x_{i}^T\beta_{c'}\right)}$$
This is a less than full rank parameterisation and can be useful if you are using penalised likelihood (such as GLMNET).  We could in principle use IRLS/newton rhapson on the full beta matrix $(\beta_1,\dots,\beta_{C})$, however you end up with non-diagonal weight matrices.  Alternatively we can optimise "Gibbs-style" by fixing all categories betas except for one, and then optimising just over that category.  Then proceed to the next category, and so on.  You can see that because the probabilities have the form
$$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{  where  }\frac{\partial A}{\partial \beta_c}=0$$
$$p_{ic'}=\frac{B}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{  where  }\frac{\partial B}{\partial \beta_c}=0$$
That the quadratic expansion about $\beta_c$ will have the same form as for logistic regression, but with the IRLS weights calculated differently - although we still have $W_{ii,c}=n_{ic}p_{ic}(1-p_{ic})$ in the usual $(X^TWX)^{-1}X^TWY$ update of beta.

A: Yes, with a Poisson GLM (log linear model) you can fit multinomial models. Hence multinomial logistic or log linear Poisson models are equivalent.
You need to see random counts $y_{ij}$ as Poisson random variables with means $μ_{ij}$ and specify the following the following log-linear model
$\log(μ_{ij}) = o + p_i + c_j + x_iβ_j$
To get a multinomial logit model the parameters are:
A parameter $p_i$ for each multinomial observation, for example individuals or group. This assures exact reproduction of the multinomial denominators and actually establishes the equivalence of Poisson and multinomial model. They are fixed in the multinomial likelihood, but random in the Poisson likelihood.
A parameter $c_j$ for each response category. This way the counts can be different for each response category and the margins can be non-uniform.
What you are really interested in are the interaction terms $x_iβ_j$ that represent the effects of $x_i$ on the log-odds of response $j$.
The log-odds can be simply calculated by $\log(μ_{ij}/μ_{ik}) = (c_j-c_k) +x_i(β_j-β_k)$. It is the log odds that observation i will fall in response category j relative to the response category $k$.
Then, the parameters in the multinomial logit model (denoted in latin letters) can be obtained as differences between the parameters in the corresponding log-linear model, i.e. $a_j = α_j-α_k$ and $b_j = β_j-β_k$.


text:
Q: Remove white space from isql output Is there any way to stop isql from adding spacing before and after the returned fields? I just want the values from the table row separated by ,. At the moment, using -b and -s ',', I get:
,some_column_entry         ,          3213,            another_column_entry,

however, I want:
,some_column_entry,3212,another_column_entry,

I read through all the switches, but couldn't seem to find anything appropriate. My wish is to get isql to output in this form rather than parsing the output.
EDIT:
select top 1 rtrim(ltrim(some_column)) from table

returns
,abc             ,

isql seems to output based on the size of max characters, because if I run the following:
select top 1 rtrim(ltrim(convert(varchar(3), some_column)) from table

I get:
,abc,

A: Try this
    Use RTRIM(LTRIM(ColumnName)) in your -q Query Select command.

A: The contrast between
some_column_entry         ,

and
,            another_column_entry,

leads me to think that the spaces are part of your field entries, as opposed to the delimiters used.
From man isql:

-dx    Delimit columns with x.
-x0xXX Delimit columns with XX, where XX is in hex.  For example -x0x09 will use a tab.

If that doesn't work, then you can pipe the output of isql through a simple sed use case:
isql ... | sed -e 's/\ //g'


text:
Q: Javascript: array ask the current day from the week I am brand new with javascript and I am struggling a lot. I am doing school work to learn javascript. My first end task is how to ask current day of the week. I will explain.
Request the day of the week via JavaScript. So the computer date, not through a prompt.
Create an array: dayNames. This already contains the names of the days.
Write the name of the day in the document via JS.
If it is a weekday, also write:
It's a workday, so get to work.
If it is a weekend day, write:
It's the weekend, break.
So the result is eg.
Today is "Thursday".
It's a workday, so get to work.

        let daynames =  ["maandag", "dinsdag", "woensdag", "donderdag","vrijdag", "zaterdag", "zondag"];

        if(daynames == daynames.getDay()){
            print ("It's a workday")
        }

        else(daynames == daynames.getDay()) {
            print("It's weekendday")
        }

        document.write(`<p>Today is ${daynames}</p>`);

the only thing I am strunggling with is ask the current day throu an array that has the weekdays and weekend. I know it's probally with an IF and ELSE but I got no idea how.

A: To get the current day, you should use
Date.prototype.getDay()

This method will return An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
Because the method returns 0 for Sunday, it is easier to put Sunday as the first item in the array.
let daynames =  ["zondag", "maandag", "dinsdag", "woensdag", "donderdag","vrijdag", "zaterdag"];

const today = new Date().getDay()

//prepare the string to output
let output = ""

// if today is 0 meaning Sunday or 6 meaning Saturday, it is the weekend
//else it is a weekday
if(today === 0 || today === 6){
  output = `Today is ${daynames[today]}, it is the weekend.`
}
else{
  output = `Today is ${daynames[today]}, it is a weekday.`
}

document.write(output)


text:
Q: Artist data only save to database but not logged in magento I am new in magento. We have artist concept in my site.
I want that when an artist register, data will save to database  but it will not be logged in.
By default data is saved to database and it will go to dashboard page but i want when an artist will do register then data will save to database but it will not login and redirect to same page.
I tried a lot but unable to stop the login concept only redirecting to same page but login functionalitily is still working using this condition
AccountController.php
if($data['artists']=='art'){
     $successUrl = $this->_getUrl('artistregister/index/index', array('_secure' => true));
 }
else{
     $successUrl = $this->_getUrl('*/*/index', array('_secure' => true));
}

protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
    {
        $session = $this->_getSession();
        if ($customer->isConfirmationRequired()) {
            /** @var $app Mage_Core_Model_App */
            $app = $this->_getApp();
            /** @var $store  Mage_Core_Model_Store*/
            $store = $app->getStore();
            $customer->sendNewAccountEmail(
                'confirmation',
                $session->getBeforeAuthUrl(),
                $store->getId()
            );
            $customerHelper = $this->_getHelper('customer');
            $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.',
                $customerHelper->getEmailConfirmationUrl($customer->getEmail())));
            $url = $this->_getUrl('*/*/index', array('_secure' => true));
        } else {
            $session->setCustomerAsLoggedIn($customer);
            $url = $this->_welcomeCustomer($customer);
        }
        $this->_redirectSuccess($url);
        return $this;
    }

if anyone knows this, please help me out.
Thanks

A: You will need to put condition in function _successProcessRegistration
In this function customer is logged in session by function
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);

You can put condition for your artist here and change the URL as per your requirement.