text:
Q: The given key was not present in the dictionary. Which key? Is there a way to get the value of the given key in the following exception in C# in a way that affects all generic classes? I think this is a big miss in the exception description from Microsoft.
"The given key was not present in the dictionary."

A better way would be:
"The given key '" + key.ToString() + "' was not present in the dictionary."

Solutions might involve mixins or derived classes maybe.

A: This exception is thrown when you try to index to something that isn't there, for example:
Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];

Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):
if (test.ContainsKey(myKey))
   return test[myKey];
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Or more efficient (thanks to @ScottChamberlain)
T retValue;
if (test.TryGetValue(myKey, out retValue))
    return retValue;
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!

A: If anyone still cares in 2021 and can afford to move to .NET Core, .Net 5 finally tells us the name of the offending key:
class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new()
        {
            ["foo"] = new object()
        };
        Console.WriteLine(dictionary["bar"]);
    }
}

Will give you:
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'bar' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at KnfTest.Program.Main(String[] args)

The same code in .Net Framework 4.8 gives the old dreaded message.
As for those who can't afford moving to Core yet I'm afraid there is no real working solution. Replacing all indexer invocations with TryGetValue is cumbersome -not to say absurd. Subclassing from Dictionary is practically impossible. Yes you can declare a new indexer but then polymorphism goes out the window as your indexer will be called only when using a reference of the subclass. Finally, creating your own Dictionary wrapper might be a solution but that's again a non trivial process, especially if you want to replicate exactly the Dictionary which implements not only IDictionary<TKey,TValue> but also:
System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>
System.Collections.IDictionary
System.Runtime.Serialization.IDeserializationCallback
System.Runtime.Serialization.ISerializable

Quite an overkill "just" for an exception message.

A: string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.

A: In the general case, the answer is No.
However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.
In Visual Studio, this option is located here:
Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic
There, you can check the Thrown box.

For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

A: If you want to manage key misses you should use TryGetValue
https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

A: You can try this code
Dictionary<string,string> AllFields = new Dictionary<string,string>();
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

If the key is not present, it simply returns a null value.

A: Borrowed from @BradleyDotNET's anwser, here's the extension method version:
public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
    if (dictionary.TryGetValue(key, out TValue result))
    {
        return result;
    }
    else
    {
        throw new KeyNotFoundException($"The given key '{key}' was not present in the dictionary.");
    }
}

A: In C# 7.0 or greater, you can Use the out parameter modifer to solve your problem in one line, and only make one call to the indexer. It works in c# 7.0 or greater.
public TItem GetOrException<TKey,TItem>(TKey key) where TKey : IFormattable =>
    dictionary.TryGetValue(key, out var item) ? item : throw new KeyNotFoundException( "Key: " + key.ToString() );

You can also opt for the longer try catch block which gives better exception information:
public TItem GetOrException<TKey,TItem>(TKey key) where TKey : IFormattable {
    try{ return dictionary[key]; }
    catch (KeyNotFoundException e) { throw new KeyNotFoundException("Key:" + key.ToString(), e);}
}


text:
Q: Speed up json conversion with pypy3 Is there a way to speed up converting streams of strings to json/dictionary using pypy3?  I know ujson in python3 could be faster than python3's json, but its not really faster than pypy3's json.loads().
More info on what I have, I have a program reading stream of json strings from a subprocess and converting (loading) them using json.loads().  If I comment out the json load execution line (basically just reading the stdout from the subprocess, it just takes about 60% of the total execution.
So I was thinking using a pool of processes or threads could improve it (maybe at least up to 80% execution time), and perform the conversion in parallel.  Unfortunately, it did not do anything.  Using multithreads had the same results, and the multiprocess took longer than 1 single process (probably mostly due to the overhead and serialization).  Is there any other change I could improve performance with pypy3?
For reference, here's a quick example of code (just reading from some file instead):
import json
import timeit
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool

def get_stdout():
    with open("input.txt", "r") as f:
        for line in f:
            yield line

def convert(line):
    d = json.loads(line)
    return d

def multi_thread():
    mt_pool = ThreadPool(3)
    for dict in mt_pool.imap(convert, get_stdout()):
        pass

def multi_process():
    with Pool(3) as mp_pool:
        for dict in mp_pool.imap(convert, get_stdout()):
            pass

def regular():
    for line in get_stdout():
        d = convert(line)

print("regular: ", timeit.repeat("regular()", setup="from __main__ import regular", number=1, repeat=5))
print("multi_thread: ", timeit.repeat("multi_thread()", setup="from __main__ import multi_thread", number=1, repeat=5))
print("multi_process: ", timeit.repeat("multi_process()", setup="from __main__ import multi_process", number=1, repeat=5))

Output:
regular: [5.191860154001915, 5.045155504994909, 4.980729935996351, 5.253822096994554, 5.9532385260026786]
multi_thread: [5.08890142099699, 5.088432839998859, 5.156651658995543, 5.781010364997201, 5.082046301999071]
multi_process: [26.595598744999734, 30.841693959999247, 29.383782051001617, 27.83700947300531, 21.377069750000373]

A: The problem with the current code is that the cost of sending Python object back from imap processes is very expensive due to inter-process communication. Sending the input strings to worker processes may also decrease the performance too. The current code should not be bounded by the input parsing but by the creation CPython objects and the transfer of the objects between processes. The threading version is not useful since the code is likely not IO bound and the Python Global Interpreter Lock (ie. GIL) prevent any performance improvement with multiple threads currently. The multiprocessing version can be made much faster by not sending results back : you need to process the json documents in the worker processes and send back the minimal amount of information to the main process. You can use a shared memory area to retrieved basic Numpy arrays efficiently from the workers to the main process if needed. Finally, using Simdjson can be much faster as long as you do not need to decode all the document.
PyPy had a scalable transactional memory mechanism probably useful to implement a faster multithreaded json parsing implementation. However, AFAIK no module is currently using it and pypy-stm is not developed.
If you really want to process (big/many) Json documents to a bunch of heterogeneous objects and you need to compute all of them quickly (without using multiple independent processes), then Python is probably not the right tool.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in Google Earth Engine: 'Error generating chart: No features contain non-null values of "system:time_start"' I try to apply an expression to the satellite image and then try to chart the mean of the series of images but I'm getting this error:

"Error generating chart: No features contain non-null values of
  "system:time_start"

Link to the code:
https://code.earthengine.google.com/c977a6ea5b61ec830b15835036e64c97
Code:
var app = function (image)
{
var conv = image.expression(
    'band/(4.4615*10**-4)',  //formula for coverting mol/m2 to DU(Dobson)
    {
        band: image.select('SO2_column_number_density'),
  });

return  conv;
};

// Load the sentinel data
var sentinel = ee.ImageCollection('COPERNICUS/S5P/NRTI/L3_SO2')
.filterDate('2019-04-01', '2019-04-21')
.map(app)

//Identify country
var region = ee.FeatureCollection("ft:1p_3AqEj1T9fG0BNu6pGqmP6_HdDOalruzpk54Ne8");
Map.addLayer(region);

Map.addLayer(sentinel)

var TS5 = Chart.image.series(sentinel, region, ee.Reducer.mean(),1000, 'system:time_start').setOptions({
          title: 'pollutants Full Time Series',
          vAxis: {title: 'mol/m2'},
});
print(TS5);

A: using an image expression, the image will losse it's original properties. Copy the properties of the source (image) to the new image (conv):
var app = function (image)
{
var conv = image.expression(
    'band/(4.4615*10**-4)',  //formula for coverting mol/m2 to DU(Dobson)
    {
        band: image.select('SO2_column_number_density'),
  });

return  ee.Image(conv.copyProperties(image)).set('system:time_start', image.get('system:time_start'));
};

A: This has helped me too. I was unable to plot my time series of NDVI due to the same error.
I narrowed it down to the part of my code where there is a mathematical calculation
 return image.updateMask(mask).divide(10000)

}
I fixed it by changing it to
  return image.updateMask(mask).divide(10000).copyProperties(image).set('system:time_start', image.get('system:time_start'));

}
Works perfectly now.

A: I just tried the same thing and had to copy Sentinel's system:index into system:time_start to make it work.
.copyProperties(image).set({'system:time_start', image.get('system:index')});


text:
Q: When is it appropriate to use linear regression vs. Naive Bayes? Based on my readings, it appears as though linear regression lends itself to cases where both X and Y are numerical and you have a large sample size, whereas Bayes is better for categorical variables with a small sample size.
Is there a criteria for scenario type?
My scenario in this case is measuring my own tiredness level everyday, and seeing if that correlates with whether I had breakfast that day, or the noisiness level at night.
I plan to have a new intervention every week and A/B test to see if there's a high correlation or not (eg only breakfast every other day).
I was trying to use Bayesian statistics to analyze my data, eg P(tired | breakfast), but the calculations became trickier when I had continuous variables like P(time it takes to fall asleep | noise level).
What is the best method for evaluating correlation between different variables and my tiredness levels if I am making interventions?


