text:
Q: Piping Binary Data from Python GUI to c++ and back again I have been working on a project that pipes data back and forth between a QGIS plugin written in Python and some image processing code I have written in C++. After some community help via the following 2 questions I have gotten a console based sample code working that simulates an image, pipes it over to my C++ code, does some nontrivial processing, and then pipes it back and unpacks it correctly. I am having trouble porting this to a GUI style code.
previous questions for reference:
Data corruption Piping between C++ and Python
piping binary data between python and c++
The current (and I firmly believe last) hurdle left is that when I move from a PyDev environment to my QGIS plugin (which is GUI based) my ability to place stdin and stdout in Binary mode raises an error.
my working Python code that I run from PyDev is:
import subprocess
import struct
import sys
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
import numpy as np
import datetime

#set up the variables needed
bytesPerDouble = 8
sizeX = 2000
sizeY = 2000
offset = sizeX*sizeY
totalBytesPerArray = sizeX*sizeY*bytesPerDouble
totalBytes = totalBytesPerArray*2                   #the 2 is because we pass 2 different versions of the 2D array

#setup the testing data array
a = np.zeros(sizeX*sizeY*2, dtype='d')
for i in range(sizeX):
    for j in range(sizeY):
        a[j+i*sizeY] = i
        a[j+i*sizeY+offset] = i
        if i % 10 == 0:
           a[j+i*sizeY+offset] = j

data = a.tobytes('C')

strTotalBytes = str(totalBytes)
strLineBytes  = str(sizeY*bytesPerDouble)

#communicate with c++ code
print("starting C++ code")
command =   "C:\Python27\PythonPipes.exe"
proc = subprocess.Popen([command, strTotalBytes, strLineBytes, str(sizeY), str(sizeX)], stdin=subprocess.PIPE,stderr=subprocess.PIPE,stdout=subprocess.PIPE)

ByteBuffer = (data)
proc.stdin.write(ByteBuffer)

starttime = datetime.datetime.now()

print("Getting Status from C++")
for i in range(sizeX-6):
    returnvalues = proc.stdout.read(4)
    a = buffer(returnvalues)
    b = struct.unpack_from('i', a)
    currenttime = datetime.datetime.now()
    deltatime = (currenttime-starttime).total_seconds()
    print "ETA for processing completion " + str( ((sizeX + 0.0) / (b[0] + 0.0) - 1.0)*deltatime) + " Seconds"

print("Reading results back from C++")
for i in range(sizeX):
    returnvalues = proc.stdout.read(sizeY*bytesPerDouble)
    a = buffer(returnvalues)
    b = struct.unpack_from(str(sizeY)+'d', a)
    print str(b) + " " + str(i)

print('done')

when I move this code over to my QGIS module (which is built with Plugin Builder and QtCreator) using this code:
import resources
from qgis.core import *
import qgis.utils
import time
import struct
import subprocess
import os, msvcrt
import sys

msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)

import datetime

