text:
Q: unable to send sms using java using sms gateway I am trying to send sms using java and the sms gateway used is fullonsms.com but its givingg error.Please tell me where did i do mistake.
package sms;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class MobileTry
{
private final String LOGIN_URL    = "http://fullonsms.com/home.php";
private final String SEND_SMS_URL = "http://fullonsms.com/home.php";
private final String LOGOUT_URL = "http://fullonsms.com/logout.php?LogOut=1";

private final int MESSAGE_LENGTH = 10;
private final int MOBILE_NUMBER_LENGTH = 140;
private final int PASSWORD_LENGTH = 10;

private String mobileNo;
private String password;
private DefaultHttpClient httpclient;
MobileTry(String username,String password)
{
 this.mobileNo = username;
 this.password = password;
 httpclient = new DefaultHttpClient();
}

public boolean isLoggedIn() throws IOException {
 // User Credentials on Login page are sent using POST
 // So create httpost object
 HttpPost httpost = new HttpPost(LOGIN_URL);

 // Add post variables to login url
 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 nvps.add(new BasicNameValuePair("MobileNoLogin", mobileNo));
 nvps.add(new BasicNameValuePair("LoginPassword", password));
 httpost.setEntity(new UrlEncodedFormEntity(nvps));

 // Execute request
 try{
 HttpResponse response = this.httpclient.execute(httpost);
 HttpEntity entity = response.getEntity();
 if (entity != null) {
     System.out.println("entity " + slurp(entity.getContent(), 10000000));
     System.out.println("entity " + response.getStatusLine().getStatusCode());

  return true;
 }
 }
 catch(Exception e)
 {
     e.printStackTrace();
     System.out.println(e);
 }
 //Check response entity
return false;

}

public boolean sendSMS(String toMobile,String message) throws IOException {
 HttpPost httpost = new HttpPost(SEND_SMS_URL);
 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 nvps.add(new BasicNameValuePair("MobileNos", toMobile));
nvps.add(new BasicNameValuePair("Message", message));

httpost.setEntity(new UrlEncodedFormEntity(nvps));
 HttpResponse response = this.httpclient.execute(httpost);
 HttpEntity entity = response.getEntity();
 if(entity != null) {
                       System.out.println("entity " + slurp(entity.getContent(), 10000000));
                       System.out.println("entity " + response.getStatusLine().getStatusCode());
  return true;
 }
 return false;
}

public boolean logoutSMS() throws IOException {
 HttpGet httpGet = new HttpGet(LOGOUT_URL);
 HttpResponse response;
 response = this.httpclient.execute(httpGet);
 HttpEntity entity = response.getEntity();
 if (entity != null) {
  System.out
    .println("entity " + slurp(entity.getContent(), 10000000));
  System.out.println("entity "
    + response.getStatusLine().getStatusCode());
  return true;
 }
 return false;
}

public static String slurp(final InputStream is, final int bufferSize)
{
  final char[] buffer = new char[bufferSize];
  final StringBuilder out = new StringBuilder();
  try {
    final Reader in = new InputStreamReader(is, "UTF-8");
    try {
      for (;;) {
        int rsz = in.read(buffer, 0, buffer.length);
        if (rsz < 0)
          break;
        out.append(buffer, 0, rsz);
      }
    }
    finally {
      in.close();
    }
  }
  catch (UnsupportedEncodingException ex) {
    /* ... */
  }
  catch (IOException ex) {
      /* ... */
  }
  return out.toString();
}

/**
 * @param args
 */
public static void main(String[] args) {
 String username = "number";
 String password = "password";
 String toMobile = "number";

 String toMessage = "Message Sent";

 MobileTry fullOnSMS = new MobileTry(username, password);
 try{
  if(fullOnSMS.isLoggedIn() && fullOnSMS.sendSMS(toMobile,toMessage))
  {
   fullOnSMS.logoutSMS();
   System.out.println("Message was sent successfully " );
  }
  System.exit(0);
 }

 catch(IOException e)
 {
     System.out.println(e);
     System.out.println("Unable to send message, possible cause: " + e.getMessage());
 }
}
}

following is the error
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.apache.http.impl.client.CloseableHttpClient.<init>(CloseableHttpClient.java:60)
    at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:271)
    at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
    at sms.MobileTry.<init>(MobileTry.java:35)
    at sms.MobileTry.main(MobileTry.java:142)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 5 more

A: This is caused by missing of commons-logging-xxx.jar. Please add it to your classpath. If you use Maven then,
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
</dependency>

Will add the dependency to your project. Hope this helps!


text:
Q: Kraken exchange futures API - Generate Authentication Strings - Authentication Error. NodeJs I'm trying to generate a signed message for private endpoints. From Kraken Futures API documentation steps are:

*

*Concatenate postData + nonce + endpointPath

*Hash the result of step 1 with the SHA-256 algorithm

*Base64-decode your api_secret

*Use the result of step 3 to hash the result of step 2 with the
HMAC-SHA-512 algorithm

*Base64-encode the result of step 4

This is what I have done:
//Definition of arguments
const secret = 'SecretGeneratedByKraken...rEqyX3nPw3UURLCu/M'
var nonce =  new Date() * 1000;
const path = 'https://futures.kraken.com/derivatives/api/v3/' + fills;
const signature = getMessageSignature(path,params,secret,nonce);

//Auth function
getMessageSignature = (path, params, secret, nonce) => {
    var message = qs.stringify(params);
    var concat = message + nonce + path;  // 1
    var hash = crypto.createHash('sha256');
    var hash_digest   = hash.update(concat).digest('binary'); // 2
    var secret_decoded = Buffer.from(secret, 'base64'); // 3
    var hmac = crypto.createHmac('sha512', hash_digest);
    var hmac_digest = hmac.update(secret_decoded, 'binary').digest('base64'); //4 and 5
    return hmac_digest;
}

Double checked that I'm passing the right arguments, any help will be much appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PyInstaller newbie: hello world I'm trying to use PyInstaller v2.1 to create a single executable out of a simple hello world script (Python 2.7). The script, hello.py, has just one line:
print 'Hello, World!'

I then open a command window in the folder containing the script and enter:
pyinstaller -F hello.py

I get the following output:
C:\Users\chris\workspace\HelloPy>pyinstaller -F hello.py
43 INFO: wrote C:\Users\chris\workspace\HelloPy\hello.spec
66 INFO: Testing for ability to set icons, version resources...
79 INFO: ... resource update available
83 INFO: UPX is not available.
115 INFO: Processing hook hook-os
299 INFO: Processing hook hook-time
304 INFO: Processing hook hook-cPickle
402 INFO: Processing hook hook-_sre
585 INFO: Processing hook hook-cStringIO
721 INFO: Processing hook hook-encodings
741 INFO: Processing hook hook-codecs
1332 INFO: Extending PYTHONPATH with C:\Users\chris\workspace\HelloPy
1332 INFO: checking Analysis
1539 INFO: checking PYZ
1644 INFO: checking PKG
1655 INFO: building because C:\Users\chris\workspace\HelloPy\build\hello\hello.exe.manifest changed
1656 INFO: building PKG (CArchive) out00-PKG.pkg
7801 INFO: checking EXE
7803 INFO: rebuilding out00-EXE.toc because pkg is more recent
7803 INFO: building EXE from out00-EXE.toc
7809 INFO: Appending archive to EXE C:\Users\chris\workspace\HelloPy\dist\hello.exe

The build and dist folder are created as expected, as is the executable. I try to run it and get the following output:
C:\Users\chris\workspace\HelloPy>cd dist

C:\Users\chris\workspace\HelloPy\dist>hello
WARNING: file already exists but should not:      C:\Users\chris\AppData\Local\Temp\_MEI58962\include\pyconfig.h
Hello, World!

If I run pyinstaller instead without the single executable switch, i.e. without the -F then I don't get the "WARNING: file already exists"
I'm probably missing something really obvious but I've searched around and can't seem to find this problem anywhere else. Any help or a pointer to the solution elsewhere would be much appreciated.

A: There was a ticket reported to the PyInstaller team here that points to this SO answer as a workaround:
Pyinstaller --onefile warning pyconfig.h when importing scipy or scipy.signal
You modify your spec file with the following block under the a=Analysis line:
for d in a.datas:
    if 'pyconfig' in d[0]:
        a.datas.remove(d)
        break

That should work for you as it seems to work for most.
Personally I prefer py2exe. Here is a link to a "Hello, World" example do to the exact same thing you are trying to achieve: http://www.py2exe.org/index.cgi/Tutorial


text:
Q: how can i implement a concurrent execution queue class? I need to have a class that will execute actions in thread pool, but these actions should be queued. For example:

method 1
method 2
method 3

When someone called method 1 from his thread he can also call method 2 or method 3 and they all 3 methods can be performed concurrently, but when another call came from user for method 1 or 2 or 3, this time the thread pool should block these call, until the old ones execution is completed.
Something like the below picture:

Should I use channels?

A: To should i use channels?, the answer is yes, but there are other features available too.
Dataflow
.NET already offers this feature through the TPL Dataflow classes. You can use an ActionBlock class to pass messages (ie data) to a worker method that executes i the background with guaranteed order and a configurable degree of parallelism. Channels are a new feature which does essentially the same job.
What you describe is actually the simplest way of using an ActionBlock - just post data messages to it and have it process them one by one :
void Method1(MyDataObject1 data){...}

var block=new ActionBlock<MyDataObject1>(Method1);

//Start sending data to the block

for(var msg in someListOfItems)
{
    block.PostAsync(msg);
}

By default, an ActionBlock has an infinite input queue. It will use only one task to process messages asynchronously, in the order they are posted.
When you're done with it, you can tell it to Complete() and await asynchronously for all remaining items to finish processing :
block.Complete();
await block.Completion;

To handle different methods, you can simply use multiple blocks, eg :
var block1=new ActionBlock<MyDataObject1>(Method1);
var block2=new ActionBlock<MyDataObject1>(Method2);

Channels
Channels are a lower-level feature than blocks. This means you have to write more code but you get far better control on how the "processing blocks" work. In fact, you can probably rewrite the TPL Dataflow library using channels.
You could create a processing block similar to an ActionBlock with the following (a bit naive) method:
ChannelWriter<TIn> Work(Action<TIn> action)
{
    var channel=Channel.CreateUnbounded<TIn>();
    var workerTask=Task.Run(async ()=>{
        await foreach(var msg in channel.Reader.ReadAllAsync())
        {
            action(msg);
        }
    })

    var writer=channel.Writer;

    return writer;
}

This method creates a channel and runs a task in the background to read data asynchronously and process them. I'm cheating "a bit" here by using await foreach and ChannelReader.ReadAllAsync() which are available in C#8 and .NET Core 3.0.
This method can be used like a block :
ChannelWriter<DataObject1> writer1 = Work(Method1);

foreach(var msg in someListOfItems)
{
    writer1.WriteAsync(msg);
}

writer1.Complete();

There's a lot more to Channels though. SignalR for example uses them to allow streaming of notifications to the clients.

A: Here is my suggestion. For each synchronous method, an asynchronous method should be added. For example the method FireTheGun is synchronous:
private static void FireTheGun(int bulletsCount)
{
    var ratata = Enumerable.Repeat("Ta", bulletsCount).Prepend("Ra");
    Console.WriteLine(String.Join("-", ratata));
}