text:
Q: How build combinations with maximum sum, that contains only from one digit per row and their total prices must be less then 15 How build combinations with maximum sum along the column, that contains only from one digit per row and their total prices must be less then 15
I need to find maximum sum along the column, each column has a price. Maximum allowable price 15$, but the price can be repeated, example [4, 4, 3, 2, 2]. Each row has 1 field with null.
The result should be an array of 5 values with maximum sum.
example
I tried doing like this:

    //const g1 = [89, 85, 76, 65, 60];
    //const g2 = [85, 83, 72, 63, 35];
    //const f1 = [84, 78, 64, 56, 46];
    //const f2 = [83, 76, 62, 55, 45];
    //const y1 = [85, 79, 61, 50, 43];
    // 60 + 72 + 78 + 55 + 85 = 337
    console.log(76 + 85 + 56 + 76 + 43)
    const g1 = [89, 85, null, 65, 60];
    const g2 = [null, 83, 72, 63, 35];
    const f1 = [84, 78, 64, null, 46];
    const f2 = [83, null, 62, 50, 45];
    const y1 = [85, 79, 61, 50, null];

    const getAllIndexes = (arr, val) => {
        let indexes = [], i = -1;
        while ((i = arr.indexOf(val, i+1)) != -1){
            indexes.push(i);
        }
        return indexes;
    }

    const arrayAllMaxIndexes = (array) => {
        return getAllIndexes(array, Math.max.apply(null, array));
    }

    const arrayAllMinIndexes = (array) => {
        return getAllIndexes(array, Math.min.apply(null, array));
    }

    const choosedIndexes = [];
    for (let i = 0; i < 5; i++) {
      const row = [g1[i], g2[i], f1[i], f2[i], y1[i]].map((item, index) => {
        if (choosedIndexes.includes(index)){
          return 0;
        } else {
          return item;
        }
      });

      const maxIndexes = arrayAllMaxIndexes(row);
      console.log(maxIndexes)
      let maxIndex = null;;
      if (maxIndexes.length > 1) {
        const nextValues = [];
        maxIndexes.forEach((index) => {
            switch(index) {
              case 0:
                nextValues.push(g1[i + 1] ? g1[i + 1] : g1[i - 1]);
                break;
              case 1:
                nextValues.push(g2[i + 1] ? g2[i + 1] : g2[i - 1]);
                break;
              case 2:
                nextValues.push(f1[i + 1] ? f1[i + 1] : f1[i - 1]);
                break;
              case 3:
                nextValues.push(f2[i + 1] ? f2[i + 1] : f2[i - 1]);
                break;
              case 4:
                nextValues.push(y1[i + 1] ? y1[i + 1] : y1[i - 1]);
                break;
            }
        });
        const newMinIndexes = arrayAllMinIndexes(nextValues);
        maxIndex = maxIndexes[newMinIndexes[0]]
      } else {
        maxIndex = maxIndexes[0]
      }
      choosedIndexes.push(maxIndex);
    }

    const players = [];
    choosedIndexes.forEach((choosed, index) => {
      switch(choosed) {
          case 0:
            players.push(g1[index])
            break;
          case 1:
            players.push(g2[index])
            break;
           case 2:
            players.push(f1[index])
            break;
            case 3:
            players.push(f2[index])
            break;
           case 4:
            players.push(y1[index])
            break;
      }
    })

    console.log(players);

    console.log(players.reduce((prev, next) => {
      return prev + next
    }, 0));


text:
Q: vertical alignment in texstudio I am making a table with texstudio, and I have trouble with vertical alignment of the texts. When I have \hline, the text crosses the line.
Here is the code:
\documentclass{article}
\usepackage{siunitx}
\begin{document}
\begin{tabular}{lcccc}
\hline\hline
 & \textbf{$d_{(O_{1}-Zn/Mg)}(\SI{}{\angstrom})$}
 & \textbf{$d_{(O_{2}-Zn/Mg)}(\SI{}{\angstrom})$}
 & \textbf{$d_{(O_{3}-Zn/Mg)}(\SI{}{\angstrom})$}
 & \textbf{$d_{(O_{\bot}-Zn/Mg)}(\SI{}{\angstrom})$} \\[1mm]
\hline
\textbf{Pure HB-NWs} &  &  &  &   \\
\hline\hline
\end{tabular}
\end{document}

And I have also enclosed the undesired result to make my point clear.

A: I would suggest using the booktabs package which addresses rules and lines in tables quite well. See its documentation for some notes on table formatting and how to used it. In short, adding
\usepackage{booktabs}

to your preamble will let you use a number of new commands for rules in tables:
\toprule
\midrule
\bottomrule

combining these with your example gives a table looking as follows:

or, if you insist on using double rules at top and bottom:

In both cases I don't see the need for your additional '[1em]' space below the top line - without it things would look like this:
,

This will generate a pdf with all three examples to allow easy comparison:
\documentclass{article}
\usepackage{siunitx}
\usepackage{booktabs}
\begin{document}

Using \emph{booktabs} style rules:\\\vskip\baselineskip
\begin{tabular}{lcccc}
  \toprule
    & \textbf{$d_{(O_{1}-Zn/Mg)}(\SI{}{\angstrom})$}
    & \textbf{$d_{(O_{2}-Zn/Mg)}(\SI{}{\angstrom})$}  \\[1mm]
  \midrule
    \textbf{Pure HB-NWs} &  &  &  &   \\
  \bottomrule
\end{tabular}
\vskip\baselineskip
also works without the additional `[1mm]' spacing at the bottom of the line:
\vskip\baselineskip
\begin{tabular}{lcccc}
  \toprule
    & \textbf{$d_{(O_{1}-Zn/Mg)}(\SI{}{\angstrom})$}
    & \textbf{$d_{(O_{2}-Zn/Mg)}(\SI{}{\angstrom})$} \\
  \midrule
    \textbf{Pure HB-NWs} &  &  &  &   \\
  \bottomrule
\end{tabular}
\vskip\baselineskip
\vskip\baselineskip

Using \emph{double rules}:
\vskip\baselineskip
\begin{tabular}{lcccc}
  \midrule\midrule
    & \textbf{$d_{(O_{1}-Zn/Mg)}(\SI{}{\angstrom})$}
    & \textbf{$d_{(O_{2}-Zn/Mg)}(\SI{}{\angstrom})$} \\[1mm]
  \midrule
    \textbf{Pure HB-NWs} &  &  &  &   \\
  \midrule\midrule
\end{tabular}
\vskip\baselineskip
and again without the additional `[1mm]' spacing at the bottom of the line:
\vskip\baselineskip
\begin{tabular}{lcccc}
  \midrule\midrule
    & \textbf{$d_{(O_{1}-Zn/Mg)}(\SI{}{\angstrom})$}
    & \textbf{$d_{(O_{2}-Zn/Mg)}(\SI{}{\angstrom})$} \\
  \midrule
    \textbf{Pure HB-NWs} &  &  &  &   \\
  \midrule\midrule
\end{tabular}
\end{document}

On a side note: the 'siunitx' package you're using provides a '\si' command specifically for printing only units, rather than using the '\SI' command with an empty argument; i.e. you might want to use the following:
\si{\angstrom}

rather than:
\SI{}{\angstrom}


text:
Q: Почему в цикле while не работает оператор and? мучаю проект Эйлера. Данный код должен выдать число, которое одновременно делиться и на 3, и на 5 без остатка. Однако выдает лишь первое число, которое отвечает одному из условий, в данном случае число - 3. Вопрос, почему не работает оператор and? Пересмотрел все статьи, которые находил, но ответа не нашёл. (Задача №5 ПЭ)
y = 1
x = 1
while y == 1:
    if (x % 3 != 0) and (x % 5 != 0):
        x = x + 1
    else:
        print(x) y = 0

A: Оператор and работает, подставьте 3 в условие: (x % 3 != 0)
Будет False, следовательно всё выражение False и исполняется ветка else, то есть печатается 3
Насколько я понял, Вам нужно найти НОК. Вот исправление для Вашего кода:
x = 1
while True:
    if (x % 3 == 0) and (x % 5 == 0):
        print(x)
        break
    else:
        x += 1

Оптимизированный алгоритм поиска НОК:
a = 3
b = 5

m = a * b
while a != 0 and b != 0:
    if a > b:
        a %= b
    else:
        b %= a
x = m // (a + b)

print(x)


text:
Q: Perhaps vs probably To express stronger uncertainty what word is correct, Perhaps or probably?

Perhaps I was wrong
Probably you were right

A: With the example you give, they express equal uncertainty. How you say it changes the meaning a lot.

PERhaps I was wrong = I was not wrong
Perhaps I WAS wrong = I might have been wrong
Probably you were riGHT? = You might have been right
Probably you WERE right = You were right

In general, however, perhaps is more uncertain than probably.
(I'd say perhaps is 50% certain and probably is 90% certain, but others might disagree.)


text:
Q: Packet Loss in Darwin Streaming Server I am using Darwin Streaming Server (DSS) to generate rtp streams.
The DSS interface configured on the server, however shows some Packet Loss which, to a certain extent, is also visible on the client side while playing the video stream.
I would like to know whether this loss signifies the packets lost while traveling over the network. More so, what could be the reasons for packet loss in my Live stream ?

A: For calculating packet loss RTCP is used in form of SR and RR. It works on sequence number field present on each RTP packet.
Yes loss signifies the packet lost over the network.
There can be many reasons for packet loss: due to bandwidth, connectivity, distance between client and server, network congestion... or client application itself.
alam

A: When UDP (RTP/AVP) transport is used, the packet loss is inevitable due to the nature of UDP.
However, DSS also supports TCP transport and Reliable UDP transport, which could solve the packet loss problem, in the circumstances that the bandwidth from server to client is enough.


text:
Q: Algorithm for allowing concurrent walk of a graph In a directed acyclic graph describing a set of tasks to process, i need to find all tasks that can be processed concurrently. The graph has no loops and is quite small (~1000 nodes, ~2000 edges), performance is not a primary concern.
Examples with desired result:

*

*[] is a group. All tasks in a group must be processed before continuing

*[x & y] means x and y can be processed concurrently (x and y in parallel)

*x -> y means x and y must be processed sequentially (x before y)

1

a -> [b & c] -> c

2

[a & e] -> b -> c -> [d & f]

3

[ [a -> b] & [e -> f] ] -> [ [c -> d] & g ]

I do not want to actually execute the graph, but rather build a data structure that is as parallel as possible, while maintaining the order. The nomenclature and names of algorithms is not that familiar to me, so i'm having a hard time trying to find similar problems/solutions online.

A: Mathematically, I would frame this problem as finding a minimally defined series-parallel partial order extending the given partial order.
I would start by transitively reducing the graph and repeatedly applying two heuristics.

*

*If x has one dependent y, and y has one dependency x, merge them into a new node z = [x → y].

*If x and y have the same dependencies and dependents, merge them into a new node z = [x & y].

Now, if the input is already series-parallel, the result will be one node. In general, however, this will leave a graph that embeds an N-shaped structure like b → c, b → g, f → g from the last example in the question. This structure must be addressed by adding one or more of b → f, c → f, c → g, f → b, f → c, g → c. But in a different instance, this act would in turn create new N-shaped structures. There's no obvious notion of a closure, which is why this problem feels hard to me.
Some of these choices seem worse than others. For example, c → f forces the sequence b → c → f → g, whereas f → c is the only choice that doesn't increase the length of the critical path.
I guess what I'd try is,

*If heuristics 1 and 2 have no targets, form a graph with edges x--y if and only if x and y have either a common dependent or a common dependency, compute the connected components of this graph, and &-merge the smallest component that isn't a singleton, followed by another transitive reduction.

A: Here's a solution i came up with (pseudocode):
sequence = []
for each (node, depth) in depthFirstSearch(graph)
  sequence[depth].push(node)
return sequence

The sequence defines the order to process the graph. If an item in it contains more than one node, they can be processed concurrently.
While this allows for some concurrency, it does not advance as fast as it could. For example, f in the 3rd example in the question would require a to be completed first (as it will be at depth 1, when a and e are depth 0). Ideally work on f could start when e is done.


text:
Q: Logout safe way to have ssh-agent session for server processes I am having a server process which is using a passphrase protected SSH key. Currently I log in via SSH to give the key every time the process is restarted. I do:
eval `ssh-agent`
ssh-add mykey
# Enter passphrase
# start my server process

I'd like to change this process, so that I enter SSH passphrase only once, after the server is rebooted. Then the key would be accessible by all processes of a certain UNIX user on that server until the server is restarted again.
How could I set up such setup? Any other ideas how to make this process more smooth?
Ubuntu Server 12.04.

A: So, you want a certain UNIX user on that server enter SSH passphrase only once, and want that SSH passphrase will be good until the server is restarted again, right? Anything more than that?
If no more than that, then Keychain is your answer.

Keychain is an OpenSSH key manager, typically run from
  ~/.bash_profile. When  keychain is run, it checks for a running
  ssh-agent, otherwise it starts one.  It saves the ssh-agent
  environment variables to ~/.keychain/\${HOSTNAME}-sh,  so that
  subsequent logins and non-interactive shells such as cron jobs can
  source the file and make passwordless ssh connections.  In addition,
  when  keychain runs, it verifies that the key files specified on the
  command-line  are known to ssh-agent, otherwise it loads them,
  prompting you for a password  if necessary.

With Keychain, I only need to type in my SSH passphrase once after my box is rebooted.


text:
Q: Android app create TLS connection with RabbitMQ error The error message is SSL handshake aborted, I/O error during system connection is reset by peer. Can Anybody tell me what's going on?
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new
 PlaceholderFragment()).commit();
    }
    Thread thread =  new Thread()
    {
        @Override
            public void run(){
            char[] keyPassphrase = "MySecretPassword".toCharArray();
            KeyStore ks = null;
            try {
            ks = KeyStore.getInstance("PKCS12");
            ks.load(new FileInputStream("/sdcard2/keycert.p12"), keyPassphrase);

            KeyManagerFactory kmf =  KeyManagerFactory.getInstance("X509");
            kmf.init(ks, keyPassphrase);

            char[] trustPassphrase = "MySecretPassword".toCharArray();
            KeyStore tks =  KeyStore.getInstance("BKS");
            tks.load(new FileInputStream("/sdcard2/clienttruststore.bks"), trustPassphrase);
            TrustManagerFactory tmf =  TrustManagerFactory.getInstance("X509");
            tmf.init(tks);

            SSLContext c = SSLContext.getInstance("TLS");
            c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("192.168.10.1");
            factory.setPort(5671);
            factory.setVirtualHost("/");
            factory.setUsername("admin");
            factory.setPassword("123456");
            factory.useSslProtocol(c);
            Connection conn = factory.newConnection();
            Channel channel = conn.createChannel();
         channel.queueDeclare("rabbitmq-java-test", false, true, true, null);

            channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());

            GetResponse chResponse = null;
                chResponse = channel.basicGet("rabbitmq-java-test", false);

            if(chResponse == null) {
                System.out.println("No message retrieved");
            } else {
                byte[] body = chResponse.getBody();
                System.out.println("Recieved: " + new String(body));
            }
            System.out.println("message 8");
            System.out.println("## message retrieved");
            System.out.println("## message retrieved");
            }catch(IOException e){
                e.printStackTrace();
                //e.getCause().getMessage();
                Log.i("test","IO error message");
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();Log.i("test","message4");
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();Log.i("test","message5");
            } catch (CertificateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();Log.i("test","message6");
            } catch (UnrecoverableKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();Log.i("test","message7");
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();Log.i("test","message8");
            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
    thread.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
  }

}