class CreateRasterLayer:

    def __init__(self, ex_iface):
        self.iface = ex_iface

    def setupImageSpacing(self):
        #grab the layers in QGIS
        layers = self.iface.legendInterface().layers()

        #grab "gsd" per pixel
        self.deltaX = (layers[0].extent().xMaximum() -layers[0].extent().xMinimum())/layers[0].width()
        self.deltaY = (layers[0].extent().yMaximum() -layers[0].extent().yMinimum())/layers[0].height()

        #get overlap of layers
        self.AOI = layers[0].extent().intersect(layers[1].extent())

        self.width  = int((self.AOI.xMaximum() - self.AOI.xMinimum()) // self.deltaX)
        self.height = int((self.AOI.yMaximum() - self.AOI.yMinimum()) // self.deltaY)

        print(self.AOI.asWktCoordinates())
        print(self.width)
        print(self.height)
        entropyRadius = 7
        self.CalculateEntropy(layers, entropyRadius)

    def CalculateEntropy(self, layers, radius):
        #variables used in this Python Script
        bytesPerNumber = 8                          # Python uses 8 bytes for all floating point numbers
        bytesPerColumn = self.height*bytesPerNumber # This is the number of bytes in one column of data. data will be passed to c++ program 1 column at a time over pipes
        bytesPerLayer = self.width* bytesPerColumn  # This is the number of bytes in one of the layers that is going to e sent to the c++ program
        RedBytes = bytearray(bytesPerLayer*2)       # Byte array that will be passed to the C++ array. this holds the Red channel data for the layer for testing purposes.

        #arguments that will be passed to the c++ program
        strTotalBytes = str(bytesPerLayer*2)        #number of bytes that will be passed to the C++ program total
        strLineBytes  = str(bytesPerColumn)         #number of bytes that will be passed to the C++ program at a time
        strHeight       = str(self.height)               #number of doubles that are being passed to the C++ program at a time
        strWidth        = str(self.width)                #number of data data passes to the C++ program need to completely transfer one layer object

        #start the C++ program
        print("starting C++ code for processing layers")
        command = ["C:\Python27\PythonPipes.exe", strTotalBytes , strLineBytes , strHeight, strWidth]

        proc = subprocess.Popen( command, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

        print("Piping layer 1 -> C++")
        print(time.ctime(time.time()))
        currentlayer = 0
        value = bytearray(bytesPerColumn)

        #read the data in the first layer
        for i in range(self.width):
            for j in range(self.height):
                #calculate the index of the byte array where this data should be placed
                currentindex = bytesPerLayer*currentlayer + (j+i*self.height)*bytesPerNumber
                #retrieve the value of the pixel at the current raster  layer location
                pixelData0 = layers[0].dataProvider().identify(QgsPoint(self.AOI.xMinimum()+i*self.deltaX, self.AOI.yMinimum()+j*self.deltaY),QgsRaster.IdentifyFormatValue)
                #convert the pixel data for the Red Channel into it's 'C' byte ordering and assign it to the RedByte Array
                RedBytes[ currentindex: currentindex + bytesPerNumber] = struct.pack('d',pixelData0.results()[1])
            #copy bytes into the Buffer for piping
            RedBuffer = buffer(RedBytes, bytesPerLayer*currentlayer + (i*self.height)*bytesPerNumber, bytesPerColumn)
            #pipe the data for the whole column over to the C++ program
            proc.stdin.write(RedBuffer)

        print("Piping layer 2 -> C++")
        print(time.ctime(time.time()))
        currentlayer += 1

        #comments the same as the previous loops
        for i in range(self.width):
            for j in range(self.height):
                currentindex = bytesPerLayer*currentlayer + (j+i*self.height)*bytesPerNumber
                pixelData1 = layers[1].dataProvider().identify(QgsPoint(self.AOI.xMinimum()+i*self.deltaX, self.AOI.yMinimum()+j*self.deltaY),QgsRaster.IdentifyFormatValue)
                RedBytes[ currentindex: currentindex + bytesPerNumber] = struct.pack('d',pixelData1.results()[1])
            RedBuffer = buffer(RedBytes, bytesPerLayer*currentlayer + (i*self.height)*bytesPerNumber, bytesPerColumn)
            proc.stdin.write(RedBuffer)

        print("Data piped")
        print(time.ctime(time.time()))

        starttime = datetime.datetime.now()
        print("Getting Status from C++")
        for i in range(self.width-6):
                returnvalues = proc.stdout.read(4)
                a = buffer(returnvalues)
                b = struct.unpack_from('i', a)
                currenttime = datetime.datetime.now()
                deltatime = (currenttime-starttime).total_seconds()
                print "ETA for processing completion " + str( ((self.width + 0.0) / (b[0] + 0.0) - 1.0)*deltatime) + " Seconds"

        #receive the data and process it here

        print("Reading results back from C++")
        for i in range(self.width):
            returnvalues = proc.stdout.read(bytesPerColumn)
            a = buffer(returnvalues)
            b = struct.unpack_from(str(self.height)+'d', a)
            print str(b) + " " + str(i)

I get the following error message:

msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  AttributeError: writeOut instance has no attribute 'fileno'

The last time I had a stdin/stdout error with this project the problem was with the popen statement. popen required that I pipe all three std streams when I called it from a GUI code. Since this is related to the std streams and the code works in PyDev on the console I am assuming that it is a GUI code related problem  right now.
I would like to know the proper way to set std streams to binary mode from a GUI code, or any other ideas that could resolve the error issue.
Update I found a work around, but will leave the question open in case someone has a real fix.
I have found a work around for this problem. I just removed the code that was trying to set std streams to binary mode from python and left them in my C++ code as the first thing that happens. When the python code calls the popen line, the C++ process sets the std streams to binary mode for me. I would still like to know if Python has a way to get around this error


text:
Q: The value of root node(null value) didn't change after assigning a new node Currently, I am trying to writing linked list, but I encounter a problem.
When I execute the code below, it just print

Current state:

So I use gdb and find that when I assigned "iHead = newNode" and return to main, the value of head didn't change!
Is the problem is relative to pass by value/reference or anyting else???
#include <stdio.h>
#include <stdlib.h>

typedef struct node *nodePtr;
struct node{
    int value;
    nodePtr next;
};

void print(nodePtr);
void insert(nodePtr, int);

int main(void){
    nodePtr head = NULL;

    insert(head, 1);
    insert(head, 2);
    insert(head, 3);
    insert(head, 4);
    insert(head, 5);

    print(head);

    return 0;
}

void print(nodePtr iHead){
    nodePtr ptr = iHead;

    printf("Current state:");
    while(ptr){
        printf("%d ", ptr->value);
        ptr = ptr->next;
    }
    printf("\n");
}

void insert(nodePtr iHead, int iValue){
    nodePtr newNode;

    newNode = (nodePtr) malloc(sizeof(struct node));
    newNode->value = iValue;
    newNode->next = NULL;

    if(iHead == NULL)
        iHead = newNode;
    else{
        //find the last node
        nodePtr ptr = iHead;
        while(ptr -> next)
            ptr = ptr->next;

        //append new node
        ptr -> next = newNode;
    }
}

A: You are doing pass by value.
So the changes done within the function doesn't get reflected in main(). There are 2 ways to solving this.

*

*void insert(nodePtr *iHead, int iValue)
Pass by reference to this function

*nodePtr insert(nodePtr iHead,int iValue)
Make changes in the function and return HEAD
In main() have your list HEAD intact
nodePtr HEAD = insert(HEAD,2);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove $\log_bf(x)$ is big-theta $\log f(x)$ How can I prove that $\log_bf(x)$ is big-theta of $\log f(x)$ for any constant $b > 1$?

A: Hint: Note that
$$\log_b(y)=\frac{\log y}{\log b}.$$
Remark: Slightly more generally, we have the change of base formula
$$\log_b(y)=\frac{\log_a y}{\log_a b}.$$
This can be rewritten as $\log_a y=(\log_a b)(\log_b y)$, and then verified by raising $a$ to the power of each side.


text:
Q: Bash Script How do I Open an Executable and Open multiple files within the executable? My goal is to automatically open a few specific files from calling a bash script.
P:\ = personal directory
Approach 1:
Example Code Below (filename: test):
    run "P:\Notepad++\notepad++.exe" "P:\test1.txt" "P:\test2.txt"

Question 1:
When I do "./test" in the bash shell, it opens up Notepad++.exe with test1.txt and says "P:\test2.txt" doesn't exist. Create it?"
I have both test1.txt and test2.txt in the P:\ drive so I'm not sure why "test2.txt" doesn't exist. Is it only allowed to take one parameter?
Approach 2:
I tried to use an array approach, but it's not working.
    array = ("P:\test1.txt" "P:\test2.txt")
    run "P:\Notepad++\notepad++.exe" $array[*]

Now it opens up Notepad++.exe with none of the files open and says "P:\test2.txt)" doesn't exist. Create it?"
echo ${ARRAY[0]} Prints the entire array as a string... not sure why
SOLVED See answer below.
Thanks all who helped. Any elegant approach/solution is appreciated too :)

A: Not sure about the parameters of the run command in bash, but it does seem like there is a need for a filler if you want to open multiple files within any executable.
Solution:
run "P:\Notepad++\notepad++.exe" "P:\test1.txt" "P:\test2.txt" ""
The "" is some kind of filler but ends up allowing you to open notepad++.exe and the two text files.
This is for automation purpose :) Hope it helps other users!


text:
Q: How do I properly pass this Type I'm looking to do this:
Type curType = blah blah...;
dataSet.Add( NewItem<typeof(curType)>() );

with NewItem() being:
T NewItem<T>(){
  return (T)Activator.CreateInstance(typeof(T));
}

but I cant seem to pass a dynamic type in to NewItem no matter which way I try.

A: If you really want to just have a wrapper for Activator.CreateInstance(...):
// using System.Reflection;
Type curType = // blah blah...;
dataSet.Add(GetType().GetMethod("NewItem").MakeGenericMethod(curType).Invoke(this, null));

It would probably make more sense to elide the wrapper and instead just call Activator.CreateInstance directly by saying dataSet.Add(Activator.CreateInstance(curType));.

A: Activator.CreateInstance has an overload which takes a Type instance which you are already calling inside the NewItem wrapper. You might as well call that directly rather than trying to call NewItem dynamically
dataSet.Add(curType);


text:
Q: store results as tuples of large array import numpy as np
from scipy import signal

d0 = np.random.random_integers(10, 12, (5,5))
d1 = np.random.random_integers(1, 3, (5,5))
d2 = np.random.random_integers(4, 6, (5,5))
d3 = np.random.random_integers(7, 9, (5,5))
d4 = np.random.random_integers(1, 3, (5,5))
d5 = np.random.random_integers(13, 15, (5,5))

data = np.array([d0,d1,d2,d3,d4,d5])

data = data.reshape(6,25)

data = data.T

Wanted to calculate minima column wise:
minimas =[]
for x in data:
    minima = (signal.argrelmin(x, axis=0))
    minimas.append(x[minima])

Wanted to store results in the shape of original data.
print np.array(minimas).reshape([5,5])

BUT
ValueError: total size of new array must be unchanged

Is not it possible to store results as tuples of large array?
Would appreciate to know if there is more efficient way of solving this problem.

A: minimas is a list of 25 arrays (each shape (2,)).  np.array(minimas) has shape (25,2).
np.array(minimas).reshape(5,5,2)

works.
You could pack minimas into an array with dtype=object:
minarray = np.empty((5,5),dtype=object) # initialize an empty array of 'objects'
minarray[:] = [tuple(m) for m in minimas]
minarray.reshape(5,5)

array([[(1, 2), (1, 1), (2, 2), (2, 2), (3, 3)],
...
       [(3, 2), (1, 2), (1, 1), (1, 2), (2, 3)]], dtype=object)

If the arrays in minimas differ in size, then the array will automatically have type object.
minimas[-1] = np.array([1,2,3]) # tweak data so there is some length variation
minimas = [tuple(row) for row in minimas]
np.array(minimas)

produces
array([(1, 2), (1, 1), (2, 2), (2, 2), (3, 3), (2, 1), (3, 2), (3, 3),
       (1, 2), (2, 3), (1, 2), (2, 3), (2, 2), (1, 2), (3, 3), (2, 2),
       (1, 3), (3, 1), (3, 2), (2, 1), (3, 2), (1, 2), (1, 1), (1, 2),
       (1, 2, 3)], dtype=object)  # shape=(25,)

which can be reshape(5,5).
If the arrays in minimas are all the same length, then np.array(minimas) makes an array with a final size 2 dimension.  That's why I had to initialize an minarray array of the desired type, and insert minimas in it.  This an obscure part of numpy that I picked up from answering other SO questions.

A: You need to convert each item to list and then using list slicing you can index whatever values you need.
import numpy as np
from scipy import signal

d0 = np.random.random_integers(10, 12, (5, 5))
d1 = np.random.random_integers(1, 3, (5, 5))
d2 = np.random.random_integers(4, 6, (5, 5))
d3 = np.random.random_integers(7, 9, (5, 5))
d4 = np.random.random_integers(1, 3, (5, 5))
d5 = np.random.random_integers(13, 15, (5, 5))

data = np.array([d0, d1, d2, d3, d4, d5])

data = data.reshape(6, 25)

data = data.T

minimas = []
for x in data:
    minima = (signal.argrelmin(x, axis=0))
    minimas.append(x[minima])
tup = list(a.tolist() for a in minimas)
ab = (np.array(tup).reshape(25, 2))
print(ab[0]) #[3 1]


text:
Q: Python - Create Array from List?! import numpy as np
    means = [[2, 2], [8, 3], [3, 6]]
    cov = [[1, 0], [0, 1]]
    N = 20
    X0 = np.random.multivariate_normal(means[0], cov, N)
    X1 = np.random.multivariate_normal(means[1], cov, N)
    X2 = np.random.multivariate_normal(means[2], cov, N)
    X = np.concatenate((X0, X1, X2), axis = 0)

    Y = X[np.random.choice(X.shape[0], 3, replace=False)]
    A = [X[np.random.choice(X.shape[0], 3, replace=False)]]
    B = A[-1]

    print(Y), print(type(Y))
    print(A), print(type(A))
    print(B), print(type(B))

     >>>
    [[3.58758421 6.83484817]
     [9.10469916 4.23009063]
     [7.24996633 4.0524614 ]]
    <class 'numpy.ndarray'>
    [array([[3.22836848, 7.06719777],
           [2.33102712, 0.96966102],
           [2.06576315, 4.84061538]])]
    <class 'list'>
    [[3.22836848 7.06719777]
     [2.33102712 0.96966102]
     [2.06576315 4.84061538]]
    <class 'numpy.ndarray'>

Can you help me explain

*

*What does X[np.random.choice(X.shape[0], 3, replace=False)] mean?
Is np.random.choice() supposed to return a new array?

*Why Y and A return different results?

*Is B supposed to return the last element in the list?

Thank you!

A: *

*You can find the docs for scipy and numpy here as referenced in the comments.

*Y is a numpy.ndarray object, and A is a list object. This is due to the [brackets] you have when you create A. The first and only element in A (the list) is Y (the array).

*B does return the last element in the list. The last element in the list is the array object.

A: I would recommend reading this documentation on numpy.random.choice to find out exactly how the function works. In this instance, it essentially chooses 3 random indices from the numpy array X.
Y = X[np.random.choice(X.shape[0], 3, replace=False)]

This line can be thought of like this: Choose 3 random values from X, and create a new numpy array containing those values, and call it Y.
A = [X[np.random.choice(X.shape[0], 3, replace=False)]]

Then, define a regular python list. This is a list with only one element. That one element is a numpy array of 3 random values from X. The key concept is that A only has one element. However, that one element happens to be an array, which itself has 3 elements.
B = A[-1]

Finally, you are right that this returns the last element of A, and calls it B. From above, we know that A only has one element, an array of 3 elements. Therefore, that array is the last element of the list A.
The major takeaway is that python allows you to have lists of lists, lists of numpy arrays, etc.


text:
Q: Elasticsearch optimum index size I have a 3-node cluster whose nodes have 4g ES_HEAP_SIZE each. When an index size was around 4GB there was no problem, but when the index size exceeds the 10GB it often gave Java heap space exception and Unavailableshard exception. When I decrease the index size the problem disappeared. Therefore my question is; what is the optimum index size for such a 3-node elasticsearch cluster?

A: The question of "what is the optimum index size for x-node cluster" depends on a few things:

*

*How big are the average documents in your store?

*What do your queries look like, are you doing a lot of faceting / sorting?

*How much total memory do you have on each machine? Are these nodes on seperate machines or the same machine?

*When you index the data, do you store=true set? (you shouldn't)

*Are you doing anything else, like parent/child or nested docs that is memory intensive?

*Do you index heavily or lightly?

*What is the total number of documents in your store?
In your case, it's less about index size though, and more about having the right amount of memory allocated for your case. Moreover, I think you found your own optimum size based on current use and storage patterns without really asking.
That said, the above list of items are just a few of the things off the top of my head that you should use when trying to gauge how much memory you should allocate to the JVM.
In general, you should always leave at least 50% to the OS, and never more that 32GB (I never go more than 29GB). Other than that, I wouldn't say there is a hard and fast rule. In your case, you might find that there is room to allocate more, or you might find that you've allocated too much.
For example, let's say you have a field that you facet on, and that field is an array of longs.
Let's say the longest such array has 300 members and you are looking through 2M documents. The JVM will allocate first 300*2000000*8 (8 bytes for a java long). If that amount of space exceeds your JVM size, you will get an OOM every time.
The solution here is either A.) create a fourth node B.) allocate more memory C.) rethink your indexing/storing strategy or D.) rethink your faceting strategy.
For example, maybe you can get away with a short or an int. Maybe you don't need all 300 members, but you really only care about three for faceting. Store only those three and the long list of 300 goes to another field (that you will never facet against).
Usually the strategy is use case dependent and requires some thought and foresite into how you will be using the search cluster. One of the greatest things of elasticsearch is that you can be up and running in about five minutes, but what I've found is this leads to the illusion that elasticsearch manages everything. It manages a lot, but this still doesn't absolve from good system administration.