The asynchronous counterpart FireTheGunAsync is very simple, because the complexity of queuing the synchronous action is delegated to a helper method QueueAsync.
public static Task FireTheGunAsync(int bulletsCount)
{
    return QueueAsync(FireTheGun, bulletsCount);
}

Here is the implementation of QueueAsync. Each action has its dedicated SemaphoreSlim, to prevent multiple concurrent executions:
private static ConcurrentDictionary<MethodInfo, SemaphoreSlim> semaphores =
    new ConcurrentDictionary<MethodInfo, SemaphoreSlim>();

public static Task QueueAsync<T1>(Action<T1> action, T1 param1)
{
    return Task.Run(async () =>
    {
        var semaphore = semaphores
            .GetOrAdd(action.Method, key => new SemaphoreSlim(1));
        await semaphore.WaitAsync();
        try
        {
            action(param1);
        }
        finally
        {
            semaphore.Release();
        }
    });
}

Usage example:
FireTheGunAsync(5);
FireTheGunAsync(8);

Output:

Ra-Ta-Ta-Ta-Ta-Ta
  Ra-Ta-Ta-Ta-Ta-Ta-Ta-Ta-Ta

Implementing versions of QueueAsync with different number of parameters should be trivial.

Update: My previous implementation of QueueAsync has the probably undesirable behavior that executes the actions in random order. This happens because the second task may be the first one to acquire the semaphore. Below is an implementation that guaranties the corrent order of execution. The performance could be bad in case of high contention, because each task is entering a loop until it takes the semaphore in the right order.
private class QueueInfo
{
    public SemaphoreSlim Semaphore = new SemaphoreSlim(1);
    public int TicketToRide = 0;
    public int Current = 0;
}

private static ConcurrentDictionary<MethodInfo, QueueInfo> queues =
    new ConcurrentDictionary<MethodInfo, QueueInfo>();

public static Task QueueAsync<T1>(Action<T1> action, T1 param1)
{
    var queue = queues.GetOrAdd(action.Method, key => new QueueInfo());
    var ticket = Interlocked.Increment(ref queue.TicketToRide);
    return Task.Run(async () =>
    {
        while (true) // Loop until our ticket becomes current
        {
            await queue.Semaphore.WaitAsync();
            try
            {
                if (Interlocked.CompareExchange(ref queue.Current,
                    ticket, ticket - 1) == ticket - 1)
                {
                    action(param1);
                    break;
                }
            }
            finally
            {
                queue.Semaphore.Release();
            }
        }
    });
}

A: What about this solution?
public class ConcurrentQueue
{
    private Dictionary<byte, PoolFiber> Actionsfiber;
    public ConcurrentQueue()
    {
        Actionsfiber = new Dictionary<byte, PoolFiber>()
        {
            { 1, new PoolFiber() },
            { 2, new PoolFiber() },
            { 3, new PoolFiber() },
        };
        foreach (var fiber in Actionsfiber.Values)
        {
            fiber.Start();
        }
    }

    public void ExecuteAction(Action Action , byte Code)
    {
        if (Actionsfiber.ContainsKey(Code))
            Actionsfiber[Code].Enqueue(() => { Action.Invoke(); });
        else
            Console.WriteLine($"invalid byte code");
    }

}

public static void SomeAction1()
{
    Console.WriteLine($"{DateTime.Now} Action 1 is working");
    for (long i = 0; i < 2400000000; i++)
    {

    }
    Console.WriteLine($"{DateTime.Now} Action 1 stopped");
}

public static void SomeAction2()
{
    Console.WriteLine($"{DateTime.Now} Action 2 is working");
    for (long i = 0; i < 5000000000; i++)
    {

    }
    Console.WriteLine($"{DateTime.Now} Action 2 stopped");
}

public static void SomeAction3()
{
    Console.WriteLine($"{DateTime.Now} Action 3 is working");
    for (long i = 0; i < 5000000000; i++)
    {

    }
    Console.WriteLine($"{DateTime.Now} Action 3 stopped");
}

public static void Main(string[] args)
{
    ConcurrentQueue concurrentQueue = new ConcurrentQueue();

    concurrentQueue.ExecuteAction(SomeAction1, 1);
    concurrentQueue.ExecuteAction(SomeAction2, 2);
    concurrentQueue.ExecuteAction(SomeAction3, 3);
    concurrentQueue.ExecuteAction(SomeAction1, 1);
    concurrentQueue.ExecuteAction(SomeAction2, 2);
    concurrentQueue.ExecuteAction(SomeAction3, 3);

    Console.WriteLine($"press any key to exit the program");
    Console.ReadKey();
}

the output :

8/5/2019 7:56:57 AM Action 1 is working
8/5/2019 7:56:57 AM Action 3 is working
8/5/2019 7:56:57 AM Action 2 is working
8/5/2019 7:57:08 AM Action 1 stopped
8/5/2019 7:57:08 AM Action 1 is working
8/5/2019 7:57:15 AM Action 2 stopped
8/5/2019 7:57:15 AM Action 2 is working
8/5/2019 7:57:16 AM Action 3 stopped
8/5/2019 7:57:16 AM Action 3 is working
8/5/2019 7:57:18 AM Action 1 stopped
8/5/2019 7:57:33 AM Action 2 stopped
8/5/2019 7:57:33 AM Action 3 stopped

the poolFiber is a class in the ExitGames.Concurrency.Fibers namespace.
more info :
How To Avoid Race Conditions And Other Multithreading Issues?


text:
Q: Required form for integral of exponentially weighted cosine distribution across $xy$ plane I am currently trying to find the required form of an integral for my code. In this case, I have an $xy$ plane ranging from $-1$ to $1$ in both dimensions and fixed at $z = 0$. At each point, I am assuming that I have a $\exp(-(x^2 + y^2))\cos(\theta_{emiss})$ distribution where $x$ and $y$ are the aforementioned coordinates on the plane and $\theta_{emiss}$ is an angle defined relative to the normal vector of the plane in the $+z$ direction. I am also assuming this distribution is azimuthally symmetric.
What I would like to do is to see what would the integrated distribution look like as a function of $\theta$ and $\phi$ at a distance $d$ away from the origin. So for that I would need to set up some integral, but I am unsure what the required form would be in order to do this. Does anyone have any ideas?
Thanks in advance

Edit:
For a physical context, this problem represents a Gaussian temperature distribution on a finite plane. Within this problem, I am also assuming that emission occurs from the surface with a emission distribution proportional to cos($\theta$), as defined above, and the emission strength is proportional to the value of the Gaussian at the coordinates ($x$,$y$). This emission also has a 1/$r^2$ dependence where $r$ is the distance between an observation point ($x_0,y_0,z_0$) and a point on the plane $(x,y,0)$
Now assuming I have a hemispherical shell with a radius, $d$, from the origin of the plane $(0,0,0)$ (where $d$ is much larger than the size of the plane), I would like to know if an integral expression can be found to calculate the distribution across the hemispherical screen as a function of polar angle, $\theta_{screen}$ and the azimuthal angle, $\phi_{screen}$.
I am also assuming that emission occurs in the $+z$ direction and that the screen spans from $0 - 2\pi$ in $\phi_{screen}$ and $0-\pi/2$ in $\theta_{screen}$.

