text:
Q: Replacing substrings in C without using string library functions While this code is hideous and I've clearly solved the problem incorrectly, the code works (for the moment). I want to mess around with it, but I truly don't know what I'm doing wrong here. The goal is to, without using any built in functions, take the string "This is a test" and replace the "te" with "gho" to spell out "This is a ghost".
int main(int argc, const char * argv[]) {

    char *s = "This is a test";
    char *newstring = malloc(strlen(s));

    for (int i = 0 ; s[i] != '\0' ; i++){
        if (s[i] == 't' && s[i+1] == 'e') {
            newstring[i] = 'g';}
        else if (s[i] == 'e' && s[i+1] == 's') {
            newstring[i] = 'h';}
        else if (s[i] == 's' && s[i+1] == 't') {
            newstring[i] = 'o';
        }
        else if (s[i] == 't') {
            newstring[i] = 's';
        }
        else {
            newstring[i] = s[i];
        }
        }
    printf("%st",newstring);

    return 0;
}

My problem is that I don't know how to append characters to a new string in C so that I can maintain the integrity of the original string while just replacing single characters.

A: char *s = "This is a test";
int len = 0;

while(s[len++]);//strlen(s) + 1
for (int i = 0 ; s[i] != '\0' ; i++){
    if (s[i] == 't' && s[i+1] == 'e') {//count "te"
        ++len;
        ++i;
    }
}

char *newstring = malloc(len);
int j = 0;
for (int i = 0 ; s[i] != '\0' ; i++){
    if (s[i] == 't' && s[i+1] == 'e') {
        newstring[j++] = 'g';
        newstring[j++] = 'h';
        newstring[j++] = 'o';
        ++i;
    } else {
        newstring[j++] = s[i];
    }
}
newstring[j] = '\0';
puts(newstring);
free(newstring);

A: We should recognize a pattern in what you want to do. For a start, it's a useful trick to remember that you can fill out a new array like so:
int num = 0;
int buf[256];

buf[num++] = 123;
buf[num++] = 456;
buf[num++] = 789;

This is a shorthand. The line:
buf[num++] = 123;

Provides equivalent behavior to:
buf[num] = 123;
++num;

So what do we want to do here? We want to make a new string which is the same as the original except that it replaces "te" with "gho". So how about this?
#include <stdio.h>

int main(int argc, const char * argv[])
{
    const char *s = "This is a test";
    int i = 0;
    int new_len = 0;

    // We don't know what the final size of the string will be, so
    // let's make one that's generally large enough. Can do more
    // elaborate things here if you want a really robust solution.
    char new_string[256] = {0};

    // For each character in the string:
    for (i=0; s[i] != '\0'; ++i)
    {
        if (s[i] == 't' && s[i+1] == 'e')
        {
            // If we find "te", add "gho".
            new_string[new_len++] = 'g';
            new_string[new_len++] = 'h';
            new_string[new_len++] = 'o';

            // ... and skip one character to ignore both the 't' and the 'e'.
            ++i;
        }
        else
        {
            // Otherwise just add the same character.
            new_string[new_len++] = s[i];
        }
    }

    // Add the null terminator at the end of our new string.
    new_string[new_len] = '\0';

    // Output the new string.
    printf("%s\n", new_string);
}

A: int myStrLen( char * );

int myStrlen( char *testStr )
{
    int rtnCount;

    for( rtnCount = 0; testStr[rtnCount]; rtnCount++ ) {;}

    return( rtnCount );
} // end function: myStrlen

other string functions can be implemented in a similar manner.
then the 'home grown' string functions could be used similar to this:
// get length of original string
int oldStringLen = myStrLen( s );

// provide room on the stack for the new string
char newString[oldStringLen+2] = {'\0'};

// search for occurrence of string to be replaced
char * targetString = myStrStr( s, "test" );
if( NULL == targetString )
{ // then target string not found
    // handle error??
    return( -1 );
}

// implied else, target string found in 's'

// copy first part of original string
myStrNCpy( newString, s, (targetString - s) +1 );

// append the replacement string
myStrCat( newString, "ghost" );

// append remainder of original string
myStrCat( newString, &targetString[4] );

does the code need to keep looking in the original string
for other possible replacements?
of course, how to display the result to the user
may be 'interesting' since C has no ability to perform any I/O
without using something like the stdio.h library


text:
Q: All ways to partition a string recursively with a minimum length I stumbled upon this neat recursive function.
static ArrayList<ArrayList<String>> recursive(String str) {
    System.out.println(str);
    ArrayList<ArrayList<String>> result = new ArrayList<>();

    if (str.length() == 1) {
        result.add(new ArrayList<>());
        result.get(0).add(str);
        return result;
    }

    for (ArrayList<String> list : recursive(str.substring(1, str.length()))) {
        ArrayList<String> append = new ArrayList<>(list);
        String aps = str.substring(0, 1) + append.get(0);

        append.set(0, aps);
        ArrayList<String> add = new ArrayList<>(list);
        String ads = str.substring(0, 1);

        add.add(0, ads);
        result.add(append);
        result.add(add);
    }
    return result;
}

It returns if you give it the arg "haus":
[[haus], [h, aus], [ha, us], [h, a, us], [hau, s], [h, au, s], [ha, u, s], [h, a, u, s]]

Now I can't figure out how to implement a minimum length for each part and don't quite get how the function does it.
If I set a minimum length of 2, my desired output is:
[[haus], [aus], [ha, us], [us], [hau], [au]]

Can this be accomplished without looping through the results afterwards? Not creating elements that don't fit the minimum in the first place.

A: Yes, it should be possible. But IMHO your algorithm is hard to understand and modify, for these reasons:

*

*It modifies the content of a list (append.set(0, aps);)

*It concatenates strings, so if you skip processing a 1-length string, you break the iteration.

I was not able to change it, so... I rewrote the algorithm my way:
static List<List<String>> recursive(String str) {
    List<List<String>> list = new ArrayList<>();
    for (int i = 0; i < str.length(); i++) {
        recursive(list, str, i);
    }
    return list;
}

static void recursive(List<List<String>> list, String str, int index) {
    if (index == 0) {
        List<String> stringList = new ArrayList<>();
        addToList(stringList, str);
        list.add(stringList);
        return;
    }

    List<List<String>> newList = recursive(str.substring(index));
    String pref = str.substring(0, index);
    for (List<String> ls : newList) {
        List<String> stringList = new ArrayList<>();
        addToList(stringList, pref);
        addToList(stringList, ls.toArray(new String[ls.size()]));
        if (!stringList.isEmpty()) {
            list.add(stringList);
        }
    }
}

static void addToList(List<String> list, String... strings) {
    Stream.of(strings)
            .filter(s -> s.length() > 1)
            .forEach(list::add);
}

It provides this result for haus:
[[haus], [aus], [us], [au], [ha, us], [hau]] which is the expected one I think.

One last point: filtering out the 1-length strings afterwards can be done like this:
    List<List<String>> outputList = recursive("haus").stream()
            .map(List::stream)
            .map(stringStream -> stringStream.filter(str -> str.length() > 1))
            .map(stringStream -> stringStream.collect(Collectors.toList()))
            .filter(ls -> !ls.isEmpty())
            .collect(Collectors.toList());

redpajama_set_name: RedPajamaStackExchange


text:
Q: proving that a matrix is hermitian or unitarian i am not sure about this question.
given two real matrices  P,Q (nxn) with real componponents(real valued), and U= P+iQ. $D=\begin{pmatrix}P&-Q\\ Q&P\end{pmatrix}$
a)prove that if U is hermitian matrix, then D is symmetrical matrix
b)prove that if U is unitary matrix, then D is orthogonal matrix.
what i did:
i tried to use the properties of a)hermitian matrix(if a given matrix is hermetian and its components are real valued then both terms should be equivalent, since an hermitian matrix is $a^H=a$, so $x^Hax \in R$ for every $x \in C^{nx1}$, so we get that if eigen values of given matrix is in R then a is hermitian ($eig(a) \in R$).
b)if a given matrix is orthogonal, then $a^ta=aa^t=I$. now, since a unitary matrix is unitary iff it applies $a*a=aa*=I$. both terms are close and related to each other, but i don't know how to prove it.
i've tried to put it all together, but i don't know how to show that they apply, i never get to it. i'm stuck on it for quite a while.

A: Part a) is easy:
$$
D^T = \pmatrix{P^T & Q^T\\-Q^T & P^T}, \qquad U^H = P^T - iQ^T
$$
verify that if $U = U^H$, then $D = D^T$.
Part b) is a little trickier.  Note that
$$
U^HU = (P^TP + Q^TQ) + i(P^TQ - Q^TP)
$$
So, if $U$ is unitary, then $P^TP + Q^TQ = I$ and $P^TQ - Q^TP = 0$. Now, using block-matrix multiplication, verify that
$$
D^TD = \pmatrix{P^TP + Q^TQ & P^TQ - Q^TP\\Q^TP - P^TQ & P^TP + Q^TQ}
$$
so that if $U$ is unitary, we have $D^TD = I$ as desired.


text:
Q: Migrating from concrete5 to wordpress I need to convert a concrete5 site to a WordPress site.
I can't find any plugins on both sides. There might be a solution via a feed ex-/import but it does not support all the contents and images.
Is there any idea how to do this?

A: I don't know of any pre-packaged solution for this. If there aren't too many pages (under 50 or 100), your best bet is to do it manually -- hire a temp worker for a day if you're a developer with a non-trivial rate.
If there are hundreds or thousands of pages, though, then you'll want to come up with your own automated solution. You can get some kind of XML representation of site content I believe via the Dashboard "backup site" functionality (not the "backup database" one). Or look into the concept of "Starting Points" in Concrete5 -- there's a free addon in the marketplace that lets you export site content in another XML format.
Then look into wordpress importers, and figure out how to transform the C5 output XML into whatever format your wordpress importer requires.
Best of luck.

A: There's a plugin at the WordPress plugin directory for an automated migration. It supports to migrate posts, attachments (images and videos), content images and list of other things, so it might answer your request.
The quick guide to the process includes following steps -

*

*You install the plugin on your WP website

*Create the account at the service

*Download the bridge folder and connect to your concrete5 website via FTP

*Choose the entities you want to migrate

*Try the demo migration (it migrates up to 10 posts)