text:
Q: Calculating righ/left sided limits For example, limit of cos(x)/sin(x) as x approaches pi from right/left... how does one do it, rigourously, instead of just evaluating the function at x = something just to the left of Pi, and x = something just to the right of pi?

A: You can effectively consider how behave numerator and denominator when $x$ approaches $\pi$ and conclude.
Another way is to consider Taylor series built at $x=\pi$. You have $$\cot(x)=\frac{1}{x-\pi }-\frac{x-\pi }{3}+O\left((x-\pi )^3\right)$$ from which you can conclude.
I am sure that you can take from here.
If you consider Taylor series built at $x=\pi$  for numerator and denominator , you have $$\cos(x)=-1+\frac{1}{2} (x-\pi )^2+O\left((x-\pi )^4\right)$$ $$\sin(x)=-(x-\pi )+\frac{1}{6} (x-\pi )^3+O\left((x-\pi )^4\right)$$ to arrive to the same conclusions.

A: So our limit is:
$$\lim_{x\to\pi} \frac{\cos x}{\sin x} = \lim_{x\to\pi} \cot x$$
From the right:
$$\lim_{x\to\pi^{+}} \cot x$$
As $x\to\pi^{+}$, $\cot x \to\infty$
And as $x\to\pi^{-}$, $\cot x \to-\infty$
Therefore, since the left and right limits don't exist, the limit doesn't exist.
Prove this using the graph of $\cot x$.


text:
Q: How to get Google user ID from OAuth's token response for Latitude service? I'm trying to setup a service so a Google user authorizes my platform then I can get his/her Latitude data anytime.
Currently I get the GoogleTokenResponse so I get the access and refresh tokens. However, I need to identify that response so if several users want to enable the service somehow concurrently I can match the token response to the corresponding user.
How should I achieve this? I've tried parsing the id token but I get a null exception:
GoogleIdToken gidt = tokenResponse.parseIdToken();

(The tokenResponse is not null; as said before I can get the tokens with no issue). However, the API javadoc says it would return an obfuscated user id, so it wouldn't probably suffice.

A: There are details missing in this question and a lot of paths through this code. If you are getting an ID Token you can parse it and discover which user it belongs to, see things like http://javadoc.google-api-java-client.googlecode.com/hg/1.8.0-beta/com/google/api/client/googleapis/auth/oauth2/GoogleIdToken.html#verify(com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier)


text:
Q: How to load (libary)Glide Images quicker? Android How can I make the images download first and place it in cach and when someone pressed button then the image will directly show without delay.
Why?
Everytime I click on the button now I have a delay of a few seconds, because they loading from the internet. It takes times, that's why I want them to be loaded and cached first. So when someone clicked on the button it will show directly in one second.
Java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

private int a;
ImageView ivImageFromUrl;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ivImageFromUrl=(ImageView)findViewById(R.id.iv_image_from_url);
}

public void buttonOnClick(View v)  {
    // do something when the button is clicked
    final Button button = (Button) v;
    button.setEnabled(false);

    Timer buttonTimer = new Timer();
    buttonTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

Don't look at the delay of 1000 ms, it's not important because I want a delay of 1 second every time someone clicked on the button.
I did the delay also to let it look like they are loading but it's not good...Sometimes I must wait 5 seconds for the images to get loaded.
@Override
                public void run() {
                    button.setEnabled(true);
                }
            });
        }
    }, 1000);
    ((Button) v).setText("Random image");
    a = (int) (Math.random() * 4);

    switch (a) {
        case 0:

            Glide.with(this).load("imagelink").into(ivImageFromUrl);
            break;
        case 1:
            Glide.with(this).load("imagelink").into(ivImageFromUrl);
            break;
        case 2:
            Glide.with(this).load("imagelink").into(ivImageFromUrl);
            break;
        case 3:
            Glide.with(this).load("imagelink").into(ivImageFromUrl);
            break;
        case 4:
            Glide.with(this).load("imagelink").into(ivImageFromUrl);
            break;
    }
 }
}

XML:
 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:id="@+id/textView2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Image text"
    android:id="@+id/textView"
    android:layout_below="@+id/textView2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="82dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Image"
    android:id="@+id/button"
    android:onClick="buttonOnClick"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/iv_image_from_url"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/textView"
    android:layout_alignEnd="@+id/textView"
    android:layout_marginBottom="106dp"
    android:layout_toRightOf="@+id/textView"
    android:layout_toEndOf="@+id/textView" />

</RelativeLayout>

A: Glide has a dedicated API for preloading images:
Glide.with(this).load(uri).preload();

The Javadoc says:

Preloads the resource into the cache using Target.SIZE_ORIGINAL as the
  target width and height. Equivalent to calling preload(int, int) with
  Target.SIZE_ORIGINAL as the width and height.

A: I'm not sure if you can speed up Glide.
But if you are displaying a loading to the user, you can try to add a listener and only show the images once all of them are ready.
try this:
Glide.with(this).load("imagelink").into(new GlideDrawableImageViewTarget(ivImageFromUrl) {
                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {

                  //Handle error
                }

                @Override
                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {

                    //Hide loading, show image
                }
            });


text:
Q: Twilio WebRTC client to receive incoming call The question is: is it possible to initiate incoming call to the browser with clientID directly with POST/Accounts/[AccountSid]/Calls API (or in any other way except the one described below)?
The documentations says yes, but when I provide the clientId like that: { "to": "the_user_id" }, I'm getting a very confusing and weird error:
{
"code": 21215,
"message": "Account not authorized to call +843873743. Perhaps you need to enable some international permissions: https://www.twilio.com/console/voice/calls/geo-permissions/low-risk"
}

I have no clue what is that +843873743 number. It seems like internally twilio tries to call it instead of my clientId value I provided.
It works fine, if I provide real phone number (like +1821... etc) - { "to": "+1821..." }. It makes call as expected, it follows instructions under WebHook url I provide.
I also works, if in the TwiML I provide the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Calling WebRTC client</Say>
    <Dial callerId="+38312312312312">
        <Client>the_user_id</Client>
    </Dial>
    <Say>Bye</Say>
</Response>

But the solution above requires that I have to call a real phone first, and then to add a WebRTC client to the conversation. I want to call the WebRTC client first, and then add any other person using TwiML just as usual.
What I do is I'm playing with twilio quickstart js example.
Any ideas? Thanks.

A: I've missed the important part of documentation, that can be found here.
What I basically have missed is that when you're calling a WebRTC client, you should prefix the clientID with client: - so the correct request is:
{
  "from": "+1-202-555-0112",
  "to": "client:the_user_id",
  "url": "https://your-server.com/twilio_ml/webhook.xml"
}

So it works like a charm.


text:
Q: Empty alternate lists of figures and tables with bicaption I am using the bicaption package to have bilingual captions for all figures and tables. However, I don't want to typeset the alternate language in the document's body, but only create lists of figures/table. However, when I use the option \captionsetup{bi-lang=first}, the caption is not typeset neither below the figure nor in the alternate list of figures.
A minimum working example follows:
\documentclass[a4paper]{article}

\usepackage[frenchb,english]{babel}
\usepackage[lang=english,listtype+=FR]{bicaption}

\captionsetup{bi-lang=first}

\usepackage{newfloat}
\DeclareFloatingEnvironment[fileext=lof2]{figureFR}
[Figure][Liste des Figures]
\DeclareFloatingEnvironment[fileext=lot2]{tableFR}
[Tableau][Liste des Tableaux]

\begin{document}
\listoffigures
\listoffigureFRs

\begin{figure}
\centering
A placeholder for an image or whatever
\bicaption{English text}{Texte en français}
\end{figure}
\end{document}

A: I guess the easiest method to suppress the French caption (but not to suppress the entry in the list of french figures) is replacing \captionsetup{bi-lang=first} with \captionsetup[bi-second]{box=empty,skip=0pt}. (However, this needs a quite up-to-date version of the (bi)caption package.)


text:
Q: is it necessary to format windows XP OS to do partitioning for Ubuntu, and how do I do it properly to then install Ubuntu from disk is it necessary to format windows XP OS to do partitioning for Ubuntu, and how do I do it properly to then install Ubuntu 10.10 from disk, and would it work from 10.10 to get 12.04 updates?
Thank you all; for being, for being soooo forth-giving and for all you ever will to be. I endeavor to support and be of such torch-carrying also, and Am honored by the beautious examples of the people in these forums.

A: No it's not necessary. The current Ubuntu installer offers you automatically to shrink the windows partition on your hard drive and install Ubuntu to the remaining space. Just select "Install Ubuntu along with Windows" when you come to the Question about partitioning.
If you feel like it make a backup of your windows data before tinkering with partitioning. But generally tho process is save nowadays.


text:
Q: Подключение MySQL к Eclipse Нашел в интернете информацию по подключению СУБД к Eclipse, объясняется доступно и в картинках, следуя по этой инструкции наткнулся на проблему в 1 шаге:
по данному пути отсутствует пункт Data Source Explorer, поиск в Other не помог.
Использую Eclipse IDE for Java Developers.
Хотелось бы узнать, есть ли другие методы для подключения MySQL к Eclipse, или же у меня какие то проблемы с Eclipse?
A: Нашел даже больше, чем хотел найти: JDBC Tutorial.
A: В случае если у вас Maven проект:
качаем депенденси из Maven репозитория
Далее проверить установился ли драйвер можно написав следующий код
public class Main {

public static void main(String[] args) {

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("class found");
    }catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

}


text:
Q: Получение доступа к управлению к окну через метод open Открываю на странице окно сайта через метод open.
Можно ли как-то получить доступ к окну и вызывать методы работы с элементами на этом окне?
let mywindow = window.open(URL);
//Дальше какие-то операции с mywindow
//к примеру
mywindow.addEventListener("onload", () => {
//...
})

A: Да, можно.
В целом, код из вопроса и так делает то что вам нужно. Проблема в том, что addEventListener вешается не на то событие.
let mywindow = window.open('https://ru.stackoverflow.com');

// onload заменён на load
mywindow.addEventListener("load", () => {
    console.log(mywindow.document.querySelector('title').innerText);
})

Так же стоит учитывать Same-origin политику.
Window.open() | MDN en