A: Here's a model for the problem after the edit. We break down the plane in infinitesimal sized black bodies. The power emitted per unit solid angle of the plane per unit solid angle can be described by
$$dP(x,y,0)=\sigma (T(x,y))^4\frac{\cos\theta}{\pi}d\Omega d xdy$$
Here $d\Omega=\sin \theta d\theta d\phi$.
Now consider an infinitesimal part of the hemispherical shell detector located at $(\theta_s,\phi_s)$, which subtends a solid angle determined by
$$d\Omega=\hat{n}\cdot \frac{(\mathbf{r}-\mathbf{r}')}{|\mathbf{r}-\mathbf{r}'|^3}dS$$
where $\hat{n}=(\sin\theta_s\cos\phi_s, \sin\theta_s\sin\phi_s, \cos\theta_s)$ is the outward normal vector to the spherical surface, $dS=R^2\sin\theta_s d\theta_s d\phi_s$, $\mathbf{r}=R\hat{n}$ is the position of the spherical shell infinitesimal and $\mathbf{r'}=(x',y',0)$ denotes an arbitrary surface point. To obtain the distribution of luminosity per unit area of the semispherical detector  we need to integrate over the whole luminous plane surface to take into account all the infinitesimal contributions:
$$\begin{align}&dP_{\text{received}}(\theta_s,\phi_s)=dS \int\int dx'dy' dP_{\hat{n}, \mathbf{r}}(x',y',0)\\\Rightarrow &\frac{dP_\text{received}}{dS}(\theta_s,\phi_s)=\frac{\sigma}{\pi }\int\int dx'dy'T^4(x',y')\frac{[\hat{n}\cdot(\mathbf{r}-\mathbf{r'})][\hat{z}\cdot(\mathbf{r}-\mathbf{r'})]}{|\mathbf{r}-\mathbf{r'}|^4}\end{align} $$
For large detector radius $R$, one requires a multipole expansion of the kernel $\frac{[\hat{n}\cdot(r-r')][\hat{z}\cdot(r-r')]}{|r-r'|^4}$ to obtain a reasonable approximation for large observer distances.


text:
Q: Spark TaskMetrics bytesRead SparkListenerTaskEnd provides a val to get the TaskMetrics. In turn, TaskMetrics provides access to various metrics as well. When I try to use InputMetrics of TaskMetrics to get the bytes read I see 0 all the time, even though I'm reading data from hdfs. I do use my custom-made source (not parquet or avro) to pump data into Dataframe.
Is there something I'm missing here? Would it not be possible to monitor the amount of data that has been read for that particular task?
VK


text:
Q: Symmetrical encryption of email attributes with Devise authentication I try to encrypt email attribute for User model. email is used by Devise.
class User < ActiveRecord::Base
end

devise :database_authenticatable, :registerable, :confirmable,
    :recoverable, :rememberable, :trackable
To encryption I use attr_encrypted gem: https://github.com/attr-encrypted/attr_encrypted
I'd like to use this gem but I'm not attached to.
Actually I'm receiving a lot of issues related with this.
Does anyone has encrypted email attribute in Rails project where Devis was used, ideally using attr_encrypted ? What was your approach to that ?


text:
Q: A subspace $Y$ of a Banach space $X$ is complete iff the set $Y$ is closed in $X$.
A subspace $Y$ of a Banach space $X$ is complete iff the set $Y$ is
  closed in $X$.

Proof:⇒)  If $x∈cl(Y)$ there exists a sequence $x_
n$ in Y which converges to x and as a consquence is a Cauchy sequence (in X and Y). But Y is complete, so xn converges in Y to a point $x′$. According to the uniqueness of the limit, $x=x′∈Y$. That is, $cl(Y)⊂Y$ and hence, $Y$ is closed.
⇐) Let $x_n$ be a Cauchy sequence in $Y$. The limit $x$ of $x_n$ exists in $X$ because $X$ is complete. As $Y$ is complete, contains all its limit points, so $x∈Y$ and so, $Y$ is complete.
It may be obvious but i'm not getting Why $x_n$ is a cauchy sequence??

A: This is basic metric space theory.  Suppose $x_n\to x$.  Given $\varepsilon>0$ there is some $N\in\mathbb N$ such that $\|x_n-x\|<\varepsilon/2$ for $n\geq N$.  Then for $n,m\geq N$ we have
$$\|x_n-x_m\|\leq\|x_n-x\|+\|x-x_m\|<\varepsilon.$$
Therefore the sequence $(x_n)$ is Cauchy.


text:
Q: Content height is not automatically adjusted when scrolling I am trying to create a modal that has a footer and an header. The content has two columns: LeftSection and RightSection. I want to have the second column fill the height of the content depending on what the first columns height is (which can differ based on content). From the snippet, this means to have the black div go down as much as the red one does.

.Container {
  margin: auto auto;
  width: 80vw;
  height: 250px;
  background-color: #8080801a;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.Header {
  height: 50px;
  width: 100%;
  background-color: #61dafb;
}

.FlexContainer {
  flex: 1;
  display: flex;
  overflow: auto;
}

.LeftSection {
  width: 200px;
  height: 400px;
  background: red;
}

.RightSection {
  width: 100%;
  background-color: black;
}

.Footer {
  height: 50px;
  background-color: blue;
  width: 100%;
}

A: Do you want this?

.Container {
  margin: auto auto;
  width: 80vw;
  height: 250px;
  background-color: #8080801a;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.Header {
  height: 50px;
  width: 100%;
  background-color: #61dafb;
}

.FlexContainer {
  flex: 1;
  display: flex;
  overflow: auto;
}

.LeftSection {
  width: 200px;
  height: 400px;
  background: red;
  position: sticky;
  top: 0;
}

.RightSection {
  width: 100%;
  background-color: black;
  position: sticky;
  top: 0;
}

.Footer {
  height: 50px;
  background-color: blue;
  width: 100%;
}


text:
Q: pyhon sort lists of dicts by n values and case insensitive This sorts by two values of the dicts:
results = sorted(results, key=itemgetter('category', 'elementName'))

How can I make the sort case-insensitive?

A: This will probably work for you
results = sorted(results, key=lambda x: (x["category"], x["elementName"].lower()))

A: str.casefold could be useful here:
from operator import itemgetter

results = [{'category': 'a', 'elementName': "B"},
           {'category': 'a', 'elementName': 'c'},
           {'category': 'a', 'elementName': 'a'}]

results = sorted(
    results,
    key=lambda r: tuple(
        map(str.casefold, itemgetter('category', 'elementName')(r))
    )
)
print(results)

Output:
[{'category': 'a', 'elementName': 'a'}, {'category': 'a', 'elementName': 'B'},
 {'category': 'a', 'elementName': 'c'}]

A: Try making copies where every key is in lower case, you could discard them later.


text:
Q: How to use NTILE function to create two groups for two columns where one is a nested NTILE of the other? I have financial data that I want to categorise (using NTILE()) by two columns that contain percentage values (risk, debt_to_assets). My end goal is that I want to aggregate some other column (profit) by the two categories, but that's not related to my issue at hand. The data looks something like this:

profit
risk
debt_to_assets

7000
0.10
0.20

1000
0.40
0.70

3000
0.15
0.50

4000
0.30
0.30

2000
0.20
0.60

The issue I'm trying to solve is that I want the categories to be nested such that, in addition to the population distribution being uniform, the categories of the inner quantile are consistent across the categories of the outer quantile in terms of the range that defines the categories (i.e. I want the min and max value for the inner categories (x0, y0), (x1, y0), (x2, y0), ... to all be the same or as close as possible, where the x's are the outer category and the y's are the inner category).
Ideally if I were to aggregate the columns used for the NTILE() function (using 3 inner categories and 3 outer categories for example) I'd want a table that resembles the following:

risk_cat
dta_cat
min_risk
max_risk
min_dta
max_dta
count

1
1
0.00
0.33
0.00
0.33
100

1
2
0.00
0.33
0.34
0.67
100

1
3
0.00
0.33
0.68
1.00
100

2
1
0.34
0.67
0.00
0.33
100

2
2
0.34
0.67
0.34
0.67
100

2
3
0.34
0.67
0.68
1.00
100

3
1
0.68
1.00
0.00
0.33
100

3
2
0.68
1.00
0.34
0.67
100

3
3
0.68
1.00
0.68
1.00
100

These are the solutions I've tried but they only solve part of the issue, not the whole thing:
SELECT *,
    NTILE(3) OVER (
        ORDER BY risk
    ) AS risk_cat,
    NTILE(3) OVER (
        ORDER BY debt_to_assets
    ) AS dta_cat
FROM my_table

This would result in an aggregated table like this:

risk_cat
dta_cat
min_risk
max_risk
min_dta
max_dta
count

1
1
0.00
0.33
0.00
0.33
10

1
2
0.00
0.33
0.34
0.67
55

1
3
0.00
0.33
0.68
1.00
180

2
1
0.34
0.67
0.00
0.33
135

2
2
0.34
0.67
0.34
0.67
140

2
3
0.34
0.67
0.68
1.00
100

3
1
0.68
1.00
0.00
0.33
130

3
2
0.68
1.00
0.34
0.67
110

3
3
0.68
1.00
0.68
1.00
40

The problem is that the count across the two categories isn't uniform.
WITH outer_cat AS (
    SELECT *,
        NTILE(3) OVER (
            ORDER BY risk
        ) AS risk_cat
    FROM my_table
)
SELECT *,
    NTILE(3) OVER(
        PARTITION BY risk_cat
        ORDER BY debt_to_assets
    ) AS dta_cat
FROM outer_cat

The aggregated table for this might resemble the following:

risk_cat
dta_cat
min_risk
max_risk
min_dta
max_dta
count

1
1
0.00
0.33
0.10
0.70
100

1
2
0.00
0.33
0.71
0.90
100

1
3
0.00
0.33
0.91
1.00
100

2
1
0.34
0.67
0.05
0.35
100

2
2
0.34
0.67
0.36
0.60
100

2
3
0.34
0.67
0.61
0.90
100

3
1
0.68
1.00
0.00
0.25
100

3
2
0.68
1.00
0.26
0.50
100

3
3
0.68
1.00
0.51
0.80
100

The problem this time is that the min and max values for the inner category vary to much across the outer category.
SELECT *,
    NTILE(9) OVER(
        ORDER BY risk, debt_to_assets
    ) AS dual_cat
FROM my_table

The aggregated table for this looks something like the following:

dual_cat
min_risk
max_risk
min_dta
max_dta
count

1
0.00
0.11
0.55
1.00
100

2
0.12
0.22
0.35
1.00
100

3
0.23
0.33
0.15
1.00
100

4
0.34
0.44
0.40
1.00
100

5
0.45
0.55
0.10
1.00
100

6
0.56
0.66
0.10
0.95
100

7
0.67
0.77
0.05
1.00
100

8
0.78
0.88
0.20
1.00
100

9
0.89
1.00
0.00
1.00
100

This was just a last attempt at a solution after the previous two didn't work. This attempt didn't capture any of the behaviour that I was looking for.
Is there a solution to my problem that I'm not seeing?


text:
Q: grails textfield with formatDate I have the following textfield in my gsp page that does not work as expected:
<g:textField name="startTime"
     value="${formatDate(date: occurrenceStart ? new Instant(occurrenceStart).toDate() : eventInstance?.startTime, format: 'dd/MM/yyyy hh:mm a')}"
     class="datetime" />

I'm using the source code found here, but each time I select a date and time, the date is shown as MM/dd/yyyy. Where is the place in which I need to change the format?
EDIT:
Usually I use Mozilla Firefox to test my project. If I use Google Chrome browser, I have the following formatting date(choosing the 12th of January 2014, 5:00 AM) after the change suggested in Adavis answer:
12/January/20142014 hh:01 a 05:00 am
If I remove the code added, I have the same behaviour described above, with formatting MM/dd/yyyy

A: In this file: https://github.com/craigburke/google-calendar-grails/blob/master/web-app/js/calendar.js, line 60, in setupDatePickers(), you need to add your date format to the default options of datetimepicker.  See below...
function setupDatePickers() {
    $("input.datetime").datetimepicker({
        ampm: true,
        stepMinute: 15,
        dateFormat: 'dd/MM/yyyy hh:mm a'
    });
}

A: Solved with the following code:
function setupDatePickers() {
$.datepicker.setDefaults({
    dateFormat: 'dd/mm/yy'
});
$("input.datetime").datetimepicker({
    ampm: true,
    stepMinute: 15
});

}


text:
Q: Python: Return certain class variable in array from linked list
Problem

I am working with class objects in a single linked list. It could be nice to have a method that returns the specific variables requested. Is this possible?

So far I am having a method under the Linked List class:
Works
class SLinkedList:
    def __init__(self):
        self.headval = None

    def getListZ(self,):
        val = self.headval
        arr = []
        while val is not None:
            arr.append(val.val.Z)
            val = val.nextval
        return arr

Wants:
class SLinkedList:
    def __init__(self):
        self.headval = None

    def getListZ(self,var):
        item = self.headval
        arr = []
        while val is not None:
            arr.append(item.val.var)
            item = item.nextval
        return arr

Questions

*

*How can I write a method that returns a list of certain variables from the class objects? Let's say that I want to return a list of all the impedances. How would I do that?

Workaround

I can get a list for any desired variable (in the example, the list is called from another class):
vals1 = [item.val.val1 for item in self.list]

Iteration is possible with the following method:
    def __iter__(self):
        node = self.headval
        while node:
            yield node
            node = node.nextval

However
I would still be able to dynamically print several variables from my object in a linked list. How can I make this a variable instead of hard-coding this as I have done below?

Code

Script
class Node:
    def __init__(self, val=None):
        self.val = val
        self.nextval = None

class SLinkedList:
    def __init__(self):
        self.headval = None

    def __iter__(self):
        node = self.headval
        while node:
            yield node
            node = node.nextval

    # Function to add newnode
    def AtEnd(self, newdata):
        NewNode = Node(newdata)
        if self.headval is None:
            self.headval = NewNode
            return
        laste = self.headval
        while(laste.nextval):
            laste = laste.nextval
        laste.nextval=NewNode

    # Print the linked list
    def listprint(self,):
        printval = self.headval
        while printval is not None:
            try:
                print (printval.val.nodes,printval.val.Ctype,printval.val.Z,sep='\t')
            except:
                print (printval.val.nodes,printval.val.Ctype,sep='\t')
            printval = printval.nextval


text:
Q: How would an ASP.NET MVC3 application call some code when controller action is cancelled on client timeout? There's an ASP.NET MVC3 application where some of controller actions use an external mechanism for processing the input data. The input data is first saved into a temporary file and then an external program is being run and the path to the temporary file is passed at the command line. This is done using System.Diagnostics.Process class.
The external program usually exits promptly - earlier than in one second after it was started, so no problem, just wait for its completion with Process.WaitForProcessExit() and the dispose the Process object.
It gets harder if the external program hangs and doesn't exit in a timely manner. It happens very very rarely, but when it happens then Process.WaitForProcessExit() hangs too and the controller action runs for some time but then the client timeout happens and the controller action is cancelled but there's no way I could find that would cause forcible termination of the external program. I could of cause use Process.Kill() but I have to wire this call into somewhere such that it's invoked when the controller action is cancelled because of client timeout.
I tried to override Controller.OnException() but it looks like it's not invoked in this scenario.
How can ASP.NET MVC3 code be changed such that it calls some custom code (such as external program termination) when a client timeout occurs?

A: I've checked the solution from the comments based on Task - it is useful when you have blocking operation. You can avoid the blocking call WaitForProcessExit() and create more simple solution.
The solution is in the form of wrapper.
public enum SafeProcessState { Exit = 1, Killed = 2 }

public class SafeProcess
{
    private readonly Process process;
    private readonly Func<bool> killPredicate;

    public SafeProcess(Func<bool> killPredicate, Process process)
    {
        this.killPredicate = killPredicate;
        this.process = process;
    }

    public async Task<SafeProcessState> WaitAsync()
    {
        var state = SafeProcessState.Exit;

        while (true)
        {
            await Task.Delay(100);
            if (this.killPredicate())
            {
                state = SafeProcessState.Killed;
                if (this.process.HasExited == false)
                {
                    this.process.Kill();
                }
                break;
            }
            else if (this.process.HasExited)
            {
                break;
            }
        }

        return state;
    }
}

This is how you can use it in ASP NET MVC action (Not .NET CORE);
public async ...... ActionName()
{
  var process = Process.Start("....");
  var wrapper = new SafeProcess(() => HttpContext.Current.Response.IsClientConnected == false, process);

 var state = await wrapper.WaitAsync();
}

It basically waits (by checking every 100ms) for the process to exit or the client to disconnect and returns information about the exit reason - Exit or Killed.
Kills the process if the user has disconnected.

Using async / await Task.Delay ensures we will free the execution thread and doing so for 100 ms is purely done for performance reasons.
NOTE: You can get into scenario of killing already exited process, which will throw exception (you have concurrency between the process and your asp net action). You you will need some synchronization between the process execution and .Kill() ... or you can wrap the call in try / catch.
If you choose the try / catch forget scenario, definitely log the situation.


text:
Q: ResKit iOS - Application crash when i receive HTTP Error Code in RKObjectManager postObject method i'm using RKObjectManager to make iOS RESTful requests to map responses to local objects. When i receive HTTP error codes like 400, RestKit sends data to RKObjectLoaderDelegate method:
- (void)objectLoaderDidLoadUnexpectedResponse:(RKObjectLoader *)objectLoader

but immediately afterwards the application crash without any reason.
The debugger doesn't give me any more information, where and why the application crashes.
To make the request
RKObjectManager * objectManager = [RKObjectManager objectManagerWithBaseURL:SERVER_BASE_URL];

RKDynamicRouter* router = [[RKDynamicRouter new] autorelease];
objectManager.router = router;
objectManager.format = RKMappingFormatJSON;

[router routeClass:[RKTUser class] toResourcePath:@"sessions" forMethod:RKRequestMethodPOST];

[[RKObjectManager sharedManager] postObject:user delegate:self];

Anyone with the same problem?

A: I just updated RestKit framework, and it start to work.


text:
Q: Xcode 8: different entitlements for each scheme causing errors I found an issue with Xcode 8 where .entitlements files are not being referenced properly for each scheme.  Basically, my Debug .entitlements file is being referenced for my Release scheme.  This is causing an issue because we implemented the new Rich push notification logic and that requires the use of App groups.
I am using two different teams (Development and Production), so there will be two specific App Groups.

A: Though Tim's solution mostly worked for me, Xcode got all upset and said automatic provisioning couldn't resolve issues with the entitlements file. I don't think it liked the variable.
Our solution was to:

*

*Enable all app groups on every target that needed access.

*Define a project-level user-defined setting called PROJECT_APP_GROUP for the app group name by going to Project -> Build Settings, clicking the "+" button, and selecting "Add User-Defined Setting."

*Set a variable in the info.plist file for each target that needs access to your app group.

*Then access the correct app group at runtime by getting the APP_GROUP variable from your target's info.plist file.
+ (NSString *)appGroupIdentifier
{
    // this method returns the app group identifier by fetching it from the info.plist file.
    // this string is dynamic based on build scheme. for instance group.ourApp vs. group.ourApp-dev
    return [[[NSBundle mainBundle] infoDictionary] valueForKey:@"APP_GROUP"];
}

OR
Now that I think of it, if you have preprocessor macros set up for each build, it might be easier to do something like:
+ (NSString *)appGroupIdentifier
{
#ifdef BUILD_DEV
    return @"group.myApp-dev";
#elif BUILD_STAGING
    return @"group.myApp-staging";
#else
    return @"group.myApp";
#endif
}

A: I found a solution.  Make one .entitlements file add this:
<key>aps-environment</key>
<string>$(APS_ENVIRONMENT)</string>
<key>com.apple.security.application-groups</key>
<array>
    <string>$(APP_GROUP)</string>
</array>

Then in Target > Build settings
Set the same .entitlements file in Signing > Code Signing Entitlements
Add User-Defined Setting for APS_ENVIRONMENT and APP_GROUP setting the correct group for each target.
So, based on the target Xcode will use what you set for APS_ENVIRONMENT and APP_GROUP.
You can do this in plist too...did some amazing clean up today.


text:
Q: Iterate over all the UITableCells given a section id Using Swift, how can I iterate over all the UITableCells given a section id (eg: all cells in section 2)?
I only see this method: tableView.cellForRowAtIndexPath, which returns 1 cell given the absolute index, so it doesn't help.
Is there an elegant and easy way?
Note: I want to set the AccesoryType to None for all of the cells in a section, programatically, say: after a button is clicked, or after something happends (what happends is not relevant for the question)
I have the reference for the UITableView and the index of the section.

A: For Swift 4 I have been using something along the lines of the following and it seems to work pretty well.
for section in 0...self.tableView.numberOfSections - 1 {
            for row in 0...self.tableView.numberOfRows(inSection: section) - 1 {
                let cell = self.tableView.cellForRow(at: NSIndexPath(row: row, section: section) as IndexPath)

                print("Section: \(section)  Row: \(row)")

            }
        }

A: Im using same way of iterating all table view cells , but this code worked for only visible cells , so I'v just add one line allows iterating all table view cells wether visible they are or not
   //get section of interest i.e: first section (0)
       for (var row = 0; row < tableView.numberOfRowsInSection(0); row++)
       {

        var indexPath = NSIndexPath(forRow: row, inSection: 0)

            println("row")
            println(row)
    //following line of code is for invisible cells
        tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)

    //get cell for current row as my custom cell i.e :roomCell

            var cell :roomCell = tableView.cellForRowAtIndexPath(indexPath) as roomCell
      }

* the idea is to scroll tableview to every row I'm receiving in the loop so, in every turn my current row is visible ->all table view rows are now visible :D

A: To answer my own question: "how can I iterate over all the UITableCells given a section id?":
To iterate over all the UITableCells of a section section one must use two methods:

*

*tableView.numberOfRowsInSection(section)

*tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section))
So the iteration goes like this:
// Iterate over all the rows of a section
for (var row = 0; row < tableView.numberOfRowsInSection(section); row++) {
    var cell:Cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section))?

   // do something with the cell here.
}

