text:
Q: Selection of data in a region of interest in a matrix (with Mathematica) I am having a (mathematica 8.0.1.0-) problem which I cannot solve by myself.
I have measurement data in a matrix, I want to select some of them and then add them up.
To explain my problem better, here an easy example. The data can be produced by a matrix S:
S = Table[ -Sin[i/2] - Sin[j/2], {i,20}, {j,20}];

They can be nicely plotted with:
xmin = N[Min[S]];
xmax = N[Max[S]];
mycolorfun = Function[ Blend[{Blue,Cyan,Green,Yellow,Red},#] ];

and
MatrixPlot[S, PlotRange -> {All,All,All}, AspectRatio -> 1/1,
   ColorFunction -> (mycolorfun[ Rescale[ #1{xmin,xmax} ] ]&),
   ColorFunctionScaling -> False, MaxPlotPoints -> Automatic,
   FrameLabel -> {y,x} ]

Then one should get a picture similar to this one:

Now I want to select the data which are inside of the brown drawn polygon. These data should be added up at the end.
How can I do this?
Ok, I could use rectangles and build a sub-matrix by choosing/guessing good start and end indices. Then I just have to build the sum of this sub-matrix. But I would prefer polygons (more precise if we do not argue about little problems with the matrix values which are crossed by the line of the polygon). And I would love it if I could select my region of interest (ROI) directly by "painting" the polygon into the Matrix (no more time consuming choosing/guessing of matrix indices).
Could somebody here help me with my problem? If it is not solvable with mathematica, is there some other program which I could use?
I would be very happy about some help and hints!

A: Perhaps this:
upl = 20;
s = Table[-Sin[i/2] - Sin[j/2], {i, upl}, {j, upl}];

xmin = N[Min[s]]; xmax = N[Max[s]]; mycolorfun =
Function[Blend[{Blue, Cyan, Green, Yellow, Red}, #]];

mp = MatrixPlot[s, PlotRange -> {All, All, All}, AspectRatio -> 1/1,
ColorFunction -> (mycolorfun[Rescale[#1, {xmin, xmax}]] &),
ColorFunctionScaling -> False, MaxPlotPoints -> Automatic,
FrameLabel -> {"y", "x"}];
Manipulate[
{{x1, y1}, {x2, y2}} =
 Floor /@ {{p1[[1]], upl - p1[[2]]}, {p2[[1]], upl - p2[[2]]}};
    mp,
{{p1, {1, 1}}, Locator}, {{p2, {19, 19}}, Locator}]

Dynamic[{{x1, y1}, {x2, y2}}]
Dynamic[N@s[[y2 ;; y1, x1 ;; x2]] // MatrixForm]

which produces things like

with the part of the matrix updated live as you move the locators.
To create polygons instead, just add more locators. Selecting the part of the matrix is then more complicated and it depends on how you want things output.

A: If I got it right, you need to find a connected component of similar pixel values.
You can use image processing functions:
First Binarize the image using an appropriate threshold.  Then use MorphologicalComponents that will identify all connected regions.  Finally, you can extract the image data and use Pick to get the pixel values corresponding to the component you are interested in.
EDIT: Here's an illustration of the concept:

A: If selecting the area of interest graphically by hand is not a problem, then you could:
First, create an image out of your data, using a visualization which makes it easy for you to select manually afterward:
S = Table[-Sin[i/50.] - Sin[j/50.], {i, 400}, {j, 400}];
img = ReliefImage@S

Then use the Front End Graphic Tools to draw the polygon over the region that interests you (right click mouse button):

Follow by getting the mask that corresponds to your polygon (again, right click button):

Finally, make a binary image out of the mask and use it to recover the sum of the pixel inside the polygon:
Total[S*ImageData@mask, Infinity]

The whole process looks like this:

EDIT: If you'd like to define your area of interest using a free-hand contour, use the Free-hand line tool instead of polygon. Make sure to increase the width of the stroke so that it is easy to close the contour when drawing. You may do so by moving the Stroke>Thickness slider to the right.
That would look like this:

Then create the mask by filling the inside of the free-hand contour using the function FillingTransform, and proceed as before:


text:
Q: Dissolve points with MODE in ArcGIS I have a huge point dataset with many different type of fields (text, int and double). I would like to dissolve them by a common ID and for the fields I would like to populate with the most common value (MODE). So far I couldn't find a tool that would have this option.
I am handy with python scripting.

A: *

*Summarise using 2 fields as case field

*Sort descending using FREQUENCY field

*Delete identical using commonID field, remaining rows is your answer.

This will definitely work for text ant integer fields.
When dealing with doubles, first convert them to integers, using reasonable multiplier, e.g. 100 for metres.
I tested it using 1 million point and 1980 rectangles placed over DEM.
I applied 100 multiplier to DEM and compared values derived using zonal majority statistics (MAJOR column) with values derived by above method (MJR):

Most of results were identical, few centimetres difference can be explained by same frequency for different values, although first row raises question about reliability of zonal statistics..., or perhaps terrain too steep.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minimum number of jumps required to climb stairs I recently had an interview with Microsoft for an internship and I was asked this question in the interview.
Its basically like, you have 2 parallel staircases and both the staircases have n steps. You start from the bottom and you may move upwards on either of the staircases. Each step on the staircase has a penalty attached to it.
You can also move across both the staircases with some other penalty.
I had to find the minimum penalty that will be imposed for reaching the top.
I tried writing a recurrence relation but I couldn't write anything because of so many variables.
I recently read about dynamic programming and I think this question is related to that.
With some googling, I found that this question is the same as
https://www.hackerrank.com/contests/frost-byte-final/challenges/stairway
Can you please give a solution or an approach for this problem ?

A: Create two arrays to keep track of the minimal cost to reach every position. Fill both arrays with huge numbers (e.g. 1000000000) and the start of the arrays with the cost of the first step.
Then iterate over all possible steps, and use an inner loop to iterate over all possible jumps.
foreach step in (0, N) {
    // we're now sure we know minimal cost to reach this step
    foreach jump in (1,K) {
        // updating minimal costs here
    }
}

Now every time we reach updating there are 4 possible moves to consider:

*

*from A[step] to A[step+jump]

*from A[step] to B[step+jump]

*from B[step] to A[step+jump]

*from B[step] to B[step+jump]

For each of these moves you need to compute the cost. Because you already know that you have the optimal cost to reach A[step] and B[step] this is easy. It's not guaranteed this new move is an improvement, so only update the target cost in your array if the new cost is lower then the cost already there.

A: Isn't this just a directed graph search? Any kind of simple pathfinding algorithm could handle this. See

*

*https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

*https://en.wikipedia.org/wiki/A*_search_algorithm
Just make sure you enforce the directional of the stairs (up only) and account for penalties (edge weights).
Worked solution
Of course, you could do it with dynamic programming, but I wouldn't be the one to ask for that...

A: import java.io.;
import java.util.;
public class Main {
public static int csmj(int []a,int src,int[] dp){

     if(src>=a.length){
         return Integer.MAX_VALUE-1;
     }

     if(src==a.length-1){
         return 0;
     }

     if(dp[src]!=0){
         return dp[src];
     }

        int count=Integer.MAX_VALUE-1;
        for(int i=1;i<=a[src];i++){

            count = Math.min( count , csmj(a,src+i,dp)+1 );
        }

        dp[src] = count;

        return count;
}

public static void main(String args[] ) throws Exception {

    Scanner s = new Scanner(System.in);
    int n = s.nextInt();
    int a[] = new int[n];
    for(int i=0;i<n;i++){
        a[i] = s.nextInt();
    }

    int minJumps = csmj(a,0,new int[n]);
    System.out.println(minJumps);

}

}
bro you can have look at that solution my intuition is that


text:
Q: Output of Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") and OperatingSystem.Platform on Windows RT I'm writing a cross-platform application and I really need some basic info about the system.
Not just for switching it (I could use compile variables, since I have the same code linked in platform-specific projects).
So don't tell me that knowing the platform and architecture info is useless:
Windows RT and c#
Can anybody provide me with this info, because I don't have any easy way to get it by my-self (I have no emulator/device to work with, I'm using a netbook with linux installed on it, so no VT-d capability and so on).
P.S. Please just avoid posting something like: "use qemu, use xxx, yyyy" etc. Consider that somebody might be looking for this info as well.

A: Output of 'set' on a Surface RT

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\[user]\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=SURFACE
ComSpec=C:\windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\
LOCALAPPDATA=C:\Users\[user]\AppData\Local
LOGONSERVER=\\MicrosoftAccount
NUMBER_OF_PROCESSORS=4
OS=Windows_NT
Path=C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=ARM
PROCESSOR_IDENTIFIER=ARM Family 7 Model C09 Revision 209, NVIDIA
PROCESSOR_LEVEL=3081
PROCESSOR_REVISION=0209
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\windows
TEMP=C:\Users\[user]\AppData\Local\Temp
TMP=C:\Users\[user]\AppData\Local\Temp
USERDOMAIN=SURFACE
USERDOMAIN_ROAMINGPROFILE=SURFACE
USERNAME=
USERPROFILE=C:\Users\[user]
windir=C:\windows

Ok, and the platform value:

PS C:\Users\[user]> [system.environment]::OSVersion.Platform
Win32NT

Note that this is from the desktop. For immersive/metro applications you will probably need a different api.


text:
Q: how to create connection in oracle sql developer Version 18.1.0.095 in windows 7 i just install oracle sql developer to my pc windows 7 but when i tried to connecting its giving me Status : Failure -Test failed: IO Error: The Network Adapter could not establish the connection as per search in net manually i created folder C:\Oracle_Client\network\admin and there created tns.ora file but still i unable to connect my database anyone can help me how can i connect my db here is my tns.ora file
Flytech=
 (DESCRIPTION =
   (ADDRESS_LIST =
     (ADDRESS = (PROTOCOL = TCP)(HOST = Localhost)(PORT = 1521))
   )
 (CONNECT_DATA =
   (SERVICE_NAME = Flytech)
 )
)


text:
Q: check Object type from String I'm extracting value from XML and trying to convert it to an appropriate Object... Lets say, value can be numeric/boolean/String.
as an example...
<value> 123 </value>
<value> TRUE </value>
<value> some Strings </value>

I'm reading the value from XML as String. Any idea what would be the best approach to convert the String to the appropriate java Object? (ie. BigDecimal/Boolean/String)
This is what I'm thinking as a solution:
    private Object convertParameterValIntoObject(String value){

    Object toreturn = null;
    BigDecimal numeric = null;
    Boolean boo = null;

    try{
        //deal with numeric val
        numeric = new BigDecimal(value.trim());
        return numeric;
    }
    catch (NumberFormatException e) {

        try{
            //deal with Boolean
            if(value.trim().equalsIgnoreCase("true") ||
                    value.trim().equalsIgnoreCase("false")){

                boo = new Boolean(value.trim());
                return boo;
            }
            else throw new Exception();
        }
        catch (Exception e1) {

            // String
            return value.trim();
        }
    }
}

Thanks in advance,
Hasan.

A: Solving this problem without supplying more information would result in a bad solution.
I highly recommend supplying an XSD for your XML, the XSD contains meta data about your XML including the data type. Once the XSD is available you have many options for converting the XML to a Java Object (I recommend JAXB)
Using JAXB you can generate the Java Objects from the XSD, or write the Objects yourself and use JAXB annotations to supply some meta data.

A: You could use java.util.Scanner which has all the type detection you need. Here's a working example. You need to make sure you probe the type from the most specific to the least specific, here I test for boolean, then number, then string.
String[] testValues = { "123", "123.4", "FALSE", "false",
        "some strings" };

for (String test : testValues) {
    Scanner scanner = new Scanner(test);
    scanner.useDelimiter("^");
    if (scanner.hasNextBoolean()) {
        boolean value = scanner.nextBoolean();
        System.out.println("boolean " + value);
    } else if (scanner.hasNextDouble()) {
        double value = scanner.nextDouble();
        System.out.println("number " + value);
    } else if (scanner.hasNext(".*")) {
        String value = scanner.next();
        System.out.println("string " + value);
    }
}

Output
number 123.0
number 123.4
boolean false
boolean false
string some strings

A: Why do not use XStream? In your case it will be very simple: (below a quote from XStream 2 minutes tutorial)
To construct an object, purely from the XML:
Person newJoe = (Person)xstream.fromXML(xml);

And that's how simple XStream is!


text:
Q: How to access the url categoryid as setcategoryid in Magento? Can we access the url category id to setCategoryId field in the CMS page Layout xml (Magento)?
<action method="setCategoryId"><category_id>3</category_id></action>
<action method="setCategoryId"><category_id>{ url_id }</category_id></action>


text:
Q: How to overwrite a .docx file using openxml in visual studio? I have created a word file using openxml in visualstudio. But I want to overwrite the file. How should I proceed?

A: Your question is not really clear to me. So I decided to give you a starting point:
public void YourAwesomeMethod()
{
       WordprocessingDocument wordDocument = WordprocessingDocument.Create("path", WordprocessingDocumentType.Document);

       // do all the crazy stuff with your document...

       wordDocument.MainDocumentPart.Document.Save(); // save it!
}


text:
Q: C# Sendgrid Webhook Request Validator what is a payload? I have this validator:
public async Task<bool> IsValidRequest(HttpRequest request, string verificationKey, string payload)
{
    try
    {
        var pk = ConvertPublicKeyToECDSA(verificationKey);
        if (pk == null)
        {
            return false;
        }
        request.Headers.TryGetValue(SIGNATURE_HEADER, out var signatureHeaderValues);
        request.Headers.TryGetValue(TIMESTAMP_HEADER, out var timestampHeaderValues);

        var signature = signatureHeaderValues.FirstOrDefault();
        var timestamp = timestampHeaderValues.FirstOrDefault();

        if (string.IsNullOrWhiteSpace(signature) || string.IsNullOrWhiteSpace(timestamp))
        {
            return false;
        }

        var timestampedPayload = timestamp + payload;
        var decodedSignature = Signature.fromBase64(signature);
        return Ecdsa.verify(timestampedPayload, decodedSignature, pk);
    }
    catch(Exception e)
    {
        var error = e;
        return false;
    }
}

This is partly from their official C# github. However, I don't understand what is a payload? What is it suppose to contain?
When a request comes in from Sendgrids Webhook, I take the object[] Input and serialize it, this is what it looks like:
[{"EmailFunction":"DEFAULT_EMAIL_FUNCTION","ReceiverId":"f695b097-8de4-8b632e930518","email":"test@test.net","event":"delivered","ip":"129.73.147.11","response":"250 OK id=1mUiib-0006ga-Cn","sg_event_id":"ZGVsaXZlcmVkLTAtMTk5ODU4MjgtUDZmTk55OHVSeXV2QWpFYTBqbVp6dy0w","sg_message_id":"P6fNNy8uRyuvAjEa0jmZzw.filterdrecv-656998cfdd-bkftm-1-61514F42-1.0","sg_template_id":"d-769wew2124b43bbfbb9db6ec3d3b5","sg_template_name":"Untitled Version","smtp-id":"<P6fNNy8uRyuvAjEa0jmZzw@geopod-ismtpd-4-0>","timestamp":1632718704,"tls":1}]

Am I supposed to just add a timestamp in front of it?
So far this always fails and returns false.

A: Twilio SendGrid developer evangelist here.
According to the comments in the C# library the payload is the "event payload in the request body". Further, according to the docs on validating the request:

When verifying the signature, be aware that we deliver a payload that must be used in its raw bytes form. Transformations from raw bytes to a JSON string may remove characters that were used as part of the generated signature.

So, you should not serialize the input you receive, but validate the raw body of the request.
In this example the contents of the HttpRequest body are read with a StreamReader:
    using (var reader = new StreamReader(request.Body))
    {
        requestBody = reader.ReadToEnd();
    }

Taking your example and working with that example code, I came up with this:
using System.IO;

public async Task<bool> IsValidRequest(HttpRequest request, string verificationKey)
{
    try
    {
        var pk = ConvertPublicKeyToECDSA(verificationKey);
        if (pk == null)
        {
            return false;
        }
        request.Headers.TryGetValue(SIGNATURE_HEADER, out var signatureHeaderValues);
        request.Headers.TryGetValue(TIMESTAMP_HEADER, out var timestampHeaderValues);

        var signature = signatureHeaderValues.FirstOrDefault();
        var timestamp = timestampHeaderValues.FirstOrDefault();
        string payload;

        using (var reader = new StreamReader(request.Body))
        {
            payload = reader.ReadToEnd();
        }

        if (string.IsNullOrWhiteSpace(signature) || string.IsNullOrWhiteSpace(timestamp))
        {
            return false;
        }

        var timestampedPayload = timestamp + payload;
        var decodedSignature = Signature.fromBase64(signature);
        return Ecdsa.verify(timestampedPayload, decodedSignature, pk);
    }
    catch(Exception e)
    {
        var error = e;
        return false;
    }
}

I don't have a C# environment to test this with, but hope it helps!


text:
Q: How to create operation loop for two 1 to 1 lists Say I have 2 lists:
A = [a1,a2,a3,...,an]
B = [b1,b2,b3,...,bn]

The lists are one-to-one.
So how do I create a loop that operates (any operation):
a1 with b1
a2 with b2
...
an with bn

A: Use zip
a = [1,2,3];
b = [4,5,6];

for x,y in zip(a,b):
    print x,y;

A: Since your lists are one-to-one, then they must both be the same size. In this case zip() is the best option here. This function makes an iterator and aggregates elements into tuple pairs from each of the iterables:
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> zipped = zip(a, b)
>>> print(list(zipped))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> print(tuple(zipped))
((1, 5), (2, 6), (3, 7), (4, 8))

This means that you can apply a function on each of the tuples within the zipped iterable:
>>> print([sum(x) for x in zipped])
[6, 8, 10, 12]
>>> print([max(x) for x in zipped])
[5, 6, 7, 8]

You can also achieve similar behavior with map():
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> print(list(map(lambda x, y : x + y, a, b)))
[6, 8, 10, 12]
>>> print(list(map(lambda x, y : x * y, a, b)))
[5, 12, 21, 32]

I'd also suggest writing a zip() function with iterators to see how it works:
def my_zip(seq1, seq2):
    i1 = iter(seq1)
    i2 = iter(seq2)
    while True:
        yield next(i1), next(i2)

Additionally, another less preferred way would be to loop over the first list, and use the indices to also access the elements in the second list:
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> for i in range(len(a)):
        print(a[i], b[i])
1 5
2 6
3 7
4 8
>>> print([a[i] + b[i] for i in range(len(a))])
[6, 8, 10, 12]

This is not very pythonic, but it also works. I recommend using zip() over this.

A: Just to process:
for ea, eb in zip(A, B):
    f(ea, eb)

If you want to keep results,
[f(ea, eb) for ea, eb in zip(A, B)]

The zip builtin sews together two or more lists elementwise into a list of tuples that we can then iterate on, either by an explicit loop or by a comprehension.


text:
Q: Product Identity Multiple Angle or $\sin(nx)=2^{n-1}\prod_{k=0}^{n-1}\sin\left(\frac{k\pi}n+x\right)$ I have run across this interesting identity that I am unable to verify.
$$\sin(nx)=2^{n-1}\prod_{k=0}^{n-1}\sin\left(\frac{k\pi}n+x\right)$$
Can anyone provide a hint as how one would prove this?
This identity was found on the Wolfram site1.

A: You may prove such identity through Herglotz trick, for instance. Both the RHS and the LHS are entire functions in the complex plane of order $1$, having simple zeroes at every point of $\frac{\pi}{n}\mathbb{Z}$ and only there. Additionally, they both are $\frac{2\pi}{n}$-periodic functions. It follows that such identity holds as soon as it holds for some $x\not\in\frac{\pi}{n}\mathbb{Z}$, like $x=\frac{\pi}{2n}$. In such a case, it is straightforward to prove through De Moivre's identity $\sin(x)=\frac{e^{ix}-e^{-ix}}{2}$.
Since $\sin(\pi z)=\frac{\pi}{\Gamma(z)\Gamma(1-z)}$, you may also prove it through the multiplication theorem for the $\Gamma$ function.

A: The right side is odd and periodic with period $2\pi/n$.  Repeated use of the identities for $\sin(a) \sin(b)$ and $\cos(a) \sin(b)$ must give you a sum of terms of the form $a_j \sin(j x)$ and $b_j \cos(j x)$ with $0 \le j \le n$, but the oddness and periodicity implies that the terms for $j < n$ and the $\cos$ terms cancel, leaving a multiple of $\sin(nx)$.    Now all you have to do is show that the constant is $1$...

A: This solution herein is inspired by a comment left by @user1952009 on another posted solution.  That solution is elegant in that it relies on only $(i)$ Euler's formula to write
$$\sin(nx)=\frac{e^{inx}-e^{-inx}}{2i}\tag 1$$
and $(ii)$ the $n$ roots of unity, $z=e^{-i2k \pi/n}$ for $k=0,\dots,n-1$, of the equation $z^n=1$ to write
$$z^n-1=\prod_{k=0}^{n-1}(z-e^{-i2\pi k/n})\tag 2$$
Proceeding, we find
$$\begin{align}
\sin(nx)&=\frac{e^{inx}-e^{-inx}}{2i}&\\\\
&=\frac{e^{-inx}}{2i}\left(e^{i2nx}-1\right)\\\\
&=\frac{e^{-inx}}{2i}\prod_{k=0}^{n-1}(e^{i2x}-e^{-i2\pi k/n})\\\\
&=\frac{e^{-inx}}{2i}\prod_{k=0}^{n-1}\left(\color{blue}{e^{ix}}\color{red}{e^{-i\pi k/n}}\color{green}{(2i)}\sin\left(x+\frac{k \pi}{n}\right)\right)\\\\
&=\frac{e^{-inx}}{2i} \color{blue}{e^{inx}} \color{red}{e^{-i(\pi/n)n(n-1)/2}}\color{green}{(2i)^n}\prod_{k=0}^{n-1}\sin\left(x+\frac{k \pi}{n}\right)\\\\
&=2^{n-1}\prod_{k=0}^{n-1}\sin\left(x+\frac{k \pi}{n}\right)
\end{align}$$
as was to be shown!


text:
Q: Turtle Filling Colors - I'm trying to choose the color when I call the function, so that I can easily change it in the future So I want to choose the color when I call the function. However, whenever I choose the color it says that the color is not defined.
import turtle

def square(color):
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.end_fill()

square(brown)

>> NameError: name 'brown' is not defined

A: Your indentation is wrong in the code you show, but that may be just because you are not familiar with how to show code on this site. So I have corrected that for you in your question.
More important, the color should be surrounded by quotes. Python is correct: the variable brown is not defined but the string "brown" is known. Try this code:
import turtle

def square(color):
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.left(90)
    turtle.forward(90)
    turtle.end_fill()

square("brown")


text:
Q: Expand existing RAID1 zpool into RAID10 zpool I'd like to expand/convert my existing RAID1 (2x 3TB mirror) zpool to RAID10 zpool by adding 2 more 3TB HDDs without losing (or moving) data stored on my existing pool.
The final result will look like 2x3TB (existing mirror) + 2x3TB (new mirror) combined into RAID0 zpool
Is it possible?

A: Yes, it's possible. The incantation you are looking for is:
zpool add poolname mirror newdisk1 newdisk2


text:
Q: Good alternative to SQL access on iPhone I am working on an app for a business that is essentially a catalog. The client has a website that uses a MySQL database, but he doesn't want that to be used by the app. His website offers RSS feeds, but I don't think that this would be a good idea. The app is supposed to be searchable based on a number of (optional) factors and show details of each item when selected.
Somehow, I don't think that RSS is the way to go, but how to convince him? Is there an alternative way that will work? The catalog is often updates and that means downloading updates will be necessary. Should I try to convince him to allow for read-only access?
Assuming that I'm using RSS, what would be the best update schedule? How would searching work? I'm confused...
Please note:
[Thinking aloud here...]
{I am new to iPhone development, this being my first app. I've done websites for 6+ years and I know HTML, JS, CSS, PHP, MySQL and Visual Basic 2008. I have dabbled in desktop languages (C, C++, Java) and I am now learning Objective C as I work.}
EDIT:
I'm not familiar with JSON. Tutorial links?

A: RSS is not the answer you're looking for. RSS is not really suited for arbitrary structured data, it's built around syndicating web content.
You definitely don't want to expose direct database access for a few reasons (security, response time, etc.). I would build a web service on the server side that provides a few methods (making some assumptions based on what I know about most catalogs):

*

*"get category hierarchy" - would query the database for the category structure and provide that back to the app

*"get items in category" - returns the item data for a particular category

*"search" - would accept a set of parameters, search the database using those, and return the matching set of items

I would use JSON as my data interchange format, as it's a lot simpler than dealing with XML.

A: How large is the database?  How large are the RSS updates?  Is the entire catalog accessible through that RSS stream?  Does the app need to function without an internet connection?  The answers here will likely drive your decision.
I certainly wouldn't advocate for direct MySQL access.  It's a big security risk, and it is very implementation dependent.  Your client couldn't do a database redesign without breaking the iPhone app, for example.
If you have access to the website (or could convince the client), perhaps a good solution would be to leverage your strengths and expose a RESTful interface to the SQL over the web.  Then your iPhone app can simply be a JSON or XML (or whatever) parser and interface.  You wouldn't need to worry about the backing store or searching on the iPhone; it'd all be done server-side.
You could potentially use RSS, but a big I presume that only the changes are pushed out through the stream.  You'd need to keep a copy of the database on the phone, and use RSS to keep it updated.  However, you'll have a very tough time with the first sync (since the prepopulated data may be quite stale) and then any sync after a long delay since not all changes may be available anymore.  You'd probably have to allow for the entire database to be downloaded through some secondary mechanism.  And if it is really big, neither users nor the host will be too happy about that.  Moreover, the heuristics of the syncing would be tricky.


text:
Q: How to split a Ruby array into a certain number of smaller arrays? I have a large Ruby array that I would split into smaller arrays. I don't care about how many items are in each array, rather, I care about specifying how many arrays I will end up with. I will be displaying the items in columns. For example, how can I split the array into two, or three smaller arrays?

A: If you're using Rails (you don't say) you could use in_groups.
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]

http://api.rubyonrails.org/classes/Array.html#method-i-in_groups
Or, if not Rails, just take the source for that method...

A: Without Rails, I'd use each_slice:
2.0.0p247 :006 > arr = %w(1 2 3 4 5 6 7 8 9 10)
 => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

2.0.0p247 :007 > n = 3  # how many arrays you want
 => 3

2.0.0p247 :009 > arr.each_slice((arr.size/n.to_f).ceil) {|slice| p slice };nil
["1", "2", "3", "4"]
["5", "6", "7", "8"]
["9", "10"]
 => nil

A: list = (1..10).to_a
nsublists = 3
sublists = []
list.each_slice((list.size.to_f/nsublists).ceil) { |slice| sublists << slice }

sublists # => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]


text:
Q: Unable to install Jekyll on Mac OSX 10.9.1 with xcode and rvm installed Not having any luck installing Jekyll on Mac OSX 10.9.1
I have rvm installed and also Xcode 5.0.2.
When I run gem install jekyll it tells me...

Permission denied -
  /Users/Vivid/.rvm/gems/ruby-1.9.2-p320/extensions/x86_64-darwin-12

I then ran sudo gem install jekyll and I then get:
ERROR:  Error installing jekyll:
    ERROR: Failed to build gem native extension.

    /Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/bin/ruby extconf.rb
creating Makefile

make  clean

make
gcc-4.2 -I. -I/Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/include/ruby-1.9.1/x86_64-darwin12.2.0 -I/Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/include/ruby-1.9.1/ruby/backward -I/Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/include/ruby-1.9.1 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE   -fno-common -I/Users/Vivid/.rvm/usr/include -fno-common -pipe  -o porter.o -c porter.c
make: gcc-4.2: No such file or directory
make: *** [porter.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/gems/1.9.1/gems/fast-stemmer-1.0.2 for inspection.
Results logged to /Users/Vivid/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/gems/1.9.1/extensions/x86_64-darwin-12/1.9.1/fast-stemmer-1.0.2/gem_make.out

This is the contents of /Users/Vivid/.rvm/gems/ruby-1.9.3-p327/gems/fast-stemmer-1.0.2/ext/gem_make.out:
/Users/Vivid/.rvm/rubies/ruby-1.9.3-p327/bin/ruby extconf.rb
creating Makefile

make
compiling porter.c
make: /usr/bin/gcc-4.2: No such file or directory
make: *** [porter.o] Error 1

Something is clearly not right. Any advice would be magic, cheers.

A: You need to install gcc-4.2. Make sure you have Homebrew installed and run
brew install apple-gcc42

Make sure you see happy output when you run:
which gcc-4.2

Then try re-running:
sudo gem install jekyll

Boom! Installed.


text:
Q: Sending byte[] to Java REST POST changes actual array I  have a Spring REST service set up which has a POST method to receive a byte array. The goal of this method is to accept a zipped JSON string, hence the byte array. The unzipped string is to be mapped to a list and then sent to a database.
@RequestMapping(value = "/receiveData.do", method = RequestMethod.POST)
public
@ResponseBody boolean receiveData(@RequestParam byte[] data,
                                  @RequestParam String configurationName) {
    String jsonString = ZipController.unZip(data);
    JSONMapper jsonMapper = new JSONMapper();
    List<Message> messages = null;
    try {
        messages = jsonMapper.parseToMessage(jsonString, configurationName);
        saveData(messages);
    } catch (Exception e) {
        return false;
    }
    return true;
}

The zipping and the unzipping of the String works without flaws, as tests that I have written show. The converting to a list and then storing it in a database works perfectly too. However, when I zip a string, and send it to the address, somehow it isn't recognized as a zip anymore. Further digging revealed that the actual byte[] has completely changed in the process. Before I send it, the array prints to
[B@7186333e

However, after sending it, it suddenly prints to (for example)
[B@fee07cc

This appears to be random, but the [B@ is always the same. The rest is random. I am using the REST-assured framework to test, but SOAPui gives the same problem. The code I'm using to send the call is:
expect().
body(containsString("true")).
when().
given().
parameters("data",ZipController.zip(correctJSONMessage)).
post("/receiveData.do");

The method returns a true or false as feedback whether it succeded or not.
The whole service runs on a Tomcat 6 server, is it possible that this messes with the array? How can I fix this?


text:
Q: ElasticSearch suggestions on blog name, authors and tags I've been looking all over the place for a good answer to my question but I just can't find any...
I'm using ElasticSearch along with Laravel. I've used ElasticSearch on another project but never used suggestions. I'm following this tutorial as I think it provides a great starting point for using Laravel with ElasticSearch: https://blog.madewithlove.be/post/how-to-integrate-your-laravel-app-with-elasticsearch/
My question is about suggestions; I want my search to be a search-as-you-type just like the one you would find on Spotify. I want my users to type a few letters in the search box and have the results be organized into multiple categories: blogs, authors, tags.
If I index my data into one index, with authors and tags being blog's nested objects, I can easily get suggestions using the completion suggester for blog names, but not for nested objects. I could also split each model and index data separately into different indexes, but that would mean I would have to make 3 queries to get my results back.
Am I doing something wrong? Should I structure my data differently? Is making 3 queries the way to go or is there a way to have a single query output search results from different indexes?
Thanks!
Xavier

A: Something that I did when I built a search-as-you-type was I used a separate index for suggestions. In your situation, you'd index the name (title, author, whatever) in one field and the type in another. Then you could search on one field and display the grouped results.
The advantage here is speed. This will likely be a heck of a lot faster than trying to do a suggester on your nested data. (Which you can probably do, but I'm not sure how.) And speed is pretty important for this type of feature.


text:
Q: Broken Screenshots using Emulator I'm having a problem taking a screenshot when a dialog is showing.  I'm trying to take it from the emulator, and the problem is that only portions of the dialog show up, and other portions show through from behind.  Here is the emulator screenshot on the left, and one from my device on the right:

I have tried running different API levels in the emulator, as well as both the ARM and Intel Atom images, none of which helped.  I even tried it on both my laptop and desktop to no avail.  Has anybody else run into this problem?


text:
Q: Merge Datasets based on 3 columns with not the same size I want to merge two datasets but i don't know how. The first dataset have the following format.
  Year    Team    Wins   Loses
  ----------------------------
  2020    MLK     14       4
  2020    BRKL    10       5
  2020    PHX      5      10
  2019    BRKL    11       4
  2019    MLK     10       5
  2019    PHX      8       7
  2018    ...     ...     ...

The second dataset has the following format:
  Year    Team1  Points1  Team2   Points2
  ---------------------------------------
  2020    MLK      80      PHX      66
  2020    PHX      71      BRKL     70
  2020    BRKL     90      MLK      80
  2019    PHX      69      BRKL     70
  2019    ...      ...     ...      ...

The final dataset i want to have the following format:
  Year    Team1  Points1  Team2   Points2 Team1Wins Team1Loses  Team2Wins  Team2Loses
  2020    MLK      80      PHX      66       14         4           5          10
  2020    PHX      71      BRKL     70       5          10          10          5
  2020    BRKL     90      MLK      80       10         5           14          4
  2019    PHX      69      BRKL     70       8          7           11          4
  2019    ...      ...     ...      ...      ...        ...         ...         ...

I have read questions here but i don't have find a solution for my problem. I have tried something like above but it is not the right solution.
  import pandas as pd

  a = pd.read_csv("Score.csv",error_bad_lines=False)
  b = pd.read_csv("Team.csv",error_bad_lines=False)
  merged = pd.merge(a, b, how='left', on=['Year'])
  print(merged)

Is there a way of achieving this?

A: Use DataFrame.merge with rename columns:
d = {'WIN%':'Team1Wins','FG%':'Team1Loses','Team':'Team1'}
df = b.merge(a.rename(columns = d)[['Team1Wins','Team1Loses','Team1','Year']],
             on=['Year', 'Team1'])

d = {'WIN%':'Team2Wins','FG%':'Team2Loses','Team':'Team2'}
df = df.merge(a.rename(columns = d)[['Team2Wins','Team2Loses','Team2','Year']],
              on=['Year', 'Team2'])
print (df)
   Year Team1  Points1 Team2  Points2  Team1Wins  Team1Loses  Team2Wins  \
0  2020   MLK       80   PHX       66         14           4          5
1  2020   PHX       71  BRKL       70          5          10         10
2  2020  BRKL       90   MLK       80         10           5         14
3  2019   PHX       69  BRKL       70          8           7         11

   Team2Loses
0          10
1           5
2           4
3           4


text:
Q: Place Tab Activity at the bottom of the screen Hi guys how can I position the acitvity tab at the bottom of the screen? below I have inserted xml of the activity. When I create an activity tab to be inserted it is always inserted at the top! When I create an activity tab to be inserted it is always inserted at the top
Tab Image:

XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".View.TabActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <!--<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>-->

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/home"
                android:text="Home" />

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/articoli"
                android:text="Articoli" />

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/rapportini"
                android:text="Rapportini" />

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

A: Use BottomNavigationView instead of tab view and link your view pager to this:
https://developer.android.com/reference/android/support/design/widget/BottomNavigationView
layout resource file:
 <android.support.design.widget.BottomNavigationView
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/navigation"
     android:layout_width="match_parent"
     android:layout_height="56dp"
     android:layout_gravity="start"
     app:menu="@menu/my_navigation_items" />

 res/menu/my_navigation_items.xml:
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:id="@+id/action_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_search" />
     <item android:id="@+id/action_settings"
          android:title="@string/menu_settings"
          android:icon="@drawable/ic_add" />
     <item android:id="@+id/action_navigation"
          android:title="@string/menu_navigation"
          android:icon="@drawable/ic_action_navigation_menu" />
 </menu>


text:
Q: CloudKit allUserIdentitiesFromContacts() failing due to too many requests (http 429) I'm making a simple call to fetch all app users in contacts:
let userIdentities = try await CKContainer.default().allUserIdentitiesFromContacts()

which fails with the message:

Request failed with http status code 429

HTTP 429 is the code for too many requests.
I get the same response in both development and production apps.
I've tried this in a test app that only makes this and no other calls, with the same result.
I have nearly 1,000 contacts on the phone where this fails. On another test device that only has 2 contacts, the request succeeds.
I'm assuming this is a bug, but just asking in case I'm missing something.


text:
Q: Synchronizing against unknown database schema in Android I have an online (postgresql) database, and a local copy of the db in an Android app. The data in these is synchronized, so the app can function offline, but can download new data and upload results when it can. Data is transfered via http GET and POST requests.
I have no problem synchronizing the data for known tables, however, I would like it to be possible to create new tables/alter tables in the online database and have that change reflected in the Android db automatically i.e. without having to release a new version with the updated synchronization code. Is there an obvious/standard way to do this that I haven't found? Google searches I have performed just refer to database migrations for two of the same system or for known schema.

A:
Is there an obvious/standard way to do this that I haven't found?

There's no "standard" way but there are ways to do it depending on your requirements and how your app works.
It's actually a broad question but solvable if you give it a bit of thought.
My app downloads data from a server on a daily basis. Part of the download process involves downloading a DB version file (just a plain text file) similar to the following...
db_version=12345

...the string representation of the previous version (if any) is saved in SharedPreferences as an int value.
If the version in the file is greater than the one in SharedPreferences, the downloader pulls some text files which contain SQL commands for creating, dropping, altering tables etc. Only after the changes have been successfully made does the downloader pull the actual data files and update the DB data (not forgetting to update the latest version in SharedPreferences).
If the version in the file is the same as in SharedPreferences  then obviously the download simply does the normal daily data download and DB data update.


text:
Q: Estimate kubelka-munk coeffs at home (originally i asked it on chemistry stackexchange)
I want to estimate Kubelka-Munk coeffs (absorption and back-scattering) for acrylic pigment. I want to do this only for three wavelengths that correspond to RGB colors of digital display. Workflow I assume is:

*

*using scanner do a scan of empty white sheet

*estimate reflectance of sheet for every wavelengths of RGB colors using equation: pixel_value/255 - this will be used as substrate reflectance in KM equation

*cover same white sheet with layer of pigment of known thickness (using 3d printed spatula)

*using scaner do a scan of pigmented sheet

*estimate reflectance of pigmented sheet for every wavelengths of RGB colors using equation: pixel_value/255
-Repeat process for black sheet
Then resolve inverted Kubelka-Munk equation for every wavelength using reflectances from white and black sheet measurments.
Is is possible to get any reasonable results with such approach? I do not aim to have very precise results but something that can be still usable for basic calculations. Is there any better way to estimate coefficienta at home?


text:
Q: Rails: Should I be handling rendering logic in the view or controller? My Rails app /index path should show one page to logged in users, an entirely different page to admin users, and a totally different one for users who aren't logged in.
So, one controller (HomeController), one action (index), three views.
I can implement this in two ways:

*

*Insert if clauses into views/home/index.html.erb making it do the right thing.

*Put the conditional logic into the controller somehow (make the controller find out who the user is) and then render a different layout accordingly, as described under 2.2.12 Finding Layouts in http://guides.rubyonrails.org/layouts_and_rendering.html.

I have a strong feeling the latter solution is the right one. But I'm not sure how to implement it, what with the user controller being a totally different controller. How can my home controller find out who the current user is to decide what view to render?

A: You have access to current_user object in all controllers, to check whether user is logged-in or not. Also we can get user role from the current_user object by

current_user.role_name

You can pass this role name to render partial as file name(Keep different files).


text:
Q: Error code 0x8000500D when trying to access PasswordLastChanged I'm writing a VBScript that will simply check each user in AD if their password has been changed within a given number of days. When I was trying to get it working for a single user, I came up with the following working code:
Option Explicit

Dim objUser, strLDAPConnection, intPwdExpLimit

strLDAPConnection = "CN=Test User,OU=Test,OU=Employees,DC=domain,DC=com"

intPwdExpLimit = 90

Set objUser = GetObject("LDAP://" + strLDAPConnection)

WScript.Echo DaysSincePwdChange(objUser)

Function DaysSincePwdChange(objUserAccount)
    DaysSincePwdChange = dateDiff("d", objUserAccount.PasswordLastChanged, Now)
End Function

So then I tried to get it to work by looping through all users in a Test OU with the following code:
Option Explicit

Const strOffice = "Test"

Dim objEmployeesOU, objUser, intPwdExpLimit

intPwdExpLimit = 90

Set objEmployeesOU = GetObject("LDAP://OU=" & strOffice & _
                     ",OU=Employees,DC=domain,DC=com")

For Each objUser In objEmployeesOU
    If objUser.class = "user" Then
        If ((DaysSincePwdChange(objUser)) >= intPwdExpLimit) Then
            MsgBox(objUser & ": Password Expired.")
        Else
            MsgBox(objUser & ": Password Current.")
        End If
    End If
Next

Function DaysSincePwdChange(objUserAccount)
    DaysSincePwdChange = dateDiff("d", objUserAccount.PasswordLastChanged, Now)
End Function

The above code produces a 0x8000500D error and googling the error says that it can't find the property in the cache (referring to the PasswordLastSet property, see error description link here).
Any ideas why the first block of code works fine but the second has a problem accessing that property?

A: Error code 0x8000500d means E_ADS_PROPERTY_NOT_FOUND. The password of the user has never been changed, so the property is not set. You could handle the condition like this:
Function DaysSincePwdChange(objUserAccount)
    On Error Resume Next
    DaysSincePwdChange = dateDiff("d", objUserAccount.PasswordLastChanged, Now)
    If Err Then
      If Err.Number = &h8000500d Then
        DaysSincePwdChange = -1
      Else
        WScript.Echo "Unexpected Error (0x" & Hex(Err.Number) & "): " & _
          Err.Description
        WScript.Quit 1
      End If
    End If
End Function

and modify the check like this:
passwordAge = DaysSincePwdChange(objUser)
If passwordAge >= intPwdExpLimit) Then
    MsgBox(objUser & ": Password Expired.")
ElseIf passwordAge = -1 Then
    MsgBox(objUser & ": Password never changed.")
Else
    MsgBox(objUser & ": Password Current.")
End If


text:
Q: How can I add these custom cells to a TableView? Using Xamarin.Forms, how can I achieve a layout like this one?

I'm talking about the textual hints on grey background:

Turn on Personal Hotspot to share ...

All I can add to a ListView or TableView are standard ViewCells, and they all get rendered with separators and white background.
If this layout isn't possible by using TableView or ListView, how can I render a ViewCell (like the Wi-Fi Password one in the sample image) in a standard StackLayout?

A: Even though there's no out-of-the-box ViewCell for the TableView to do that, you can certainly roll out your own implementation. There obviously is a TextCell but it doesn't let you specify the font size and other stuff.
You could do something like this:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DemoTableView.TablePage" Title="TableView">
    <ContentPage.Content>
        <TableView Intent="Settings">
            <TableRoot>
                <TableSection>
                    <SwitchCell Text="Personal Hotspot" />
                    <ViewCell> <!-- Simple text -->
                        <Label Text="Turn on personal hotspot..." FontSize="Small" ForegroundColor="Gray" />
                    </ViewCell>
                    <ViewCell> <!-- More complex cell -->
                        <StackLayout Orientation="Horizontal>
                            <Image Source="someicon" />
                            <StackLayout>
                                <Label Text="TO CONNECT USING WIFI" FontSize="Large"/>
                                <Label Text="Something more" FontSize="Small" />
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </TableSection>
            </TableRoot>
        </TableView>
    </ContentPage.Content>
</ContentPage>

This is just a quick example written in hurry but you get the idea. You can also programmatically define your own cells by inheriting from the ViewCell class and show them in the TableView.
Here's more about custom cells on the official documentation.

Edit: As per your comment, we need to dig a bit into the platform specific code to disable selection on the text-only cells. You should create a custom ViewCell implementation with the following custom renderer for iOS:
[assembly: ExportCell(typeof(YourCell), typeof(YourCellRenderer))]
namespace YourProject.iOS
{
    public class YourCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell (Cell item, UITableView tv)
        {
            var cell = base.GetCell (item, tv);
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
            return cell;
        }
    }
}


text:
Q: Specman coverage: How to cover only that some transition occurred? I need to make sure that at least 1 change occurred in a specific uint item X, i.e. X had 2 different values (it is unknown what specific values). Something like this:
cover some_event {
    item X : uint = some_uint using no_collect;
    transition X using when = (prev_X != X);
};

** The code causes compilation error
Is it possible to define such coverage in Specman?
Thank you for your help

A: what you wrote is almost accurate, but instead of "when" - use "ignore"
cover some_event is {
    item X : uint = some_uint using no_collect;
    transition X using ignore = (prev_X == X);
};


text:
Q: setTimeout() and clearTimeout() with Promise in TypeScript (strict mode + all annotations) I saw many examples of timer with Promise for JavaScript. Most of them are too complicated, but I suppose, it could be implemented more simply. However, I need the solution for TypeScript in "strict": true mode with all annotations.
I tried to do it until below code:
import Timeout = NodeJS.Timeout;

let testTimeout : Timeout;
const DELAY: number = 3000;

testTimeout = (): Promise<void> => (
  new Promise<void>( (resolve): void => {
    setTimeout(resolve, DELAY);
  })
);

testTimeout = testTimeout().then( () => {
  console.log('done');
});
clearTimeout(testTimeout);

It has errors:
TS2739: Type '() => Promise<void>' is missing the following properties from type 'Timeout': ref, refresh, unref

TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Timeout' has no compatible call signatures.

I suppose, I do something wrong.

A: Try this:
function setTimeoutPromise(fn: () => number, delay: number): Promise<number> {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(fn())
        }, delay)
    })
}

setTimeoutPromise(() => {
    console.log('resolving...');
    return 10;
}, 5000).then((res) => console.log('should print 10 after 5 secs', res));

this compiles fine with tsc --strict true. I am not sure if this what you are looking for though. Let me know!
There is another way of achieving this that I have just thought about:
import * as util from 'util';

const setTimeoutPromise = util.promisify((delay, fn) => setTimeout(fn, delay));
setTimeoutPromise(5000).then(() => console.log('hey you!'));

It might look a bit strange but it works. Basically .promisify expects a standard callback-last function to be passed to it as an argument where as the setTimeout has the opposite signature. So we reverse them:)


text:
Q: Error in parsing Google Suggest API in Japanese When i search "ア" Data From Google Suggest API And my current language in device is English. Then I am getting below response in iPhone device.
<?xml version="1.0"?>
<toplevel>
<CompleteSuggestion>
<suggestion data="アマゾン"/>
<num_queries int="69300000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="アメブロ"/>
<num_queries int="66400000"/>
</CompleteSuggestion>
</toplevel>

When i search "ア" Data From Google Suggest API And my current language in device is Japanese. Then I am getting below response in iPhone device.
<?xml version="1.0"?>
<toplevel>
<CompleteSuggestion>
<suggestion data="ÉAÉ}É]Éì"/>
<num_queries int="69300000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="ÉAÉÅÉuÉç"/>
<num_queries int="66400000"/>
</CompleteSuggestion>
</toplevel>

For English XML Parsing working fine But for Japanese response it gives me error in Parsing XML And not data will be displayed.
Please suggest any way to solve this.
I am using below code for get response from Google Suggest API.
NSString *strUrl = [NSString stringWithFormat:@"http://google.com/complete/search?output=toolbar&q=ア"];

NSURL *url = [NSURL URLWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString * urlData = [NSString stringWithContentsOfURL:url];

// Print the data that get from google suggest api.
NSLog(@"URL Data :: %@", urlData);

Thanks.

A: I am solved that issue. in my case google api return me a Japanese Characters.
So i am change my code as per below:
NSString *strUrl = [NSString stringWithFormat:@"http://google.com/complete/search?output=toolbar&q=ア"];

NSURL *url = [NSURL URLWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSError * isError;
NSString * urlData = [NSString stringWithContentsOfURL:url encoding:NSShiftJISStringEncoding error:&isError];

NSLog(@"URL Data :: %@", urlData);

Thanks.


text:
Q: One-way ANOVA for loop: how do I initiate through multiple colums of a dataframe I want to run more than 1000 different one way ANOVA's
I would like to see if the number of reads from a single miroRNA changes between four different groups. And I would like that from each of the more than 1000 miRNAs.
My tibble dataframe looks like this:
I have my 4 groups (YC, OC, YH, OH) and a different miRNA in each column.
enter image description here
I tried a for-loop through which I expect R to iterate through the name of the miRNAs and then summaries an ANOVA table and TukeyHSD test:
    for(i in 2:ncol(test))
{column<-names(test[i])AVz<-summary(aov(test[,i]~Group,data =
test))tk<-TukeyHSD((aov(test[,i]~Group,data =
test)))print(column)print(AVz)print(tk)}

BUT this didn't work:
Error: unexpected symbol in "for(i in 2:ncol(test)){column<-names(test[i])AVz"

A: If you would like to run aov you can use cbind
 formula <- as.formula(paste0("cbind(", paste(names(iris)[-5], collapse = ","), ") ~ Species"))

    fit <- aov(formula, data=iris)
    summary(fit)

Response Sepal.Length :
             Df Sum Sq Mean Sq F value    Pr(>F)
Species       2 63.212  31.606  119.26 < 2.2e-16 ***
Residuals   147 38.956   0.265
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Response Sepal.Width :
             Df Sum Sq Mean Sq F value    Pr(>F)
Species       2 11.345  5.6725   49.16 < 2.2e-16 ***
Residuals   147 16.962  0.1154
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Response Petal.Length :
             Df Sum Sq Mean Sq F value    Pr(>F)
Species       2 437.10 218.551  1180.2 < 2.2e-16 ***
Residuals   147  27.22   0.185
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Response Petal.Width :
             Df Sum Sq Mean Sq F value    Pr(>F)
Species       2 80.413  40.207  960.01 < 2.2e-16 ***
Residuals   147  6.157   0.042
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


text:
Q: Lock application while factory reset Programmatically I'm developing an application which runs in stealth mode and I Don't want it t get uninstalled when the user applies factory reset to his cell phone. Is there any way to lock the application so that it may not get uninstalled during factory reset?

A: Build your own custom ROM. Pre-install your app on that custom ROM. Anyone who factory-resets their device that is running this ROM will get the app back, though probably not its data.
Beyond that, there should be no way to survive a factory reset, outside of security flaws.


text:
Q: How to unregister BroadcastReceiver associated with repeating alarm? It's unclear to me how to accomplish this, and I'm getting lost in the Android docs. I would assume this a common enough scenario though, so could someone show me the appropriate way to get hold of a BroadcastReceiver so I can unregister it (or point me in the right direction so I can educate myself) ?
SETTING THE ALARM:
registerReceiver(alarmHandler, new IntentFilter("com.blah.alarm"));
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("com.blah.alarm"), 0);
AlarmManager am = (AlarmManager) (this.getSystemService( Context.ALARM_SERVICE ));
am.setRepeating(
        AlarmManager.RTC_WAKEUP, someCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);

UNSETTING THE ALARM:
PendingIntent pi = PendingIntent.getBroadcast(
            this, 0, new Intent("com.blah.alarm", PendingIntent.FLAG_NO_CREATE);
if (pi != null) {
    AlarmManager am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    am.cancel(pi);
}
unregisterReceiver(????????); // how do I get alarmHandler ref ??

A: You'll need to save the alarmHandler reference in a variable somewhere so that you can get it when you need to call unregister()`. Android doesn't provide any method you can call to get a reference to it.


text:
Q: Using type in template class of derived template class Try to implement the CRTP pattern. Therefore I created two template classes. With the first draft of only one template class PDerived everything is fine. But for my purpose in a bigger project I need two template classes. Which results in an error: All types of the PDerivced class are not found. But I have no idear why. In the following the is a minimalistic example.
In this example myType can not be found? If TDerived is no template class everything is fine. Is there some namespace needed?
#include <iostream>

template< typename PDerived >
class TBase
{
 public:
  using myType = uint8_t;

  void Foo( void )
  {
   static_cast< PDerived* > ( this )->Bar();
  }
};

template< typename Derived > class TDerived : public TBase< TDerived<Derived> >
{
  friend class TBase< TDerived > ;
 protected:
  void Bar( void )
  {
   std::cout << "in Bar" << std::endl;
  }
 private:
  myType myVariable;

};

int main( void )
{
 TDerived<uint8_t> lD;

 lD.Foo();

 return ( 0 );
}

Error message:
error: 'myType' does not name a type

A: If you want to refer to some templated stuff of your base class, you have to give the compiler a hint how to find it.
Change your line:
myType myVariable;

to
TBase< TDerived<Derived> >::myType myVariable;

The underlying problem is, that unqualified names are not resolved during this stage until the template is fully defined. You get the same problem if you try to call member functions or variables from your base class. In this case you can simply use this->MemberFunc().


text:
Q: Backbone.js - using browser back button router not initiating In my app..
While i load the page or refresh the page my router not properly responding and calling the default view method. in case if i use other link to vist other hash url... works as well the back button doing fine.
Even while i load my page, my initiate function as well works fine. but the default method not triggering while i load the page and use the back button of the browser.
what cause this.. here is my code:
    define([
    "backbone",
    "../model/model",
    "../collection/collection",
    "../views/appView",
    "../views/listView",
    "../views/appViews"],
    function(Backbone,appModel,collection,appView,listView,appViews){

    var appRouter = Backbone.Router.extend({
        routes:{
            "":"defaultView",
            "list":"listAItem",
            "add":"listViewIt"
        },
        initialize:function(){
            console.log("initiated....."); //works properly
        },
        defaultView:function(){
            new appViews(); // not working..
        },
        listAItem:function(){
            console.log("from listAItem");
                    // on click and using back button woks fine
        },
        listViewIt:function(){
            new listView();
                   // on click and using back button woks fine
        }
    });

    Backbone.history.start(); // removed and updated to where i call my app...

    return appRouter;
})

Now i updated my Backbone.history to call after initiating my app.. now my initial method (defual view called) but still while i use my back / font buttons in my browser not working.. but reset are works fine..
how to fix it..
here is my updated code:
 $.when.apply(null,requests).done(function(){
        var app = new router();
       //on refresh works, but not working while use back / front button of browser use.
        Backbone.history.start();
    });

A: It works...
It was my mistake to other view to set the initial element removed. now i realized that. now works fine. thank for all..
update code :
this.$el.find("ul").html("
New html has to come here
");

it was been wrongly as:
this.$el.html("
New html has to come here
");


text:
Q: Ubuntu - unable to ID AD Accounts After following this guide,
I got to the point were it tells me to verify using ID "username"
which just straight up tells me this account does not exist.
I have been adding debian machines to the same domain without issue (also using realmd + SSSD) but this is my first ubuntu. (ubuntu server)
realm list gives me the following result:
Foo.Bar
  type: kerberos
  realm-name: FOO.BAR
  domain-name: Foo.Bar
  configured: kerberos-member
  server-software: active-directory
  client-software: sssd
  required-package: sssd-tools
  required-package: sssd   required-package: libnss-sss
  required-package: libpam-sss   required-package: adcli
  required-package: samba-common-bin   login-formats: %U   login-policy:
  allow-realm-logins

I also noted that su does not recognize the domain and just ignores my \ resulting in:
user@ubuntu:~$ su foo\user
No passwd entry for user 'foouser'

UPDATE:
dig –t SRV _ldap._tcp.foo.bar | grep –A2 "ANSWER SECTION"
grep: ANSWER SECTION: No such file or directory

However, we checked with nslookup and nslookup can find the SRV records:
user@ubuntu:/home/user# nslookup
> set type=srv
> _ldap._tcp.foo.bar
Server:         172.16.0.1
Address:        172.16.0.1#53

_ldap._tcp.foo.bar service = 0 100 389 server1.foo.bar.
_ldap._tcp.foo.bar service = 0 100 389 server2.foo.bar.
_ldap._tcp.foo.bar service = 0 100 389 server3.foo.bar.


text:
Q: Prove that $f(w)=\frac{1}{2\pi}\int_{\partial\Bbb{D}}\frac{f(z)}{1-w\bar{z}}|dz|$ Let $f$ be analytic in an open set containing $\bar{\Bbb{D}}$. If $w\in \Bbb{D}$ then prove that $$f(w)=\frac{1}{2\pi}\int_{\partial\Bbb{D}}\frac{f(z)}{1-w\bar{z}}|dz|$$
First of all,since $\frac{1}{1-u}=\sum_{k=0}^{\infty}u^k$ for all $u\in \mathbb{D}$, I can let $u=w\bar{z}$ and we have $\frac{1}{1-w\bar{z}}=\sum_{k=0}^{\infty}(w\bar{z})^k$. Also, since $f(z)$ analytic, it has a power series expansion $\sum_{n=0}^{\infty}a_nz^n$. If $w\in \mathbb{D}$ is fixed, then for any $z\in \mathbb{D}$, $\frac{1}{1-w\bar{z}}$ converges uniformly, as well as $f(z)$. Consequently, I can deduce that it's product $\frac{f(z)}{1-w\bar{z}}$ is uniformly convergent.
Can anyone help me finish the proof?

A: On $\partial \Bbb D$, $\bar{z} = z^{-1}$ and $|dz| = \dfrac{dz}{iz}$, making
$$\frac{1}{2\pi}\int_{\partial \Bbb D} \frac{f(z)}{1 - w\bar{z}}\lvert dz\rvert = \frac{1}{2\pi}\int_{\partial \Bbb D} \frac{f(z)}{1 - wz^{-1}} \frac{dz}{iz} = \frac{1}{2\pi i}\int_{\partial \Bbb D} \frac{f(z)}{z - w}\, dz$$
The last expression is equal to $f(w)$ by the Cauchy integral formula.


text:
Q: Athena ID Protect v2 Token triggers Select Card dialog on PKCS#11 C_Login I am playing around with an Athena IDProtect v2 Token from NXP (the one compatible with the IDProtect Laser product line) on Windows 10 Pro (x64 german).
After installing the Athena client middle ware 7.10.00 (x64) - with and without setting the Athena CSP Provider as default for Windows - and after formatting the token I can use it from Pkcs11Admin tool as well as OpenSC pkcs11-tool.
The library used is C:\Windows\System32\asepkcs.dll from the ASE Cryptoki 3.1.
The "Select Smartcard dialog" pops up on PKCS#11 function C_Login it seems, and it happens no matter if I have one or more readers present. It happens in multiple PKCS11 clients (including Java keytool):

Sorry for the german, the message says "the requested operation cannot be executed or another smartcard is required".
The PKCS11 Spy Log from PKCS11Admin tool is most telling. The C_Login hangs until I press "Cancel" in the dialog and then returns with CKR_OK:
0x00000274 : 0x00001494 : Calling C_OpenSession
0x00000274 : 0x00001494 : Input
0x00000274 : 0x00001494 :  slotID: 0
0x00000274 : 0x00001494 :  flags: 6
0x00000274 : 0x00001494 :   CKF_RW_SESSION: TRUE
0x00000274 : 0x00001494 :   CKF_SERIAL_SESSION: TRUE
0x00000274 : 0x00001494 :  pApplication: 0000000000000000
0x00000274 : 0x00001494 :  Notify: 0000000000000000
0x00000274 : 0x00001494 :  phSession: 0000004AD91FD370
0x00000274 : 0x00001494 :  *phSession: 3642741616
0x00000274 : 0x00001494 : Output
0x00000274 : 0x00001494 :  phSession: 0000004AD91FD370
0x00000274 : 0x00001494 :  *phSession: 1
0x00000274 : 0x00001494 : Returning 0 (CKR_OK)
0x00000274 : 0x00001494 : *********************** 2017-06-03 21:24:14 ***
0x00000274 : 0x00001494 : Calling C_Login
0x00000274 : 0x00001494 : Input
0x00000274 : 0x00001494 :  hSession: 1
0x00000274 : 0x00001494 :  userType: 1 (CKU_USER)
0x00000274 : 0x00001494 :  pPin: 00000236C5779128
0x00000274 : 0x00001494 :  *pPin: *** Intentionally hidden ***
0x00000274 : 0x00001494 :  ulPinLen: 8
... <here it hangs till I cancel the dialog> ...
0x00000274 : 0x00001494 : Returning 0 (CKR_OK)
0x00000274 : 0x00000d38 : ********************** 2017-06-03 21:26:24 ***
0x00000274 : 0x00000d38 : Calling C_GetSlotInfo
0x00000274 : 0x00000d38 : Input
0x00000274 : 0x00000d38 :  slotID: 0
0x00000274 : 0x00000d38 :  pInfo: 0000004AEBE7E630
0x00000274 : 0x00000d38 : Output
0x00000274 : 0x00000d38 :  pInfo: 0000004AEBE7E630
0x00000274 : 0x00000d38 :   slotDescription: Athena IDProtect Key v2 0
0x00000274 : 0x00000d38 :   manufacturerID: Athena
0x00000274 : 0x00000d38 :   flags: 7
0x00000274 : 0x00000d38 :    CKF_TOKEN_PRESENT: TRUE
0x00000274 : 0x00000d38 :    CKF_REMOVABLE_DEVICE: TRUE
0x00000274 : 0x00000d38 :    CKF_HW_SLOT: TRUE
0x00000274 : 0x00000d38 :   hardwareVersion:
0x00000274 : 0x00000d38 :    major: 1
0x00000274 : 0x00000d38 :    minor: 0
0x00000274 : 0x00000d38 :   firmwareVersion:
0x00000274 : 0x00000d38 :    major: 1
0x00000274 : 0x00000d38 :    minor: 0
0x00000274 : 0x00000d38 : Returning 0 (CKR_OK)

I noticed that when I use certutil.exe -SCInfo it has the same problem, but can be suppressed with -silent (but I think certutil is not using PKCS#11 but directly the CNG drivers. In Certutil it happens with both the Microsoft base card driver as well as the Athena card driver).
BTW: only certutil and Windows popup name this card "CJCOP3", an other name is provisioned in the profile.
Any idea what that might be?

A: I got answer from my Crypto Dealer of choice (shout out to cryptoshop.com). This is a known limitation of the most recent Athena Middleware Clients and it helps to remove those Smartcards from the framework by deleting the following registry keys:
HKLM\SOFTWARE\Microsoft\Cryptography\Calais\SmartCards\CJCOP3
HKLM\SOFTWARE\Wow6432Node\Microsoft\Cryptography\Calais\SmartCards\CJCOP3


text:
Q: Elementor Custom Control: How to get input value? I'm creating a custom widget and control in Elementor. What I want to achieve is a button, when clicked, will open the file dialog to let the user choose a file. Once a file is chosen, an ajax script will upload the file and returns the download link. Please see below the pictures of what I want to achieve.

The file is uploading properly and I can set the value of the hidden input field with the file's url. But I can't get the url to show on the frontend.
Here is my current code:
Control (file-upload.php)
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

class File_Upload_Control extends \Elementor\Base_Data_Control {

    public function get_type() {
        return 'fileupload';
    }

    protected function get_default_settings() {
        return [
            'label' => 'Download File',
        ];
    }

    public function content_template() {

        $control_uid = $this->get_control_uid();
        ?>

            <label for="<?php echo $control_uid; ?>" class="elementor-control-title">{{{ data.label }}}

                <form action="" method="post" name="eae-file-upload-form">
                    <?php wp_nonce_field('eae-file-upload'); ?>
                    <input type="file" name="eae-file">
                </form>

            <input id="<?php echo $control_uid; ?>" type="hidden" name="eae-file-link" class="elementor-control-tag-area" title="{{ data.title }}" data-setting="{{ data.name }}" />

        <?php

    }

    public function enqueue() {
        wp_register_script( 'eae-file-upload', plugins_url( 'assets/js/file-upload.js', __DIR__ ) );

        $data = array(
                    'upload_url' => admin_url('async-upload.php'),
                    'ajax_url'   => admin_url('admin-ajax.php'),
                    'nonce'      => wp_create_nonce('media-form')
                );

        wp_localize_script( 'eae-file-upload', 'su_config', $data );

        wp_enqueue_script( 'eae-file-upload' );
    }

}

Widget (download-button.php)
<?php
class Download_Button_Widget extends \Elementor\Widget_Base {

    public function get_name() {
        return 'Download Button';
    }

    public function get_title() {
        return __( 'Download Button', 'elementor-artbees-extension' );
    }

    public function get_icon() {
        return 'fa fa-download';
    }

    public function get_categories() {
        return [ 'basic' ];
    }

    protected function _register_controls() {
        $this->start_controls_section(
            'content_section',
            [
                'label' => __( 'Content', 'elementor-artbees-extension' ),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'button_text',
            [
                'label' => __( 'Text', 'elementor-artbees-extension' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'input_type' => 'text',
                'default' => __( 'Click here', 'elementor-artbees-extension' ),
                'placeholder' => __( 'Enter button text here', 'elementor-artbees-extension' ),
            ]
        );

        $this->add_control(
            'download_file',
            [
                // 'label' => __( 'Download File', 'elementor-artbees-extension' ),
                'type' => 'fileupload',
            ]
        );
    }

    protected function render() {
        $settings = $this->get_settings_for_display();

        echo '
';

        echo $settings['button_text'] . '
';
        echo $settings['download_file'];

        echo '
';
    }

    protected function _content_template() {}

}

JS (file-upload.js)
(function($) {
    $(document).ready(function() {
        var notice = $('.eae-form-notice');
        var form = $('form[name=eae-file-upload-form]');
        var file = form.find('input[name=eae-file]');

        file.live('change', function(e) {
            e.preventDefault();

            var formData = new FormData();

            formData.append('action', 'upload-attachment');
            formData.append('async-upload', e.target.files[0]);
            formData.append('name', e.target.files[0].name);
            formData.append('_wpnonce', su_config.nonce);

            $.ajax({
                url: su_config.upload_url,
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                type: 'POST',
                beforeSend: function() {
                    file.hide();
                    notice.html('Uploading…');
                },
                success: function(resp) {
                    // console.log(resp.data.url);
                    $('input[name=eae-file-link]').val(resp.data.url);
                }
            });
        });
    });
})(jQuery);

A: The issue here is not about getting the value — $settings['download_file'] (in PHP) would give you that value, if any.
What you're really looking for, is to make Elementor aware of the file input changes, so that the new value will be saved by Elementor.
And the trick is, trigger the input event on the file input after the file has been successfully uploaded:

*

*In file-upload.js, find this:
$('input[name=eae-file-link]').val(resp.data.url);

*And change it to:
$('input[name=eae-file-link]').val(resp.data.url).trigger('input');

Reference.


text:
Q: Custom child activity inside another custom activity doesn't persist i have a custom activity which contains other activity inside it to use execution property like this :
public sealed  class GlobalContainerActivity:NativeActivity
{

[RequiredArgument]
 public InArgument<WfParam> WfparamInArg { get; set; }
        /// <summary>
    ///   Gets or sets Body.
    /// </summary>
    [DefaultValue(null)]
    public Activity Body { get; set; }

    protected override void Execute(NativeActivityContext context)
    {
        var generalargument = context.GetValue(WfparamInArg);
        context.Properties.Add(GlobalWfparam.Name, new GlobalWfparam(generalargument));

        if (Body != null)
        {
            context.ScheduleActivity(Body);
        }
    }

and i have a child custom activity which persist the workflow for human interact  like this:
 public  class WaitActivity :NativeActivity
{
   public string BookmarkName { get; set; }

   public OutArgument<WfBookmark> WfBookmark { get; set; }

    protected override void Execute(NativeActivityContext context)
    {
        try
        {
            BookmarkName = "ResumeFlow";
            context.CreateBookmark(BookmarkName, Continue);
        }
        catch (Exception)
        {

            throw;
        }

    }
    private void Continue(NativeActivityContext context, Bookmark bookmark, object value)
    {
        WfBookmark wfBookmarkParam = (WfBookmark)value;
        WfBookmark.Set(context, wfBookmarkParam);

       }
    protected override bool CanInduceIdle
    {
        get
        {
            return true;
        }
    }
}

and after finishing this class work flow stop without any error but after that i want to resume the workflow i have error that mention the InstanceStore Id is not persist and doesn't resume the flow

A: I Found That There is some think Called No Persistent Area And I use it in Wrong way So I Re commend  Not TO use it When Ever you want To Persist WorkFlow


text:
Q: Finding certain digits of constructible irrational numbers. Let $n\neq m^q$ and $round(\sqrt[q]{n})=m$ for some $\{m,n,q\}\in\mathbb{N}$. Then, is there any way to find the $n^r$th digit of $\sqrt[q]{n}$, for $r\in\mathbb{N}$? I once saw something about someone claiming to know the $2^{2020}$th digit of $\sqrt2$, so I'm curious now. However, I myself have no idea how to ever find the digit.

A: You can find a method for calculating every digit of $\sqrt[q]{n}$ at this link:
https://en.wikipedia.org/wiki/Nth_root#Computing_principal_roots


text:
Q: SQL query to find highest GPA I am currently taking a Stanford online MOOC course on SQL. I have a question in regards to an SQL query. I have three tables: Student, Apply, and College. Student has student ID (sID) and GPA (GPA). Apply has the college name (cName) and Student ID. College has the college name (cName) and state the college is in (state). This is the query the teacher is using:
Select distinct College.cName, state, GPA
From College, Apply, Student
Where College.cName = Apply.cName
And Apply.sID = Student.sID
And GPA >= all (select GPA from Student, Apply
Where Student.sID = Apply.sID
And Apply.cName = College.cName)

I don't understand why we need Student.sID=Apply.sID and Apply.cName=College.cName. I know it makes sure they match up, but why is this necessary?

A: Your professor is using old style joins which are hard to undestand here is it written in new style joins
Select distinct College.cName, state, GPA
From Student
JOIN College on College.cName = Apply.cName
JOIN Apply on Apply.sID = Student.sID
WHERE GPA >= all (
  select GPA
  from Student
  JOIN Apply ON Student.sID = Apply.sID AND Apply.cName = College.cName
)

Old style joins were old in the 90s.  Your teacher is living in the past.
Of course this example is horrible for teaching anything in general but even worse if students don't even understand simple joins yet.
I'm sorry.

side note -- if your question is does the order matter in Student.sID = Apply.sID AND Apply.cName = College.cName -- The answer is no.  In a compare like this it is the same as Apply.sID = Student.sID AND College.cName = Apply.cName

A: This is to find all matching rows in the Apply table that student has applied to a college and find all the college names that student has applied to from college table. Also let me correct you Student, Apply and College are not databases here. They are tables of your database. Hope that makes sense.

A: The line: From College, Apply, Student
is an implicit join. The were Student.sID=Appply.sID and Apply.cName=College.cName lines are to tell the query how to match the tables together.
If no restrictions are given, it will take each item on the table College, duplicate it for the number of rows in Apply and have amend each row of apply to every row of College (cross multiply). Then duplicate the newly created table 'College joined to Apply' for each item on the table Student and apply each item on the table Student to each of the duplicated rows.


text:
Q: How to find if the network path is available or not How to find if the directory is available or not?
Using VB 6.0
databasetext = network path available
If Len(Dir(databasetext)) = False Then
MsgBox "Database Path Not Available"
End if

I am selecting the file from the network path, if the network path is not available, it showing error "bad file name or number"
How to solve this problem?
Need VB 6 code Help

A: I use PathIsDirectory from Shlwapi.dll. Here is some VB6 code:
Private Declare Function PathIsDirectory Lib "Shlwapi" _
    Alias "PathIsDirectoryW" (ByVal lpszPath As Long) As Long

Function DirExists(ByVal sDirName As String) As Boolean
  'NB The shlwapi.dll is built into Windows 2000 and 98 and later:  '
  '   it comes withInternet Explorer 4 on NT 4 and 95. '
  'NB Calling "Wide" (Unicode) version. Always available. '
  DirExists = (PathIsDirectory(StrPtr(Trim$(sDirName))) <> 0)
End Function

EDIT: You can also use FileSystemObject, but I prefer to avoid the Microsoft Scripting Runtime (including FileSystemObject). In my experience it's occasionally broken on user machines, perhaps because their IT department are paranoid about viruses.

A: From my stock library. I think I included all the declarations needed.

Private Declare Function FindClose Lib "Kernel32" (ByVal hFindFile As Long) As Long
Private Declare Function FindFirstFile Lib "Kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long

Private Const INVALID_HANDLE_VALUE = -1
Private Const MAX_PATH = 260

Private Type FILETIME
   dwLowDateTime As Long
   dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
   dwFileAttributes As Long
   ftCreationTime As FILETIME
   ftLastAccessTime As FILETIME
   ftLastWriteTime As FILETIME
   nFileSizeHigh As Long
   nFileSizeLow As Long
   dwReserved0 As Long
   dwReserved1 As Long
   cFileName As String * MAX_PATH
   cAlternate As String * 14
End Type

Public Function FolderExists(ByVal FolderSpec As String) As Boolean
   Dim rst As Long
   Dim udtW32FindD As WIN32_FIND_DATA
   Dim lngFHandle As Long
   Dim strFolder As String 'set to FolderSpec parameter so I can change it

   strFolder = FolderSpec
   If Right$(strFolder, 1) <> "\" Then
      strFolder = strFolder & "\"
   End If
   strFolder = strFolder & "*"   'add the wildcard allows finding share roots

   lngFHandle = FindFirstFile(strFolder, udtW32FindD)
   If lngFHandle  INVALID_HANDLE_VALUE Then
      Call FindClose(lngFHandle)
      FolderExists = True
   End If

End Function


text:
Q: Scrolling is not smooth in android Grid View In my android application, I am loading the images from the API's. but after the images are loaded in the Grid View, the scrolling is not smooth. I am using Asynchronous threads to fetch the images so that it does not block the UI.
Any suggestions now to improve the performance of scrolling.

A: Loading images in separate thread definitely helps, however there's another important performance issue to take care of here, and that's "view reusability", once you've set the image in your Adapter, make sure that you are actually reusing the views provided in the getView method of the adapter, and not creating/inflating a new Layout(GridElement) every time that method is called, this is usually what causes the scrolling to go slow once all the images have been loaded, there's several patterns available to approach this issue, you should read about ViewHolder, is the most common and easy to use pattern for this issue...
Hope this Helps...
Regards

A: Code for getView() method
{{{
@Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                final HashMap<String, String> song = songsList.get(position);
                imageURL = song.get(VariablesList.TAG_ALBUM_IMAGE);
                View v = null;
                if (convertView != null)
                        v = convertView;
                else
                        v = inflater.inflate(R.layout.gridlayout_item, parent, false);
                final ImageView imageView = (ImageView) v.findViewById(R.id.icon_image);
                final Thread startAlbum = new Thread() {
                        public void run() {

                                imageView.setImageBitmap(AlbumList
                                                .LoadImagetoGridView(imageURL));

                                synchronized (this) {
                                        this.notifyAll();
                                }
                        }
                };

                synchronized (startAlbum) {
                        startAlbum.start();
                        try {
                                startAlbum.wait();
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                        // @Override
                        public void onClick(View v) {
                                albumUrl = new StringBuffer(resources.getString(R.string.songsListURL));
                                String albumIndex = song.get("id");
                                albumName = (song.get("name"));
                                imageURL = song.get(VariablesList.TAG_ALBUM_IMAGE);
                                SongsList albumList = new SongsList(imageURL, albumUrl,
                                                albumName,albumIndex,resources);
                                Thread threadAlbumList = new Thread(albumList);
                                threadAlbumList.start();

                                synchronized (albumList) {
                                        try {
                                                albumList.wait();
                                        } catch (InterruptedException e) {
                                                e.printStackTrace();
                                        }
                                }
                                if (!NewMediaPlayer.mediaPlayer.isPlaying()) {
                                        HashMap<String, String> playingSong = NewMediaPlayer.selectedSongs
                                                        .get(0);
                                        if (playingSong != null) {
                                                String url = playingSong.get("songUrl");
                                                String songName = playingSong.get("songName");
                                                if (songName != null)
                                                        {
                                                         NewMediaPlayer.songTitleLabel.setText(albumName
                                                                        + " - " + songName);
                                                         NewMediaPlayer.songTitle.setText(albumName+"-"+songName);
                                                        }
                                                NewMediaPlayer.playSong(url);
                                        }
                                }
                        }
                });

                TextView itemAlbumName = (TextView) v.findViewById(R.id.icon_text);
                itemAlbumName.setText(song.get("name"));
                itemAlbumName.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                                HashMap<String, String> song = songsList.get(position);
                                String songIndex = song.get("id");
                                String albumName = (song.get("name"));
                                Intent in = new Intent(context, SongListActivity.class);
                                in.putExtra("albumIndex", songIndex);
                                in.putExtra("albumName", albumName);
                                in.putExtra("AlbumImage", song.get(VariablesList.TAG_ALBUM_IMAGE));
                                context.startActivity(in);
                        }
                });

                return v;
        }

}}}

A: Instead of taking efforts Use Universal Image loader library.And its performance is good.
In onCreate method
  gridView.setAdapter(new ImageAdapter(this,ImagesArrayPath));
    private static class ImageAdapter extends BaseAdapter {
    private  final String[] IMAGE_URLS ;

    private LayoutInflater inflater;

    private DisplayImageOptions options;

    ImageAdapter(Context context,String source[]) {
        inflater = LayoutInflater.from(context);
        IMAGE_URLS=source;

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ico_place_holder)
                .showImageForEmptyUri(R.drawable.ic_empty)
                .showImageOnFail(R.drawable.ic_error)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public int getCount() {
        return IMAGE_URLS.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        View view = convertView;
        if (view == null) {
            view = inflater.inflate(R.layout.item_grid_image, parent, false);
            holder = new ViewHolder();
            assert view != null;
            holder.imageView = (ImageView) view.findViewById(R.id.image);
            holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        ImageLoader.getInstance()
                .displayImage(IMAGE_URLS[position], holder.imageView, options, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        holder.progressBar.setProgress(0);
                        holder.progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        holder.progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        holder.progressBar.setVisibility(View.GONE);
                    }
                }, new ImageLoadingProgressListener() {
                    @Override
                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
                        holder.progressBar.setProgress(Math.round(100.0f * current / total));
                    }
                });

        return view;
    }
}

static class ViewHolder {
    ImageView imageView;
    ProgressBar progressBar;
}

May this will help you. Enjoy Coding.


text:
Q: Getting TypeError: Cannot read property 'map' of undefined I am using react with material-UI every thing working fine but getting error TypeError: Cannot read property 'map' of undefined . i am also using axio API for getting demo data. I am using react with material-UI every thing working fine but getting error TypeError: Cannot read property 'map' of undefined . i am also using axio API for getting demo data.
import React, { Component } from 'react'
import ApiService from "../../service/ApiService";
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Button from '@material-ui/core/Button';
import CreateIcon from '@material-ui/icons/Create';
import DeleteIcon from '@material-ui/icons/Delete';
import Typography from '@material-ui/core/Typography';

class ListUserComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            users: [],
            message: null
        }
        this.deleteUser = this.deleteUser.bind(this);
        this.editUser = this.editUser.bind(this);
        this.addUser = this.addUser.bind(this);
        this.reloadUserList = this.reloadUserList.bind(this);
    }

    componentDidMount() {
        this.reloadUserList();
    }

    reloadUserList() {
        ApiService.fetchUsers()
            .then((res) => {
                this.setState({users: res.data.result})
            });
    }

    deleteUser(userId) {
        ApiService.deleteUser(userId)
           .then(res => {
               this.setState({message : 'User deleted successfully.'});
               this.setState({users: this.state.users.filter(user => user.id !== userId)});
           })
    }

    editUser(id) {
        window.localStorage.setItem("userId", id);
        this.props.history.push('/edit-user');
    }

    addUser() {
        window.localStorage.removeItem("userId");
        this.props.history.push('/add-user');
    }

    render() {
        return (

                <Typography variant="h4" style={style}>User Details</Typography>
                <Button variant="contained" color="primary" onClick={() => this.addUser()}>
                    Add User
                </Button>

                    <TableHead>
                        <TableRow>
                            <TableCell>Id</TableCell>
                            <TableCell>FirstName</TableCell>
                            <TableCell align="right">LastName</TableCell>
                            <TableCell align="right">UserName</TableCell>
                            <TableCell align="right">Age</TableCell>
                            <TableCell align="right">Salary</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {this.state.users.map(row => (
                            <TableRow key={row.id}>
                                <TableCell component="th" scope="row">
                                    {row.id}
                                </TableCell>
                                <TableCell align="right">{row.firstName}</TableCell>
                                <TableCell align="right">{row.lastName}</TableCell>
                                <TableCell align="right">{row.username}</TableCell>
                                <TableCell align="right">{row.age}</TableCell>
                                <TableCell align="right">{row.salary}</TableCell>
                                <TableCell align="right" onClick={() => this.editUser(row.id)}><CreateIcon /></TableCell>
                                <TableCell align="right" onClick={() => this.deleteUser(row.id)}><DeleteIcon /></TableCell>

                            </TableRow>
                        ))}
                    </TableBody>

        );
    }

}

const style ={
    display: 'flex',
    justifyContent: 'center'
}

export default ListUserComponent;


text:
Q: Open source OCR for Chinese I've searched around for open source OCR for Chinese. But without any luck there rarely seems to be some open source OCR (for Chinese) that are usable.
So I am here wondering:

*

*Is there any open source OCR for Chinese that could be used for production environment?

*What's the main differences when implementing an OCR for Latin-languages and for Chinese? I know some good OCR such as Tesseract or Ocropus, what should I do if I want to make it support Chinese?
Any help is appreciated and thanks in advance~

A: You can choose:

*

*Tesseract 3.0 support chinese/japanese

*NHOCR support japanese

A: Chinese has far more characters than Latin languages. There are some commercial products. One of the ways is to contact them and get help.
I don't think there is an open source for Chinese or Japanese characters. In the area of OCR, there are a lot of techniques beyond the pattern recognition algorithms, where a company is good at, not the open source community.


text:
Q: ".fileprovider" doesn't get recognized I am trying to set up a fileprovider to access images taken with an Intent.
But while trying to define it in the manifest, the name doesn't get recognized.
It is the ..."fileprovider" in the third line that is the problem.
<provider
            android:authorities="androidx.core.content.FileProvider"
            android:name="com.mobila.project.today.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

as I understand the part before .fileprovider should match my package. But its name looks like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.mobila.project.today">

How can i resolve this? Is there a workaround for using a fileprovider where I can save the pictures directly in an ArrayList for example?


text:
Q: Why does user.identity.name can't be called in Model - MVC As User.Identity.Name can be call in View and Controller.
Why does User.Identity.Name can't be called in Model even thought my model has a using System.Web.MVC library?
Anyone please explain this to me?