I create the certificate according to RabbitMQ intro.It works in pure Java version.However, Android cannot read .JKS file,I reconstruct a .BKS truststore. Really need your help.


text:
Q: Converting CMYK pdf to RGB results in white lines and some font problems I use the following command to convert a pdf from CMYK to RGB - I dont have access to the generation of these PDFs.  The reason I'm doing it is so that the colours look correct on an iPod device.
ps2pdf -dPDFSETTINGS=/screen -dOptimize=true -dUseCIEColor some.pdf converted.pdf
When I run this there are some white lines that appear and the fonts on some parts of the page are messed up.  These problems are not present on the source pdf files.
Thanks!

A: This is the wrong command to achieve what you want. Try this one instead (using the full Ghostscript commandline instead of the ps2pdf wrapper around it):
gs \
 -o converted.pdf \
 -sDEVICE=pdfwrite \
 -sProcessColorModel=DeviceRGB \
 -sColorConversionStrategy=sRGB \
 -sColorConversionStrategyForImages=sRGB \
  some.pdf


text:
Q: Using tinytest to test Meteor client while the server is running Is it possible to test the Meteor client while the server is running using tinytest? Here's my example testing the client only:
Tinytest.add("Add object to a collection", function(test) {
  var people = new Meteor.Collection("people");
  people.insert({"name": "Andrew"}, function(error, id) {
    test.isNull(error);
  });
});

For a fraction of a second this passes, but then it goes into the state of "waiting". I'm also positive that error is not null.
Meteor.Error {error: 404, reason: "Method not found", details: undefined}

I know this is happening because their is no server for the client to communicate with. When I try to run this test on the server and client, I continue to get the same issue with the client. Is there a way to test the client while the server is running?
Thanks, Andrew

A: Use new Meteor.Collection with no argument to create a stub collection that doesn't require the server. See the docs on Collections:

If you pass null as the name, then you're creating a local collection. It's not synchronized anywhere; it's just a local scratchpad that supports Mongo-style find, insert, update, and remove operations.

A: This is an async test, so you'll have to use addAsync.
Tinytest.addAsync("Add object to a collection", function(test, next) {
  var people = new Meteor.Collection("people");
  people.insert({"name": "Andrew"}, function(error, id) {
    test.isNull(error);
    next();
  });
});

Note the next argument which signals that you are done in the callback.


text:
Q: Add custom field in order->shipment in Magento I would like to add one more field i.e qty ordered by customer in Order -> Shipment part.Can some one help me on this.
Regards
Vishavdeep Goyal

A: I'm unaware of how you would like to select "qty ordered by customer" from, but the example bellow shows how to display total_qty_ordered field form sales_flat_order table in Shipment grid:
1) Copy file app/code/core/Mage/Adminhtml/Block/Sales/Shipment/Grid.php to app/code/local/Mage/Adminhtml/Block/Sales/Shipment/Grid.php
2) Modify the _prepareCollection() method
protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel($this->_getCollectionClass());
        $collection->getSelect()->joinLeft(array('order' => Mage::getSingleton('core/resource')->getTableName('sales_flat_order')), 'main_table.entity_id = order.entity_id', 'total_qty_ordered');
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

2) Modify the _prepareColumns() method and the following code to it
$this->addColumn('total_qty_ordered', array(
            'header' => Mage::helper('sales')->__('Total Qty Ordered'),
            'index' => 'total_qty_ordered',
            'type'  => 'number',
        ));


text:
Q: Export BLENDER model into an OpenGL geometry inside a C++ header file I'm developing an Android application.
I have a 3D model drawn with Blender. Do you know if there is a way to export that model into a OpenGL geometry?
I'm going to use C++ code to load model and draw it with OpenGL. But if you know a better choice, please tell me.

A: There is no such format defined as OpenGL geometry. You will have to create your own structures to store and manage your vertices and triangles.
If you don't want to use any third party loader, the probably the easiest thing would be using the Wavefront OBJ format. It's really simple to parse, and you can export models from blender can export to obj natively.
If you don't feel like starting from scratch, you can use my very basic OBJ loader for OpenGL. Download from here.

A: Here's a doc on the .blend format: http://www.atmind.nl/blender/mystery_ot_blend.html
Although, you'd probably be better off exporting it to a different format.  There's a tool to convert called readblend that's part of Bullet, if you're stuck with .blend files.
How you use the data is dependent on how your OpenGL app is structured.  If you're still at the planning stage, perhaps Ogre3D would be useful? http://www.ogre3D.org


text:
Q: Show graphic progress while copying files using File Channels I am new to Swing Applications.
I have a simple app that copies files from a directory to another one. To copy the files I use FileChannel instances. I was wondering if it is possible to show a progress bar to inform the user How much of the files have been copied.
Here is my code:
public class Foo extends JFrame{
    long size;
    FileChannel inp = null,
                outp= null;
    File sourceFile = new File("C:/test/movie.mkv"),
           destFile = new File("C:/output/movie.mkv");
    public void createUI(){
        JPanel panel = new JPanel();
        JButton btn = new JButton("Copy Files");
        panel.add(btn);
        /*code to create and position the jframe*/
        btn.addActionListener((e)->{
            try {
                inp = new FileInputStream(sourceFile).getChannel();
                outp = new FileOutputStream(destFile).getChannel();
                size = inp.size();
                outp.transferFrom(inp,0,size);
            } catch (Exception e2) {
                System.out.println("FIle not found");
                return;
            }
        });
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new Foo().createUI());
    }
}