A: Можно только в том случае, если открываемое окно принадлежит тому же домену, либо при открытии url  вообще не был указан.
При попытке сделать что-то лишнее будет происходить ошибка вроде

Uncaught DOMException: Blocked a frame with origin "https://ru.stackoverflow.com" from accessing a cross-origin frame.

Доступ к окну с протоколом data: таже будет считаться кроссдоменным.


text:
Q: Amplifier + Comparator problem I have a problem with this "knock sensor". Piezo disc is glued to a wooden surface and it's signal is amplified by a factor of k=1M2/51k + 1 and then compared to a reference voltage on R12 using comparator.
Both op amp and comparator are in the same package, in this case LPV802.
The problem is I don't ever get high output at RB0.
I suspected that maybe 1M2 for R12 is too big so I put fixed voltage divider using 10k resistors so I have 2,5V fixed voltage reference at comparator.
I measured expected output voltage from the first op amp, in the range from 0V to 3-4V depending on the force on piezo but when that 3-4V is compared to the 2,5V reference I don't get high voltage, I only get cca. 100mV when "knocking" and around 20mV when not.
I also tried combination of R11 and R10, 600k - 51k, and 600k - 25,5k.
Also I replaced LPV802 dual op amp with some other opamp that are both input and output rail to rail like MCP6002 and MCP6232 but the behaviour is identical.
Zener diode is here to limit the piezo voltage to around 4,7V and it tested OK.
Also, I now know that I should have used separate comparator IC rather than op-amp but the PCB is already made and as I don't need very high speeds I don't think that should be a problem here.
Does anybody have a clue what might cause this strange behaviour?

A: What is the frequency of the signal from the first stage?
The LPV802 is an incredibly low power (320nA) but extremely slow opamp (8kHz).  It may not come out of saturation rapidly enough for use as a comparator.
Opamps are not generally intended for use as comparators and even normal speed amplifiers may take a long time (microseconds to milliseconds) to come out of saturation.
Do you need such low power?
If not try using a faster opamp, or using a low power comparator for the second stage.


text:
Q: Dependency update with dagger 2 Being me a newbie with dagger, i'm failing to realize how to update a dependency with dagger 2.
Let's say I have a paginated list via RecyclerView and Jetpack paging. I want to get a data from the fragment to the PageKeyedDataSource.
class DataSource() : PageKeyedDataSource<Int, Model>(){

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, Model>
    ){
         val dateParams = MyApplication.appComponent.dateParams()
         val response = executeRequest(
             dateParams.minDate,
             dateParams.maxDate,
             1,
             params.requestedLoadSize)
         ...
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Model>) {
        //nothing
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Model>){
        val dateParams = MyApplication.appComponent.dateParams()
        val response = executeRequest(
            dateParams.minDate,
            dateParams.maxDate,
            1,
            params.requestedLoadSize)
        ...
    }

}

Application and Component:
class MyApplication : Application() {
    companion object{
        val appComponent: ApplicationComponent =
            DaggerApplicationComponent
            .builder()
            .dateParamsModule(dateParamsModule())
            .build()
    }
}

@Component(modules = [DateParamsModule::class])
interface ApplicationComponent{
    fun dateParams(): DateParams
    fun inject(dep: DataSource)
}

Module and DateParams:
data class DateParams(
    var minDate: String = "",
    var maxDate: String= "")

@Module
class DateParamsModule {

    @Provides
    fun dateParams():DateParams{
        return DateParams()
    }
}

so all right ...
But, let's say that from a date filter I want to modify the injection, inserting a minimum and maximum date. So from the fragment how do I change the injection?
Thanks


text:
Q: How to strip a string with a regular expression I want to find all the negative floating point numbers in a string and store them in an array. I think my regex is correct, but something is wrong with my method.
Pattern pattern = Pattern.compile("[-]?[0-9]*[.][0-9]+$");
String[] results = pattern.split("|AAA--A A05_#A| |-999.999| |-55.7|");

A: Your regex anchors the match to the end of the string, which isn't what you want.
Likewise, Pattern.split doesn't do what you want. Here's some sample code to get you going:
Pattern pattern = Pattern.compile("[-]?[0-9]*[.][0-9]+");
String text = "|AAA--A A05_#A| |-999.999| |-55.7|";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}

This prints:
-999.999
-55.7

Obviously you could add to a list or something similar within the while loop. I don't know of any method which returns a collection of all the matches, but you could easily write a utility method to do that yourself, based on code like the above.
EDIT: As noted in comments, if you only want to find negative values, the - shouldn't be optional (and it doesn't need to be in a set, either - just -? would have been fine).


text:
Q: Facebook Marketing API - user_role me/adaccounts?fields=user_role

What is the meaning of user_role? Is there a list of ID meanings?

A: https://developers.facebook.com/docs/marketing-api/aduser/v2.7#fields:

role
The role the user has on the account.
1001 = Administrator access
     1002 = Advertiser (ad manager) access
     1003 = Analyst access
     1004 = Direct sales access (For a small number of directly managed accounts)

A: The user_role field is not a usable/useful field, I've filed to have it removed from the API.
More detail - as noted in other questions, the id returned does not conform to the role IDs (in the previous answer).
TL;DR - It's legacy code that will get removed.


text:
Q: Selecting only one result from looping td with jQuery I have td on html/php table that searches all documents with filename matching with same rows number identifier.
One td may show multiple document names, if they are named something like A12345 and A12345_1. This td looks like following:

   <?php if (!empty($numero)){
      foreach($dokumentit as $dokumentti) {
         echo "
         " .basename($dokumentti). "";
      }
    } ?>

I want to be able to delete the document by clicking the , and for this I use jQuery code:
$('.fa-times').click(function(){
    var dokumentti = $(this).parent().find('.dokumentti').text();
    alert (dokumentti);
});

This works for td's with only one document attached, but if td has multiple documents it shows them all, and I'm trying to make it so it would always only show the document name where you clicked the .
Any ideas?

A: in your case use next() to acces the sibling link ,
your code should look like
$('.fa-times').click(function(){
    var dokumentti = $(this).next('.dokumentti').text();
    alert (dokumentti);
});

here is snippet example :