At the end of my question, I also wrote a note: "Note: I want to set the AccesoryType to None for all of the cells in a section, programatically". Notice that this is a note, not the question.
I ended up doing that like this:
// Uncheck everything in section 'section'
for (var row = 0; row < tableView.numberOfRowsInSection(section); row++) {
    tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section))?.accessoryType = UITableViewCellAccessoryType.None
}

If there is a more elegant solution, go ahead and post it.
Note: My table uses static data.

A: Swift 4
More "swifty", than previous answers. I'm sure this can be done strictly with functional programming. If i had 5 more minutes id do it with .reduce instead. ✌
func cells(tableView:UITableView) -> [UITableViewCell]{
    var cells:[UITableViewCell] = []
    (0..<tableView.numberOfSections).indices.forEach { sectionIndex in
        (0..<tableView.numberOfRows(inSection: sectionIndex)).indices.forEach { rowIndex in
            if let cell:UITableViewCell = tableView.cellForRow(at: IndexPath(row: rowIndex, section: sectionIndex)) {
                cells.append(cell)
            }
        }
    }
    return cells
}

A: You misunderstand how table views work. When you want to change the configuration of cells, you do not modify the cells directly. Instead, you change the data (model) for those cells, and then tell your table view to reload the changed cells.
This is fundamental, and if you are trying to do it another way, it won't work correctly.
You said "I need the array of cells before modifying them…" Same thing applies. You should not store state data in cells. As soon as a user makes a change to a cell you should collect the changes and save it to the model. Cells can scroll off-screen and their settings can be discarded at any time.
@LordZsolt was asking you to show your code because from the questions you're asking it's pretty clear you are going about things the wrong way.
EDIT:
If you are convinced that you need to iterate through the cells in a section then you can ask the table view for the number of rows in the target section, then you can loop from 0 to rows-1, asking the table view for each cell in turn using the UITableView cellForRowAtIndexPath method (which is different than the similarly-named data source method.) That method will give you cells that are currently visible on the screen. You can then make changes to those cells.
Note that this will only give you the cells that are currently on-screen. If there are other cells in your target section that are currently not visible those cells don't currently exist, and if the user scrolls, some of those cells might be created. For this reason you will need to save some sort of state information to your model so that when you set up cells from the target section in your datasource tableView:cellForRowAtIndexPath: method you can set them up correctly.

A: Im using this way of iterating all table view cells , but this code worked for only visible cells , so I'v just add one line allows iterating all table view cells wether visible they are or not
  //get section of interest i.e: first section (0)
   for (var row = 0; row < tableView.numberOfRowsInSection(0); row++)
   {

    var indexPath = NSIndexPath(forRow: row, inSection: 0)

        println("row")
        println(row)
//following line of code is for invisible cells
    tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)

//get cell for current row as my custom cell i.e :roomCell

        var cell :roomCell = tableView.cellForRowAtIndexPath(indexPath) as roomCell
  }

* the idea is to scroll tableview to every row I'm receiving in the loop so, in every turn my current row is visible ->all table view rows are now visible

A: You can use
reloadSections(_:withRowAnimation:) method of UITableView.
This will reload all the cells in the specified sections by calling cellForRowAtIndexPath(_:). Inside that method, you can do whatever you want to those cells.
In your case, you can apply your logic for setting the appropriate accessory type:
if (self.shouldHideAccessoryViewForCellInSection(indexPath.section)) {
    cell.accessoryType = UITableViewCellAccessoryTypeNone
}

A: I've wrote a simple extension based on Steve's answer. Returns the first cell of given type (if any) in a specified section.
extension UITableView {
  func getFirstCell<T: UITableViewCell>(ofType type: T.Type, inSection section: Int = 0) -> T? {
    for row in 0 ..< numberOfRows(inSection: section) {
      if let cell = cellForRow(at: IndexPath(row: row, section: section)) as? T {
        return cell
      }
    }
    return nil
  }
}


text:
Q: Invalid conversion from String to List then invalid conversion from List to String with same string I am trying get the device_config field from a deserialized JSON packet and cast it as a List<Object> I keep getting the following error Invalid conversion from runtime type String to List<ANY>. If I try to cast it as a String I get the following error Invalid conversion from runtime type List<ANY> to String. The code below is incomplete with what I ultimately want to do with it. Really need to get over this hump. Please help
@RestResource(urlMapping='/order/assets')