*If you like it you can try the full migration (it's not free)

You may refer this for more info & this service is also represented in WordPress Codex.
Hope it helps.


text:
Q: Words invented or redefined by one person What do you call a word that was invented or redefined by someone, but only used by that one person?
I think "neologism" is the general case, but I am not sure if there's a word for a neologism that's specifically used by only one person, or rarely used by anyone else. Is there any related word?
For example:

This philosopher uses a lot of _____, which makes him impossible to
  understand.

A: The term jargon refers to special words used by a group or a profession.  It wouldn't make sense if your philosopher was talking to other philosophers, but otherwise it works well in your sample sentence.
Sniglet is too obscure and refers to deliberately constructed joke words (e.g. luposlipophobia, fear of being chased by wolves while wearing socks on a slippery floor).
If you say he coined a term or used a neologism, both imply he created a term that became generally used, which is not the case here.
To emphasize that these words are invented by and known only to the philosopher, I would call them nonsense words or non-words or just made-up words.

A: One term you could use is sniglet, but you should know that sniglet is a sniglet in its own right.
The term sniglet might go unrecognized by people who are not familiar with the pop-culture reference. Originally, most sniglets were designed to be more humorous than functional, but I've heard the word sniglet used on occasion. It was used in this 2011 blog post, for example, and was also apparently used in a New York Times crossword puzzle last year.
For the record, I think your suggestion of neologism would work better in a lot of contexts (particularly more formal ones). Nevertheless, sniglet is a viable informal term that could be used. (I almost didn't even leave it as an answer, but opted to do so when I found the Wikipedia article about sniglets.)

A: These are sometimes called "nonce word".  It comes from the (old, rare) expression "for the nonce" meaning "for now but not for later".  It applies to words that seem to have been used only by a single author, and often only used once by that author.
Such words are also called "nonces".  The term has been in use since before 1910. It was coined by the editor of the OED (who had to understand and define nonce words in old texts)
Note that "nonce" words are not "nonsense words"  The meaning and etymology are different.  A nonsense word may, or may not be a nonce.


text:
Q: ASP.NET MVC 4 Action on AJAX Request Is there a way to call a javascript function every time an AJAX request is sent, and then another when the call is finished? I know you can do it individually for each form with the OnBegin and OnComplete functions, but I want a universal one.
Specifically, I would like the wait cursor to show every time it sends an ajax call, and then go back to the default cursor when done.
With webforms you could do
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

but I need something for MVC 4.
Any suggestions on how to accomplish this task would be appreciated, or alternatives if it's just a bad idea.

A: Tr this global ajax event handlers


text:
Q: Hadoop MAC OS installation woes So I'm trying to install hadoop on MAC OS X Leopard following the steps in this note: Running Hadoop on a OS X Single Node Cluster.
I reached Step 4: Formatting and running Hadoop, where I entered the following:
hadoop-*/bin/hadoop namenode -format

This produced the following unpleasant output:

Macbook009:~ Hadoop$ hadoop-*/bin/hadoop namenode -format
    Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:317)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:317)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)

I did some googling, and learned that JAVA_HOME may be set incorrectly. I created a .bash_profile file like this:
export JAVA_HOME=/system/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
export HADOOP_HOME=~/Users/Hadoop/hadoop-0.20.203.0

export PATH=$HADOOP_HOME/bin:$PATH

No go. Same freaking error.
What am I doing wrong?

A: I suspect that the JVM that's actually running Hadoop is not the expected one, but an older one (Java 5). Verify this by running ps (or any Mac equivalent) and examining the command line.
Try to set JAVA_HOME in $HADOOP_HOME/conf/hadoop-env.sh to the same path as you did in your .bash_profile.

A: It may still be a problem with setting your JAVA_HOME as it could be different from examples on the web. Use this command in your terminal to find your JAVA_HOME directory /usr/libexec/java_home

A: This is caused when the jre you are running is older than the jre that compiled the class files. For example running 1.6 compiled java with the 1.5 jre.  If the class was compiled just for 1.6 it will not work with 1.5.
Do a
  java -version

and see which jre you have.  Most likely you have an old one and need to upgrade it.

A: Try typing jps and seeing how many nodes are actually running .
There should be 6 of them . You shouldn't have a problem hopefully .

A: Following steps worked seamlessly for me:
http://ragrawal.wordpress.com/2012/04/28/installing-hadoop-on-mac-osx-lion
For wordcount example, you need to copy your file to hdfs, for which you can find the command here: (this is the only step where I struggled after following the above page).
http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/#running-a-mapreduce-job

A: However for newer versions of OS X like 10.9 setting PATH described above is not working.
Found a way where you can add default PATH environment for MAC in file /etc/paths.
Open this file using Terminal in SUDO mode.
$ sudo nano /etc/paths (enter password when prompted).
Append the path in below format.
/users/hadoop/hadoop-1.2.1/bin
/users/hadoop/hadoop-1.2.1/sbin
save the file and restart the Machine. Next time no need to type whole command to run Hadoop script command from Script.


text:
Q: Viewport Confusion When You Want IPad To Display Desktop Site And Then Use Media Queries For Smaller Mobile Devices I have read a great deal about viewport tags and understand the principles of them however I do still have some confusion over how to best use them in certain situations such as this.
So currently I am working on a site where there is a container div that is set to a width of 1024px.  To make this work on the IPad I set the following viewport tag:
<meta name="viewport" content="width=1024" />

All good so far.  Rotation works fine.
I then have a number of media queries to target mobile devices with a smaller screen.  I understand that the IPad is considered a mobile device.  So the site looks as I would expect BUT the viewport has to be set to:
<meta name="viewport" content="initial-scale=1">

So the two can't be combined so I would like to know how to solve this issue or what I am doing wrong?
Can you have a different viewport tag based on device width?
All time and help is greatly appreciated.

A: In conjunction with the Twitter Bootstrap framework, I'm using this so that on all tablets we see the desktop version but on all mobile phones we see the mobile version.
<meta name="viewport" content="width=device-width, user-scalable=false, initial-scale=1.0;">

Another one I had issues with were Windows Phones. They seemed to do the reverse before I had this meta tag, and show the desktop version instead of the mobile version!


text:
Q: MongoDB Fails due to permission error even though its setup Attempting to start my MongoDB server using service mongod start fails for the reason: exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /var/lib/mongo/, terminating
I've setup the permissions to the directories it needs using chown mongod:mongod -R /var/lib/mongo/ and also ran chmod 775 -R /var/lib/mongo
Even though I can see that the group and permissions are setup for the directory /var/lib/mongo its still saying the folder is read-only?
Have I missed something in my setup? I'll attach the ls -ld output of my mongo data folder.
drwxrwxr-x. 5 mongod mongod 8192 May 29 15:35 /var/lib/mongo


text:
Q: Insert using a Sequence as generator for a Primary Key value in Entity Framework I have a sequence that looks like this:
CREATE SEQUENCE dbo.NextWidgetId
 AS [bigint]
 START WITH 100
 INCREMENT BY 2
 NO CACHE
GO

And a table that looks like this:
CREATE TABLE [dbo].[Widget_Sequenced]
(
    [WidgetId] [int] NOT NULL DEFAULT(NEXT VALUE FOR dbo.NextWidgetId),
    [WidgetCost] [money] NOT NULL,
    [WidgetName] [varchar](50) NOT NULL,
    [WidgetCode] [int] NOT NULL,
    [LastChangedBy] [int] NOT NULL,
    [RowVersionId] [timestamp] NOT NULL,

    CONSTRAINT [PK_Widget_Sequenced]
    PRIMARY KEY CLUSTERED ([WidgetId] ASC) ON [PRIMARY]
) ON [PRIMARY]

Is there a way to add a new record to this table structure using Entity Framework?
I tried setting StoreGeneratedPattern for WidgetId to computed and I tried it with Identity. Both gave me errors.
I tried this with EF 5. But I could move to EF 6 if it fixes this.

A: It's possible from version 6.2, using this code:
System.Data.Entity.SqlServer.SqlProviderServices.UseScopeIdentity = false;
More information on EF6 does not work with primary key from sequence

A: You can replace your sequence with IDENTITY(100, 2) and everything will work out of the box.


text:
Q: How can I get random row from array python I have a np.ndarray of length 398 and this is my train set, X_train.
I am trying to make 10 different train sets,
X_train1
X_train2
X_train3

so on and so forth, by getting random rows from array X_train, all of equal length 40.
How can I do this?

A: Sample the data set over 10 iterations, and save the sample in a dictionary object with the name you want.
import numpy as np

data = {}
for i in range(10):
    name = 'X_train' + str(i+1)
    data[name] = np.random.choice(X_train, 40)

A: I think you have one of the below problem.
Problem 1 :- you have 2D array and wants to have few small X_trains out of it. check below code and output for this.
CODE
import numpy as np
X_train = np.random.randint(5, size=(10,3)) #### here you'll have your 2D array

count=1
X_train_change={}

number_of_xtrain=5 ### number of chunk of X_train
for i in range(number_of_xtrain):
    shp=np.random.randint(np.size(A,0))
    #print(A[shp,:])
    X_train_change['X_Train%s'%count]=A[shp,:]
    count+=1

print(X_train_change)

Output
{'X_Train1': array([4, 1, 4]), 'X_Train2': array([3, 1, 1]), 'X_Train3': array([3, 1, 1]), 'X_Train4': array([4, 1, 4]), 'X_Train5': array([3, 4, 2])}

Problem 2 :- you have 1D array like this [1,2,3,4,5,6,7,8,9,10] and you want to have small xtrains like this X_Train1=[1,2,3,4,] , X_train2=[5,6,7,8,9,10]. check below code for this.
CODE
import numpy as np
X_train = np.random.randint(5, size=(400)) ### make sure to have size which can be splitted in number columns (length should be directly divided by number of columns you want)
print(X_train)
print(X_train.reshape(-1,40))

Output
    [[4 3 1 2 1 3 3 3 0 3 1 1 0 3 4 4 3 4 3 0 2 1 2 1 1 1 0 4 4 4 0 0 1 4 4 1
  1 1 1 4]
 [4 1 1 0 1 2 2 0 2 3 0 3 4 2 0 4 2 3 1 4 4 4 2 0 1 3 1 3 2 1 4 2 2 2 3 3
  1 1 4 4]
 [1 3 0 0 0 2 0 4 0 0 2 1 3 3 2 4 0 1 0 0 3 2 1 4 4 1 4 1 3 2 2 0 2 4 0 2
  3 4 4 4]
 [0 3 1 2 0 1 0 0 0 1 0 2 4 3 1 2 2 3 4 0 3 4 4 2 4 1 2 0 4 4 2 3 2 2 2 2
  4 0 3 3]
 [0 1 4 3 1 2 3 1 4 0 0 3 4 4 2 2 0 0 0 1 3 2 4 4 0 2 3 1 0 0 1 3 4 4 3 1
  1 0 0 2]
 [4 2 1 2 3 1 1 3 2 1 1 2 3 3 2 0 1 0 1 3 0 1 2 3 1 3 3 1 2 4 2 1 4 2 1 3
  3 4 3 4]
 [4 3 4 1 1 0 4 1 4 2 0 4 3 1 2 4 0 1 3 3 2 1 3 0 4 3 1 1 1 3 2 1 4 0 2 0
  0 4 3 2]
 [0 1 0 4 2 4 1 1 4 0 1 2 4 1 4 1 2 3 4 4 4 2 1 3 2 3 1 4 4 4 2 2 0 4 1 0
  0 0 4 2]
 [0 0 2 4 4 4 2 4 4 1 1 1 2 0 1 1 4 1 0 0 3 0 4 3 1 3 4 2 0 4 4 3 1 0 4 1
  0 3 0 1]
 [2 1 4 4 2 2 1 1 4 0 1 1 2 1 1 1 0 4 0 4 1 4 4 0 4 3 4 2 4 4 1 1 2 0 3 2
  3 2 1 1]]