text:
Q: An R-matrix in a quasitriangular Hopf algebra I am new to the theory of Hopf algebra. So I am sorry if the following question has really trivial answer.
Suppose that we have a quasi triangular Hopf algebra with the universal R-matrix $R$. It satisfies the following equation by definition:
$$(\Delta \otimes \mathrm{id})(R)=R_{13}R_{23}$$
where
$\Delta$ is the comultiplication and $ R_{13}=\phi_{13}(R)$ with $\phi_{13}(a\otimes b)=a\otimes 1 \otimes b$ and $ R_{23}=\phi_{23}(R)$ with $\phi_{23}(a\otimes b)=1\otimes a \otimes b$.
Let us write $R=\sum e_i\otimes f_i$. Let $R'=\sum f_i \otimes e_i$.
My question is whether we can replace $R$ with $R'$ in the above equation. Namely:
Is
$$(\Delta \otimes \mathrm{id})(R')=R'_{13}R'_{23}$$
hold true?

A: In general the identity : $$(\Delta \otimes id)R'=R'_{13}R'_{23}\qquad (E)$$
does not hold (See Counterexample below). But it is true that $R'$ satisfy the conditions of "quasi-triangularity" with respect to $\Delta^{op}$ and therefore, we have :
$$(\Delta^{op} \otimes id)R'=R'_{13}R'_{23}\qquad (E)$$
$\textbf{Counterexample:}$
Le $H$ be the Sweedler's algebra like in http://en.wikipedia.org/wiki/Sweedler%27s_Hopf_algebra.
Sweedler's hopf algebra is quasi-triangular with respect to:
$$R=\frac 1 2 (1\otimes 1 +1\otimes g + g\otimes 1-g\otimes g) +\frac \lambda 2 (x\otimes x+x\otimes gx+gx\otimes gx -gx\otimes x), $$
this is given in Kassel's quantum groups.
Let us take $\lambda=1$ ($\lambda\neq 0$ works).
We have $R'=R+R''$ with $R''=gx\otimes x-x\otimes gx$.
Assuming that $R'$ satisfies $(E)$ we get :
$$ (\Delta \otimes id)R''= R_{13} R''_{23}+R''_{13}R'_{23}\qquad (*).$$
Denote $V_a=a\otimes H\otimes H$ and $W=V_x\oplus V_g \oplus V_{xg}$.
Direct computation shows that :
$$(\Delta \otimes id)R''\in -(1\otimes x\otimes gx)+W.$$
On the other hand, since $R''_{13} \in W$ and $ R'_{23} \in V_1 $, using that $W\cdot V_1 \subset W$ gives that $R''_{13}R'_{23} \in W$. So if (*) holds we should have :
$$ R_{13} R''_{23} \in  -(1\otimes x\otimes gx)+W \qquad(**).$$
Let us compute. We see that $R_{13} \in 1\otimes 1\otimes \frac{1+g}{2} +W $ and $R''_{23}\in V_1$. Therefore :
$$ R_{13} R''_{23}\in (1\otimes 1\otimes \frac{1+g}{2})R''_{23} +W.$$
Finaly, we check that :
$$ (1\otimes 1\otimes \frac{1+g}{2})R''_{23} \notin  -(1\otimes x\otimes gx)+W .$$
Wich leads to a contradiction.


text:
Q: Using gdal_rasterize with a MSSQL Connection, possible? I'm a bit new to gdal, I mostly use ogr2ogr for data imports to MS SQL Server -- so I'm a bit out of my tree on gdal_rasterize
My goal is to create png raster files 200x200 from a geometry column.  I tried something like with no avail.
gdal_rasterize -src_datasource "MSSQL:server={server};database=
     {database};uid={user};pwd={pwd};" -a geom -l layer1 -of png -burn
     255 -b geom -sql "SELECT top 1 geom from {myTable}" tract.png -of png -ts 200 200


text:
Q: Show that the pair $(\varphi, \mbox{Hom}(V^*,W))$ is a tensor product to $V,W$.
Let $V,W$ be linear spaces and $\varphi: V\times W \rightarrow \mbox{Hom}(V^*,W)$ given by: $\varphi(v,w)(f) = f(v)w$ for every $v\in V, w\in W, f\in V^*$. Supposing that $\dim(V) <\infty$, prove that the pair $(\varphi, \mbox{Hom}(V^*,W))$ is a tensor product to $V,W$.

Notation: $\mbox{Hom}(V,W)$ is the set of all linear maps from $V$ to $W$.
Well, i've shown that $\varphi(v,w)$ is indeed an element of $\mbox{Hom}(V^*,W)$ for every $v\in V,w\in W$, by proving that $\varphi(v,w)$ is indeed linear. Also, i've shown that $\varphi$ is a bilinear map.
Therefore, by universal property we guarantee a unique $\overline \varphi\in \mbox{Hom}(V\otimes W, \mbox{Hom}(V^*,W))$ such that $\varphi(v,w) = \overline \varphi (v\otimes w) $ for every $v\in V , w\in W$.
Since any other tensor product to $V,W$ is given by $(f\circ \otimes, f(V\otimes W))$, where $f$ is bijection, if we prove that $\overline \varphi$ is actually bijective,  we are done. We proceed to show this:
$\overline \varphi$ is injective: given $u\in \mbox {Ker}(\overline \varphi)$, we choose an expression  $u = \sum_{i=1}^m v_i\otimes w_i$
where $v_i$ and $w_i$ are linearly independent (minimal rank). We argue that $m=0$. If not, since $v_1 \neq 0 $, we choose $f_1\in V^*$ such that $f_1(v_j) = \delta_{1,j}$. Hence,
$$ 0 = \overline \varphi(u) = \sum_{j=1}^{m}\overline \varphi (v_j\otimes w_j) = \sum_{j=1}^{m}\varphi(v_j,w_j).$$
Evaluating at $f_1$, then:
$$0  = \overline\varphi(u)(f_1) = \sum_{j=1}^{m}\varphi(v_j,w_j)(f_1) = \sum_{j=1}^{m}f_1(v_j)w_j = f_1(v_1)w_1$$
and since $w_1$ is l.i., it must be $f_1(v_1) = 0$, a contradiction with our choice of $f_1\in V^*$. Therefore, $m=0$ and hence  $u = 0$.
Question: How to prove surjection? Since $\mbox{dim}(V)<\infty$, we have $\mbox{dim}(V) = \mbox{dim}(V^*)$. Will this ensure that $\mbox{dim}(V\otimes W) = \mbox{dim}(\mbox{Hom}(V^*,W))$? How?
Thanks in advance!


text:
Q: GPRS+GPS communication My project is using GPRS and GPS shield. My board has 2 UART ports so there will be no problem when I use the 2 shields. My codes for both shields works fine alone, but when I already integrated the two in one board, the code for the GPS doesnt continue (GPRS works), its like stuck in this command
ptr = strstr(GPS_data, "$GPGGA"); //search GPGGA String

but this command runs perfectly if I only use the GPS shield alone with the board. Im using 2 baud rates, 57600 for GPRS and 9600 for the GPS. What could possibly be the problem for this? Thank you!
This is a part of my GPS code.
void SEND_data()
{
  digitalWrite(gpsPin, HIGH);

  Serial1.begin(9600); //GPS shield communication
  pinMode(TX1, OUTPUT);
  digitalWrite(TX1, HIGH);

  Serial1.write(Serial1.read());
  while(!ptr)
  {
    while(Serial1.available())
    delay(10);
    {
      GPS_data[i]=Serial1.read(); //output of the GPS
      i++;
      j=0;
      delay(10);
    }
    ptr = strstr(GPS_data,"$GPGGA"); //search GPGGA String
    digitalWrite(gogoPin, HIGH);
  }
   digitalWrite(sendPin, HIGH);

My problem is that digitalWrite(sendPin, HIGH) above doesnt light anymore, so basically the running code stops in the part of the digitalWrite(gogoPin, HIGH); just above the bracket ({).

A: Your problem seems to be in fact a shield stacking problem. If you have bought your shields from same place as your Arduino board this is the case.
Seesntially, you have connected 2 devices to TX/RX pins which is not supported. Following post should explain it better Arduino Uno RX TX Pins.
Generally, in order to make it work, you have to rewire one of the shelds to use different pins and use SoftwareSerial library to communicate with them. This also means you cannot use stacking capability unless physically modifying one of your shields.
On a side note, you might want to use Electronics StackExchange site for futher questions regarding Arduino.


text:
Q: How to determine if a Twitter user has a default profile image I know you can find the profile image of a twitter user using the following url:
https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger
But how can I determine if it is the default image or the image uploaded by the user?

A: https://dev.twitter.com/docs/user-profile-images-and-banners

Users who have not uploaded a profile image can be identified by the default_profile_image field of their user object having a true value.


text:
Q: AS3 - Dictionary objects allocated by a simple dictionary[key]=value call While profiling my app in Scout I noticed it shows that the method JSONObject.internalPut is responsible for allocating 2,355 Dictionary objects.
The method's code is as follows:
internal function internalPut(key:String, value:*):void {
    _map[key] = value;  // _map is a Dictionary
}

How can we explain this?
_map is a Dictionary object created in JSONObject's constructor without the weakKeys parameter (i.e. it's false)
Can a simple dictionary[key]=value allocate anything??
Thanks for any help
Eyal

A: So it turns out that in Flash/AS3, empty Dictionary or Array objects may internally create another instance of their own class during first object assignment, that is when the first 'put' operation on a Dictionary occurs, or the first 'push' command on an Array occurs.
From what I investigated, this will only happen when these collection objects were cleared before (i.e. they had values and then emptied via their 'delete' or 'splice' calls)
Hope it helps,
Eyal


text:
Q: Cannot change the dtype using tf.cast, when value passed is dataset.take(1) I want to change the dtype of one element of my dataset. (element shape = (32,28,28)--> this is one batch of 28 by 28 images in mnist dataset)
So i ran the following command: tf.cast(dataset.take(1),tf.float32).
the type of my dataset is tensorflow.python.data.ops.dataset_ops.PrefetchDataset
It threw an error: : Attempt to convert a value (<TakeDataset shapes: (32, 28, 28), types: tf.uint8>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.TakeDataset'>) to a Tensor.
So i took one element from the dataset using the code:
    for batch_data in dataset:
        one_element = dataset
        break

and then I ran tf.cast(one_element,tf.float32) and it works.
May I know why this is happening?

A: tf.data.Dataset.take() returns Dataset not tensor (even when you call take(1)): https://www.tensorflow.org/api_docs/python/tf/data/Dataset


text:
Q: How to use JDBC on working Hibernate/Spring web-app? I have working Hibernate/Spring web-app (HibernateDaoSupport, getHibernateTemplate(), etc). For several tasks i need to use JDBC (jdbcTemplate ?). How to do it in that scenerio ?

A: Just create JdbcTemplate and use the same DataSource that is being used by HibernateDaoSupport, HibernateTemplate. Hibernate is just a fancy library working on top of JDBC DataSource/connection. You might use it manually. Try:
@Autowired
private DataSource ds;

If you are lucky, this should work. A better idea is to create JdbcTemplate as a Spring bean and inject proper data source:
<bean id="jdbcTemplate" class="org.springframework.jdbc.coreJdbcTemplate">
  <constructor-arg ref="dataSource"/>
</bean>

Consider using JdbcOperations interface, also look at SimpleJdbcOperations.
@Autowired
private JdbcOperations jdbc;

If you start to access the same database/connection pool both by Hibernate and using direct JDBC access code, you have to watch out for some side effects:

*

*Hibernate L2 cache is not aware of JDBC modifications

*JDBC code is not aware of Hibernate optimistic locking

*transaction management

*...

Another approach is to access JDBC connection used by Hibernate session (in HibernateDaoSupport:
getSession().connection()

A: You may use Session.doWork to execute code using JDBC connection used by Hibernate.
This of course requires that you use and have access to Hibernate's Session object.


text:
Q: Create a file which can be renamed while in use I have a application which has two sub modules. Also their is custom Log class written to log module activities.Requirement I am working on is each module should create log file with same name and write log into that. To explain it better consider initial run in which module1 is wrting logs in app.log now when another session of application starts with module2 it should also create app.log and start writing. but before that old app.log should get rename to something app.log.1.
Issue I am facing when log file is open with one module function fails to rename. I am working in C++ on window 7. To create a file I am using -
std::ofstream s_ofs.open("app.log", std::ios::out | std::ios::app);

A: Windows does not allow this. When you open a file, for writing or for reading, it's locked and you can't do operations such as rename or delete while the file is open.
You might want to reconsider your design. Either so that each submodule have its own uniquely named log file. Or use a logging module that can receive logging input from multiple sources and multiplex those into a single file.

A: You can achieve this by synchronizing access to the Log class object. An approach could be as follows:

*

*Application creates the Log class object on startup Create a
Synchronization object (say Mutex) which protects access to the
Logging

*Have the Log method accept a flag which will differentiate
between accesses from two different modules

*Module1 gains access and  starts logging

*When module2 wants to write, the Logger will detect that it has a Log request from another module, and will close the file and then rename it and create another log file with the same     name


text:
Q: How to evaluate deterministic vs stochastic components of a time series? Suppose we are working with a real data set , say in R.
What are the approaches/methods for determining underlying structure.
That is,
How can we separate stochastic components vs deterministic?
Can we use state space modelling, and if so, how to best implement in R?
Thank you all for any advice.

A: Thank you for your question! I must reflect that this is a profound question as it is never treated in either texts or the classroom.
There is an R version of AUTOBOX (a commercial piece of software I helped to write) which identifies both the stochastic components (ARIMA & possible variance stabilizing transforms) while sorting out/identifying possible deterministic components. This is accomplished by evaluating alternative threads or approaches. The deterministic components are found primarily through proprietary scripted search procedures. For example a particular day-of-the month or week-of-the-month may be important or a change in daily-effects over time which would be detected by evaluating alternative hypothesis/data structures. Pulses,level shifts,local time trends,seasonal pulses are also discovered/detected by search procedures. Long-weekend effects, days-before and after each holiday can also be identified in a similar manner.
The interaction between ARIMA and possible deterministic structure is an added dimension/complication/opportunity that needs to be woven into a self-checking iterative procedure to ensure parsimony and estimability. All of the above needs to be done while accounting for the timely response and anticipation of user specified variables.
I am unaware of any state-space modelling that conducts this level of signal /noise deconstruction . If you wanted to post a real world data set I would be glad to demonstrate the results of AUTOBOX to routinely/automatically perform this task of forming a minimally sufficient model containing both stochastic and deterministic components.


text:
Q: request scoped property in session scoped JSF bean I would like to have a session scoped JSF bean with one property that is request (page) scoped. Is it possible at all?

A: No, that's not possible. Managed property injection only happens during creation of the bean. However, when a session scoped bean is been created there is not necessarily a request present and the injected request scoped bean would be invalid in subsequent requests in the remnant of the session.
Do it the other way round. E.g.
@ManagedBean
@SessionScoped
public class UserManager {

    private User current;

    // ...
}

and
@ManagedBean
@RequestScoped
public class Login {

    private String username;
    private String password;

    @ManagedProperty(value="#{userManager}")
    private UserManager userManager;

    @EJB
    private UserService userService;

    public String submit() {
        User user = userService.find(username, password);

        if (user != null) {
            userManager.setCurrent(user);
            return "home?faces-redirect=true";
        } else {
            addErrorMessage("Unknown login, please try again");
            return null;
        }
    }

    // ...
}


text:
Q: Polar coordinates; Jacobian and order of the variables I'm trying to understand the Jacobian a bit. I know the general form of the transformation with two variables:
$$\int\int_Ag(x,y)\,\mathrm dx\,\mathrm dy=\int\int_{T(A)}g\big(x(u,v),y(u,v)\big)\lvert J(u,n)\rvert \,\mathrm du\,\mathrm dv.$$
Say we'd like to change to polar coordinates;
$$\int\int_Ag(x,y)\,\mathrm dx\,\mathrm dy=\int\int_{T(A)}g\big(x(r,\theta),y(r,\theta)\big)\lvert J(r,\theta)\rvert \,\mathrm dr\,\mathrm d\theta.$$
How do we know the order of $(r,\theta)$? Could it also have been $(\theta,r)$? This would yield to the same Jacobian determinant but with the opposite sign.

A: Well it would lead to a sign difference but the magnitude would be the same. Switching order is fine.
Like in Linear Algebra. Elementary row operations change the sign of the determinant but the magnitude remains unchanged.


text:
Q: Signing Android apk : INSTALL_PARSE_FAILED_NO_CERTIFICATES I'm trying to sign an Android apk created using Processing.
Here's what I did (based on this : http://www.akeric.com/blog/?p=1352 ) :
keytool -genkey -v -keystore myapp-release-key.keystore -alias myname -keyalg RSA -keysize 2048 -validity 10000

ant release

jarsigner -verbose -keystore myapp-release-key.keystore <PATH>/android/bin/<APPNAME>-release-unsigned.apk myname

jarsigner -verify <PATH>/android/bin/<APPNAME>-release-unsigned.apk

zipalign -v 4 bin/<APPNAME>-release-unsigned.apk bin/<APPNAME>-release.apk

adb install bin/<APPNAME>-release.apk

But I get an error :
INSTALL_PARSE_FAILED_NO_CERTIFICATES

The jarsigner verify terminated with :
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope

jar verified.

Warning:
    This jar contains entries whose certificate chain is not validated.
    This jar contains signatures that does not include a timestamp. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (2042-09-08) or after any future revocation date.

Any ideas as to what's wrong? Something to do with those warnings?

A: Make sure you add the following 2 options: -sigalg SHA1withRSA -digestalg SHA1 to your jarsigner command even though you've already specified something similar when generating the key. Like that:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore myapp-release-key.keystore <PATH>/android/bin/<APPNAME>-release-unsigned.apk myname

Took me AGES to realise these were NOT optional... Doc definitely un-clear on that one.
Hope that helps. Good luck.


text:
Q: How to repeat a delta using SAP_CDC connector from Azure Data Factory We've just started with ADF and are using the SAP_CDC connector to connect to generic data sources in ODP. This all works but one time the update in Azure failed yet the ODP request was flagged as confirmed. Our only option seemed to be to reinitialise the data source by deleting the subscription in ODQMON and dropping the table in Azure.
In BODS we're able to specify a timestamp to repeat extraction from and there is SAP doco on this (2399296 - How to recover a delta load for ODP Extractor in Data Services).
My questions are:

*

*Is it possible to repeat a delta request in ADF

*In ODQMON the subscription only appears as the technical/timestamp - there is no descriptive label, and the icon next to the subscription is missing (greyed out).

Will appreciate any answers.
Thank you.

A: Is it possible to repeat a delta request in ADF?
In my view Yes, it brings last delta records (which are not pulled thru last delta info pack) and latest delta records as well - given in MS Q&A  861785  by @KranthiPakala-MSFT.
In ODQMON the subscription only appears as the technical/timestamp - there is no descriptive label, and the icon next to the subscription is missing (greyed out).
As per my analysis on referring to @PremShanker  article in this  blog  it appears as timestamp.
Refer to the MS  Doc1  for the SAP CDC connector in Azure Data Factory and  Doc2  for frequent debugging issues!


text:
Q: Additional Labels in Plotly Sankey Diagram I created a Sankey Diagram using Plotly in R and want to add vertical labels to the far left and right of the plot. Is this possible? I found the possibility of Annotations in Plotly but can't get it to work with the Diagram.
Code looks like this:
library(plotly)
fig <- plot_ly(
  type = "sankey",
  orientation = "h",

  node = list(
    label = c("Level 1", "Level 2", "Level 3",
              "Level 1", "Level 2", "Level 3", "Level 4", "Level 5"),
    color = c("rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)",
              "rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)", "rgba(148, 103, 189, 1)", "rgba(148, 103, 0, 1)"),
    pad = 20,
    thickness = 15,
    line = list(
      color = "black",
      width = 0.5
    )
  ),

  link = list(
    source = c(0,0,0,0,1,1,1,1,2,2,2,2),
    target = c(3,4,5,6,3,4,5,6,4,5,6,7),
    value =  c(482,52,1,1,20,127,19,1,1,1,3,1),
    color = c("rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)",
              "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)",
              "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)")
  )
)
fig <- fig %>% layout(
  title = "Title of the Plot",
  font = list(
    size = 10
  )
)

fig

Thanks for your help.
EDIT:
I tried using "add_annotations", but as soon as I shift the x-axis of the text lower than 0 (to move the text farther left) it vanishes:
%>% add_annotations(
  xref="paper",
  yref="paper",
  x=-0.1,
  y=0.5,
  text="Test",
  showarrow=FALSE
)

A: After some more tinkering I found the Solution myself:
I added some margin to the layout:
layout(
  title = "Name of the Plot",
  font = list(
    size = 10
  ),
  margin = list(
    r = 30,
    l = 30
  )

Then I used "add_annotations" to create the text and shifted it further to the right/left using "xshift":
add_annotations(
  xref = "paper",
  yref = "paper",
  x = 1,
  y = 0.5,
  xshift = 25,
  text = "Text I wanted to add",
  font = list(
    size = 14
  ),
  showarrow = FALSE,
  textangle = 90

The final code looks something like this:
fig <- plot_ly(
  type = "sankey",
  orientation = "h",
  node = list(
    label = c("Level 1", "Level 2", "Level 3",
              "Level 1", "Level 2", "Level 3", "Level 4", "Level 5"),
    color = c("rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)",
              "rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)", "rgba(148, 103, 189, 1)", "rgba(214, 39, 40, 1)"),
    pad = 20,
    thickness = 15,
    line = list(
      color = "black",
      width = 0.5
    )
  ),

  link = list(
    source = c(0,0,0,1,1,1,1,2,2,2,2,2),
    target = c(3,4,5,3,4,5,6,3,4,5,6,7),
    value =  c(614,27,4,12,35,6,1,1,1,2,5,1),
    color = c("rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)",
              "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)",
              "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)")
  )
) %>% layout(
  title = "Name of the plot",
  font = list(
    size = 10
  ),
  margin = list(
    r = 30,
    l = 30
  )
) %>% add_annotations(
  x = 1,
  y = 0.5,
  xshift = 25,
  text = "Text 1",
  font = list(
    size = 14
  ),
  showarrow = FALSE,
  textangle = 90
) %>% add_annotations(
  x = 0,
  y = 0.5,
  xshift = -25,
  text = "Text 2",
  font = list(
    size = 14
  ),
  showarrow = FALSE,
  textangle = -90
) %>% show()

A: Not an answer, only a suggestion to slightly improve the code.
Instead of using add_annotations twice you can add both labels in one go.
add_annotations(
  x = c(1,0),
  y = 0.5,
  xshift = c(25, -25),
  text = c("Text 1", "Text 2"),
  font = list(
    size = 14
  ),
  showarrow = FALSE,
  textangle = c(90, -90)
)


text:
Q: Enum.GetName display Annotation I have a enum that I am able to display in a EnumDropDownListFor with no problem and save the enum. Now I am trying to take that value from my record and display the DataAnnotation for it. I have been trying Enum.GetName however coming across some issues.
my enum -
public enum LandOwner
    {
        [Display(Name = "Yes")]
        Y =1 ,
        [Display(Name = "No")]
        N =2,
        [Display(Name = "No Nearby Land Owner")]
        O =3
    }

    public LandOwner ownerDropDown { get; set; }

When I save the record it save an Y, N or O.
My Enum.GetName - where Model.LandOwnersNotified is the Y, N, or O.
@Enum.GetName(typeof(OpenBurn.Models.BurnPile.LandOwner), Model.LandownersNotified)

However when I run this I get the following error -
The value passed in must be an enum base or an underlying type for an enum, such as an Int32.\r\nParameter name: value
When I change the Enum.GetName to
 @Enum.GetName(typeof(OpenBurn.Models.BurnPile.LandOwner), 1)

I know the latter part of the Enum.GetName is looking for an int however doesn't the Model.LandownersNotified in combination with the enum provide that?
I will receive the Y for everything. At no time do I receive the [Display(name="...")].

A: Can't say i understand what you are trying to do.  But  @Enum.GetName is designed to return the name for the value of the enum.   So you can't pass the enum to it.
Model.LandownersNotified.ToString() -> Y,N,O
(int)Model.LandownersNotified -> 1,2,3


text:
Q: Issue inserting data from textbox into sqlite table I am trying to enter data into an sqlite database. I am using the following code, but something I am doing is wrong and it is not working.
  string dbConnection = "Data Source=" + dbString + ";Version=3;";
        using (SQLiteConnection myConnection = new SQLiteConnection(dbConnection))
        {
            SQLiteCommand sqlCommand = new SQLiteCommand("INSERT INTO Products (First_Name,Last_Name,Company_Name,Address1,Address2,City,State,Zip,Phone_Number1,Phone_Number2,Email_Address) Values (@First_Name, @Last_Name,@Company_Name, @Address1,@Address2, @City,@State, @Zip, @Phone_Number1, @Phone_Number2, @Email_Address,)", myConnection);
            sqlCommand.Parameters.AddWithValue("@First_Name", FNAME_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Last_Name", LNAME_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Company_Name", CNAME_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Address1", ADDRESS1_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Address2", ADDRESS2_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@City", CITY_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@State", STATE_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Zip", ZIP_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Phone_Number1", PHONE1_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Phone_Number2", PHONE2_TXT.Text);
            sqlCommand.Parameters.AddWithValue("@Email_Address", EMAIL_TXT.Text);

            myConnection.Open();
            return sqlCommand.ExecuteNonQuery();

when I execute the code, I get:
"A first chance exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll
Additional information: SQL logic error or missing database
near ")": syntax error"
This is the code that creates the Database:
      sqlite_conn = new SQLiteConnection(dbLoc);
                sqlite_conn.Open();
                sqlite_cmd = sqlite_conn.CreateCommand();
                sqlite_cmd.CommandText = "CREATE TABLE Customer ("
                        + "Customer_ID_PK integer primary key,"
                        + "First_Name VARCHAR(32),"
                        + "Last_Name VARCHAR(32) NOT NULL,"
                        + "Company_Name VARCHAR(50),"
                        + "Address1 VARCHAR(45) NOT NULL,"
                        + "Address2 VARCHAR(45),"
                        + "City VARCHAR(25) NOT NULL,"
                        + "State VARCHAR(2) NOT NULL,"
                        + "Zip CHAR(5) NOT NULL,"
                        + "Phone_Number1 CHAR(10) NOT NULL,"
                        + "Phone_Number2 CHAR(10),"
                        + "Email_Address VARCHAR(25))";
                sqlite_cmd.ExecuteNonQuery();
                sqlite_conn.Close();

Thank you for your help.

A: Remove your last comma
... @Email_Address,)"

To
 @Email_Address)"

A: Remove extra comma in your query.
Change this:
INSERT INTO Products (First_Name,Last_Name,Company_Name,Address1,Address2,City,State,Zip,Phone_Number1,Phone_Number2,Email_Address) Values (@First_Name, @Last_Name,@Company_Name, @Address1,@Address2, @City,@State, @Zip, @Phone_Number1, @Phone_Number2, @Email_Address,)

to:
INSERT INTO Products (First_Name,Last_Name,Company_Name,Address1,Address2,City,State,Zip,Phone_Number1,Phone_Number2,Email_Address) Values (@First_Name, @Last_Name,@Company_Name, @Address1,@Address2, @City,@State, @Zip, @Phone_Number1, @Phone_Number2, @Email_Address)


text:
Q: Can Anyone Check This Image Upload Code In Laravel? I wrote this Code For Image Upload but I do not know if it is secure, or not. Is There any issue or vulnerability in this code??
if($request->hasFile('image')){

    $AllowedImages = ['jpeg', 'jpg', 'png'];
    $AllowedImageTypes = ['image/jpeg', 'image/png'];

    $image = $request->image;
    $ImageNameWithExtension = $image->getClientOriginalName();
    $ImageName = pathinfo($ImageNameWithExtension, PATHINFO_FILENAME);
    $ImageExtension = $image->getClientOriginalExtension();
    $ImageType = $image->getMimeType();
    $ImageLocalPath = $image->getPathName();
    $ImageSize = $image->getSize();
    $ImageError = $image->getError();
    $ImageNewName = sha1(md5($ImageName)).''.sha1(time()).'.'.$ImageExtension;

    if(in_array($ImageType, $AllowedImageTypes) && in_array($ImageExtension, $AllowedImages) && getimagesize($ImageLocalPath) && ($ImageError === 0) && ($ImageSize <= 2000000)){

        if($ImageType == 'image/jpeg' && ( $ImageExtension == 'jpeg' || $ImageExtension == 'jpg')){
            $img = imagecreatefromjpeg($ImageLocalPath);
            imagejpeg( $img, $ImageNewName, 100);
        }
        elseif($ImageType == 'image/png' && $ImageExtension == 'png'){
            $img = imagecreatefrompng($ImageLocalPath);
            imagepng( $img, $ImageNewName, 9);
        }
        imagedestroy($img);
        try
            {
            $StoreImage = $image->storeAs('public/Upload/', $ImageNewName);
            if(!$StoreImage){
                throw new customException('File Upload Failed');
            }
        }
        catch(customException $e){
            session()->flash('File_Error', $e->errorMessage());
            return back();
        }
    }
    else{
        session()->flash('File_Error', 'Image Validation Error Found');
        return back();
    }
}
else{
    return back();
}

A: Consider this refactor for your code, it will help make your code cleaner.
public function store(Request $request)
  {
    $record = Model::create( $this->validateRequest() ); // this can insert other data into your database. In the db table, initially set the image related fields to nullable

    $this->storeFile($record); // this will check if the request has a file and update the image related fields accordingly, else it will remain blank as it is nullable by default

    return 'all data is saved';

  }

private function validateRequest(){

       return request()->validate([
            'type' => 'nullable',
            'image'=> request()->hasFile('image') ? 'mimes:jpeg,jpg,png|max:2000' : 'nullable', // 2000 means a maximum of 2MB
            'other_field_1' => 'required',
            'other_field_2' => 'required',
            'other_field_3' => 'required'

            ]);

    }

private function storeFile($record){

        if( request()->hasFile('image') ){

            $record->update([
                'type' => request()->file->extension(),
                'image' => request()->file->store('uploads/files', 'public') // The file will be hashed by default. public is used as second argument so you can access the uploaded file via your public folder
            ]);
        }

    }

This is check for file in the request, validate the file and other data, upload the file into storage folder.

A: You can use this code, for upload image :
In Request file :
public function rules()
{
    return [
        'image' => 'required|mimes:jpeg,jpg,png|max:50000'
    ],
}

And in your controller :
    public function uploadImage(YourRequestClass $request){
        $image = $request->file('image');

        try{
        $order=new Order();
        if (!file_exists('upload/' . $image)) {
                $currentDate = Carbon::now()->toDateString();
                $imageName = $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
                if (!file_exists('upload/')) {
                    mkdir('upload/', 0777, true);
                }
                $image->move('upload/', $imageName);
                $order->image = $imageName;
            }
        $order->save();
        return back();
        } catche(\Exception $e){
            Log::error($e);

            return back();
        }
    }


text:
Q: How to show a child or another depending on parent hover state (CSS Only) I'm building a Menu component in react that shows a list of options. Each option has a text on the left and the '>' icon on the right. But, when I hover on the parent I want the '>' symbol to change to '>>'. How can I do this? I have added the current state of the source. I just need to hide BsChevronRight on parent hover and show BsChevronDoubleRight and viceversa.
function Menu({data}:{data:IMenuItemData[]}) {
    return (

            {data.map(el => {
                return
                        {el.text}
                        <BsChevronRight></BsChevronRight>
                        <BsChevronDoubleRight></BsChevronDoubleRight>

            })}

    )
}

I'm looking for a CSS only solution.

A: Add hidden group-hover:block classes for your second chevron (that should appear) or any fadeIn effect like: invisible group-hover:visible or opacity-0 group-hover:opacity-100. Your parent a element should have group class to work.
Note: if you're using TailwindCSS without jit mode enabled you need to extend some properties to support group-hover variant
// tailwind.config.js
module.exports = {
  variants: {
      extend: {
        display: ['group-hover'],
        visibility: ['group-hover'],
      }
   }
}

DEMO: https://play.tailwindcss.com/XifyCwLkFV

A: Well, it seems that I go a solution. It feels a bit hacky to me but It works.
The trick is to have a parent and 2 children that flip the display property between none and block.
For me it does the job. If anyone has a better solution I'm all ears.
HTML:

      Hello

CSS:
.parent {
   width:300px;
   height:300px;
   background-color:yellow;
   display:flex;
}

.parent:hover > .child1 {
  display:block;
}

.parent:hover > .child2 {
  display:none;
}

.child1 {
  display:none;
  width: 100px;
  height:100px;
  background-color: green;
}

.child2 {
  display:block;
  width: 100px;
  height:100px;
  background
}

https://jsfiddle.net/pyfL7r03/42/

A: Try creating a state isHovered and toggle using onMouseEnter and onMouseLeave
function Menu({data}:{data:IMenuItemData[]}) {
    const [isHovered , setIsHovered] = useState(false);
    const handleMouseEnter = ()=>{
          setIsHovered(true)
    }
    const handleMouseLeave = ()=>{
          setIsHovered(false)
    }
    return (

            {data.map(el => {
                return
                        {el.text}
                        {!isHovered ? <BsChevronRight/> :
                        <BsChevronDoubleRight/>}

            })}

    )
}

A: There's a quick way to do this in Tailwind:
1.) Add a "group" class to the parent e.g.

2.) Add the hover effect on the child, prefixing with group e.g.

More info in the tailwind docs: https://tailwindcss.com/docs/hover-focus-and-other-states


text:
Q: VBA is changing constant values of its own accord I am working on a section of a fairly large VBA macro that is designed to apply conditional formatting when another cell is equal to 1, so that the cell can be highlighted as 'selected.'
When generating the conditional formatting formula that does this, excel seems to be changing constant values of its own accord - all the values it reads from should be at row 99 and this is in the code, but excel instead changes the formula to =IF(B101=1,1,0) for the first one, then =IF(B105=1,1,0) for the next one and so on.
These are merged cells, so I would assume that excel is trying to autocomplete my code by offsetting the formula by how many rows down I am. Obviously this is not desired, does anyone know how I can stop excel from doing this? The relevant section of code is below:
    For Each x In Range(crange)
            condrow = 99
            Range(Cells(coffset + 3, y + 1), Cells(coffset + 2 + currentdiv, y + 1)).FormatConditions.Delete
            Cells(coffset + 3, y + 1).Value = x
            selectform = "=IF(" & ConvertToLetter(Cells(coffset + 3, y + 1).Column) & CStr(condrow) & "=1,1,0)"
            Range(Cells(coffset + 3, y + 1), Cells(coffset + 2 + currentdiv, y + 1)).Merge
        Range(Cells(coffset + 3, y + 1), Cells(coffset + 2 + currentdiv, y + 1)).FormatConditions.Delete
        Range(Cells(coffset + 3, y + 1), Cells(coffset + 2 + currentdiv, y + 1)).FormatConditions.Add Type:=xlExpression, Formula1:= _
            "clashform"

A: I believe you need to prefix a row or column reference by a "$" to prevent Excel from automatically adjusting it for different rows or columns.
For example, "B$101" will allow the column (B) to be adjusted as the formula moves to a different location, but not the row, which is preceeded by a "$".


text:
Q: How many one-to-one functions are there from 4-byte words to 4-byte words? How many onto functions? How many one-to-one functions are there from 4-byte words to 4-byte words? How many onto
functions?
My attempt:
{{a, b, c, d}, {a, b, d, c}, {a, c, b, d}, {a, c, d, b}, {a, d, b,
  c}, {a, d, c, b}, {b, a, c, d}, {b, a, d, c}, {b, c, a, d}, {b, c,
  d, a}, {b, d, a, c}, {b, d, c, a}, {c, a, b, d}, {c, a, d, b}, {c,
  b, a, d}, {c, b, d, a}, {c, d, a, b}, {c, d, b, a}, {d, a, b,
  c}, {d, a, c, b}, {d, b, a, c}, {d, b, c, a}, {d, c, a, b}, {d, c,
  b, a}}
So the answer is 4!. Is this correct?

A: For maps $f:S \rightarrow S$ for finite sets $S$ (in this case the set of $4$-byte words), one-to-one functions, onto functions and permutations all describe the same functions.
There are $2^{4 \times 8}$ distinct $4$-byte words (assuming a byte consists of $8$-bits), so $|S|=2^{32}$.  The number of permutations of $S$ is $|S|!=2^{32}!$.
What you have listed are the permutations $f:\{a,b,c,d\} \rightarrow \{a,b,c,d\}$, of which there are indeed $4!$.


text:
Q: Finding Curve Length
Find the curve length when $\alpha(t)=(a(t-\sin t),a(1-\cos t))$ where $a>0$ and $t\in [0,2\pi]$

So I am using: $$\int_{a}^{b}\|\alpha'(t)\|\,\mathrm dt$$
$\alpha'(t)=(a-a\cos t,a\sin t)$
$$\|\alpha'(t)\|=\sqrt{(a-a\cos t)^2+(a\sin t)^2}=\sqrt{a^2-2a^2 \cos t+a^2\cos^2t+a^2\sin^2t}=\sqrt{a^2-2a^2 \cos t+a^2(\cos^2t+\sin^2t)}=\sqrt{2a^2-2a^2 \cos t}=\sqrt{2a^2(1-\cos t)}=\sqrt{2a^2(2\sin^2(t/2))}=\sqrt{4a^2(\sin^2(t/2))}=2a\sin(t/2)$$
So we have $$\int_{0}^{2\pi}2a\sin(t/2)\,\mathrm dt=2a\int_{0}^{\pi}\sin(t/2)\,\mathrm dt=2a(-2\cos(t/2))|^{\pi}_{0}=4a$$
But the answer is $8a$

A: There's a typo in the integral calculation.
$$\int_0^{2\pi}2a\sin\frac t2\,dt=2a\int_0^{\mathbf 2\pi}\sin\frac t2\,dt=2a\left[-2\cos\frac t2\right]^{2\pi}_0=8a$$


text:
Q: How to pass data in a button event handler on a Google script extending a spreadheet? Extending a Google Spreadsheet, I run a script showing some data in a sidebar. At the bottom I want to add a button to mail the data.
However I can't figure out how the data can be passed from button to handler:

*

*There's no possibility to pass data into the event call;

*There's no way to get the button object from the event info, I can merely get the ID, which is useless if I can't get to the uiInstance (created outside of the handler function).

So what's the trick?

A: You have to add a callback element (possibly a panel wrapping everything you need) to the server handler  before assigning it to the button. For example:
function myFunction() {
  var app = UiApp.createApplication();
  var panel = app.createVerticalPanel();
  panel.setId('myPanel').add(
    app.createTextBox().setName('boxExample')).add(
    app.createListBox().setName('listExample').addItem('A').addItem('B'));
  //                                                       ↓↓ this is what you need ↓↓
  var handler = app.createServerHandler('callbackFunction').addCallbackElement(panel);
  var btn = app.createButton(btn, handler);

  app.add(panel.add(btn));
  //show app...
}

function callbackFunction(e) {
  var app = UiApp.getActiveApplication();
  app.getElementById('myPanel').add(
    app.createLabel(e.parameter.boxExample)).add(
    app.createLabel(e.parameter['listExample']));
  return app;
}

A: Using PropertiesService
I found (I don't know how) Google Script offers a data storage service called PropertiesService.
Assuming, as in this case, the data is for user only, I would need to first store the data as such:
var userProperties = PropertiesService.getUserProperties()
userProperties.setProperty("myKey", "myValue")
// Note myValue will be a string, so to store an array,
// you'd need JSON.stringify(myArray)

Then as the button handler is called, the script can retrieve the data easily:
var userProperties = PropertiesService.getUserProperties()
var myValue = userProperties.getProperty("myKey")

Using Hidden Widget
An alternative seems to be the use of a "hidden" widget.

 function doGet() {
   var app = UiApp.createApplication();
   // Note that the name "appState" for callbacks, and the id "hidden" for
   // getting a reference to the widget, are not required to be the same.
   var hidden = app.createHidden("appState", "0").setId("hidden");
   app.add(hidden);
   var handler = app.createServerHandler("click").addCallbackElement(hidden);
   app.add(app.createButton("click me!", handler));
   app.add(app.createLabel("clicked 0 times").setId("label"));
   return app;
 }

 function click(eventInfo) {
   var app = UiApp.createApplication();
   // We have the value of the hidden field because it was a callback element.
   var numClicks = Number(eventInfo.parameter.appState);
   numClicks++;
   // Just store the number as a string. We could actually store arbitrarily complex data
   // here using JSON.stringify() to turn a JavaScript object into a string to store, and
   // JSON.parse() to turn the string back into an object.
   app.getElementById("hidden").setValue(String(numClicks));
   app.getElementById("label").setText("clicked " + numClicks + " times");
   return app;
 }

(code from linked reference)


text:
Q: Maya Python Select component I'm currently working on a tool to make clusters from selected edge loops. I was wondering if any of you know how do I get the edge loop from my selection.

A: Obj = cmds.ls(sl=True, o=True)
Edges = cmds.ls(Obj[0]+'.e[*]', fl=True)

Here is a link for the orderedSelection flag and loop edges :
http://forums.cgsociety.org/t/return-selection-orderd-by-edge-loop-maya-api/1577329/6
Note that highliting ls and right clicking, you can open maya documentation about 'ls' and you have a quick that open a tab with all flags


text:
Q: Using Bash to delete a bracket delimited substring from string variable I have this string in a variable:
strVar="Hello World [randomSubstring].zip"

I would like to extract [randomSubstring], where that substring inside the brackets could be anything.
The expected result must be something like this:
echo "$strVar"
Hello World .zip

I tried several combinations with grep and awk but without success, I am using CentOS 7.
echo "Hello World [RNVE5Z].zip" | grep -oP '(?<=[).*(?=])'
echo "Hello World [RNVE5Z].zip" | awk -F"["" '{print $1}' | awk -F"]" '{print $2}'

A: Bash only:
echo ${strVar/\[*\]/}

A: Just use bash's substring manipulation:
echo ${strVar/\[*\]/}

I would prefer it over an external call to sed, except there is more to be done, why I use sed anyway:
echo $strVar | sed 's/\[.*\]//'

I don't think there is an elegant solution for grep but might be wrong. In awk I'm not that fluent.


text:
Q: Cannot generate classes because no top-level elements with complex type where found I am trying to create a class from a xsd file using the XSD.EXE tool. but for some reason i get this error.

Warning: cannot generate classes because no top-level elements with
  complex type were found.

I have looked around on stack and seen that i could put a type on the complex type element but i cannot seem to get i to work. here is the xsd file
    <?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
     targetNamespace="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader"
     xmlns="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader"
     elementFormDefault="qualified" attributeFormDefault="unqualified">

  <xs:complexType name="DocumentIdentification">
    <xs:sequence>
      <xs:element name="Standard" type="xs:string"/>
      <xs:element name="TypeVersion" type="xs:string"/>
      <xs:element name="InstanceIdentifier" type="xs:string"/>
      <xs:element name="Type" type="xs:string"/>
      <xs:element name="MultipleType" type="xs:boolean" minOccurs="0"/>
      <xs:element name="CreationDateAndTime" type="xs:dateTime"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Thanks!

A: You XSD only defines a type (as Sergio also suggested). As such, it cannot be used for validation of XML, unless it is imported by another XSD . Likewise, other tools like xsd.exe will not be able to anything sensible with it.
You can compare this with a C# library having an interface definition, but no implementation of the interface.
You can fix this in a variety of ways. Considering your current code, I would suggest something along those lines:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader"
    xmlns="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader"
    elementFormDefault="qualified" attributeFormDefault="unqualified">

    <xs:complexType name="DocumentIdentification">
        <xs:sequence>
            <xs:element name="Standard" type="xs:string" />
            <xs:element name="TypeVersion" type="xs:string" />
            <xs:element name="InstanceIdentifier" type="xs:string" />
            <xs:element name="Type" type="xs:string" />
            <xs:element name="MultipleType" type="xs:boolean" minOccurs="0" />
            <xs:element name="CreationDateAndTime" type="xs:dateTime" />
        </xs:sequence>
    </xs:complexType>

    <xs:element name="DocumentIdentification" type="DocumentIdentification" />
</xs:schema>

Though you may consider renaming the type name, to prevent confusion to readers. A common pattern is to suffix typenames with Type, in your case, DocumentIdentificationType.
The code above is importable with xsd.exe without any problems.

A: It would be better to use SvcUtil.exe instead of xsd.exe. It will allow you to avoid the problem with generating classes based on types-only XSDs. An example of .bat file:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools\SvcUtil.exe MySchema.xsd TypesSchema.xsd /dconly /n:*,MyNamespace
pause


text:
Q: Quadtree split operation I have trouble understanding the quadtree split operation. Say the maximum number of items a node can hold is 2; when we add a third element we create four sub-nodes. The question is, does the parent node keep its 2 items and the one who caused the overflow is inserted in a child-node or all three nodes are inserted in the sub-nodes?

A: All three nodes get inserted into a child node. Only the leaves node can hold some data in a tree.
This can make a difference with say, for example, kd-tree, where the space partition is more data oriented instead of fixed space partitioning, thus saving memory. On the other hand, fixed space partitions are easier to handle and can even be precomputed for even faster access.


text:
Q: Fancybox and mcustomscrollbar ipad issue I am using Fancybox and mcustomscrollbar together. i want to open my project in fancybox and it works fine in Computer but in ipad i have to maintain pressed and then it open the contextual menu and after select open it open the fancybox. can you please explain what i have to do to open fancybox with just a single touch on project image.
Url:- http://studioplusarch.com/gsc/
Please help me to solve this issue.
Thanks.

A: I read this Probleme:
"If I open the last
page directly the mcustomscrollbar work ok, but if that page is open
with the fancybox, then the mcustomscrollbarr doesn´t work."
My answer is: The class, for example 'fancy-content' where you hide the fancy content before you load with the fancybox link, don't make it "display: none", do as in the example below:
/* element bifore load */ .fancy-content{ display: block; /*not none*/ height: 0px; overflow: hidden; visibility: hidden; } /*  element after load in fancybox inner */ .fancybox-inner .fancy-content{ height: auto; overflow: hidden; visibility: visible;}


text:
Q: Не работает функция mail() в скрипте? Есть сервак (CentOS 7) на нём установлена виртуальная машина Битрикс, на которой работает коробка CRM. После очередного супер мега пупер обновления отвалилась всякая отправка почты. После ковыряния конфигов и чтения форумов ( все статьи сильно устарели, так как виртуальная машина уже 7!) подправил конфиг (bitrixenv.ini) :
;sendmail_path = msmtp -t -i
sendmail_path = /usr/sbin/sendmail -t -i

И о чудо, из консоли письма уходят по команде:
php -r "mail('admin@test.ru', 'Test', 'Test');"

Внимание вопрос! Почему в с корня сайта в test.php письма не уходят (скрипт зависает до 504)? Содержание файла:
$result = mail("xkav@bitrix.ru", "TEST", "TEST", "From: test@mail.ru\r\n");
var_dump($result);

Логи файла msmtp.log:
Feb 26 17:00:03 host=smtp.yandex.ru tls=on auth=on user=info@test.ru

from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551189603-fRuatm3cyB-037m551h 1551189603-PEQME1I1IE-02aqPLvt' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:12:37 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190357-QWdxVjBzbe-CbBeN9J0 1551190357-w62lOC3Fir-Cak8XANP' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:12:39 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190359-0bDXDBoMVB-CdmeYJpO 1551190359-Z3pRkBVvdh-CckqFTgS' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:14:02 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru mailsize=957 smtpstatus=250 smtpmsg='250 2.0.0 Ok: queued on smtp3p.mail.yandex.net as 1551190442-2ppu0r6Wak-E2gm2iR6' exitcode=EX_OK
Feb 26 17:14:03 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru mailsize=873 smtpstatus=250 smtpmsg='250 2.0.0 Ok: queued on smtp4o.mail.yandex.net as 1551190443-l4HzALy1GG-E3Qqj7UX' exitcode=EX_OK
Feb 26 17:14:53 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190493-hmonlVSexL-ErB0jp98 1551190493-Dq9wDQnvMI-EqE8xoJl' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:14:56 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190496-6PmUzDXsdc-EuaWP5k8 1551190496-Vm5qS6N8FS-Euq4dvpS' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:15:37 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190537-2FeHZuIenY-Fbk0lZS2 1551190537-9MtZJgoKP2-Fbkqc5BK' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:16:13 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@yandex.ru mailsize=843 smtpstatus=250 smtpmsg='250 2.0.0 Ok: queued on smtp4o.mail.yandex.net as 1551190573-9cxKuJegOR-GCQixFgW' exitcode=EX_OK
Feb 26 17:16:28 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190588-1IxK6i581Q-GS7CFWUd 1551190588-wxndNEqoZC-GR4e6JKj' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:17:36 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=admin@test.ru smtpstatus=554 smtpmsg='554 5.7.0 Failed to authorize the sender 1551190656-7KCU4zAps1-HaXmZcAU 1551190656-KpG9eeGBU5-HaEiLNxD' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:17:58 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@mail.ru smtpstatus=554 smtpmsg='554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190678-vjtBwtXIlG-Hq4WRT3Y' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:18:02 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@yandex.ru smtpstatus=554 smtpmsg='554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190682-6UbGvzFHeS-Hwqq0h6e' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
фев 26 17:18:03 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@mail.ru mailsize=24997 smtpstatus=250 smtpmsg='250 2.0.0 Ok: queued on smtp1p.mail.yandex.net as 1551190683-Dp6XypmYLg-I348bNrW' exitcode=EX_OK
Feb 26 17:18:06 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@***.com smtpstatus=554 smtpmsg='554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190686-cKc5fXX1Vg-I3a0TMaD' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:18:11 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@yandex.ru smtpstatus=554 smtpmsg='554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190691-HKBQfLH2wd-I7qKRllN' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:18:15 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@rambler.ru smtpstatus=554 smtpmsg='554 5.7.1 [1] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190695-FMkLi0ViVV-IBa4bf8R' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:18:16 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@***.ru smtpstatus=554 smtpmsg='554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/1IrBc 1551190696-JOuMqgmi6v-IF4i4iKg' errormsg='the server did not accept the mail' exitcode=EX_UNAVAILABLE
Feb 26 17:18:55 host=smtp.yandex.ru tls=on auth=on user=info@test.ru from=info@test.ru recipients=***@mail.ru mailsize=10493214 smtpstatus=250 smtpmsg='250 2.0.0 Ok: queued on smtp4p.mail.yandex.net as 1551190735-Q4QFSX6RWj-Imk4Kirs' exitcode=EX_OK

Какие то уходят а какие то нет


text:
Q: System.TypeInitializationException was unhandled What does it mean when MS Visual Studio 2005 throws this message?
"The type initializer for 'RMDC.clsVariables' threw an exception."

Error log is as follows
System.TypeInitializationException was unhandled
  Message="The type initializer for 'RMDC.clsVariables' threw an exception."
  Source="RMDC"
  TypeName="RMDC.clsVariables"
  StackTrace:
       at RMDC.clsFunctions.getRegistryValue() in D:\Magnus Project\Project Backup\RMDC\RMDC\Class\clsFunctions.cs:line 704
       at RMDC.Program.Main() in ..\RMDC\RMDC\Program.cs:line 39
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

The class with error in question
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.Collections;

namespace RMDC
{
    class clsVariables
    {
        public SqlConnection conn = new SqlConnection();

        public SqlDataAdapter sAdapter = new SqlDataAdapter();
        public DataSet sDataSet = new DataSet();

        public static string sMessageBox = "";
        public static string sUsername;
        public static string sUserFullname;
        public static string sUserLogin;
        public static string sUserType;
        public static int sUserID;
        public static string sServer = "system-10";
        public static string sDatabase = "";
        public static string sDBUserID = "";
        public static string sDBPassword = "";
        public static bool sDontShow = false;
        public static string sCompanyName;
        public static string sContactName;
        public static string sCompanyAddress;
        public static string sPhoneNumber;
        public static string sFaxNumber;
        public static string sEmailAddress;
        public static string sWebAddress;
        public static string sOfficeCd = "01";
        public static int sfiscalYrId = 1;
        public static string sfiscalYr;
        public static DateTime sFiscalStart = DateTime.Today;
        public static DateTime sFiscalEnd = DateTime.Today;
        public static int sRoleId;

        public static byte[] m_barrImg;

        public static SqlConnection cnn = new SqlConnection();

        public OpenFileDialog openIMG = new OpenFileDialog();

        public static NepEngCalanderProvider.NepEngDateClass nepDate = new NepEngCalanderProvider.NepEngDateClass();
        public static NumberToWord.InWordsClass NumericWords = new NumberToWord.InWordsClass();

        public enum QueryType
        {
            Insert,
            Update,
            Delete
        }
    }
}

A: Well, it means what it said - something in the type initializer for RMDC.clsVariables (which is an unconventional name, btw) went bang.
This could be a static variable initializer:
static int foo = GetInitialValueForFoo();

or a static constructor:
static clsVariables
{
    DoSomething();
}

Whatever it was, it failed, leaving your type unusable.
If you run the code in the debugger, it should break in as soon as the exception is thrown, making it easier to work out what's going on.

A: You have to look at the exception's InnerException to find the reason that the TypeInitializationException got raised.  It's impossible to guess what's wrong without that information.
What ever code generated the error log needs a bit of work so that it doesn't forget to display the inner exception as well.  That's automatic if you use the Exception.ToString() method.  Implement an event handler for AppDomain.CurrentDomain.UnhandledException if necessary, log the value of e.ExceptionObject.ToString().