global with sharing class REST_asset_controller {

    @HttpPost
    global static void doPost(String JSON_packet) {

        System.debug('JSON_packet: ' + JSON_packet);

        Map<String, Object> deserialized_JSON;

        String order_number;
        String account_id;
        String account_name;

        List<Object> shipment_details;
        Map<String, Object> shipment_info;

        String product_code;
        String product_short_name;
        String quantity_shipped;

        List<Object> device_list;

        deserialized_JSON = (Map<String, Object>)JSON.deserializeUntyped(JSON_packet);
        order_number = (String)deserialized_JSON.get('order_number');

        account_id = (String)deserialized_JSON.get('account_id');
        account_name = (String)deserialized_JSON.get('account_name');

        shipment_details = (List<Object>)deserialized_JSON.get('shipment_details');

        List<Asset> assets = new List<Asset>();

        System.debug('JSON_packet: ' + JSON_packet);
        System.debug('deserialized_JSON:' + deserialized_JSON);
        System.debug('salesforce_order_number: ' + order_number);
        System.debug('salesforce_account_id: ' + account_id);
        System.debug('salesforce_account_name: ' + account_name);
        System.debug('shipment_details: ' + shipment_details);

        for(Object shipment : shipment_details) {

            shipment_info = (Map<String, Object>)shipment;
            Asset assets_list = new Asset();

            device_list = (List<Object>)shipment_info.get('device_list');

            System.debug('shipment_info: ' + shipment_info);
            System.debug('device_list: ' + device_list);

            assets_list.order_number__c = order_number;

            for(Object device : device_list) {

                System.debug('device: ' + device);

                assets_list.device__c = (String)device;

                //List<Object>device_config = (List<Object>)shipment_info.get('device_config');
                String device_config = (String) shipment_info.get('device_config');

                System.debug('device_config: ' + device_config);

            }

            assets.add(assets_list);
            System.debug('assets_list: ' + assets_list);

        }

        Database.insert(assets, False);

    }

}

Below is an example of the JSON packet:
{
    "order_number": "",
    "sf_order_number": "10000001",
    "account_id": "0000001",
    "account_name": "Test account",
    "shipment_details": [
        {
            "product_code": "22-5578",
            "product_short_name": "TestProd1",
            "qty_shipped": "3",
            "device_list": [
                "000000000100000",
                "000000000100001",
                "000000000100002"
            ],
            "device_config": ""
        },
        {
            "product_code": "22-5571",
            "product_short_name": "TestProd2",
            "qty_shipped": "5",
            "device_list": [
                "000000000200001",
                "000000000200002",
                "000000000200003",
                "000000000200004",
                "000000000200005"
            ],
            "device_config": ""
        },
        {
            "product_code": "22-5571",
            "product_short_name": "TestProd2",
            "qty_shipped": "5",
            "device_list": [
                "000000000300002",
                "000000000300003",
                "000000000300004",
                "000000000300005",
                "000000000300006"
            ],
            "device_config": [
                "Test sensor 1",
                "Test sensor 2",
                "Test sensor 3",
                "Test sensor 4 (Wireless)"
            ]
        }
    ]
}

A: The formatting with the JSON packet being transmitted to me seems to be the problem. The parameter device_config switches from being a string, device_config : "", to an array of strings, device_config : [...], whenever it isn't sent with the [] which is confusing Salesforce. Thank you all for your help


text:
Q: Completeness of product measure Given two measure spaces $(X,\mathcal{A},\mu)$ and $(Y,\mathcal{B},\nu)$, we can define the product measure $\mu\times\nu$ on the algebra $\mathcal{A}\times\mathcal{B}$ defined as the $\sigma$-algebra generated by all measurable rectangles in $X\times Y$.
Assuming $\mu$ and $\nu$ are complete, $\mu\times\nu$ need not be. For example, consider $A\in\mathcal{A}$ with $A\ne \emptyset$ but $\mu(A)=0$, and $B\in\mathcal{P}(Y)-\mathcal{B}$ (if $\mathcal{P}(Y)-\mathcal{B}\ne\emptyset$). Then $A\times B\notin \mathcal{A}\times\mathcal{B}$, but $A\times Y\supset A\times B$ is a null set.
How can we prove that $A\times B\notin \mathcal{A}\times\mathcal{B}$? It is not obvious to me that we cannot generate $A\times B$ from the measurable rectangles. I cannot think of a way to have $A\times B\in \mathcal{A}\times\mathcal{B}$, however I do not know how I would prove that it is impossible?

A: If a set $C\subset X\times Y$ is an element of $\mathcal A\times\mathcal B$, then the  section  $C_x:=\{y\in Y: (x,y)\in C\}$ is an element of $\mathcal B$, for each $x\in X$. Now take $C=A\times B$ and $x\in A$ (using your choice of $A$ and $B$).

A: Example.Let $(X,\mathcal A,\mu)=(Y,\mathcal B, \nu)=(R, \mathcal M,m)$ where $R$ is the reals, $m$ is Lebesgue measure, and $\mathcal M=$dom $(m).$
Let $T=S\times \{0\}$ where $S\in \mathcal P(R)\backslash \mathcal M.$
Let $D_0$ be the Boolean algebra on $R^2$ generated by the Cartesian product $\mathcal M\times \mathcal M$.
For ordinal $a\in \omega_1,$ let $D_{a+1}$ be the Boolean algebra on $R^2$ generated by  unions of countable subsets of $D_a.$
For $0\ne a=\cup a\in \omega_1,$ let $D_a=\cup_{b\in a}D_b.$ $$ \text {Now }\quad \mathcal M^*= \cup_{a\in \omega_1}D_a$$ is the $\sigma$-algebra generated by the Cartesian product $\mathcal M\times \mathcal M$, because $\omega_1$ is a regular cardinal.
By transfinite induction on $a\in \omega_1,$ if $T\subset U\in M^*$ then $\{x:(x,0)\in U\}\in \mathcal M,$ so  $T\not \in \mathcal M^*.$
But for every $r>0$ there exist subsets  $\{u_n\}_{n\in N}, \{v_n\}_{n\in N}$ of $\mathcal M$ such that $\cup_{n\in N}(u_n\times v_n)\supset T$ and $\sum_{n\in N}m(u_n)m(v_n)<r.$


text:
Q: Slack Bolt API: Receiving 'not_found' error when trying to update modal view on submission So I have this app where I click a button and it begins a series of modals to take user input. I am having an issue when trying to update the current modal with a new view object.
I can update and push new views no problem when responding to other buttons within a modal but not when it's the submission button. Unfortunately when using input blocks you must include a submission button.
Here is the code I am using to handle the view_submission payload I receive when clicking submit.
app.view('callback_period', async ({ ack, body, view, client }) => { // Pass callback_id
  // Acknowledge the view_submission event
  await ack();

  // Log out view ID to confirm it is indeed the same as the initial view
  try {
    console.log(body.view.id);
    const result = await client.views.update({
      response_action: "update",
      view_id: body.view.id,
      hash: body.view.hash,
      view: views_payroll_prefill_shift
    });
    console.log(result);
    console.log(body.view.id);
  }
  catch (error) {
    console.error(error);
    console.log(body.view.id);
  }

});

So when I click the button my app receives the payload just fine but the client.views.update method just gives me a "not_found" error. I checked the documentation and it says the view_id must be invalid however I've logged the view ID from the original modal and it is consistent throughout. I don't understand why it's working for app.actions() but not app.view().
I've tried creating const for the original body.view.id and passing that but I will keep getting this not_found error from app.views().
I'm really at my wits end. Any help would be greatly appreciated.

A: So after some more digging I finally found my answer. You need to pass the updated view as arguments during your acknowledgement. When the submission button is pressed you pass along the response action and your view inside ack(). Here is the solution;
app.view('callback_period', async ({ ack, view}) => { // Pass callback_id
  // Acknowledge the view_submission event
  await ack({
    "response_action": "update",
    "view": views_payroll_prefill_shift,
  });
});


text:
Q: array in for loop merge with second for loop array javascript I have a problem merging 2 arrays in an for loop see code:
function count_days(tijden,datums ){

        var length = tijden.length;
        element = null;
        var similarities =0;
        var backup = [];
        var dateArray =[];

        for (var i = 0; i <length; i++) {
                element = tijden[i];
                tijden[i] = element;

            dateArray = getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']));

         }

The problem is that when the code is running i get one array for each loop. I need to get one array with the data from all loops. I tryde concat but didnt get this to work

A: It should be...
dateArray.push(
  getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']))
);

... or, if getDates method returns an array and you want dateArray to be flattened:
Array.prototype.push.apply(dateArray,
  getDates(new Date(tijden[i]['begin']),
           new Date(tijden[i]['eind']))
);

As it stands now, you just rewrite dateArray at each step of for loop.

A sidenote: this...
element = tijden[i];
tijden[i] = element;

... makes exactly zero sense: at least one of these lines (most probably the latter) is redundant. Remove this - and code becomes easier to read:
var element, currDates;
for (var i = 0, i < length; i++) {
  element = tijden[i];
  currDates = getDates(new Date(element.begin), new Date(element.eind));
  Array.prototype.push.apply(dateArray, currDates);
}


text:
Q: Get page number with javascript modulus I have the following figures to work with:
totalItems = 26;
itemsPerPage = 6;
currentItem = 17;

currentPage = ??

Given those figures (or any current item value), how can I determine what the current page is. I think I need to use the modulus function but I can't fathom out which way to go about it.
Could anyone help please? Thank you

A: You need the ceil function
//In javascript
currentPage=Math.ceil(currentItem/itemsPerPage);//=3
//17/6=2.8333.. ceiling (round up to nearest integer) = 3

It's worth pointing out this is assuming 1 based paging (first page is page 1 not page 0) and 1 based item number (meaning page 1 has items 1-6, page 2 has items 7-12).


text:
Q: color point shapefile based on cell values I am using QGIS.
After exporting a point shapefile from a raster file, I like to know how can I color the point shapefile with a cell values.

A: You can do this in the Style tab under layer properties.  Within the Style tab, change single symbol to categorized or graduated and choose which column you would like the color to be based on (cell value).  Then, choose your colors or color scheme.  Here is a resource that goes into depth about styling in QGIS: http://qgis.spatialthoughts.com/2012/02/tutorial-styling-vector-data-in-qgis.html


text:
Q: Year picker user control in sharepoint I want to know is there any SharePoint native user control for year picker? I know there was another library like jQuery and other thing that do like what I want. I need SharePoint control for some localization issue.

A: There is no yearpicker control but you can use the SharePoint DateTimeControl for selecting dates or datetimes.
Unfortunately i think its rather hard to customize it to only select years. Therefor i would suggest to use an external lib for that or just use a dropdown with dates to select?
https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.datetimecontrol.aspx


text:
Q: PNG export with specific file size using ExtendScript for Adobe Illustrator I'm trying to create a script in Extendscript that draws something and then exports the entire Artboard as a PNG in the size 4500x5400 px (or any other specific size).
This is the code I have right now:
//create new document with my desired size
var myDoc = app.documents.add();
myDoc.width = 4500;
myDoc.height = 5400;

//create a rectangle that is smaller than the artboard
var rect = myDoc.layers[0].pathItems.rectangle(700,300,72,100);

//export Image with name newImage.png (I have a specific path here)
exportFileToPNG24 ("~/newImage.png");

function exportFileToPNG24(dest) {
  if (app.documents.length > 0) {
    var exportOptions = new ExportOptionsPNG24();
    exportOptions.artBoardClipping = true; //this option makes sure I export
                                          //the whole artboard and not just
                                          //the rectangle
    var type = ExportType.PNG24;
    var fileSpec = new File(dest);

    app.activeDocument.exportFile(fileSpec, type, exportOptions);
  }
}

The script does export the whole artboard as a png. But the PNG always has the size 612x792 px. How can I get it to export in 4500x5400 px?

A: Instead of this:
var myDoc = app.documents.add();
myDoc.width = 4500;
myDoc.height = 5400;

It makes sense to create a new document this way:
var preset    = app.getPresetSettings("Web");
preset.units  = RulerUnits.Pixels;
preset.width  = 4500;
preset.height = 5400;
var myDoc     = app.documents.addDocument("Web", preset);

Or you can make a new document with default size and then change it this way:
var myDoc = app.documents.add();
myDoc.artboards[0].artboardRect = [0,5400,4500,0];


text:
Q: What is PostScript dictionary for? How to know whether or not I need it? Consider the following code,
\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pstricks-add}
\psset{linecolor=red}
\pstVerb
{
    /updateCP {2 copy CPy add /CPy ED CPx add /CPx ED} bind def
    /updateA  {1 sub sqrt 1 exch atan Angles add /Angles ED} bind def
}