text:
Q: ASP.NET Core 2 Controller PUT method failing with Concurrency Core I have an ASP.NET Core 2.0 Site that has a scaffolded controller built directly from a simple model and simple context.  I seeded the data by simply checking for the number of records in the GET method and if 0, then I added 100 records.  GET is retrieving records as I would expect repeatedly.
I'm using the inmemory database provider.
services.AddDbContext<MyDbContext>
            (opt => opt.UseInMemoryDatabase("CodeCampInMemoryDb"));

When I do a PUT with a record that I know existed in my GET, I get a concurrency error as shown at the bottom of this post.  I've not used this method of changing the EntityState of a record I created myself, so I'm not sure how this was suppose to work in the first place, but clearly now it is not working.
Maybe it has something to do with a transaction being processed on the inmemory database? I'm not sure how to avoid that if that is the problem.
// PUT: api/Sessions/5
[HttpPut("{id}")]
public async Task<IActionResult> PutSessionRec([FromRoute] int id, [FromBody] SessionRec sessionRec)
{
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != sessionRec.Id)
        {
            return BadRequest();
        }

        _context.Entry(sessionRec).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException xx)
        {
            if (!SessionRecExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
}

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Attempted to update or delete an entity that does not exist in the store.
   at Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTable`1.Update(IUpdateEntry entry)
   at Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryStore.ExecuteTransaction

A: If you marked a property as a Timestamp and don't provide it, you will get this exception every time.  You either need to load the entity with the latest Timestamp and update that (not ideal) or you have to send the Timestamp down to the client and have the client send it back up (correct way).  However, if you are using an older version of JSON serialization, you have to convert the byte[] to base 64 and then convert it back.


text:
Q: Unit testing real-time / concurrent software
Possible Duplicate:
How should I unit test threaded code?

The classical unit testing is basically just putting x in and expecting y out, and automating that process. So it's good for testing anything that doesn't involve time. But then, most of the nontrivial bugs I've come across have had something to do with timing. Threads corrupt each others' data, or cause deadlocks. Nondeterministic behavior happens – in one run out of million. Hard stuff.
Is there anything useful out there for "unit testing" parts of multithreaded, concurrent systems? How do such tests work? Isn't it necessary to run the subject of such test for a long time and vary the environment in some clever manner, to become reasonably confident that it works correctly?

A: If you can run your tests under Linux, valgrind includes a tool called helgrind which purports to detect race conditions and potential deadlocks in programs that use pthreads; you might get some benefit from running your multithreaded code under that, since it will report potential errors even if they didn't actually occur in that particular test run.

A: I have never heard of anything that can.
I guess if someone was to design one, it would have to have exact control over the execution of the threads and execute all possible combinations of stepping of the threads.
Sounds like a major task, not to mention the mathematical combinations for non-trivial sized threads when there are a handful or more of them...
Although, a quick search of stackoverflow... Unit testing a multithreaded application?

A: If the tested system is simple enough you could control the concurrency quite well by blocking operations in external mockup systems. This blocking can be done for example by waiting for some other operation to be started. If you can control all external calls this might work quite well by implementing different blocking sequences. I have tried this and it does reveal lock-level bugs quite well if you know possible problematic sequences well. And compared to many other concurrency testing it is quite deterministic. However this approach doesn't detect low level race conditions too well. I usually just go for load testing to find those, but I quess that isn't exactly unit testing.
I have seen these concurrency testing frameworks for .net, I'd assume its only matter of time before someone writes one for Java (hopefully).
And not to forget good old code reading. One of the best ways to find concurrency bugs is to just read through the code once again giving it your full concentration.

A: Most of the work I do these days involves multi-threaded and/or distributed systems.  The majority of bugs involve "happens-before" type errors, where the developer assumes (wrongly) that event A will always happen before event B.  But every 1000000th time the program is run, event B happens first, and this causes unpredictable behavior.
Additionally, there aren't really any good tools to detect timing issues, or even data corruption caused by race conditions.  Tools like Helgrind and drd from the Valgrind toolkit work great for trivial programs, but they are not very useful in diagnosing large, complex systems.  For one thing, they report false positives quite frequently (Helgrind especially).  For another thing, it's difficult to actually detect certain errors while running under Helgrind/drd simply because programs running under Helgrind run almost 1000x slower, and you often need to run a program for quite a long time to even reproduce the race condition.  Additionally, since running under Helgrind totally changes the timing of the program, it may become impossible to reproduce a certain timing issue.  That's the problem with subtle timing issues; they're almost Heisenbergian in the sense that altering a program to detect timing issues may obscure the original issue.
The sad fact is, the human race still isn't adequately prepared to deal with complex, concurrent software.  So unfortunately, there's no easy way to unit-test it.  For distributed systems especially, you should plan your program carefully using Lamport's happens-before diagrams to help you identify the necessary order of events in your program.  But ultimately, you can't really get away from brute-force unit testing with randomly varying inputs.  It also helps to vary the frequency of thread context-switching during your unit-test by, e.g. running another background process which just takes up CPU cycles.  Also, if you have access to a cluster, you can run multiple unit-tests in parallel, which can detect bugs much quicker and save you a lot of time.

A: Perhaps the answer is that you shouldn't. In concurrent systems, there may not always be a single deterministic answer that is correct.
Take the example of people boarding a train and choosing a seat. You are going to end up with different results everytime.

A: Awaitility is a useful framework when you need to deal with asynchronicity in your tests. It allows you to wait until some state somewhere in your system is updated. For example:
await().untilCall( to(myService).myMethod(), equalTo(3) );

or
await().until( fieldIn(myObject).ofType(int.class), greaterThan(1));

It also has Scala and Groovy support.


text:
Q: NSUserDefaults not saving StandardUserDefaults values I have an iOS application developed using Microsoft's Xamarin, which is why some of this code might look different. In any case, here is what I'm trying to do:
In my application, I have a set of default user settings that need to be in every single instance of the application no matter what. This is set using this method:
    public static void SetDefaults()
    {
        var keys = new object[]
        {
            "LastNotificationTime",
            "LastSyncTime",
            "LunchStartTime",
            "LunchEndTime",
            "OnLunchBreak",
            "PunchedIn",
            "PunchTime",
            "ShowDetailPane",
            "NotifyEmergency",
            "RunAtBoot",
            "RowsPerPage",
            "SyncInterval"
        };
        var values = new object[]
        {
            "",
            "",
            "",
            "",
            false,
            false,
            "",
            true,
            true,
            false,
            5,
            60
        };
        var defaults = NSDictionary.FromObjectsAndKeys(values, keys);
        NSUserDefaults.StandardUserDefaults.RegisterDefaults(defaults);
        NSUserDefaults.StandardUserDefaults.Synchronize();
    }

This works great during the initial run of my application. I will deploy on my device from scratch, run the application, and then stop. I will then redeploy the already-installed application. I don't want to wipe out the defaults and set truly-default values every time, so I perform this check before doing so (in this example, Settings.GetPreferences() returns the NSUserDefaults.StandardUserDefaults object):
    if( Settings.GetPreferences().IntForKey("RowsPerPage") == 0 ||
        Settings.GetPreferences().IntForKey("RowsPerPage") == null )
    {
        Settings.SetDefaults();
    }

As you can see above, RowsPerPage is initially set to 5. I am expecting this value, for each run after the subsequent initial installation, to persist as being 5. Or whatever the user chooses, for that matter.
However, the above check always comes out as true, and my SetDefaults() method is called, wiping out any changes the user made to their Defaults during the last run. Does anyone know why this is happening? Am I doing something wrong when setting these defaults? Even after adding the not-recommended, deprecated NSUserDefaults.StandardUserDefaults.Synchronize() method call, the defaults are still reset.

A: Your issue is that RegisterDefaults doesn't do what you think it does:
From the documentation

The contents of the registration domain are not written to disk; you need to call this method each time your application starts.

If you want to establish initial values for your defaults that persist then you will need an individual set operation for each one in your SetDefaults method, rather than using RegisterDefaults


text:
Q: Stuck loading large dataset with GraphDB When I load this DBpedia (2015-10, en, ~1 billion triples ) into GraphDB 9.1.1 the CPU load drops to 0% after around 13M triples and idles henceforth. The process does not terminate until I kill it manually.
The machine has enough disc space and sufficient more RAM than the 512GB assigned via the Xmx CMD option to java.
The file that I tried to load is provided here: https://hobbitdata.informatik.uni-leipzig.de/dbpedia_2015-10_en_wo-comments_c.nt.zst
It can be decompressed with:
zstd -d "dbpedia_2015-10_en_wo-comments_c.nt.zst" -o "dbpedia_2015-10_en_wo-comments_c.nt"

I use the following command to load the data:
java -Xmx512G -cp "$HOME/graphdb/graphdb-free-9.1.1/lib/*" -Dgraphdb.dist=$HOME/graphdb/graphdb-free-9.1.1 -Dgraphdb.home.data=$HOME/dbpedia2015/data/ -Djdk.xml.entityExpansionLimit=0 com.ontotext.graphdb.loadrdf.LoadRDF -f -m parallel -p -c $HOME/graphdb/graphdb-dbpedia2015.ttl $HOME/dbpedia_2015-10_en_wo-comments_c.nt

$HOME/graphdb/graphdb-dbpedia2015.ttl looks like:
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
@prefix rep: <http://www.openrdf.org/config/repository#>.
@prefix sr: <http://www.openrdf.org/config/repository/sail#>.
@prefix sail: <http://www.openrdf.org/config/sail#>.
@prefix owlim: <http://www.ontotext.com/trree/owlim#>.

[] a rep:Repository ;
    rep:repositoryID "dbpedia2015" ;
    rdfs:label "Repository for dataset dbpedia2015" ;
    rep:repositoryImpl [
        rep:repositoryType "graphdb:FreeSailRepository" ;
        sr:sailImpl [
            sail:sailType "graphdb:FreeSail" ;

                        # ruleset to use
                        owlim:ruleset "rdfsplus-optimized" ;

                        # disable context index(because my data do not uses contexts)
                        owlim:enable-context-index "false" ;

                        # indexes to speed up the read queries
                        owlim:enablePredicateList "true" ;
                        owlim:enable-literal-index "true" ;
                        owlim:in-memory-literal-properties "true" ;
        ]
    ].

The log of the output is:
16:11:07.438 [main] INFO  com.ontotext.graphdb.loadrdf.Params - MODE: parallel
16:11:07.439 [main] INFO  com.ontotext.graphdb.loadrdf.Params - STOP ON FIRST ERROR: false
16:11:07.439 [main] INFO  com.ontotext.graphdb.loadrdf.Params - PARTIAL LOAD: true
16:11:07.439 [main] INFO  com.ontotext.graphdb.loadrdf.Params - CONFIG FILE: /home/me/graphdb-dbpedia2015.ttl
16:11:07.444 [main] INFO  com.ontotext.graphdb.loadrdf.LoadRDF - Attaching to location: /home/me/graphdb/dbpedia2015/data
16:11:07.618 [main] INFO  c.o.t.u.l.LimitedObjectCacheFactory - Using LRU cache type: synch
16:11:08.025 [main] WARN  com.ontotext.plugin.literals-index - Rebuilding literals indexes. Starting from id:1
16:11:08.029 [main] WARN  com.ontotext.plugin.literals-index - Complete in 0.004, num entries indexed:0
16:11:08.780 [main] INFO  c.o.rio.parallel.ParallelLoader - Data will be parsed + resolved + loaded.
16:11:08.788 [main] INFO  c.o.rio.parallel.ParallelLoader - Using 128 threads for inference
16:11:09.984 [main] INFO  com.ontotext.graphdb.loadrdf.LoadRDF - Loading file: dbpedia_2015-10_en_wo-comments_c.nt
16:11:09.991 [main] INFO  c.o.rio.parallel.ParallelLoader - Using 128 threads for inference
16:11:19.987 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 2,111,690 stmts. Rate: 211,147 st/s. Statements overall: 2,111,690. Global average rate: 211,000 st/s. Now: Tue Mar 10 16:11:19 UTC 2020. Total memory: 22144M, Free memory: 4890M, Max memory: 524288M.
16:11:30.515 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 3,955,363 stmts. Rate: 192,662 st/s. Statements overall: 3,955,363. Global average rate: 192,596 st/s. Now: Tue Mar 10 16:11:30 UTC 2020. Total memory: 66432M, Free memory: 53925M, Max memory: 524288M.
16:11:40.515 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 6,889,662 stmts. Rate: 225,661 st/s. Statements overall: 6,889,662. Global average rate: 225,609 st/s. Now: Tue Mar 10 16:11:40 UTC 2020. Total memory: 199296M, Free memory: 177241M, Max memory: 524288M.
16:11:51.185 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 9,124,978 stmts. Rate: 221,474 st/s. Statements overall: 9,124,978. Global average rate: 221,437 st/s. Now: Tue Mar 10 16:11:51 UTC 2020. Total memory: 199296M, Free memory: 185106M, Max memory: 524288M.
16:12:02.877 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 11,083,153 stmts. Rate: 209,539 st/s. Statements overall: 11,083,153. Global average rate: 209,511 st/s. Now: Tue Mar 10 16:12:02 UTC 2020. Total memory: 199296M, Free memory: 184331M, Max memory: 524288M.
16:12:15.800 [main] INFO  c.o.rio.parallel.ParallelRDFInserter - Parsed 13,166,352 stmts. Rate: 200,047 st/s. Statements overall: 13,166,352. Global average rate: 200,026 st/s. Now: Tue Mar 10 16:12:15 UTC 2020. Total memory: 329312M, Free memory: 313496M, Max memory: 524288M.

Any idea why it is stuck after around 13M triples?

A: First - assign less Xmx to the process (around 38-42 GB would be enough). The database will need additional memory for the off heap so be sure to not assign all of your memory. If you still cannot load the dataset could you please send the jstack of the process or you can use the Java Flight Records if you use Oracle JDK:
jcmd <pid> VM.unlock_commercial_features
jcmd <pid> JFR.start duration=60s name=production filename=production.jfr settings=profile

Set the duration to a value, which would allow the trace of the execution. You can send the results to support@ontotext.com as it will contain information about your environment.
Another alternative is to use the Preload tool - it's purpose is loading large datasets - http://graphdb.ontotext.com/documentation/enterprise/loading-data-using-preload.html


text:
Q: How can I keep the previous task in my todolist? Previously I create a ticket because I have this error

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference?

I have this error when I wanted to close all applications in my phone to have less memory on it.
I show you all my files before my modification
List.java
public class List extends AppCompatActivity implements ItemDialog.ItemDialogListener, AdapterView.OnItemClickListener {
    private ListView listView ;

    private Button addBtn ;
    private ArrayList<EltList> eltList ;
    private ArrayAdapter<EltList> adapter ;

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

        addBtn = findViewById(R.id.addTask);
        listView = findViewById(R.id.listView);

        eltList = FileHelper.readData(this);
        adapter = new TextAdapter(this,eltList);

        listView.setAdapter(adapter);

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });
        listView.setOnItemClickListener(this);

    }

    public void openDialog(){
        ItemDialog itemDialog = new ItemDialog();
        itemDialog.show(getSupportFragmentManager(),"example dialog");
    }

    @Override
    public void applyText(String newTask, String newDateTimeTask) {
        EltList elt = new EltList(newTask,newDateTimeTask);
        adapter.add(elt);

        FileHelper.writeData(eltList,List.this);
        Toast.makeText(List.this,"Item added",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        eltList.remove(position);
        adapter.notifyDataSetChanged();
        FileHelper.writeData(eltList,this);
        Toast.makeText(this,"Delete",Toast.LENGTH_SHORT).show();
    }
}

TextAdapter.java
public class TextAdapter extends ArrayAdapter<EltList> {

    public TextAdapter(Context context, java.util.List<EltList> eltList){
        super(context,0,eltList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
        }

        ItemList itemList = (ItemList) convertView.getTag();
        if(itemList == null){
            itemList = new ItemList();
            itemList.taskName = convertView.findViewById(R.id.task);
            itemList.taskDate = convertView.findViewById(R.id.task_date) ;

            convertView.setTag(itemList);
        }

        EltList eltList = getItem(position);
        itemList.taskName.setText(eltList.getTaskName());
        itemList.taskDate.setText(eltList.getTaskDate());

        return convertView ;

    }

    private class ItemList{
        public TextView taskName ;
        public TextView taskDate ;
    }
}

FileHelper
public class FileHelper {
    public static final String FILENAME = "file.dat";

    public static void writeData(ArrayList<EltList> items, Context context){
        try{
            FileOutputStream fos = context.openFileOutput(FILENAME,Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(items);
            oos.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }

    }

    public static ArrayList<EltList> readData(Context context){
        ArrayList<EltList> itemList = null ;
        try{
            FileInputStream fis = context.openFileInput(FILENAME);
            ObjectInputStream ois = new ObjectInputStream(fis);
            itemList = (ArrayList<EltList>) ois.readObject();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();

            itemList = new ArrayList<>();
        }
        catch (IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return itemList ;
    }

}

So I modify this
ArrayList<EltList> itemList = null ;

in my FileHelper by
ArrayList<EltList> itemList = new ArrayList<>() ;

It works but if I previously write tasks it removes it.
So I remove keep ArrayList<EltList> itemList = null and I wanted to catch the error with NullPointerException but it doesn't work.
UPDATE
It's not a duplicate I just wanted to explain why all my previous task were clear, my answer is how can I keep my previous task in my list.


text:
Q: ONVIF GetStreamUri returns internal IP Address I am trying to connect to an IP camera using Onvif. This camera is not in my network and has been made available to me through an external IP address. When using the 'GetStreamUri' function I get a RTSP link with the internal IP address of the camera, this will not work. When I replace the IP manually it works just fine.
Does anybody have any other suggestions on how to handle this? Replacing the IP manually works but is not a very nice solution.

A: A camera behind NAT and with RTSP streaming in general cannot be viewed from Internet, because you'll end up with all the classic problems related to NAT and VOIP (voip uses RTSP as well as ONVIF).
But you have a possible solution: configure the camera so that it streams over HTTP. At this point you should get a URI that should be accessible from Internet. In fact, if you invoke GetStreamUri, the camera will still return you an internal IP address, since it does not know that the router is configured for NAT. If you are lucky enough, the URI will be on port 80, thus by replacing the internal IP address with the external IP address of the gateway you should be able get the video.


text:
Q: Create win8.1 boot USB from temp boot environment? Need to create a Win 8.1 boot USB drive.  However don't have any native Win8.1 machines to run MS mediacreationtool.exe from, all Win8.1 environments I have available are virtualised.  Only native OS's we have are Server 2012, WinXP & various Linux.
So question is are there any Win8.1 run from DVD type environments available that I could boot to and run mediacreationtool.exe from there?

A: Answer now found - create bootable USB manually and simply copy files there from the .iso, didn't realise that it was that simple
Would probably be more useful if I explained how:

*

*diskpart

*list disk

*select disk 2 - (USB drive)

*clean create partition

*primary select partition 1

*active

*format fs=ntfs

*exit

*XCopy {path to mounted .iso}*.* {drive letter of USB stick} /s/v


text:
Q: server could not be accessed from a different network I have created a simple http server that sends the client a response in the form of a time stamp. I have performed a port forwarding so the server could be reached through the internet.
I have tested the server using a web browser, using the local host and the ip address and it worked, on several computers.
However when i tried to connect to the server from a computer that is connected to a different network it could not be reached.
What is causing it? how can it be fixed?
Here is my code:
public class SimpleServer {

public static void main(String[] args) throws Exception {
  HttpServer server = HttpServer.create(new InetSocketAddress(8008), 0);
  server.createContext("/timestamp", new timeHandler());
  server.setExecutor(null);
  server.start();
}

static class timeHandler implements HttpHandler {
public void handle(HttpExchange t){
    if (t.getRequestMethod().contains("GET")){
        LocalDateTime ldt = LocalDateTime.now();
        try {
            String response = ldt.toString;
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        } catch (IOException ex) {System.out.println(ex);}
    }
 }
}
}

Is there any specific configuration in the code that i am missing?
thank you for your help.


text:
Q: Lemma 1.30 in Evan Chen's EGMO book
Page-15, Lemma 1.30: Points $A,B,C$ lie on a circle with center $O$. Show that $\measuredangle OAC= 90 - \measuredangle CBA$

Here we $\measuredangle CBA$ means the directed angle. I've seen this post and linked already but I think neither has solutions in the way which was intended by the hint for the question.
I think so I got the idea how to solve it, but I'd like my solution be checked because this is one of my first times working with directed angles. Here goes:
Proof:
Begin by constructing the reflection of $A$ about $O$, call it $A'$. Notice that $\triangle  ACA'$ is right angled at $C$, hence:
$$ 90 +\measuredangle A_o A C + \measuredangle CA_o A=0$$
And by the inscribed angle theorem, I note that $ \measuredangle CBA = \measuredangle CA_o A$ and also $\measuredangle A_o A C= \measuredangle OAC$, upon substituting, I get:
$$ \measuredangle OAC  + \measuredangle CBA = 90$$
Is my solution well written? How could I make it better?
Here is a drawing I used for 'thinking' about the set up(slight error , reflected should be $A'$ not $A_o$):

And for $B$ on other side:

Turns out that exact same argument as said for the other case applies here (if the first proof was valid).

Note: Acc. to Evan chen's book sum of directed angle is zero,

page-12

A: Here is an alternative approach -

Say $\angle ABC = \theta \ $. By inscribed angle theorem,
$\angle AOC = 2 \angle ABC = 2 \theta$.
As $OA = OC$, $\triangle AOC$ is isosceles triangle. So,
$\angle OAC = \angle OCA = \dfrac{180^0-2\theta}{2} = 90^0 - \theta$


text:
Q: html start tag missing greater-than char Working my way through this tutorial node-express-mongo primer
At one point is the following tag

<a href="superhero/{{superhero.id}}"{{superhero.name}}

There is no "closing" greater-than char for the anchor's start tag.
But it works as intended.
Now I can adjust the above to create an identical looking link, but with a complete start tag:

{{superhero.name}}

However I'm new at web design and feel like I'm missing some rules somewhere. Is this common practice and where would I find this kind of information? To me it feels awkard not seeing the tag completed.
Or maybe the browser is just forgiving and this is not a common practice?
Thanks in advance!

A: As there is no ending bracket for the tag, the  after it ends the starting tag. You get a starting tag without an ending tag.
The browser then figures out that the anchor tag has to end before closing the list item tag.
You should not rely on the browser implicitly closing your tags, as browsers might react differently to incorrect markup. In this specific case it's likely that browsers react the same, but in other cases they may choose to interpret the code differently, for example placing elements in a different order than you expected.


text:
Q: Know how many lines or space are left until the end of the page in MS-Word I need to know, when I insert text into a word document, how many lines or space I have left until I reach the bottom of the page.
My problem is that I am writing records (a bold title and lines of text) from a database. Sometimes, a title remains on the current page and the text on the next one. And I want to prevent this from happening, by inserting a page break. To perform this page break, I must know how much space or lines I have left before the end of the page.
Is there any way to know how many lines or how much space is left until the end of the page?
Best regards.

A: Don't try something very complicated (and unnecessary) like 'counting how much space or lines are left before the end of the page'. The definition that you need is in the 'paragraph' palette - in the 'line and page breaks' window, there is an option called 'keep with next'. This option will bump the chosen line (the title) to the next page if there is not enough room on the same page for the text which belongs to the title.
In a macro, it looks like Selection.ParagraphFormat.KeepWithNext = True


text:
Q: Locate a web element via sibling in Selenium where the sibling is determined by program I need to locate a report link. But the information of the link itself is too general to characterize but its next sibling is a span element whose text can identify the span element. So I decided to first find the span element, then use the span element by the way of preceding-siblings of xpath to find the link element.
I wonder if there is a better way to do it?
Here is the screenshot showing one of such pair of elements:

Here are the HTML segments showing their definitions and relationship:

    Cases Report
    requested on Tue, Mar 20, 2018 at 9:14 p.m.  —  CSV  —  Ready to download

Here is my attempted implementation (not fully working yet):
span_xpath = '//span[contains(., "Ready to download")]'
# . stands for text in the current node regardless of in bold or not

relative_report_link_xpath = '//preceding-sibling::a[contains(@href, "/reports/")]'

span_list = driver.find_elements_by_xpath(span_xpath)
# There might be multiple such links and spans
# I will have logic to select the desired one
# based on the timestamp in the span.
# For brevity, I just hard code the selection for now:

found_span = span_list[0] # will be logic involving timestamp
found_span.click() # make the span as the current node

driver.find_element_by_xpath(relative_report_link_xpath).click()

For example, I really don't want to click on the span element except for the purpose of making the span as the current node so that I can navigate by preceding-siblings. I wish to know a less "intrusive" implementation of making a web element as the current node without clicking on it. (Clicking on a span element, in this case, maybe OK but if it's part of another link, then the behavior would not be what I want.)
The above implementation doesn't work. The relative_report_link_xpath would find other a (link) element which is not the sibling of the clicked span at all.
I'm using Selenium with Firefox/Python.

A: Here is a solution using xpath:
span_xpath = '//span[contains(., "Ready to download")]'
# . stands for text in the current node regardless of in bold or not

span_list = driver.find_elements_by_xpath(span_xpath)
# There might be multiple such links and spans
# I will have logic to select the desired one
# based on the timestamp in the span.
# For brevity, I just hard code the selection for now:

found_index = 0

report_link_xpath = \
'//span[contains(., "Ready to download")]//preceding-sibling::a[contains(@href, "/reports/")]' + \
'[' + str(found_index + 1) + ']'
# '//span[contains(., "Ready to download")]//preceding-sibling::a[contains(@href, "/reports/")][1]'

driver.find_element_by_xpath(report_link_xpath).click()

It works as expected.
The moral of the story is that Selenium provides the minimum wrapper on top of xpath as far as web element location is concerned, all operations should be done via xpath.


text:
Q: Simple property of Darboux polynomial The Lie derivative of a differentiable function $g: \mathbb{R}^n \rightarrow \mathbb{R}$ along a vector field $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$ is
$\mathcal{L}_f(g)(x) = \left<\left(\begin{matrix}f_1(x) \\ \ldots \\ f_n(x)\end{matrix}\right),\left(\begin{matrix}\frac{\partial g}{\partial x_1} \\ \ldots \\ \frac{\partial g}{\partial x_n}\end{matrix}\right)\right>$
where $\left<\cdot,\cdot\right>$ is the inner product on $\mathbb{R}^n$.
Suppose we have a polynomial $p$ such that $\mathcal{L}_f(p) = \alpha \mathcal{L}_f(p)$ with $\alpha \in \mathbb{R}$ and $\alpha < 0$.
Does this imply that $|p(x_0)| \geq |p(x)|$ and that $p(x)$ converges to $0$ as $x$ changes according to the vector field $f$ with $x_0$ being the initial value for $x$?

A: Bit late, but assuming you meant to write $\mathcal{L}_f(p)=\alpha p$ (I.e., the definition of a Darboux polynomial), then yes that inequality is correct. In the constant cofactor case, solving $\dot{p}=\alpha p$ for $p$ gives $p=C_0e^{\alpha t}$, which strictly monotonically converges to $0$ as $t\rightarrow\infty$ for $\alpha<0$ as your inequality implies.


text:
Q: Keep the ul directly under a class open using jquery I have the following bit o' jquery:
    // Code for Side Navigation
    $("#sideNav ul li:not(:has(li.current))")
   .find("ul").hide().end() // Hide all other ULs
   .hoverIntent(
        function(){
            $(this).children('ul').slideDown('fast');
        },
        function(){
         //  $(this).children('ul').slideUp('fast');
        }
    );

It slides a nav up and down, leaving any li with the class current open.
I would like to change it so if an li has a class current, the ul directly beneath it would be open too, but others below that level would remain closed.
Here is the HTML structure:

Category 1

Currently Open

Sub Cat 1 - should show

Should not Show

Sub Cat 2 - should show

 Category 2

Should not Show>

A: First off, you need to fix your html. the second nested UL isn't closed. The second is to assign all the LI elements in the current trail the .current class.

Category 1

Currently Open

Sub Cat 1 - should show

Should not Show

Sub Cat 2 - should show

 Category 2

Should not Show

Then use this css
    li.current>ul{
    display : block;
}

li ul{
    display : none;
}

That should fix your problem without javascript. Is this what you seek?
If you need to add a hover effect all you need to do is add the .current class to li being hovered.
I have added some inspirational jquery code(haven't tested it) that should help you:
    $('li:has(ul)').bind('mousein',function(){
    $(this).find('ul').slideDown();
});
$('li:has(ul)').bind('mouseout',function(){
    $(this).find('ul').slideUp();
});

A: Figure it out:
Added
$("#sideNav ul li.topCurrent").find("ul").show();
$("#sideNav ul li.topCurrent").find("ul li:not(:has(li.current)) ul").hide();

to the bottom of the jquery code.


text:
Q: Determine constants and probability with density function Do not have answers to this problem
Please let me know if there is mistake or assistance in complete
Remi works at a large data center, and manages the hard drives for the servers. Hard drives often fail, and need to be replaced.
Assume that the probability density for a single hard drive failing after t days of use follows an exponential distribution:
$p(t) = Ce^{-λt}$ for $t ≥ 0$ where C and λ are constants.
a) Find C, in terms of λ.
b) Remi observes that the average failure time for the hard drives is 700 days. Use this to determine λ.
c) What is the probability that a single hard drive will last more that 2000 days?
Trial:
a)
\begin{align}
C\int_0^{∞} e^{-tλ}dt &= 1 \\ \\
\frac{C}{λ} &= 1 \\ \\
C &= λ
\end{align}
b)
\begin{align}
C\int_0^{∞} e^{-tλ}dt &= 1 \\ \\
λ\int_0^{∞} e^{-700λ}dt &= 1 \\ \\
λte^{-700λ} &= 1 \\ \\
...
\end{align}
Unsure what to do, how to determine λ?
t has been re-introduced after integration
c)
Assuming λ was to be discovered in part b
\begin{align}
C\int_{2000}^{∞} e^{-tλ}dt &= P \\ \\
λ\int_{2000}^{∞} e^{-700λ}dt &= P \\ \\
\end{align}
Even if λ was known, this seems incorrect approach
t will be re-introduced again after integration?
Thank you

A: Part $a$ is correct. Need to fix part $b$ and $c$.
In part b, the formula for average is $$\int_0^\infty t \left[\lambda \exp(-\lambda t)\right]\,dt$$
This expression is equal to $700$.
You might want to use integration by parts or substitution to evaluate the integral and then equate to $700$ and solve for $\lambda$.


text:
Q: iOS/objective-c: NSJSONSerialization graceful failure When there is no data (as can happen even when there is an Internet connection due to server issues), the following crashes.  Is there a way using the error term to make it degrade gracefully or do I have to use another if statement such as is there data in the feed before calling JSONSerialization.  Would like to find an alternative to another if statement.  In actually, the if statement below is earlier in the code and all the ifs get very complicated.
if (internet) {
//some code
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonFeed
                                                             options:kNilOptions
                                                               error:&error];
//some code
}

A: The only other option would be to have a method/function that wraps the call to JSONObjectWithData:options:error: and returns nil if jsonFeed is nil.  You'd just be hiding the if statement, but if you need this in many places, it may be worth it.

A: NSJSONSerialization will handle any valid NSData object with any contents whatsoever. Passing a nil NSData is a programming error which rightfully throws an exception.
You may for example pass
jsonfeed ?: [NSData data]

instead of jsonfeed. But then why are you testing "if (internet)"? That's nonsense. What counts is not whether you have an internet connection or not, what counts is whether you had a connection to the server that returned a result.


text:
Q: Simple inquality for tail sums and probability Given $K>0$ how do I show that:
$$
\sum_{n\geq0}P(T>n)\leq K \sum_{n\geq0}P(T>nK)
$$
I have tried to write out the sums to get a feeling but still could not work out how to show this... Doesn't K need to be a non-negative integer?


text:
Q: Can't centre header logo - wordpress I've tried a number of things including using the centre text tag (in CSS) and the yellow pencil plugin to try and centre the logo on this website:
The website
Via yellow pencil I can get it centred on desktop and ipad, but when it goes down to a smart phone device the logo disappears. What is the best way to centre this logo?
J
edit
I have tried applying this CSS to the logo:
display: block;
margin-left: auto;
margin-right: auto;

A: You need to make changes for the following CSS selectors:
#header_wrap #header_border #header #header_container {
    display: block;
    width: 100%;
}

#header_wrap #header_border #header #header_container #logo {
    display: block;
    white-space: nowrap;
    margin: 0 auto;
    text-align: center;
}

#header_wrap #header_border #header #header_container #logo a {
    text-decoration: none;
    display: block;
    float: none;
}

#header_wrap #header_border #header #header_container #menu_wrap {
    display: block;
    vertical-align: middle;
    text-align: center;
    position: relative;
    top: -20px;
}

#menu_wrap #menu_container > div > ul {
    list-style: none;
    margin: 0 auto;
    padding: 0;
    text-align: center;
}

ul#menu-main-menu {
    width: 684px;
    left: 0px;
    position: static;
}

Should work for you. See screenshot.
Let me know if it doesn't work for you.

A: The reason you can't centre the logo is because the menu div with the ID "menu-wrap" takes up a huge blank space above it, so you can't move the logo into this space. You need to style the menu differently.


text:
Q: Roku Web Service API Push Notifications security concern I'm integrating Roku into our multi platform app with paid subscriptions model so webhooks/push notifications are crucial for business to know when subscription being renewed, cancelled etc. I came across Roku Push Notifications documentation which seems to have big security concerns or I'm missing the point:

*

*Roku sends data down to our push notification url without any validation (e.g. like Stripe signature check does). So how do I know the data came from Roku and I can trust it?

*They require to respond with our private API KEY(!) in the header... Does it mean that we can potentially expose it to anyone who found what the url is?

*Not really a security concern but more of a business safety issue that they can stop sending push notifications without any notice if the endpoint fails consecutively which could lead to big problems again.

I would appreciate any advice on how to use Roku push notifications securely and if my concerns are valid at all.


text:
Q: Collecting attributes from dask dataframe providers TL;DR: How can I collect metadata (errors during parsing) from distributed reads into a dask dataframe collection.
I currently have a proprietary file format i'm using to feed into dask.DataFrame.
I have a function that accepts a file path and returns a pandas.DataFrame, used internally by dask.DataFrame successfully to load multiple files to the same dask.DataFrame.
Up until recently, I was using my own code to merge several pandas.DataFrames into one, and now i'm working on using dask instead. When parsing the file format i may encounter errors and certain conditions i want to log and associate with the dask.DataFrame object as metadata (logs, origin of data, etc).
Its important to note that when reasonable, I'm using MultiImdices quite heavily (13 index levels, 3 column levels). For metadata that describes the entire dataframe and not specific rows, I'm using attributes.
Using a custom function, I could pass the metadata in a tuple with the actual DataFrame. Using pandas, I could add it to the _metadata field and as attributes to the DataFrame obejcts.
How can I collect metadata from separate pandas.DataFrame objects when using the dask framework?
Thanks!

A: There are a few potential questions here:

*

*Q: How do I load data from many files in a custom format into a single dask dataframe

*A: You might check out the dask.delayed to load data and dask.dataframe.from_delayed to convert several dask Delayed objects into a single dask dataframe.  Or, as you're probably doing now, you can use dask.dataframe.from_pandas and dask.dataframe.concat.  See this example notebook on using dask.delayed from custom objects/functions.

*Q: How do I store arbitrary metadata onto a dask.dataframe?

*A: This is not supported.  Generally I recommend using a different data structure to store your metadata if possible.  If there are a number of use cases for this then we should consider adding it to dask dataframe.  If this is the case then please raise an issue.  Generally thought it'd be good to see better support for this in Pandas before dask.dataframe considers supporting it.

*Q: I use multi-indexes heavily in Pandas, how can I integrate this workflow into dask.dataframe?

*A: Unfortunately dask.dataframe does not currently support multi-indexes. These would clearly be helpful.


text:
Q: fraction of coprime integers If $p$ and $q$ are coprime positives integers , then
$$(p / q)\cdot n \notin \mathbb Z, $$ for every $n = 1, 2, ..., q-1$.
With $n = 1$ this is trivial since there is no common divisor but why is it true for:
$(p / q)*2$ or $(p / q)*3$ as long as $n \le q-1$?
Many thanks for any clarification.

A: Suppose there exist an integer $n\in\{1,2,...q-1\}$ and $m\in\Bbb{Z}$ such that $\frac pq\times n=m$.
Multiply both sides by $q$ and we get $pn=qm$. Thus $q\ |\ pn$.
As $\gcd(p,q)=1$, thus $q$ must divides $n$.
Because $n\in\{1,2,...,q-1\}$, no such integer $n$ exist which leads to a contradiction.
There for $\frac pq \times n$ is not an integer


text:
Q: Why does Apache Drill select column with the same name of a different table I have a PostgreSQL database linked to a Drill instance.
Whenever I am trying to join 2 tables which both have a column name and whenever I want to select this name Drill selects the wrong name column. What am I doing wrong?
Given the following 2 tables:
Department
| id | name |
|----|------|
| 1  |  A   |
| 2  |  B   |

Employee
| id | name | dept | salary |
|----|------|------|--------|
| 1  |  U   |  1   |  100   |
| 2  |  V   |  1   |   75   |
| 3  |  W   |  1   |  120   |
| 4  |  X   |  2   |   95   |
| 5  |  Y   |  2   |  140   |
| 6  |  Z   |  2   |   55   |

Running
select employee.name, employee.salary
from employee
inner join department on employee.dept = department.id
where department.name = 'A'

returns
| name | salary |
|------|--------|
|  A   |  100   |
|  A   |  75    |
|  A   |  120   |

Running
select dept.name, employee.salary
from employee
inner join department on employee.dept = department.id
where department.name = 'A'

returns
| name | salary |
|------|--------|
| null |  100   |
| null |  75    |
| null |  120   |

What does work, but seems very silly to me, is:
select dept.name, employee.salary
from employee
inner join (select id, name as deptname from department) as department on employee.dept = department.id
where department.deptname = 'A'

A: This seems to be because you use
select dept.name, [...]
But you have never assigned an alias for the table department (department AS dept). Hence
select department.name, [...]
should yield the value you are looking for.


text:
Q: OIDC Liberty 8.5.5.8 - NPE in OAuth20InternalException.getEncodedTraceArg I am using WebSphere Liberty 8.5.5.8 (wlp-1.0.11.cl50820151201-1942) and I am trying to setup OpenID-Connect. Most of my basic samples are working, but when I try to implement "Implicit Flow" with a pure JavaScript client (I use the client samples from https://github.com/IdentityServer/IdentityServer3.Samples), I receive an NPE in the POST after the consent form:
[ERROR   ] SRVE0777E: Exception thrown by application class
com.ibm.oauth.core.api.error.oauth20.OAuth20InternalException.getEncodedTraceArguments:76
java.lang.NullPointerException at
com.ibm.oauth.core.api.error.oauth20.OAuth20InternalException.getEncodedTraceArguments(OAuth20InternalException.java:76)
at [internal classes]

Has anybody been successfull with WLP and setting up "Implicit Flow/Grant".
Is anybody from IBM able to make a diagnosis? NPE in internal class is not very helpful.

A: Did you check for any FFDC logs to see if there are any errors logged prior to the NPE.
Also this link points to a good document on what you need to add to the request for an implicit flow.
https://www.ibm.com/support/knowledgecenter/SSD28V_8.5.5/com.ibm.websphere.wlp.core.doc/ae/twlp_oidc_auth_endpoint.html?lang=en
As you can see in the document, liberty OIDC does not support just "id_token" in the response_type. When using the implicit flow, one must always use "id_token token" ... So make sure that you have ...response_type=id_token token&scope=openid&client_id=... etc specified in your request.
If the above information does not help, then please provide your OpenID Connect provider configuration and also your example request that you are sending.

A: The expected authorization request format is
https://localhost:8020/oidc/endpoint/OP3/authorize?response_type=id_token+token&client_id=rp&state=mfjSAPtn9X4TAY52nD9T&redirect_uri=https%3A%2F%2Flocalhost%3A8021%2Foidcclient%2Fredirect%2FRP&scope=openid+profile+email+photo&nonce=xNlPy62xC5ABjyfdxSAU&response_mode=form_post
The "response_mode=form_post" is optional with default value of "fragment"


text:
Q: Restrict ordering product from different categories in one order Products have different Categories. Clients can only order multiple products from the same category and cannot order products from different categories in the same order. They would need to create a separate order for each category. My issue is I can't figure out how to set this up. See screenshot. The way it's configured now, the Order_Details has the ProductID so there is nothing stopping the client from selecting multiple products from different Categories.
If I put a CategoryID FK in Orders table or Orders_Items table, this would be in violation of the 2nd form of normalization since the Category is an attribute of a product and not of an order. It would also create redundancy since the product category would be in TWO tables.
So would I need to make ANOTHER table for this or is there a way to restrict this by some kind of constraint? (yes, I can restrict this programmatically in my application but I would rather have it set up correctly in the database.

A: I would add a CategoryID in both Orders and Order_Items, and use composite FK constraints to ensure referential integrity:
ALTER TABLE Order_Items
ADD FOREIGN KEY (OrderID, CategoryID)
REFERENCES Orders (OrderID, CategoryID);

ALTER TABLE Order_Items
ADD FOREIGN KEY (ProductID, CategoryID)
REFERENCES Products (ProductID, CategoryID);

This will require suitable indexes to be created.
Adding CategoryID in the Orders table doesn't violate 2NF or 3NF, since it's dependent on the OrderID and nothing else. It's not redundant either, since there is no other way to record or derive the functional dependency OrderID -> CategoryID.
Adding CategoryID in Order_Items violates 3NF since it creates a transitive functional dependency (OrderItemID -> OrderID -> CategoryID and OrderItemID -> ProductID -> CategoryID). However, there is no risk of data anomalies if the FK constraints above are used. Though it introduces redundancy from an informational point of view, it's managed redundancy and it's justified since it's used for referential integrity.
It's possible to achieve the same end without redundancy by using triggers (you would still need the CategoryID in Orders), but I prefer the simplicity of FK constraints.


text:
Q: Longpress in UWP I'm porting an app to Univeral Windows Platform (Windows 10).
Android has a onLongPress event. Is there an equivalent for UWP?
I found there is a Holding event which I tried to use something like this:
private void Rectangle_Holding(object sender, HoldingRoutedEventArgs e)
{
    if (e.HoldingState == HoldingState.Started)
    {
        Debug.WriteLine("Holding started!");
    }
}

Problem is the event is not triggered on Windows Desktop, when mouse is used instead of touch.

A: Mouse input doesn't produce Holding events by default, you should use RightTapped event to show the context menu, it is triggered when user long presses in a touch device and right clicks in a mouse device.
Take a look at GestureRecognizer.Holding and Detect Simple Touch Gestures, you can achieve that using the following code
public sealed partial class MainPage : Page
{
    GestureRecognizer gestureRecognizer = new GestureRecognizer();

    public MainPage()
    {
        this.InitializeComponent();
        gestureRecognizer.GestureSettings = Windows.UI.Input.GestureSettings.HoldWithMouse;
    }

    void gestureRecognizer_Holding(GestureRecognizer sender, HoldingEventArgs args)
    {
        MyTextBlock.Text = "Hello";
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        gestureRecognizer.Holding += gestureRecognizer_Holding;
    }

    private void Grid_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        var ps = e.GetIntermediatePoints(null);
        if (ps != null && ps.Count > 0)
        {
            gestureRecognizer.ProcessDownEvent(ps[0]);
            e.Handled = true;
        }
    }

    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        gestureRecognizer.ProcessMoveEvents(e.GetIntermediatePoints(null));
        e.Handled = true;
    }

    private void Grid_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        var ps = e.GetIntermediatePoints(null);
        if (ps != null && ps.Count > 0)
        {
            gestureRecognizer.ProcessUpEvent(ps[0]);
            e.Handled = true;
            gestureRecognizer.CompleteGesture();
        }
    }
}


text:
Q: W A S D keys are swapped with arrow keys? I have a desktop that I don't use that much (mostly for burning CD's and stuff). I logged on and wanted to search for a program only to realize that the W S A and D keys are swapped with the arrow keys. For example: If I'm in Notepad, and I press the Left Arrow key, it's going to type 'D'. If I press the D key, it's going to scroll right and whatnot.
How can I solve this?

A: Hold FN (function) and Then Press W And I should Fix it :D

A: Hold down the Fn key, usually on the right side of the space bar, and press W while you are holding it. Should fix it instantly. (And you can swap between them any time.)

A: I had the same problem.
I fixed by unplugging my keyboard and plugging it back in again.

A: For me I had to hold down Fn key and press the Windows key while holding, and it was fixed instantly.

A: OK, you need to factory reset immediately.
YOU MAY BE HACKED.
I know from past experiences.

CEO of FixItJay.


text:
Q: Detecting Approval button in a Swing FileChooser event I know that there is another way to do this, but I prefer to see if anyone has an answer for doing it this way. The original way is to get the integer return value after calling the ShowDialog() function; I want to grab it from within the Event (shown below) itself. I've thrown some code in there to check if a file is selected, but I need to check whether the approval button (the OK button) has been selected before it gets there. Does anyone know how to check which button is pressed in a FileChooser dialog, using a setup like below?
Here's my code:
private void FileChooser_OpenMouseClicked(java.awt.event.MouseEvent evt) {
        if(!FileChooser_Open.getSelectedFile().equals(null))
        {

        }
    }

Original method:
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);

The difference is that the original method gets a return value when the dialog box is closed, while in this method, I do not know of a way to get that return value (I believe the box has already closed, but there is nothing there to catch the return value). I apologize if I do not appear to be making a lot of sense.
edit: More information
So this is how I am creating the dialogue (a menu item, "Open" raises an event, which calls the showOpenDialog() method. As you can see, it is not capturing the return value (bear with me). Is it possible then to get the return value or at design a method to figure out whether the OK button is then pressed in the MouseClicked event? I guess I am trying to focus on an event-based programming style, where the code reacts according to the event raised, and grabbing the checking for the OK / approval button click inside the Open Menu event seems a little...disorganized from my perspective. Perhaps I am too used to C# / WinForm's approach to this problem?
private void MenuItem_OpenActionPerformed(java.awt.event.ActionEvent evt) {
        FileChooser_Open.showOpenDialog(this);
    }

private void FileChooser_OpenMouseClicked(java.awt.event.MouseEvent evt) {
        if(!FileChooser_Open.getSelectedFile().equals(null))
        {

        }
    }

A: If I understand the question, you might be able to use a JFileChooser#approveSelection() method:

*

*OTN Discussion Forums : How to react on events fired by a JFileChooser?

*java - JFileChooser with confirmation dialog - Stack Overflow

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class ApproveSelectionDemo {
  public JComponent makeUI() {
    final JPanel p = new JPanel();
    final JFileChooser fileChooser = new JFileChooser() {
      @Override public void approveSelection() {
        if(!getSelectedFile().exists()) {
          int returnVal = JOptionPane.showConfirmDialog(
                  this, "message", "title", JOptionPane.YES_NO_OPTION);
          if(returnVal!=JOptionPane.YES_OPTION) {
            return;
          }
        }
        super.approveSelection();
      }
    };
    p.add(new JButton(new AbstractAction("Open") {
      @Override public void actionPerformed(ActionEvent e) {
        int retvalue = fileChooser.showOpenDialog(p);
        if(retvalue==JFileChooser.APPROVE_OPTION) {
          System.out.println(fileChooser.getSelectedFile());
        }
      }
    }));
    return p;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new ApproveSelectionDemo().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}


text:
Q: I'm doing some scheme homework that involves recursive functions and I'm very confused For my class I need to write a function that accepts a string and add "op" after every consonant found in the string.
What I've got so far is a helper function that checks an individual letter to see if it is a consonant or a vowel. here it is:
(define (check-letter letter)

(if (null? letter)
  'empty

(or (char=? letter #\a) (char=? letter #\e)
    (char=? letter #\i) (char=? letter #\o)
    (char=? letter #\u) (char=? letter #\y))))

So that will give me a true or false for a given letter but I'm not sure how to approach the rest of the problem.
I know I need to use the "string->list" function but I'm very bad with recursive functions.
If anybody could help out and point me in the right direction or somewhere on the internet that might help that would be fantastic

A: So your initial procedure checks if a char is a vowel. The parameter is a char, no need to check for null here. Also, it's a predicate (returning true or false) so let's call it vowel?:
(define (vowel? letter)
  (or (char=? letter #\a) (char=? letter #\e)
      (char=? letter #\i) (char=? letter #\o)
      (char=? letter #\u) (char=? letter #\y)))

The wrapper function transforming a string to list and back is trivial:
(define (add-op str op)
  (list->string
   (add-op-list (string->list str) op)))

Now the recursive function, working on a list. You know that a list is constructed as:
`(cons elt1 (cons elt2 (cons elt3 (cons elt4 (.... (cons '() ))))))`

and that recursivity means that

*

*you process the first element (obtained by car), and call the same procedure on the rest of the list (obtained by cdr)

*until you reach your base case (here, list is null?, so add the final '())

So this leads to:
(define (add-op-list lst op)
  (if (null? lst) ; list is empty: finally add '()
      '()
      (let ((c (car lst))) ; c is the first element of the list
        (if (vowel? c)     ; is it a vowel?
            (cons c          (add-op-list (cdr lst) op)) ; yes, just add it to the resulting list and proces the rest
            (cons c (cons op (add-op-list (cdr lst) op))))))) ; no, add c and op

Trying:
> (add-op "Supercalifragilisticexpialidocious" #\!)
"S!up!er!c!al!if!r!ag!il!is!t!ic!ex!p!ial!id!oc!ious!"

A: Here is a tail-recursive solution (your teacher will surely give you extra-credit for using tail recursion!):
(define (vowel? c)
  (member c '(#\a #\e #\i #\o #\u #\y)))

(define (homework-1 string punc)
  (let extending ((letters (string->list string)) (result '()))
    (cond ((null? letters)
           (list->string (reverse result)))

          ((vowel? (car letters))
           (extending (cdr letters)
                      (cons (car letters) result)))

          (else
           (extending (cdr letters)
                      (cons punc (cons (car letters) result))))

> (homework-1 "abc" #\-)
"ab-c-"


text:
Q: What is Seven-Sided Strike's reach and damage division? The Monk's Seven-Sided Strike is a focus skill, a series of hits back and forth about a circle. Sometimes I'll see the Monk's animation reach enemies outside the circle. How far does this move reach, and how does it divide the 777% weapon damage over seven hits amongst the targets? If there is one target, does it get seven hits worth 111% weapon damage? Are some hits worth more than 111% (and others less)? If there are seven targets, does every one get a hit or are the hits chosen randomly within the circle (some receiving double, others receiving none)? Or do all targets in the area receive 777% weapon damage? Does the move prioritize enemies within the circle, and how many yards will the move reach if there is no one nearby?

A: Each hit does 111% weapon damage, and you hit 7 times.
I'm not positive, but I think each hit is randomly decided among available targets, so although unlikely, you can hit the same target 7 times even if other targets are available. If only 1 target is available, you will hit that target 7 times.
I haven't tested much with the range, so I don't think I can answer that part of your question very well, but if you use the ability on a regular basis you should get a good idea of the sort of range it will hit since there is an animation that shows you who you are hitting.
You do not have to be next to the target to hit them though, and I'm not even sure you need to be targetting anyone to use it. For example, one of the runes you unlock for the skill will teleport you to your target when you use that ability, so I have used it to target an enemy across the screen and teleport there.


text:
Q: Symfony: how to get values from parameters.yml in an AbstractType I'm trying to get values form an array which I declared in parameters.yml
# parameters.yml
parameters:
    ...
    objects: {object1: 1, object2: 2, object3: 3}

but once I try to get "objects" from that file using this code
$builder->add('list', ChoiceType::class, array ('objects' => $this->container->getParameter('categories') ));

I get the following error
Notice: Undefined property: Project\Bundle\Form\EntityType::$container

Any suggestions?

A: You have to inject the ContainerInterface inside your Class.
services.yml
form.my_entity_type:
  class: AppBundle\Form\MyEntityType
  arguments:
    - '@service_container'
  tags:
    - { name: form.type }

MyEntityType
/** @var ContainerInterface */
protected $container;

/**
 * @param ContainerInterface $container
 */
public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

**
 * @param FormBuilderInterface $builder
 * @param array                $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $params = $this->container->getParameter('my-params');
    ....

A: If you declare the Project\Bundle\Form\EntityType as a service, you will be able to inject the data into it, along with any other services it needs. You will still be able to refer to the type as EntityType::class when you include it, as Symfony will recognise that class is defined as a service.
It will make testing it a little more 'interesting' though


text:
Q: When do I use the self property? I am trying to better grasp the use of self. Is using self basically just a shortcut to typing out the class name? For example, in the code below, if I use self does it refer to the Tank2 class? For example, is it basically a shortcut to typing out Tank2.bonusDamage? I don't understand what "the current instance" is that self is referring to.
I don't quite grasp it because I notice for example that these top two code snippets return the exact same thing.
    //SNIPPET 1:
    var damage: Double {
    return baseDamage + Tank2.bonusDamage
}

    //SNIPPET 2:
    var damage: Double {
    return self.baseDamage + Tank2.bonusDamage

}

.
class Tank2 {
class var bonusDamage: Double {
    return Double(Upgrade.level) * 2.5
}

let baseDamage = 10.0

var damage: Double {
    return baseDamage + Tank2.bonusDamage
}

class func upgrade() {
    Upgrade.level += 1

}

struct Upgrade{
static var level = 0
}
}

A: A class definition  describes the properties and methods of the class like the plans for a car describe its size, number of seats and so on - but you can't drive  plans, you need an actual instance of a car built from those plans.
Similarly with an object class - you need an actual instance of a class to operate on.
Given a simple Car class -
Class Car
   property color:Color
   property fuelTankLevel:Integer
   propert (readOnly) capacity:Integer = 60 // Fuel tank capacity in litres

Note that this isn't Swift or Objective C, just a simplified version of  a class.
I could store instances in variables -
 let redCar=Car(color:Red)
 let blueCar=Car(color:Blue)

which is fine for referring to those cars from within my program, but what about a method of car that let me fill the fuel tank.  From my program I can say blueCar.fill() - but inside the fill method I need to operate on the right tank.  Inside fill I can't refer to blueCar and redCar because these are just instances outside of the class definition.  This is where self comes in.
self means "the current object instance", so the fill method could be
fill() {
    self.fuelTankLevel=self.capacity
}

So when this code is invoked on an object instance, self will be that instance. So when I say blueCar.fill() the code that is executed is effectively blueCar.fuelTankLevel=blueCar.capacity.
In Swift you can omit self and in Objective-C you can use _fuelTank (or whatever backing variable you @synthesized) to access the property backing variable directly, but it is a good idea to get into the habit of using self as it makes it clear that you are accessing a property and not a local or global variable.  Also in Objective-C it ensures that any setter/getter methods are invoked.
You can define Class methods - these are methods that do not operate on any particular instance.  In Objective-C you often see "constructor" class methods that wrap the two-stage alloc/init into a single Class method so instead of saying:
 Car *redCar=[[Car alloc]initWithColor:red];

You can say
 Car *redCar=[Car carWithColor:red];

A: No self is not same as typing a class name.
self is a object of current class. So all the properties and functions values which are available in that class can be references using self.
However, there are functions (called Class functions and distinguised with +), that are not dependent on a class object. These Class Functions are called via class name.
Example
Class TestClass
+ (int)addToFive:(int)input
{
   return input+5;
}

Call this method [TestClass addToFive:10], will return 15.
Class TestClass
@property int counter;

-(int)addToCounter:(int)input
{
   // self.counter corresponds to counter value for self (this particular TestClass object)
   return self.counter + input;
}

// call this method
TestClass *classObject = [TestClass alloc] init];
classObject.counter = 10;
[classObject addToCounter:10] // will return 20.

I hope this helps you.

A: In class code - such as a class method, a static method, or the initializer of a class property - self means "this class, whatever it may be".
In instance code - such as an instance method, or the initializer of an instance property - self means "this instance, whatever it may be".
But in most situations, self can be omitted - because if a message is a sent without a recipient, Swift will assume that you intend to send it to self.
In your example, baseDamage is an instance variable, and the phrase return self.baseDamage + ... appears in instance code. Thus, you can say baseDamage or self.baseDamage interchangeably, because Swift assumes that the bare message baseDamage means self.baseDamage.


text:
Q: How can I prevent key presses from changing the value of a scrollbar control? I have a form with a user control that has a vscrollbar control. I would like to handle the user control's keypress event, but when I press the 'down arrow' key (for example), the keypress event isn't handled, and the vscrollbar's value increases instead. Other navigational keys behave this way as well.
I would like to have the vscrollbar stop 'overriding' my intention to raise the keypress event. I was thinking I could set the user control's keypreview property to true, but then I noticed it doesn't have one.

A: You need to look at using the KeyDown or PreviewKeyDown event instead.


text:
Q: java lock gets locked by another thread when it's locked I'm all out of ideas on why this happens. What I'm trying to do is to have one thread do some work, then another thread process the results of that work and when it's finished the first thread goes back into action. So I'm giving both threads a reference to a single ReentrantLock. The first thread locks it, does its work, then releases it and sleeps for a few milliseconds to let the other thread acquire the lock and do its work and then the process continues.
The problem is that it appears that the lock gets locked by the second thread while it's still locked by the first. I can't figure out why. I wrote a simple class to try and recreate the scenario but there everything goes as expected. I've also looked into my code and I'm not releasing the locks anywhere unexpected. I've also tried replacing the lock with a new Semaphore(1) and the same thing happens.
Here are the relevant lines form the log:
12204 [Thread-2] DEBUG AggregatedEventProducerThread:37 - Attempting to acquire lock java.util.concurrent.locks.ReentrantLock@43e36bfa[Unlocked]. Timestamp 1453223023635
12204 [Thread-2] DEBUG AggregatedEventProducerThread:39 - Lock acquired at 1453223023636. java.util.concurrent.locks.ReentrantLock@43e36bfa[Locked by thread Thread-2]
12564 [Thread-5] DEBUG CoordinatorState:151 - Attempting to acquire lock java.util.concurrent.locks.ReentrantLock@43e36bfa[Locked by thread Thread-2]. Timestamp 1453223023995
13454 [Thread-5] DEBUG CoordinatorState:154 - Lock java.util.concurrent.locks.ReentrantLock@43e36bfa[Locked by thread Thread-5] acquired at 1453223024886.
23915 [Thread-5] DEBUG CoordinatorState:161 - Lock java.util.concurrent.locks.ReentrantLock@43e36bfa[Unlocked] released at 1453223035346.
28458 [Thread-2] DEBUG AggregatedEventProducerThread:45 - Lock released at 1453223039890. java.util.concurrent.locks.ReentrantLock@43e36bfa[Unlocked]

Any ideas?


text:
Q: How to send event from .Net client to Silverlight I would like my .Net (C#) written executable running in the local machine
to send an event to a Silverlight object (embedded in ASPX page in remote server).
Is there a simple solution for that issue ?
Can someone please supply a demo source code (or a link).
Thanks

A: This is possible, but not as simply as you would like it to be.

embedded in ASPX page in remote server

Let me clear up one misconception first: the Silverlight control is not embedded in an ASPX page on a remote server. The ASPX page and Silverlight control are hosted and served by the remote server. The Silverlight control is loaded and rendered on the client when the ASPX page is requested by the browser. The Silverlight control does not exist as a concrete instance on the server.
If you want the Silverlight control on a client machine to receive a message from a Windows client app on another machine, then you will need to introduce an intermediary like a WCF web service. This web service can be hosted on the same machine that hosts the web page and silverlight control, and both can send messages to the WCF service, and listen for messages either by regular old-fashioned polling or by using a duplex binding.
For more info on duplex WCF, check out these articles i dug up for you:

*

*WCF Duplex Messaging

*MSDN: Silverlight - How to: Access a Duplex Service


text:
Q: Passing a long/large string as an argument into a Java app? I'm attempting to pass a large/long string, a PDF binary read from disk, into a Java app and so far am having very little success. The app works when I read the file in from a local disk, so I know the problem is related to how I'm importing the data. Roughly this is what I'm looking at:
I'm reading, manipulating the pdf in PHP and using exec(); to touch the Java app, this is where I'm at with the Java:
Works:
File input = new File("C:\\Users\\Jack\\Downloads\\col_terror.pdf");
document = PDDocument.load(input);

Does not work:
PHP:
exec("/path/to/jar/java -jar JavaAppHere.jar $pdf_string",$ouput);

Java:
public static void main(String[] args) throws Exception {
...
document = PDDocument.load( args[0] );
...
}

I feel this is something quite simple I am not understanding about passing strings as args, though it has been a couple years since I've made a venture into the land of Java.

A: Please read the Javadoc of PDDocument. If PDDocument refers to PDDocument you can see that you are passing data while PDDocument.load(java.lang.String) expects the filename.
You also don't seem to encode $pdf_string with escapeshellarg()
Since there are too many variables invovled in passing binary data around as shell arguments, I'd advice against it.
The easiest solution is to write the PDF to a temporary file and pass the filename to java. The  alternative is to pass the PDF data via stdin.


text:
Q: How to obfuscate all code in project IOS I have a problem to obfuscate the project codes to protect source.

*

*is this possible to Obfuscate all project source codes.
if yes, please guide me.

A: Objective-C code cannot be 100% obfuscated. There are some open source and some commercial tools that will obfuscate the class name, the custom methods and variables, but be aware that they can easily break and crash your app.
For example, if you use a custom view controller class in your storyboard, and your code obfuscation changes the class names in the source file but not the storyboard, instantiating that custom view controller will crash your app or at the very least makes it impossible to instantiate your custom view controller.
Similarly, Objective-C variable binding can be difficult if not impossible. Objective-C was designed from the ground up to be inspectable and modifiable. Obviously all of the UIKit delegate/protocol methods cannot be obfuscated. viewDidLoad will always be called viewDidLoad.
Good luck!

Edit:
There seems to be a LLVM replacement that handles the code obfuscation for you, check out Obfuscator-LLVM Wiki.


text:
Q: Display Attribute in Edit Product Back end Magento Please help me!. I have an attribute "manufacture". How can i display this attribute into General tab in Edit Product Page ?
Thank you.

A: Simply add the desired attribute to all desired attribute sets by dragging it into the desired tab.  You can get to each individual attribute set edit form by clicking on the corresponding record in the Attribute Sets grid.

A: Go to, Catalog > Attributes > Manage Attribute Sets, Select required attribute set.
Now Drag manufacturer attribute to General block, shown below :

Now click Save Attribute Set, you should be able to see manufacture attribute in General tab