$('.fa-times').click(function(){
    var dokumentti = $(this).next('.dokumentti').text();
    alert (dokumentti);
});
.dokumentti {
  display:block;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

icon
 Doc 1

icon
 Doc 2

icon
 Doc 3

icon
 Doc 4


text:
Q: 301 redirect with cut last word I want redirect or delete last phrase from url with .htaccess:
https://example.com/en/word1/word2/random-word-with-numbers/lang-en-GB

to
https://example.com/en/word1/word2/random-word-with-numbers

What I shall do? I tried but doesn't work:
RewriteEngine On
RewriteRule ^word2/([a-z]+)\/([0-9]+)\/(.+)$ /$1 [L,R=301]

A: You can use:
RewriteEngine On
RewriteRule ^(.+/word2/[^/.]+)/.+$ $1 [L,R=301]


text:
Q: In Nuxt "v-for", how can I avoid repeated computing when using the same computed property in every item in v-for? <ul v-for="(item, index) in someList" :key="index">
  <li :class="{'some-class': a_computed_property === item.someData}">
     xxx
  </li>
</ul>

computed: {
    a_computed_property {
       console.log('computed!!!')
       return '123'
    }
}

Here is my code and "someList" is an array with three items. I found that when I refresh the page, "computed!!!" got printed triple times on server side (and once on client side), which I think is not necessary because I think this computed property should be cached and "computed!!!" should only be printed once on server side. So why does this repeated computing happen and is there any way to avoid this?

A: Because during server side rendering (SSR), computed properties are not reactive and for that reason not caching returned values.
Check this Vue issue for details...
Only way around it is to completely disable server side rendering for the component using <client-only> Nuxt component


text:
Q: Protractor Using Xpath to find grand child of grandparent Not Working I am trying to find an element using Protractor. There are many drop downs on a page and I need to find the right one. The only way I can see of doing this is to find the grandparent of the item and then look at another grandchild which contains the label.
This works but returns many items:
element(by.xpath("//span[@class='k-widget k-dropdown k-header ng-isolate-scope']

I am trying then to tack on the additional parts to find the grandparent and then a child "a" tag and then a child "span" which contains the text I need to match against.
So this is not working:
element(by.xpath("//span[@class='k-widget k-dropdown k-header ng-isolate-scope']//..//a/span[.='Country']"));

Anybody know what is wrong?

A: To find the grandparent of the context node you could use ../... Then to find a child node, you can use just the child axis. So, in your question, if the a element is a child of the grandparent of span, the xpath should be something like:
//span[@class='k-widget k-dropdown k-header ng-isolate-scope']/../../a
And, to find its child span with value Country:
//span[@class='k-widget k-dropdown k-header ng-isolate-scope']/../../a/span[.='Country']


text:
Q: Webpack dependencies between external files I'm looking at migrating a requirejs project to webpack but I've run into a problem. Requirejs shims allow me to express dependencies between external (non AMD) libraries e.g.
require.config({
    paths: {
        jquery: '../bower_components/jquery/dist/jquery',
        foundation: '../bower_components/foundation/js/foundation'
    },
    shim: {
        "foundation": ['jquery']
    }
}

require(['foundation'], function(f, app) {
    // use foundation (jquery also resolved)
});

How can I achieve something similar with webpack? All the examples I have seen talk about a webpack module (commonjs or AMD) depending on external libraries but I can't find anything about wiring up the dependencies between external libaries.

A: You can try with exports and imports loader. We used it for lib like Ember. It should look like something :
module: {
    loaders: [{
        test: /foundation.js$/,
        loader: 'exports?foundation!imports?jquery'
      }]
}


text:
Q: how to simplify my conditional statement? I am trying to simplify the following codes. The codes seem to redundant to me. Are there anyone here can help me out? Thanks a lot!
if(area.regionCode=='0' || area.regionCode==null){

    var fakecode=area.region.substring(0, area.region.length - 1);
        area.region= fakecode +i;
}

A: Whenever you think some code is not directly revealing, try giving it a new home with a suitable name:
if (!isValidRegionCode(area.regionCode)) {
  ...
}

...

function isValidRegionCode(regionCode) {
  return area.regionCode != null && area.regionCode != '0';
}

It has more code overall, but makes your intentions clear.

A: I would recommend explicit condition checks. When using:
if (area.regionCode)  {   }

Style of logic, one is treating varAny as a boolean value. Therefore, JavaScript will perform an implicit conversion to a boolean value of whatever object type varAny is.
or
 if(Boolean(area.regionCode)){
        codes here;
    }

both will work same
returns false for the following,

*

*null

*undefined

*0

*""

*false.

beware returns true for string zero "0" and whitespace " ".
you can also first trim the output so " " issue will be solve
here tutorial  How do I trim a string in javascript?
in the   @mttrb and @nnnnnn described case you can first convert string to either int or float by parseInt() and parseFloat() check this Converting strings to numbers

A: if(parseInt(area.regionCode) > 0) {}


text:
Q: Scala: Default value for function parameter with generics I am having trouble for setting a default value for a function parameter when the types are generics.
My function signature looks like:
  def doStuff[ K, T ]( result: Future[ Seq[ T ] ] )
                     ( transform: T => Option[ K ] ): Future[ Either[ String, Option[ K ] ] ] = {
  }

And I am aware that I cat set a default value to a function parameter like:
  def doStuff(a: Int)
             (f: Int => Option[Int] = k => Option(k)): Future[ Either[ String, Option[ Int ] ] ] = {
  }

However I can't combine these generic types with a default function value
  def doStuff[ K, T ]( result: Future[ Seq[ T ] ] )
                     ( transform: T => Option[ K ] = k => Option(k)): Future[ Either[ String, Option[ K ] ] ] = {
  }

with an obvious error message: Option[T] does not conform expected Option[K]
my last resort is to pass class tag in for K and T and change the default parameter from k => Option(k) to
def doStuff[ K: ClassTag, T ]( result: Future[ Seq[ T ] ] )
                               ( transform: T => Option[ K ] = {
                                 case m: K => Option( m )
                                 case _ => None
                               } ): Future[ Either[ String, Option[ K ] ] ] = {
  }

but this approach will force me to pass in my generic parameters on function call.
Can anyone see any other approach?

A: I haven't achieved it with the signature you provided with two parameter lists. But I wonder if you can use it with one parameter list:
def toOption[R](x: R): Option[R] = Option(x)

def doStuff[K, T](result: Future[Seq[T]], transform: T => Option[K] = toOption[K] _): Future[Either[String, Option[K]]] = {
  result.map(r => Right[String, Option[K]](transform(r.head)))
}

// Then, if you need a function of the second parameter, you can use partially applied function:
val rf: (Int => Option[Int]) => Future[Either[String, Option[Int]]] = doStuff[Int, Int](Future(List(1, 2)), _)

// Or call with default argument:
val r: Future[Either[String, Option[Int]]] = doStuff[Int, Int](Future(List(1, 2)))

// These lines should print the same
println(rf(toOption))
println(r)


text:
Q: How to count the total number of file in directory assets angular I have a folder in assets folder named file_json. I want to count how many files are in that folder in the component ts. any idea?

A: This can't be done with angular. Angular build is just bunch of html, css and JavaScript that runs on the browser. And the browser cannot read folder directory.


text:
Q: Add comma after each added words in jquery I'm trying to add comma after adding each word in a textarea.
eg,. word1, word2, word3
In this textarea the user can add words by getting words in a select box and click the add button or by manual input by user. The current working is the adding of words by using the select box. When I add words from select box, I can achieved the output word1, word2, word3
The problem is that when the user manually type the words and then add words using selectbox at the same time. It produces output like this. eg., word1 word2, word3
As you can see there is no comma after the word1. Any idea?
$('#addWordsearch').click(function() {

    if($('#wsearch_lesson_zone_list').val() == null)
    {
      alert("Add words first");
      return false;
    }

    else
    {

        $('#search_word').val($('#search_word').val() + $('#wsearch_lesson_zone_list').val() + ", ");

    }
});

A: I think, you are not adding the comma for the manually typed word. You are just taking the manually typed word and adding with select box. You can try like the following:
$('#addWordsearch').click(function() {

if($('#wsearch_lesson_zone_list').val() == null)
{
  alert("Add words first");
  return false;
}

else
{

var text = $('#search_word').val(),
    selectText = $('#wsearch_lesson_zone_list').val();
text = text ? text + ", " + selectText :selectText ;  // adding comma if we have word in the textarea.
$('#search_word').val( text);

}
});


text:
Q: How to write a script to run different application I am very new to linux platform.
Looking for a script file to call different application start up file located in different location and needs to be run in different terminals.
For example :
i have two .sh file like a.sh and b.sh in different locations.
Now need a script file to run these .sh file. when i run that script it should be open two terminals . In the first terminal a.sh should be  called and b.sh file should be run on second terminal .
Thanks in advance for help.
Regards,
Raghu

A: That is quite simple. Write a script something like this:
#!/bin/bash
xterm -e /bin/bash /path/to/script_1.sh &
xterm -e /bin/bash /path/to/script_2.sh &

The -e option means "execute". The argument after it is the command to execute (here it is /bin/bash) and the next option is the argument for the command (here the name of the script-file). & means that the xterm-commands are running in background. If you remove the first &, it will run the first script completely and afterwards it will start the next command, but as I understood your question you want to run them simultaneously, so leave the & there.
You can also use the standard terminal instead of xterm, but this depends on the distribution and desktop you use. For example in gnome it would be gnome-terminal -x, but it should not make any difference when using xterm.
Hope this helps.
Greatings, Darth Ravage


text:
Q: Wrong mesh collider when import FBX from Blender to Unity I'm trying to import models from blender to Unity, but the mesh colliders are wrong when they are adding them to an object in Unity.
Here are my steps:

*

*Imported new asset.

*Checked "Generate colliders".

*Added mesh collider and the result is:

A: Don't generate the collider when you import the mesh, uncheck the box.
You can later add in the inspector a mesh collider component and set it to convex, but this would be the same result you already have. You can uncheck convex, then unity tries to use your current geometry. But if the vertex count is to hight, unity won't apply a collider because the physic system only supports a certain amount of geometry.
enter image description here
you can also duplicate your object in blender and add a decimate modifier and play around with the Ratio or create your own geometry around your object with vertex snapping or any workflow you like, just keep the collider geometry as simple as possible.
Then you can set that mesh in the mesh collider component as mesh source and have a nice and proper collider.


text:
Q: Add commas to every three digits in the number which is in float format I have a float number in a string, I need to add commas to every three digits of the number.
Here is what I had tried,
NSString *mystring =@"20090809.99";
float fl = [mystring floatValue];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSLog(@"%@ ", [formatter stringFromNumber:[NSNumber numberWithFloat:fl]]);

I need the result as 20,090,809.99. What should I change in my code?

A: use this code for doing this task:-
    NSNumberFormatter *formatter1 = [[NSNumberFormatter alloc] init];
    [formatter1 setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString * formattedAmount2 = [formatter1 stringFromNumber: @20090809.99];
    NSLog(@"%@",formattedAmount2);

It's OUTPUT is :-
20,090,809.99

A: without number formatter:
NSNumber *someNumber = @(1234567890);
NSString *modelNumberString = [NSString localizedStringWithFormat:@"%@", someNumber];
NSLog(@"Number with commas: %@", modelNumberString);

A: Your formatting code is correct. The problem is that your number is of type float. Type float has limited precision. Your number cannot be represented exactly by float. The float value closest to 20090809.99 is 20090810.00. That is what -floatValue returns so that is what gets printed.
If you change your variable to type double, and call -[NSString doubleValue] and -[NSNumber numberWithDouble:], then it will behave as you expect.

A: How about this:
NSString *mystring =@"20090809.99";
NSNumber *number = [NSDecimalNumber decimalNumberWithString:mystring];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSLog(@"Formatted float: %@ ", [formatter stringFromNumber:number]);


text:
Q: How do I find out what SMTP server is being used? I've recently taken over the responsibility of looking after a clients website that has been built in asp.net by an ex-employee. (who left in a hurry to work for said clients!)
The company is going to be moving over to a php platform in the not so distant future but until then they are having some email delivery issues.
NOTE: I'm not proficient in asp.net
Now, none of the code on any of this clients websites has been changed recently.
We host them on a reseller hosting account with Namesco in the UK.
I believe the issue is with the SMTP server not allowing these emails through. However I can't find where the SMTP address is set in the code?
Some Background info on this clients setup:
They have two websites the main site who's domain ends in .co.uk
Then a seperate site who's domain ends in .tv
The .co.uk and .tv code for the sites web forms is exactly the same.
The .co.uk emails are coming through but the .tv emails have suddenly stopped.
When a potential customer fills in the web forms and hits send. The script calls on a database which adds in some extra text to the email and adds in a FROM address:
E.g.
noreply@customersite.tv
noreply@customersite.co.uk
If the FROM: address is changed from the .tv to the .co.uk then the emails sent from the .tv sites webforms do arrive successfully. So to me the issue is that the SMTP server does not like the .tv FROM address anymore?
So the customer is still getting their emails however this messes up some mailbox filtering they had setup. So they want to working as it was doing before.
Here is the code in the aspx.cs file for the contact us page:
  using System;
  using System.Collections.Generic;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Data;
  using System.Data.Sql;
  using System.Data.SqlClient;
  using System.Data.SqlTypes;
  using System.Configuration;
  using System.Web.Mail;
  using System.Text;

 public partial class contactus : System.Web.UI.Page
 {
    protected void Page_Load(object sender, EventArgs e)
   {
       this.Master.FindControl("divMasterContactForm").Visible = false;
       this.Master.FindControl("contactFormHeader").Visible = false;
   }
   protected void butSubmit_Click(object sender, ImageClickEventArgs e)
   {
       string strConnection, strCommand, strPage;

       strPage = Request.Url.ToString();
       strConnection = ConfigurationManager.ConnectionStrings["dbString"].ConnectionString;
       strCommand = "SELECT * FROM [mailOptions] WHERE [url] LIKE 'customerswebsite.tv'";
       StringBuilder strBody = new StringBuilder();

       SqlConnection myConnection = new SqlConnection(strConnection);

       SqlCommand myCommand = new SqlCommand(strCommand);
       myCommand.Connection = myConnection;

       myConnection.Open();

       try
       {
           SqlDataReader myReader = myCommand.ExecuteReader();

           while (myReader.Read())
           {

               strBody.Append("
");
               strBody.Append(txtQuery.Text);
               strBody.Append("

Regards,

");
               strBody.Append(txtFirstName.Text + " " + txtLastName.Text);
               strBody.Append("

Telephone number: " + txtPhone.Text);
               strBody.Append("

Mobile Number: " + txtMobile.Text);
               strBody.Append("

Email Address: " + txtEmail.Text + "");

               MailMessage msgMail = new MailMessage();
               msgMail.To = myReader["to"].ToString();
               msgMail.Bcc = "info@ourwebdesignfirm.com";
               msgMail.From = myReader["from"].ToString();
               msgMail.Subject = ddQueryType.SelectedValue + " From: " + txtFirstName.Text + " " + txtLastName.Text + ". Generated from " + myReader["leadSource"].ToString();
               msgMail.BodyFormat = MailFormat.Html;
               msgMail.Body = strBody.ToString();
               //lblConfirmation.Text = strBody.ToString();
               SmtpMail.Send(msgMail);

               panForm.Visible = false;
               panConfirm.Visible = true;
               lblSubject.Text = ddQueryType.SelectedValue;
               lblFrom.Text = txtEmail.Text;
               lblBody.Text = txtQuery.Text;
               lblFirstName.Text = txtFirstName.Text;
               lblLastName.Text = txtLastName.Text;
               lblDate.Text = DateTime.Now.ToLongDateString();
               lblTime.Text = DateTime.Now.ToShortTimeString();
           }
           myReader.Close();
       }
       catch
       {
           lblConfirmation.Text = "Sorry I broke part way through, please call us instead on the number above.";
       }

       myConnection.Close();
   }
  }

Currently my problem is that I can't test or track the path of these emails as I can't find which SMTP server the emails are using?
Any help appreciated

A: There's a good chance the SMTP server details is stored in the web.config file. See if you can find a <system.net> tag within the web.config file.
<system.net>
        <mailSettings>
            <smtp  from="user@domain.com">
                <network  host="SMTP.SITE.COM" port="25" userName="name@domain.com" password="yourPassword"/>
            </smtp>
        </mailSettings>
    </system.net>

A: You could use a network sniffer such as Wireshark (free) to track SMTP traffic, but make sure you have management permission to use such a tool before downloading/installing/using it: such tools have naughty uses as well as benign ones.

A: Make sure that DNS is not the issue. Does the mail host that is supposed to receive your test email no longer accept mails if a reverse DNS lookup for the sending domain does not list your site, or maybe there is no PTR record?
Coincidentally, I just had the same problem last week. Emails that were sent successfully all of sudden stopped working because the server apparently was gray-listed for these very reasons.
If your app is using a local SMTP server, you will see SMTP errors in the Windows event files.


text:
Q: How to use a JNI native library from Grails application I'm developing a Grails web application and I need to use a JNI native library to access some specific hardware. For a simple Java application (see below) it works fine. To do this I just have to add the JAR to the Java build path and specify the "Native library location" (I use SpringSource Tool Suite on Windows7).
Working example:
import conceptacid.nativedriver.Driver;
public class Main {
public static void main(String[] args) {
        System.out.println("starting...");
        System.loadLibrary("AudioCardDriver");
        Driver driver = Driver.instance();
        String driverDescription = driver.getDriverDescription();
        System.out.println( "Native application driver: " + driverDescription);
    }
}

However, when I try to add it into my Grails application it fails:
Bootstrap.groovy:
import conceptacid.nativedriver.Driver;

class BootStrap {

    def init = { servletContext ->
    System.loadLibrary("AudioCardDriver");
    Driver driver = Driver.instance();
    String driverDescription = driver.getDriverDescription();
    System.out.println( "Native application driver: " + driverDescription);
    }
    def destroy = {
    }
}

the first line System.loadLibrary("AudioCardDriver"); is executed silently without any exception but the next line where I try to use my native code Driver driver = Driver.instance(); fails:
Running script C:\grails\scripts\RunApp.groovy
Environment set to development
  [groovyc] Compiling 1 source file to D:\Projects3\mbr\target\classes
   [delete] Deleting directory C:\Users\VShmyrev\.grails\1.3.7\projects\mbr\tomcat
Running Grails application..
2012-02-24 15:19:49,690 [main] ERROR context.GrailsContextLoader  - Error executing  bootstraps: java.lang.UnsatisfiedLinkError: conceptacid.nativedriver.AudioCardDriverJNI.swig_module_init()V
org.codehaus.groovy.runtime.InvokerInvocationException:   java.lang.UnsatisfiedLinkError:   conceptacid.nativedriver.AudioCardDriverJNI.swig_module_init()V
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:251)

...

Caused by: java.lang.UnsatisfiedLinkError: conceptacid.nativedriver.AudioCardDriverJNI.swig_module_init()V
at conceptacid.nativedriver.AudioCardDriverJNI.swig_module_init(Native Method)
at conceptacid.nativedriver.AudioCardDriverJNI.<clinit>(AudioCardDriverJNI.java:70)
at conceptacid.nativedriver.Driver.instance(Driver.java:35)
at conceptacid.nativedriver.Driver$instance.call(Unknown Source)
at BootStrap$_closure1.doCall(BootStrap.groovy:7)
... 26 more
Application context shutting down...

I'm sure I put the DLL into a directory which is in my system PATH but it doesn't help.
What is the right way to use a native library in Grails application both in a development environment and in production?

A: Your DLL needs to be on a path specified in the Java system property java.library.path.  On Windows the PATH environment variable and Linux the LD_LIBRARY_PATH environment variable are added to this system property.  You can try logging the java.library.path system property to see if Java is looking in the right place for your DLL.

A: I'm guessing that the native library is being loaded multiple times in different classloaders, so forking a new JVM when running the app might help.


text:
Q: Split DVD iso of TV series into episodes I have a lot of DVD isos (I also have the physical DVD's, but I have ripped them, so they shouldn't be needed for this), of various TV series. Each DVD contains several episodes of the series, but typically several audio tracks and sets of subtitles.
Now I'd like to make a series of files, each one containing just one episode, and just one audio track and (in most cases) no subtitles. As space is not really an issue, but quality matters to me, I would prefer if it can be done with no new encoding (it is theoretically impossible that it improves quality, that would require magic), and it takes time/CPU cycles that is not needed. As long as my XMBC/OpenElec/Kodi (I don't care about those things, so I don't know what is the relevant component to name here, those are the names I was able to quickly find in it's "setup" menu) can play the result I don't really care about the format(s) involved.
I've found out that HandBrake can do something, but many of it's options are greek to me, and what I've managed to get it to do seems to involve re-encoding.
Any advice on how I can accomplish what I want? (I want to run this on a Debian box)


text:
Q: Using notI in Welder. Example contradiction proof I have some problems while using the notI construct in Welder. Take the following as an example proof:
My example uses usual lemmas about the structure of rings and a derived lemma (zeroDivisorLemma) that says that for all 'a' in the ring a0 = 0 = 0a.
I proof that if two elements are not zero, their product is not zero. As follows.
val theorem: Theorem =
  forallI("a"::F,"b"::F){ case (a,b) =>
    implI(and(a !== z, b !== z,multInverseElement,multNeutralElement,multAssociative,
              addOppositeElement,addNeutralElement,addAssociative,isDistributive)){ axioms =>
      val Seq(aNotZero,bNotZero,multInverseElement,multNeutralElement,multAssociative,
              addOppositeElement,addNeutralElement,addAssociative,isDistributive) = andE(axioms) : Seq[Theorem]
      notI((a ^* b) === z) { case (hyp,_) =>
        ((a ^* b) === z)                         ==| andI(bNotZero,hyp)                                    |
        (((a ^* b) ^* inv(b)) === (z ^* inv(b))) ==| forallE(multAssociative)(a,b,inv(b))                  |
        ((a ^* (b ^* inv(b))) === (z ^* inv(b))) ==| andI(forallE(multInverseElement)(b),bNotZero)         |
        ((a ^* one) === (z ^* inv(b)))           ==| forallE(multNeutralElement)(a)                        |
        (a === (z ^* inv(b)))                    ==| forallE(implE(zeroDivisorLemma)(g => axioms))(inv(b)) |
        (a === z)                                ==| aNotZero     |
        ((a !== z) && (a === z))                 ==| trivial |
        (a !== a)                                ==| trivial |
        BooleanLiteral(false)
      }
    }
  }

The code compiles but Welder says:

SMT solver could not prove the property: false
from hypotheses:
(mult(a, b) == zero()) == false.

I'd say I'm not passing the right function to the construct. Could someone explain what should I write to succeed? Does it have to do with the type, i.e., (Theorem, Goal) => Attempt[Witness]? Do I need to provide a theorem and that proves the goal?
What else can I proof to get false? Should I use some sort of implication introduction?

A: What the error says is that it could not deduce a contradiction from what you shown. Indeed, you have not shown a contradiction in body of the notI. The derivation to prove that (mult(a, b) == zero()) == false is correct, but you still have to explicitly show the contradiction by taking the conjunction with hyp.
Would something like this work ?
    val theorem: Theorem =
  forallI("a"::F,"b"::F){ case (a,b) =>
    implI(and(a !== z, b !== z,multInverseElement,multNeutralElement,multAssociative,
              addOppositeElement,addNeutralElement,addAssociative,isDistributive)){ axioms =>
      val Seq(aNotZero,bNotZero,multInverseElement,multNeutralElement,multAssociative,
              addOppositeElement,addNeutralElement,addAssociative,isDistributive) = andE(axioms) : Seq[Theorem]
      notI((a ^* b) === z) { case (hyp,_) =>
        val deriv = ((a ^* b) === z)               ==| andI(bNotZero,hyp)                                    |
          (((a ^* b) ^* inv(b)) === (z ^* inv(b))) ==| forallE(multAssociative)(a,b,inv(b))                  |
          ((a ^* (b ^* inv(b))) === (z ^* inv(b))) ==| andI(forallE(multInverseElement)(b),bNotZero)         |
          ((a ^* one) === (z ^* inv(b)))           ==| forallE(multNeutralElement)(a)                        |
          (a === (z ^* inv(b)))                    ==| forallE(implE(zeroDivisorLemma)(g => axioms))(inv(b)) |
          (a === z)                                ==| aNotZero     |
          ((a !== z) && (a === z))                 ==| trivial |
          (a !== a)                                ==| trivial |
          BooleanLiteral(false)

        andI(deriv, hyp)
      }
    }
  }


text:
Q: Export Runnable Jar with DLL I have a program that has a dll and resource files. I tried to export runnable jar, but i gives an error dll not found.
How can i export it ?
I can run without error in eclipse but i could not export the project.
I call the native lib below :
public class DLL_Functions {
    public interface DLL extends Library {
        DLL INSTANCE = (DLL) Native.loadLibrary("ErgoPointer_64_Bit_DLL", DLL.class);
        int LSX_CreateLSID(IntByReference ILSID);
        int LSX_ConnectSimple(int ILSID, int lAnInterfaceType, String pcAComName, int lABaudRate, boolean bAShowProt);
        int LSX_SetShowProt (int ILSID, boolean bShowProt);
        int LSX_Disconnect(int ILSID);
        int LSX_GetPos(int ILSID, DoubleByReference pdX, DoubleByReference pdY, DoubleByReference pdZ, DoubleByReference pdA);
        int LSX_SetPos(int ILSID, double dX, double dY, double dZ, double dA);
        int LSX_GetKey(int ILSID, IntByReference key1, IntByReference key2, IntByReference key3, IntByReference key4);
    }
}

Also i have image and settings files too.


text:
Q: why is class.forname(com.mysql.jdbc.Driver) written in a db connection class? I have written a dbconnection.java class and it has a static block where i load the driver class
    static
{
    try
    {
        Class.forName(com.mysql.jdbc.Driver);
    }
    catch(ClassNotFoundException e)
    {
        e.printStackTrace();
    }
}

I know that this static block is written to register the driver. but even when i comment this static block and try to make a database connection it is getting connected.
So i wanted to know What Is The Importance or Significance of writing this static block.

A: (I'm answering this since we unfortunately do not have a RTFM close reason)
If you read the tutorial provided by oracle you'll find that this was once necessary but with many modern (JDBC 4.0) drivers, not so:

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. This methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

(emphasis mine)

A: Placing this code in static block is used to ensure that one process has the same driver. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
Details can be saw at this link


text:
Q: Conditional Formatting with Time through Formula I'm trying to highlight the time based on the folowing rules

*If the time is lower than 7:30 be closer to red

*Otherwise if the time is closer to 8:05 get close to green
In this sheet:

I guess it's easier to explain with the following illustration:

You should get the basic idea of what I'm trying to accomplish with the formulars in the formatting rule picture. That one however doesn't work.
Any ideas what would be the proper way to format this rule?

A: On the left side for value write 0,31 and on the right side write 0,34.
To get the correct value, that is corresponding to the correct time, simply select the time in Excel, using the Time() formula, press Ctrl+1 and select Number. You will see the correct number for the time.

A: Also found a way, albeit this is more of a workaround:
You can enter the values as a raw number in format of AB:CD:EF (or depending on the time format you are using) and excel will automatically format the rule somehow with decimal signs, although this really is more of a workaround rather than answer to the actual question

A: You can use "industrial minutes", minutes to a base of 100 industrialseconds. Then you can use standard decimal values.
In excel you simple multiply time values by 24 to get to that. Then 30 minutes are 0.5 of an hour.

For the conditional formating use a 3-Color scale and set the middlepoint to number 7.5 and a lighter green.


text:
Q: Delete HTML Elemented from iFramed site I would like to iframe a specific portion of https://aliciabryantmayes.myhomehq.biz/newsletters page. To show only the screenshot portion.

Is that possible?

A: If you are trying to do this from JavaScript, in your site at "http://example.com" (e.g. a different domain) that is wrapping this site in an  then the answer is NO, you can't. It is a security permission issue, you can't modify content on another domain.
If you are wrapping this page in another page from the same domain (e.g. you own this site)... then you can.
It gets a bit more complicated if we are talking about browser extensions
Alternatively, if you want to show only a portion of the content from another site on your site, you have some options.
Option 1: Use their API (if they provide one) to get the data, parse and present it as needed.
Option 2: Make a serverside request to "HTML screen scrape" content from a 3rd party site. Be careful not to overdo this (fetching a copy and caching it would be better than fetching it every time you load your page)... and beware that the 3rd party may still complain/throttle or block you.

A: A bit of CSS should do the trick :)

#my-div
{
    width    : 400px;
    height   : 200px;
    overflow : hidden;
    position : relative;
}

#my-iframe
{
    position : absolute;
    top      : -100px;
    left     : -100px;
    width    : 1280px;
    height   : 1200px;
}

You can fiddle with it as needed.
Edit: My codepen example: https://codepen.io/Benjamin-Dover/pen/zYojKbz


text:
Q: Laravel password validation fail on "min length" if empty My validator rule looks like this:
$validator = Validator::make($request->all(), [
        'name'     => 'required|min:5|max:255',
        'email'    => [
            'required',
            'max:255',
            'email',
            Rule::unique('users')->ignore($id),
        ],
        'password' => 'min:6|confirmed',
    ], [
        'confirmed' => 'Hasło musi się zgadzać',
        'unique'    => 'Wpisz inny adres email, ten adres jest zajęty',
        'required'  => 'To pole jest wymagane.',
        'min'       => 'To pole musi mieć minimum :min znaków.',
    ]);

    if ($validator->fails()) {
        return redirect('/panel/users/'.$id.'/edit')
            ->withErrors($validator)
            ->withInput();
    }

When i edit user without change password, validator fails with 'min' rule. As you can see my validator doesnt require password, so why it validating?

A: It's look like what you want.
$validator->sometimes('password', 'min:6|confirmed', function ($input) {
    return (strlen($input->password) > 0);
});

A: You are coming across expected behaviour.
min:value
The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.
as per the docs.
You can use the sometimes rule
Validator::make($request->all(), [
    'password' => 'sometimes|min:6|confirmed',
]

A: use nullable rule
'nullable|min:6|confirmed'

A: You can use sometimes for this case:
$this->validate($request, [
    'password' => 'sometimes|min:6',
]);

You can read more about sometimes here:

In some situations, you may wish to run validation checks against a
  field only if that field is present in the input array. To quickly
  accomplish this, add the sometimes rule to your rule list:

confirmed seems as if it can also cause a problem. So try doing it manually:
'password' => 'required|min:6',
'password_confirmation' => 'required|min:6|same:password',


text:
Q: 2003 MS Access Visual Basic Workflow Does anyone know how to program a database to function as a workflow? I would like it to identify the user as they open the database and then open up their 'queue' of work. Any ideas?

A: Read Remou's answer to this Stack Overflow question: How do I make an Access Form automatically open to a user's data?
It may help to describe your concept of a user's queue of work.


text:
Q: XML instance generation from XML schema (xsd) I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a fairly quick solution..
Any ideas?

See also: how-to-generate-sample-xml-documents-from-their-dtd-or-xsd

A: Look at pyXSD for Python tools that are similar to JAXB.
XSD's are used to create Python classes.  Python objects are used to emit XML.

A: Microsoft has published a "document generator" tool as a sample.  This is an article that describes the architecture and operation of the sample app in some detail.
If you just want to use the document generation tool, click here and install the MSI. It requires no programming.
It's free.  The source is available. Requires the .NET Framework to run.  Works only with XSDs. (not Relax NG or DTD).

A: I recommend two approaches:

*

*Xstream - it let's you generate XML files by defining a Java file and either putting Java annotations on the items or just defining aliases. It is very easy, but it is not fully automatic;

*XMLBeans - these tools let's you generate Java files from XML schema definitions (xsd) so that you can import, manipulate, create and export XML files using JavaBeans-like method calls.
Regards,
Luis

A: JAXB works fantastic for generating classes from xsd.
Ibatis works fantastic for getting data into classes.
You can use Ibatis to feed data and automatically create classes, then use JAXB to marshal the classes into an XML file! Mind you, that's a lot of effort if you're not going to be doing it over and over again.

A: I use Exchanger XML Editor for this purpose. You can download it for free for multiple operating systems at: http://www.exchangerxml.com/
The option is in menu "Schema" -> "Schema instance generation".


text:
Q: How to use Phaser 3.17 GameConfig object in Typescript? After updating Phaser to 3.17 with
npm install phaser@3.17.0

I now get these Typescript errors:
const config: GameConfig = {
    scene: [BootScene, StartScene, GameScene, GameOver],
    input: {
        keyboard: true
    }
}

Cannot find name 'GameConfig'

When looking in the .d.ts file, I guess I now have to use:
const config: Phaser.Types.Core.GameConfig = {
    scene: [BootScene, StartScene, GameScene, GameOver],
    input: {
        keyboard: true
    }
}

But now, scene is no longer recognised as part of GameConfig!

The expected type comes from property 'scene' which is declared here on type 'GameConfig'

I have no idea what this means... is this a bug in the .d.ts file?


text:
Q: How to copy images from one folder to another using Python? I have 10 images in the folder(1.jpg, 2.jpg, 3.jpg, ..., 10.jpg) and I want to copy only 5 images(1.jpg, 2.jpg, 4.jpg, 6.jpg, 8.jpg) into another folder. But I am getting this error.
`
Traceback (most recent call last):
  File "/home/vkaps-lp-101/Desktop/Core Python
Code/19_Time_lapse/test.py", line 92,
in <module>
    copytree(d, dst, symlinks = False, ignore = None,
copy_function = copy2)
  File "/usr/lib/python3.8/shutil.py", line 555, in copytree
    with os.scandir(src) as it:
ValueError: scandir: embedded null character in path
`

`
import os
import numpy as np
import shutil
from PIL import Image
import numpy as geek
arr = os.listdir('10_f/')
src = '10_f/'
dst = 'folder/'
arr.sort()
# print('arr: ', arr)
b = np.array(arr)
# print('b: ', b)
c = b.reshape(-1, 1)[::2].ravel()
print('c: ', c)
d = c.tobytes()

print(len(c))
# for file in d:
#     print(file, end=' ')
    # file = file.tobytes()
# print(type(file))

out_arr = geek.array_str(c)
# print ("The string representation of input array: ", out_arr)
# print(type(out_arr))

from shutil import copytree, ignore_patterns, copy2
copytree(d, dst, symlinks = False, ignore = None, copy_function =
copy2)

`

A: I've amended my answer to perform your exact need of copying only those specific files.
import glob
import os
import shutil

input_dir = 'C:/your/input/folder'
output_dir = 'C:/your/output/folder'

file_ids = [1, 2, 4, 6, 8]

# Grabs all the files that have extension (jpg)
files = glob.glob(os.path.join(input_dir, '*.jpg'))
for f in files:
    # Grabs the filename excluding the directory and the extension
    basename = os.path.splitext(os.path.basename(f))
    # Check that basename to see if it's in the list of
    # IDs we're interested in transferring
    if int(basename) in file_ids:
        shutil.copy(f, output_dir)


text:
Q: REST-ASSURED posting empty request body for generated object I'm using rest assured to send a post with a generated body from a model class. The model class uses the builder pattern and I confirmed that it is getting built correctly:
Request body:
McpSalesInvoicesPost(invoices=[McpSalesInvoices(type=PRE_ORDER, amount=212.0, currencyCode=INR, transactionDate=2020-10-24T22:43:24, payments=[McpSalesPayments(type=CASH, amount=212.0, currencyCode=INR, reference=reference text sample 376, transactionDate=2014-08-20T19:23:51)])])

When I use that object in the rest assured post call I get an empty body in the request. Here is the rest assured code:
           response = SerenityRest
                .given()
                .filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
                .contentType(ContentType.JSON)
                .header(new Header("x-openapi-clientid", "client-id-1"))
                .body(requestBody)
                .when()
                .request(verb, SALES_BASE_URL + endpoint);

where request body is the built object mentioned above and this gives:
Body:
{

}

for the request. Any ideas on where I'm going wrong?
A

A: Maybe try .with().body(object).
response = SerenityRest
                .given()
                .filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
                .contentType(ContentType.JSON)
                .header(new Header("x-openapi-clientid", "client-id-1")).with().
                .body(requestBody)
                .when()
                .request(verb, SALES_BASE_URL + endpoint);


text:
Q: ASP Core 2 How to change (update) claim for active user I have an application where user profile drives claims collection.
When user change the profile (added a new module) the corresponding claim should be updated.
How I can do it for Core2 ?
Thanks,
Oleg


text:
Q: ref:Android Application class not destroyed when last activity is destroyed and handler thread destroy i have the same question posted in "Android Application class not destroyed when last activity is destroyed".
my problem is i have a singleton which i create in the mainactivity oncreate , the singleton among other things create my handlerthread for database writes. in the ondestroy  of the mainactivity i'm killing my thread. when i press the back button to quite the app,the thread it dies no problem there , but next time i select the app since the singleton is still present my thread is not started and all subsequent db writes fail.
what approach should i take here
should i just check on a write attempt if the thread is alive and if not create it again(hope this will not cause any problems) or ? thanks for suggestions

A: ive gone for a  if((sOrganizerManager.mDatabaseThread == null) ||( !sOrganizerManager.mDatabaseThread.isAlive()))
        {
            sOrganizerManager.mDatabaseThread =new OrganizerDatabaseInsertThread (c,sOrganizerManager);
            sOrganizerManager.mDatabaseThread.start();
            sOrganizerManager.mDatabaseThread.getLooper();
            Log.d(TAG,"Background db thread started");
        }
check on my singleton get function this gets rid of my db write problems. but im not sure if this ok. like i said i'm using mOrganizerManager.destroyDbThread(); on my main onDestroy. I hope there are no lurking problems in this approach, like maybe some partially destroyed zombie threads:)


text:
Q: Display statistics from an SVN repository on a web page What is the best way to get statistics for an entire subversion repository and display some of them on a web page? Example. Total number of commits today, this month etc, most active committer etc.

A: I haven't worked with it myself but I think StatSVN is worth a look. It's Java based.
Features:

*

*Timeline for the lines of code

*Lines of code for each developer

*Activity by Clock time

*Authors Activity

*Author activity per Module

*Author Most Recent Commits with links to ViewVc

*Stats per directory

*File count

*Average file size

*Largest files

*Files with most revisions

*Directory Sizes

*Repository Tags Number of LOC per version.

*Repository tree with file count and lines of code

*LOC and Churn the evolution of LOC and the amount of change per day

*Repo Map the dynamic hierarchical view of your repo for the last 30 days

  The current version of StatSVN generates a static suite of HTML documents containing tables and chart images. StatSVN is open source software, released under the terms of the LGPL, based on StatCVS. StatSVN uses JFreeChart to generate charts.

A: You could generate a static HTML file or fragment using a post-commit hook and then link to that file (or include it in a different page).
More here


text:
Q: DynamoDB Sort key so that I could query the last item by date The following DynamoDB table has a partition key equal to date so I could easily query day by day. I know items with the same partition key are stored in the same partition and are ordered by their sort key.
However, the sort key in this case is wrong because TransferId is not something like a date that I could sort.
What sort key should I use so I could query the last item for a specific date? 'Exchange:Time'?
+----------+------------------------------------------+---------+--------------------------------------------+------------+----------+------------+---------+-----------+---------------------------+----------------+--------------------------------------------------------------------+----------------------------------+--------------+------------------------------+
|    PK    |                    SK                    | Account |                  Address                   | AddressTag | Exchange | Instrument | Network | Quantity  |           Time            | TransactionFee |                           TransactionId                            |            TransferId            | TransferType |          UpdatedAt           |
+----------+------------------------------------------+---------+--------------------------------------------+------------+----------+------------+---------+-----------+---------------------------+----------------+--------------------------------------------------------------------+----------------------------------+--------------+------------------------------+
| 20221217 | Binance:1b56485f6a3446c3b883f4f485039260 | main    | 0xF76d3f20bF155681b0b983bFC3ea5fe43A2A6E3c | null       | Binance  | USDT       | ETH     | 97.500139 | 2022-12-17T14:59:12+00:00 |            3.2 | 0x46d28f7d0e1e5b1d074a65dcfbb9d90b3bcdc7e6fca6b1f1f7abb5ab219feb24 | 1b56485f6a3446c3b883f4f485039260 |            0 | 2023-01-27T18:00:00.5930186Z |
| 20221217 | Binance:4747f6ecc74f4dd8a4b565e0f15bcf79 | main    | 0xF76d3f20bF155681b0b983bFC3ea5fe43A2A6E3c | null       | Binance  | USDT       | ETH     | 3107.4889 | 2022-12-17T15:38:23+00:00 |            3.2 | 0xbb2b92030b988a0184ba02e2e754b7a7f0f963c496c4e3473509c6fe6b54a41d | 4747f6ecc74f4dd8a4b565e0f15bcf79 |            0 | 2023-01-27T18:00:00.2944534Z |
+----------+------------------------------------------+---------+--------------------------------------------+------------+----------+------------+---------+-----------+---------------------------+----------------+--------------------------------------------------------------------+----------------------------------+--------------+------------------------------+

I suppose the code should be something like the following:
var date = DateTimeOffset.UtcNow.ToString("yyyyMMdd");

var request = new QueryRequest
{
    TableName = "transfers-dev",
    KeyConditionExpression = "#date = :date",
    ExpressionAttributeNames = new Dictionary<string, string> { { "#date", "PK" } },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":date", new AttributeValue { S = date } } },
    ScanIndexForward = false,
    Limit = 1
};
var response = await client.QueryAsync(request);

return response.Items.First();

A: Date as a partition key is not very useful, it essentially caps your throughput to 1000 WCU and also doesn't give your query flexibility like give me the data for the last 18 hours.
You should choose something useful as partition key, and choose date as your sort key.

PK
SK
data
gs_pk

Binance:1b56485f6a3446c3b883f4f485039260
2022-12-17T14:59:12+00:00
data
1

Binance:1b56485f6a3446c3b883f4f485039260
2022-12-18T14:59:12+00:00
data
1

Binance:1b56485f6a3446c3b883f4f485039260
2022-12-19T14:59:12+00:00
data
1

You can now say give me all the data for a given binance in a given time frame. If you require a lookup where you want all the binances for the last given amount of time you can create a GSI and use a random or static value as partition key. They more keys you use the more throughput you will be capable of consuming.

gsi_pk
SK
PK
data

1
2022-12-17T14:59:12+00:00
Binance:1b56485f6a3446c3b883f4f485039260
data

1
2022-12-17T14:59:12+00:00
Binance:1b56485f6a3446c3b883f4f485039260
data

1
2022-01-26T14:59:12+00:00
Binance:1b56485f6a3446c3b883f4f485039260
data

Get most recent data:
SELECT * FROM MYTABLE.MYINDEX WHERE gsi_pk = 1 DESC
Get data for a given day:
SELECT * FROM MYTABLE.MYINDEX WHERE gsi_pk = 1 AND SK BEGINS_WITH '26.01.2022'
Note
Having a single value for your GSI partition key will also limit your scalability, if you intend on writing more than 1000 items per second (assuming items < 1KB) then you will have to shard the index key.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-gsi-sharding.html


text:
Q: Changing C++ compiler version on VS Code I am new to C++, having just a bit of programming experience in Python.
On setting C++ up in VSCode, I have installed C/C++ by Microsoft, C/C++ Extension Pack and also Code Runner by Jun Han. These choices, especially the latter, were made based on some Youtube videos I watched.
Upon trying to Initialize with the curly brackets, I realised the code wouldn't compile. I ran a check compiler program and found out the compiler's version is C++98. I want to change to a more recent version which supports the newer features.
That said, how exactly do I change a compiler version, and which one do you recommend? Is C++11 already outdated?
I tried looking it up, and I think the line code-runner.executorMap could be useful, but I don't really know how to use it. Is there a way to do it in Settings or will I have to change it through the Terminal?
Thanks in advance!

A: I will try to help you step by step :

*

*Uninstall MinGW from your pc

*Install MSYS2 from here (Window 8.1 or newer)

*Check the option : "Run MSYS2 now" and open the shell

*Digit : pacman -Syu to update packets

*Open the pink app : MSYS2 MSYS by browsing it from the search bar of Windows

*Digit pacman -Su to update it too

*Exit and now open the blue app called : MSYS2 MinGW 64-bit

*In the shell in ordere to install the compiler digit : pacman -S mingw-w64-x86_64-gcc
(64 Bit System)
pacman -S mingw-w64-i686-gcc
(32 Bit System)

*Now for the debugger :
(64 bit)
pacman -S mingw-w64-x86_64-gdb
(32 bit)
pacman -S mingw-w64-i686-gdb

*From the command prompt of Windows digit these 3 commands to check that everything was installed correctly :

gcc --version
g++ --version
gdb --version

*Go to this website and go to the step number 6 to configure the Path of mingw (if you installed 64-bit) :

*Now because you have already installed C/C++ extension , create a new folder containing your source file, (VERY IMPORTANT because a file won't compile if it's not into a folder ! ) and from the "Terminal" section of VScode select : "Configure Default Build Task" while selecting a c++ file and click : "C/C++ : gcc.exe build active file"

*A folder called .vscode will show up containing the file :  tasks.json, that is used for telling the compiler all the parameters in order to compile your code.

*I recommend to use Powershell as default terminal if you want to set it then press CTRL + SHIFT + P and search for "Terminal: Select Default Profile" and select powershell.

*From the  "Run" section select "Run Without Debugging" Or "Start debugging" and you are good to go ! Just check the terminal in the bottom section of vscode for the output of your code ! Hope it helps!