\def\WithoutDict{%
    \begin{pspicture}[showgrid](-5,-5)(5,5)
    \multido{\io=1+1}{15}
    {%
        \pstVerb{/Angles 0 def /CPx 1 def /CPy 0 def}% reset
        \def\points{(0,0)(1,0)}% reset
        \multido{\ii=1+1}{\io}{\xdef\points{\points(!1 \ii\space updateA Angles PtoC updateCP)}}
        \expandafter\psrline\points
        \psline(!CPx CPy)
    }
    \end{pspicture}}

\def\WithDict{%
    \begin{pspicture}[showgrid](-5,-5)(5,5)
    \multido{\io=1+1}{15}
    {%
        \pstVerb{tx@Dict begin /Angles 0 def /CPx 1 def /CPy 0 def end}% reset
        \def\points{(0,0)(1,0)}% reset
        \multido{\ii=1+1}{\io}{\xdef\points{\points(!1 \ii\space updateA Angles PtoC updateCP)}}
        \expandafter\psrline\points
        \psline(!CPx CPy)
    }
    \end{pspicture}}

\begin{document}
\WithoutDict
\WithDict
\end{document}

which produces the following outputs.

Question
\WithoutDict is different from \WithDict only in tx@Dict that \WithoutDict does not use. The use of tx@Dic in \WithDict was done by Christoph in his answer here. I really don't understand why I need it.
So the question is,

*

*What is PostScript dictionary for?

*How to use it in a simple but not trivial example?

*How do I know whether or not I need it?

Hopefully the answer can be used as a crash-course tutorial.

A: Postscript dictionaries implement the concept of name spaces which allow for control of variable visibility. To see the command line output from the Postscript interpreter, run ps2pdf on the PS file produced by dvips.
\documentclass{article}
\usepackage{pstricks}

\begin{document}
Dictionaries implement the concept of name spaces to control variable visibility
\pstVerb{
/myvar (hello!) def % `global' definition
/mydict 1 dict def
mydict begin % open namespace
  /myvar (goodbye!) def % `local' definition
  myvar == % print local value
end % close namespace
myvar == % print global value
mydict begin % reopen name space
  myvar == % print local value once more
end
}

\end{document}

If you don't know which of the existing dictionaries from the PSTricks packages you will have to put on the dictionary stack, you can always define your variables in a new dictionary of your own. Make your dictionary the current one (and the variables defined therein available) by putting it on the dictionary stack when needed.
The dictionary and the operand stacks are separate things. Putting and popping dictionaries on the dictionary stack don't affect the operand stack:
\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pstricks-add}

\begin{document}

\psset{linecolor=red}
\pstVerb
{
    /updateCP {2 copy CPy add /CPy ED CPx add /CPx ED} bind def
    /updateA  {1 sub sqrt 1 exch atan Angles add /Angles ED} bind def
}

\begin{pspicture}[showgrid](-5,-5)(5,5)
\multido{\io=1+1}{15}
{%
    \pstVerb{
      /mydict 1 dict def % roll your own dict
      mydict begin       % put it on top of the dict stack
        /Angles 0 def /CPx 1 def /CPy 0 def %define your variables
      end % pop your dict from the dict stack (it doesn't get lost!)
    }% reset
    \def\points{(0,0)(1,0)}% reset
    \multido{\ii=1+1}{\io}{\xdef\points{\points(!1 \ii\space
        mydict begin % make your dict the current (i.e. top-level) one by
                     %putting it on the dict stack
          updateA Angles PtoC updateCP % work on your variables
        end % remove it from the dict stack, point coordinates remain on
            % the operand stack
    )}}
    \expandafter\psrline\points
    \psline(!mydict begin % make your dict the current dict
      CPx CPy
    end)                  % and remove it from dict stack, CPx CPy still on the operand stack
}
\end{pspicture}

\end{document}

A: More generally, a postscript dictionary is an associative array. It can associate pairs of objects of any type, with a few exceptions. It cannot use a nulltype object as a key because it uses null to mark vacant slots in the array. It implicitly converts stringtype keys into nametype.
But it can also be used with numerical keys to implement memoized functions. It can use integer keys to represent sparse sets of character encodings, or more-generally substitution rules for string-rewriting systems. They can hold local variables for recursive functions. They can implement encapsulated objects with methods, even purely virtual ones.
Since level-2, dictionaries will automatically grow to hold their contents. This makes them very nice for implementing a growing-array, by using integer keys which work just like array indices.
/dictarr <<
    0 5
    1 7
    2 4
>> def
/regularr [
    5
    7
    4
] def
dictarr 1 get
regularr 1 get  % 7 7

dictarr dup length 9 put  % append to dict-array
/regularr [ regularr aload pop 9 ] def  % append to regular-array

To grow a regular array, you have to allocate a new one, whereas adding one more key-value pair to a dict is quite cheap since the growing of the internal array is amortized over many calls by design.
For both styles, the "index" of the last element is length 1 sub. Arrays, dicts, and even strings, can be used polymorphically with the get and put operators.


text:
Q: poltergeist onConsoleMessage initialization on Capybara I'm using the phantomjs driver via poltergeist on ruby/capybara. One thing I'm trying to setup is the ability of receiving debug messages from javascript into the ruby debug console.
I see that phantomjs has a javascript OnConsoleMessage callback to set up this, but I couldn't find a way to wire this up from ruby. Any ideas?

A: Ok, it seems that you need to enable the inspector
Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, {debug: true, :timeout => 90, :inspector => true})
end
Capybara.javascript_driver = :poltergeist

and then place
page.driver.debug

somewhere on the spec, which will bring a link to the inspector dashboard. It doesn't reload by default, so you need to hit reload from time to time to see changes


text:
Q: Accessing many-to-many details with through model in Django template I have a models.py like this:
class Work(models.Model):
[...]
    instrumentations = models.ManyToManyField('Instrument', 'Percussion',
        through='Instrumentation',
        blank=True)

class Instrument(models.Model):
    name = models.CharField(max_length=100)
    family = models.CharField(max_length=20, default='')

class Percussion(models.Model):
    name = models.CharField(max_length=100)

class Instrumentation(models.Model):

    players = models.IntegerField()
    work = models.ForeignKey(Work, on_delete=models.CASCADE)
    instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE)
    percussion = models.ManyToManyField(Percussion, blank=True, default=None) # Ideally percussions should be in the Instrument model with family 'percussion', though I don't know how to make Django like that. A separate model is a good workaround for me.

My view:
def work_edit_view(request, id=id):

    InstrumentFormSet = inlineformset_factory(Work, Work.instrumentations.through, extra=1, can_delete=True,
    fields=('instrument', 'percussion', 'players', 'work'), widgets={
    'work': forms.HiddenInput(),
    'players': forms.NumberInput(attrs={'placeholder': 'Number of players'})
    form_details = InstrumentFormSet(request.POST or None, instance=obj_work, initial=[{'work' : obj_work.id}], prefix='instruments')

})

The data gets saved correctly in my input form, so that's not an issue. My problem is visualising the information in my template. I can only access the 'instrument', not my 'percussion' or my 'players'. What am I doing wrong?
    {% for instrument in work.instrumentations.all %}
    {{ instrument }} {{ instrument.players }} # only instrument is output.

      {% for percussion in instrument.percussion.all %} # this looks to be empty.
      Percussion {{ forloop.counter }} ({{ percussion.players }}) # No luck here :(
      {% endfor %}

A: You can, but you need to access it correctly, you can access the Instrumentations with work.instrumentation_set:
{% for instrumentation in work.instrumentation_set.all %}
    {{ instrumentation.instrument }} {{ instrumentation.players }}

    {% for percussion in instrumentation.percussion.all %}
        Percussion {{ forloop.counter }} ({{ percussion.players }})
    {% endfor %}
{% endfor %}

Note: that a ManyToManyField can not refer to multiple models. The second parameter is the related_name, so you set the name of the relation in reverse to 'Percussion', which might not be ideal.


text:
Q: Cannot set headers after they are sent to the client NextJS redirect res.writeHead getInitialProps I have error when redirect to link from NextJS -> _app.js -> getInitialProps
am try to cached last user lanuage in Cookies and redirect to it when reload page
it's worked and user is redirect but I have a bugs in terminal
I have this bug, I don't understand what is his mean for (cannot set headers after they are sent to the client)
Error [err_http_headers_sent]: cannot set headers after they are sent to the client

at new nodeerror (node: internal/errors:372:5)
at serverresponse. Setheader (node: _http_outgoing:576:11)
at setheadersfromobject (c: \users\ahmed\desktop\amazon-clone-
nextjs - server-
side\node_modules\next\dist\compiled\compression\index. Js:46:680)
at serverresponse. Setwriteheadheaders (c:
\users\ahmed\desktop\amazon-clone-nextjs -
server-side\node_modules\next\dist\compiled\compression\index.
Js:46:914)
at serverresponse. Writehead (c: \users\ahmed\desktop\amazon-clone-
nextjs - server-
side\node_modules\next\dist\compiled\compression\index. Js:46:121)
at function. Myapp. Getinitialprops (webpack-internal: ///.
/pages/_app. Jsx:94:21)
at object. <anonymous> (c: \users\ahmed\desktop\amazon-clone-nextjs
- server-
side\node_modules\next\dist\shared\lib\utils. Js:75:33)
at generator. Next (<anonymous>)
at asyncgeneratorstep (c: \users\ahmed\desktop\amazon-clone-nextjs
- server-
side\node_modules\@swc\helpers\lib\_async_to_generator. Js:23:28)
at _next (c: \users\ahmed\desktop\amazon-clone-nextjs - server-
side\node_modules\@swc\helpers\lib\_async_to_generator. Js:12:17) {
code: 'err_http_headers_sent'
}

error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after
they are sent to the
client

at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at NodeNextResponse.setHeader (C:\Users\Ahmed\Desktop\Amazon-clone-
NextJs - Server-
side\node_modules\next\dist\server\base-http\node.js:59:19)
at DevServer.renderToResponseWithComponents
(C:\Users\Ahmed\Desktop\Amazon-clone-
NextJs - Server-side\node_modules\next\dist\server\base-
server.js:1039:17)
at async DevServer.renderPageComponent
(C:\Users\Ahmed\Desktop\Amazon-clone-NextJs -
 Server-side\node_modules\next\dist\server\base-server.js:1126:24)
at async DevServer.renderToResponse (C:\Users\Ahmed\Desktop\Amazon-
clone-NextJs -
Server-side\node_modules\next\dist\server\base-server.js:1145:32)
at async DevServer.pipe (C:\Users\Ahmed\Desktop\Amazon-clone-NextJs
- Server-
side\node_modules\next\dist\server\base-server.js:634:25)
at async Object.fn (C:\Users\Ahmed\Desktop\Amazon-clone-NextJs -
Server-
side\node_modules\next\dist\server\base-server.js:501:21)
at async Router.execute (C:\Users\Ahmed\Desktop\Amazon-clone-NextJs
- Server-
side\node_modules\next\dist\server\router.js:222:36)
at async DevServer.run (C:\Users\Ahmed\Desktop\Amazon-clone-NextJs
- Server-
side\node_modules\next\dist\server\base-server.js:612:29) {
code: 'ERR_HTTP_HEADERS_SENT',
page: '/'
}

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are
sent to the client

at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at NodeNextResponse.setHeader (C:\Users\Ahmed\Desktop\Amazon-clone-
NextJs - Server-
side\node_modules\next\dist\server\base-http\node.js:59:19)
at DevServer.renderError (C:\Users\Ahmed\Desktop\Amazon-clone-
NextJs - Server-
side\node_modules\next\dist\server\base-server.js:1219:17)
at DevServer.renderError (C:\Users\Ahmed\Desktop\Amazon-clone-
NextJs - Server-
side\node_modules\next\dist\server\next-server.js:516:22)
at DevServer.run (C:\Users\Ahmed\Desktop\Amazon-clone-NextJs -
Server-
side\node_modules\next\dist\server\dev\next-dev-server.js:575:35)
at async DevServer.handleRequest (C:\Users\Ahmed\Desktop\Amazon-
clone-NextJs -
Server-side\node_modules\next\dist\server\base-server.js:311:20) {
code: 'ERR_HTTP_HEADERS_SENT'
}

this code
_app.jsx

MyApp.getInitialProps = async ({ ctx }) => {
  const currentLocale = ctx.locale;
  const { cashedLocale } = ctx.req.cookies;

  if (cashedLocale && currentLocale !== cashedLocale) {
    ctx.res.writeHead(307, { Location: `/${cashedLocale + ctx.pathname}` });
    ctx.res.end();
  }

  return {};
};

A: redirect status code is 308 but you added 307
just replace this
ctx.res.writeHead(307, { Location: `/${cashedLocale + ctx.pathname}` });
ctx.res.end();

to this
ctx.res.writeHead(308, { Location: `/${cashedLocale + ctx.pathname}` }).end();


text:
Q: Converting year based on months with dates I am trying to achieve  such that a number should be rounded to the nearest integer age (ie. if 64 & 3 months = 64, if 64 & 9mths = 65).
This is my code:
    var dt = '15/11/2015';
    var roundedAge = Math.round(moment().diff(moment(dt, 'DD/MM/YYYY'), 'years', true));
    console.log('result:' + Math.round(roundedAge - 0.25));

Seems to not work for me.

A: You just need to round the Years, no need to subtract 0.4

var yrs = moment().add(64 * 12 + 3, "months").diff(moment(), 'years', true);
console.log('result:' + Math.round(yrs));

var yrs2 = moment().add(64 * 12 + 9, "months").diff(moment(), 'years', true);
console.log('result:' + Math.round(yrs2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

A: This is how i fixed it.
    var floatYears = moment().diff(moment($("#dtDOB").val(), 'DD/MM/YYYY'), 'years', true);
    var intYears = Math.round(floatYears - 0.25); // Since 0.75 = 9/12 months so shifting the offset.
    $('#calcAge').val(intYears + ' years');


text:
Q: Restoring files from a Windows 7 backup to a Ubuntu PC I am building a PC running Ubuntu 18.04LTS to replace a Windows 7 machine (about flipping time I hear you say!) for someone I help with their tech.
The backup utility from Win7 has been used to make a system backup with the data written to an external USB drive.
I will be manually copying files from Documents, Pictures, Music to the new setup initially.
I want to guard against finding in the future that there are files/folders that suddenly become needed.
I'd like to know if there is a utility for Ubuntu that can work with the .zip files and catalogs that the Win7 backup utility creates that would allow for files/folders to be restored without me having to find a Windows machine to use to get the files from the USB drive.
edit:
It is about finding a manageable way to see and extract the files contained in the set of files are are titled 'Backup Files xxx.zip'
Thanks


text:
Q: jQuery exception with runat="server" in script declaration I have an issue with declaring the jQuery 3.3.1 script in the head element throwing an exception inside of the jQuery source. I'm using runat="server" in order to have the path resolve properly when run while still preserving the intellisense while I'm coding. It throws an exception with the following error:

CS1519: Invalid token '!' in class, struct, or interface member declaration

I'm assuming the issue is that Visual Studio is trying to debug jQuery and finding what it considers errors.
What I'm wondering is if there's either a way to use runat="server" and ignore exceptions in jQuery, or if there's a different way to include jQuery using a path with ~/ in it. I've used ResolveUrl() to include jQuery, which works, but intellisense breaks for me when I do that.
The current code I'm using is:
<head runat="server">
    <script src="~/Scripts/jquery.min.js" runat="server" />
</head>

As a side note, the reason I'm attempting to use ~/ is that I'm linking to the script in a master page, so the relative path may change depending on the folder that the aspx path is in. If there's another way to accomplish this, I'd accept that as well.


text:
Q: Copy recordset data into multiple sheets to avoid problem of maximum rows limit in Excel VBA I am developing reporting application in Excel/vba 2003. VBA code sends search query to database and gets the data through recordset. It will then be copied to one of excel sheet. The retrieved data looks like as shown below.
ProductID--------|---DateProcessed---------|----State-----

1................|.. 1/1/2010..............|.....Picked Up
1................|.. 1/1/2010..............|.....Forward To Approver
1................|.. 1/2/2010..............|.....Approver Picked Up
1................|.. 1/3/2010..............|.....Approval Completed
2................|.. 1/1/2010..............|.....Picked Up
3................|.. 1/2/2010..............|.....Picked Up
3................|.. 1/2/2010..............|.....Forward To Approver

The problem is data retrieved from search query is so huge that it goes above the excel row limit (65536 rows in excel 2003). So I want to split this data into two excel sheets.
While splitting the data I want to ensure that the data for same product should remain in one sheet.
For example, if  the last record in the above result set is 65537th record then I also want to move all records for product 3 into new sheet.
So sheet1 will contain records for product id 1 and 2 with total records = 65534.
Sheet 2 will contain records for product id 3 - with total records = 2.
How can I achieve this in vba?
If it is not possible, is there any alternative solution ?
Thanks in Advance !

A: Since you did not provide any code on how you are accessing your database, I can give you only a general outline.
First, send a query to the database like this:
"SELECT COUNT(*),ProductID FROM YourTable GROUP BY ProductID order by ProductID"

From the result you can easily calculate ProductID intervals with less than 65536 records, just add the count up until you reach this limit.
Finally, you split your original query into many queries (one per data sheet), and add a WHERE condition like this:
... WHERE ProductID IS BETWEEN " + LowerIDRange + " AND " + HigherIDRange

LowerIdRange and HigherIDRange have to be the interval limits calculated from the first query.

A: Move to Excel 2007 or 2010, which have a limit of 250.000 rows I think. Or better: see if you can pre-agregate you data.
My prefered suggestion here would be to make a pivot table summarizing your data. Then by double clicking a cell, the user could get a matching subset of detail records into a new sheet.


text:
Q: docker-compose nginx return 502 to php-fpm Please help me. There was an error, a minor error. Maybe I just do not see it, but I had no idea. The essence of the problem: I am setting up a docker environment. Brought nginx, fpm. When url get a php file, nginx return 502.
Structure:
/www
 /app
   /index.php
   /index.html
 /data
   /db
 /etc
   /nginx
      default.conf
   /php
      php.ini
      php-fpm.conf

*

*Compose + env:

version: '3.5'
services:
    nginx:
        image: nginx:alpine
        volumes:
            - "./etc/nginx/default.conf:/etc/nginx/conf.d/default.conf"
            - "./etc/ssl:/etc/ssl"
            - "./app:/var/www/html"
            - "./etc/nginx/default.template.conf:/etc/nginx/conf.d/default.template"
        ports:
            - "80:80"
        environment:
            - NGINX_HOST=${NGINX_HOST}
        command: /bin/sh -c "envsubst '$$NGINX_HOST' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
        restart: always
        depends_on:
            - php
            - mysqldb
            - memcached
        networks:
            - app
    php:
        image: php:${PHP_VERSION}-fpm
        restart: always
        volumes:
            - "./etc/php/php.ini:/usr/local/etc/php/conf.d/php.ini"
            - "./etc/php/php-fpm.conf:/usr/local/etc/php-fpm.conf"
            - "./app:/var/www/html"
        networks:
            - app
        ports:
            - "9000:9000"
        networks:
            - app
    mysqldb:
        image: mysql:${MYSQL_VERSION}
        container_name: ${MYSQL_HOST}
        restart: always
        env_file:
            - ".env"
        environment:
            - MYSQL_DATABASE=${MYSQL_DATABASE}
            - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
            - MYSQL_USER=${MYSQL_USER}
            - MYSQL_PASSWORD=${MYSQL_PASSWORD}
        ports:
            - "3306:3306"
        volumes:
            - "./data/db/mysql:/var/lib/mysql"
        networks:
            - app
    memcached:
        image: memcached:${MEMCACHED_VERSION}
        container_name: ${MEMCACHED_HOST}
        ports:
            - "11211:11211"
        networks:
            - app
networks:
    app:
        driver: bridge

#!/usr/bin/env bash

# See https://docs.docker.com/compose/environment-variables/#the-env-file

# Nginx
NGINX_HOST=localhost

# PHP

PHP_VERSION=5.4

# MySQL
MYSQL_VERSION=5.7.22
MYSQL_HOST=mysql
MYSQL_DATABASE=test
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=root
MYSQL_USER=dev
MYSQL_PASSWORD=dev

# Memcached
MEMCACHED_VERSION=latest
MEMCACHED_HOST=memcached

*Nginx [/etc/nginx/default.conf]:

upstream phpserver {
    server php:9000;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name localhost;

    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass phpserver;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

*PHP [php-fpm.conf]:

[global]

error_log = /proc/self/fd/2
daemonize = no

[www]

; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

user = www-data
group = www-data

listen = 9000

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

clear_env = no

; Ensure worker stdout and stderr are sent to the main error log.
catch_workers_output = yes

*PHP [php.ini] - ini file is default. 5.4. It does not include a user, directories before sessions, etc.
Such a structure. More... The phpv should be exactly this (5,4).

What steps did I take to find my error, but did not find:

*

*curl localhost:80/index.html >> HELLO_WORLD

*curl localhost:80/index.php >> 502 nginx

*netstat -an |grep 9000 >> tcp6       0      0 :::9000            :::*                    LISTEN

*curl localhost:80/index.php + docker-compose log >> nginx_1      | 2020/08/26 16:16:09 [error] 7#7: *3 connect() failed (113: Host is unreachable) while connecting to upstream, client: 172.26.0.1, server: localhost, request: "GET /index.php HTTP/1.1", upstream: "fastcgi://172.26.0.2:9000", host: "localhost" nginx_1      | 172.26.0.1 - - [26/Aug/2020:16:16:09 +0000] "GET /index.php HTTP/1.1" 502 157 "-" "curl/7.61.1" nginx_1      | 2020/08/26 16:16:09 [info] 7#7: *3 client 172.26.0.1 closed keepalive connection

*php conteiner
root@..:/var/www/html# php index.html *>>* HELLO_WORLD
root@..:/var/www/html# php index.php *>>* HELLO_WORLD

*php conteiner >> root@..:/var/www/html# ls -ll total 13 -rwxrwxrwx. 1 root root 8518 Aug 14 11:36 index.php -rwxrwxrwx. 1 root root   34 Aug 25 21:04 index.html

*error_log  /var/log/nginx/error.log debug; >> cat
/var/log/nginx/error.log - empty
Structure www/ - root:root

I'm sorry for wasting time. Please help me. Thank!

A: I have dealt with the problem. I do not want to write in stages, but I will say it in a nutshell. The problem is caused by the fact that my OS build is centos 8. First of all, the incorrect behavior of containers will show the use of Dockerfile, problems with the repo will be identified. It is possible to solve these problems, but for me it became a trigger, which shows that my environment is not correct. Then I went and installed all the packages for docker as directed for installation under Centos 8.
& see
https://computingforgeeks.com/install-docker-and-docker-compose-on-rhel-8-centos-8/


text:
Q: Why does nohup not working in python script in os.system? I treid to use nohup in python on cluster but failed. My code is here below:
import os

path = "/ldfssz1/SP_MSI/USER/"
os.system("nohup sh "+ path + "myjobs.sh &")

Cluster only returns this:
nohup: ignoring input and appending output to `nohup.out'

There were no pid returns and job command returns nothing. Can anyone gives me some idea what's going on here? Thank you very much!


text:
Q: How can I stop the columns resizing on scroll in a WPF DataGrid with row virtualization turned on? I have a WPF DataGrid, bound to a DataTable which may contain a variable number of columns. This DataTable can change its schema and data at runtime, whenever the user chooses a new data file to load into the app (in the example below, this is simulated by clicking the Load Data button).
I've set the column width to Auto so that columns automatically resize to fit their header text or the longest piece of row content in the column (whichever is larger). Here's the MainWindow.xaml from my example:
<Window x:Class="analog.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:analog"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="600">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button x:Name="loadData" Grid.Row="0" Margin="0" Content="Load Data" Click="loadData_Click" VerticalAlignment="Top" />
        <DataGrid x:Name="dataGrid" Grid.Row="1" Margin="0" IsReadOnly="True" CanUserAddRows="False" ColumnWidth="Auto" SelectionUnit="Cell" />
    </Grid>
</Window>

And here's MainWindow.xaml.cs:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void loadData_Click(object sender, RoutedEventArgs e)
    {
        var data = new DataTable();
        data.Columns.Add("A", typeof(string));
        data.Columns.Add("B", typeof(string));
        data.Columns.Add("C", typeof(string));

        Enumerable.Range(1, 50).ToList().ForEach(i => {
            var row = data.NewRow();
            row["A"] = "aaa";
            row["B"] = "bbb";
            row["C"] = "ccc";
            data.Rows.Add(row);
        });

        var longRow = data.NewRow();
        longRow["A"] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        longRow["B"] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        longRow["C"] = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
        data.Rows.Add(longRow);

        dataGrid.ItemsSource = data.DefaultView;
    }
}

This works perfectly, except that because the DataGrid rows are virtual (i.e. rendered on demand when the list is scrolled, as opposed to upfront), the columns can only automatically resize to the content which is currently being displayed.
However, when you then scroll down to the bottom of the list, the column widths suddenly and dramatically change as the longer cell content scrolls into view, making for a really horrible, disorientating user experience.
Turning off row virtualisation isn't an option (e.g. EnableRowVirtualization="False"), as I'm loading in some large data sets and performance is unusably bad without it.
I understand the limitation on sizing when using virtualisation and I'm quite happy with that behaviour. It's perfectly OK if the columns just stay at the widths they are set to when the grid is initially rendered, but I just can't find a way to do it!
I've tried some fairly horrible hacks, including this one where I loop over the columns after the initial render and programmatically set the widths in pixels to whatever size they are currently rendered at:
foreach (DataGridColumn column in dataGrid.Columns)
{
    column.Width = new DataGridLength(column.ActualWidth, DataGridLengthUnitType.Pixel);
}

I'm currently calling this manually, by putting it in a button click handler and clicking the button after the initial data has rendered—but this has no effect whatsoever, and the resize still happens when I get down to the longer values.
So, how can I stop the columns resizing when I scroll the DataGrid?

A: Another option (not exactly as a solution for the question, but similar situations, especially when EnableColumnVirtualization is true), is to simply set the MaxWidth property of columns. An example:
public MainWindow()
{
    InitializeComponent();

    DataTable tab = new DataTable();
    for (int i = 0; i < 1000; i++)
        tab.Columns.Add("A" + i.ToString());
    for (int i = 0; i < 1000; i++)
    {
        DataRow r = tab.NewRow();
        for (int j = 0; j < 1000; j++)
            r[j] = "something " + (i * i * j * j).ToString();
        tab.Rows.Add(r);
    }

    DataGrid dg = new DataGrid() { EnableColumnVirtualization = true, EnableRowVirtualization = true };
    this.Content = dg;
    dg.ItemsSource = tab.AsDataView();
    dg.AutoGeneratingColumn += Dg_AutoGeneratingColumn;
}

private void Dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.MaxWidth = 100;
}

A: Setting the Width explicitly should work. Make sure that you do this once the DataGrid has been loaded.
Please refer to the following sample code which works for me.
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<DgItem> items = new List<DgItem>()
        {
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abc", B = "abc" },
            new DgItem() { A = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc", B = "abc" }
        };
        dg.ItemsSource = items;
    }

    private void dg_Loaded(object sender, RoutedEventArgs e)
    {
        foreach (DataGridColumn column in dg.Columns)
        {
            column.Width = new DataGridLength(column.ActualWidth, DataGridLengthUnitType.Pixel);
        }
    }
}

MainWindow.xaml:
<DataGrid x:Name="dg" AutoGenerateColumns="False" Height="100"
                  Loaded="dg_Loaded">
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding A}" />
        <DataGridTextColumn Header="2" Binding="{Binding B}" />
    </DataGrid.Columns>
</DataGrid>


text:
Q: HTML Tools: Ways to get the width and height of a desired div? If I want to make a div class in a CSS file which is simply a rectangular box on a page. how can I calculate the height and width of this div without excessive trial and error?
Really all I need is a simple tool which you can click on one section of the screen, and then click on another section of the screen and it gives you the horizontal, vertical, and diagonal  pixel distance between the 2 clicked points.  Does anyone know of a tool to do this?  Perhaps I can create one, this seems very useful.

A: regarding the first part: you can tweak around with your div in chrome developer tools- very convenient.
https://developers.google.com/chrome-developer-tools/docs/elements
regarding the second part: you can write a function than handles the mouseclick events and calculates the number you want based on the coordinates. this function can then be used as a snippet in chrome dev tools.
I will try to write one for you in a few minutes...

A: Screenshot > Open in GIMP or something similar > count pixels.
However, if you want actual developer tools, it depends on the browser:

*

*Firefox has Firebug (add-on). To find it with Firebug, look in the HTML view, right-click your element, click "Inspect in DOM", and find "innerWidth/innerHright".

*Chrome has Developer Tools (extension). I believe this shows you height/width just by hovering over the Element in HTML view.

*Opera has something built-in called DragonFly. Select your Element in HTML view, and in the right window select "Layout" and look at the "clientWidth/clientHight".

I don't believe there's a way to find either with Internet Explorer or Safari though.


text:
Q: Exposing local dockerised app using nginx docker container I have a julia app which has been dockerized using below docker file. And,I am running this local app as docker container on port 8080. The goal is to expose this docker app (port 8080) to public using nginx docker container.
I have followed this tutorial: https://www.domysee.com/blogposts/reverse-proxy-nginx-docker-compose and based on the instructions I have created two files, docker-compose.yml and nginx.conf as shown below.
Dockerfile for the local-app:
FROM julia:1.6

RUN apt-get update && apt-get install -y gcc
ENV JULIA_PROJECT @.
WORKDIR /home

ENV VERSION 1
ADD . /home

EXPOSE 8080

ENTRYPOINT ["julia", "-JApp.so", "-t", "auto", "-L", "src/App.jl", "-e", "App.run()"]

Docker-Compose:
version: "3.9"
services:
  nginx:
    image: nginx:alpine
    container_name: production_nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - .:/usr/share/nginx/html
      - ./nginx/error.log:/etc/nginx/error_log.log
      - ./nginx/cache/:/etc/nginx/cache
      - /etc/letsencrypt/:/etc/letsencrypt/
    ports:
      - 8080:80
      - 443:443

  local-app:
    image: local-app:latest
    container_name: production-local-app
    expose:
      -  "8080"

Nginx.conf:
events {

}

http {
  error_log /etc/nginx/error_log.log warn;
  client_max_body_size 20m;

  proxy_cache_path /etc/nginx/cache keys_zone=one:500m max_size=1000m;

  server {
    server_name app.local.hosting;

    location /local-app {
      proxy_pass http://localhost:8080;
      rewrite ^/local-app(.*)$ $1 break;
    }

    listen 80;
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/app.local.hosting/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.local.hosting/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
  }
}

However, running the docker-compose starts two containers, 1 app and 2 nginx, but nginx exits with some error. May I ask, what could be the potential cause of the service failure. Look forward to all the suggestions, thanks in advance!
Update:
Adding the output from terminal upon executing the docker-compose file:
user@user:~/Desktop/App$sudo docker-compose up
Starting production-local-app  ... done
Starting production_nginx      ... done
Attaching to production_nginx, production-local-app
production_nginx | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
production_nginx | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
production_nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
production_nginx | 10-listen-on-ipv6-by-default.sh: info: IPv6 listen already enabled
production_nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
production_nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
production_nginx | /docker-entrypoint.sh: Configuration complete; ready for start up
production_nginx | 2021/12/05 16:27:03 [emerg] 1#1: open() "/etc/letsencrypt/options-ssl-nginx.conf" failed (2: No such file or directory) in /etc/nginx/nginx.conf:23
production_nginx | nginx: [emerg] open() "/etc/letsencrypt/options-ssl-nginx.conf" failed (2: No such file or directory) in /etc/nginx/nginx.conf:23
production_nginx exited with code 1
production-local-app |
production-local-app |  Web Server starting at http://localhost:8080 - press Ctrl/Cmd+C to stop the server.