text:
Q: launch Python app with spark-submit in AWS EMR I'm new to Spark and having trouble replicating the example in the EMR docs for submitting a basic user application with spark-submit via AWS CLI. It seems to run without error but produces no output.  Is something wrong with my syntax for add-steps in the below workflow?
Example script
The objective is to count words in a document in S3, for this example 1000 words of lorem-ipsum:
$ aws s3 cp s3://projects/wordcount/input/some_document.txt - | head -n1
Lorem ipsum dolor sit amet, consectetur adipiscing [... etc.]

Copying from the docs, the python script looks like:
$ aws s3 cp s3://projects/wordcount/wordcount.py -
from __future__ import print_function
from pyspark import SparkContext
import sys
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: wordcount  ", file=sys.stderr)
        exit(-1)
    sc = SparkContext(appName="WordCount")
    text_file = sc.textFile(sys.argv[1])
    counts = text_file.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b)
    counts.saveAsTextFile(sys.argv[2])
    sc.stop()

The destination folder (currently empty):
$ aws s3 ls s3://projects/wordcount/output
                           PRE output/

create-cluster
Working from doc, I have a running cluster with logging, as produced by:
aws emr create-cluster --name TestSparkCluster \
--release-label emr-5.11.0 --applications Name=Spark \
--enable-debugging --log-uri s3://projects/wordcount/log \
--instance-type m3.xlarge --instance-count 3 --use-default-roles

with return message showing created {"ClusterID": "j-XXXXXXXXXXXXX"}
add-steps
Looking directly at the example, I submit add-steps as:
aws emr add-steps --cluster-id j-XXXXXXXXXXXXX \
--steps Type=spark,Name=SparkWordCountApp,\
Args=[--deploy-mode,cluster,--master,yarn,\
--conf,spark.yarn.submit.waitAppCompletion=false,\
--num-executors,2,--executor-cores,2,--executor-memory,1g,\
s3://projects/wordcount/wordcount.py,\
s3://projects/wordcount/input/some_document.txt,\
s3://projects/wordcount/output/],\
ActionOnFailure=CONTINUE

which launches { "StepIds":["s-YYYYYYYYYYY"] }
The problem
The output folder is empty -- why?
I verify that step SparkWordCountApp with ID s-YYYYYYYYYYY has Status:Completed in the EMR console.
From the console, I check the controller log file and the stderr output (below) to verify that the step completed with exit status 0.
In the Spark documentation, a somewhat different syntax is used.  Instead of making the script name the first position of the arguments list, it says:

For Python applications, simply pass a .py file in the place of
   instead of a JAR, and add Python .zip, .egg or .py
  files to the search path with --py-files.

However, the example uses sys.argv, where sys.argv[0] is wordcount.py
Additonal info: logs
Controller log file:
2018-01-24T15:54:05.945Z INFO Ensure step 3 jar file command-runner.jar
2018-01-24T15:54:05.945Z INFO StepRunner: Created Runner for step 3
INFO startExec 'hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit --deploy-mode cluster --master yarn --conf spark.yarn.submit.waitAppCompletion=false --num-executors 2 --executor-cores 2 --executor-memory 1g s3://projects/wordcount/wordcount.py s3://projects/wordcount/input/some_document.txt s3://projects/wordcount/output/'
INFO Environment:
  PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/opt/aws/bin
  LESS_TERMCAP_md=[01;38;5;208m
  LESS_TERMCAP_me=[0m
  HISTCONTROL=ignoredups
  LESS_TERMCAP_mb=[01;31m
  AWS_AUTO_SCALING_HOME=/opt/aws/apitools/as
  UPSTART_JOB=rc
  LESS_TERMCAP_se=[0m
  HISTSIZE=1000
  HADOOP_ROOT_LOGGER=INFO,DRFA
  JAVA_HOME=/etc/alternatives/jre
  AWS_DEFAULT_REGION=us-west-2
  AWS_ELB_HOME=/opt/aws/apitools/elb
  LESS_TERMCAP_us=[04;38;5;111m
  EC2_HOME=/opt/aws/apitools/ec2
  TERM=linux
  XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt
  runlevel=3
  LANG=en_US.UTF-8
  AWS_CLOUDWATCH_HOME=/opt/aws/apitools/mon
  MAIL=/var/spool/mail/hadoop
  LESS_TERMCAP_ue=[0m
  LOGNAME=hadoop
  PWD=/
  LANGSH_SOURCED=1
  HADOOP_CLIENT_OPTS=-Djava.io.tmpdir=/mnt/var/lib/hadoop/steps/s-29XVS3IGMSK1/tmp
  _=/etc/alternatives/jre/bin/java
  CONSOLETYPE=serial
  RUNLEVEL=3
  LESSOPEN=||/usr/bin/lesspipe.sh %s
  previous=N
  UPSTART_EVENTS=runlevel
  AWS_PATH=/opt/aws
  USER=hadoop
  UPSTART_INSTANCE=
  PREVLEVEL=N
  HADOOP_LOGFILE=syslog
  PYTHON_INSTALL_LAYOUT=amzn
  HOSTNAME=ip-172-31-12-232
  NLSPATH=/usr/dt/lib/nls/msg/%L/%N.cat
  HADOOP_LOG_DIR=/mnt/var/log/hadoop/steps/s-29XVS3IGMSK1
  EC2_AMITOOL_HOME=/opt/aws/amitools/ec2
  SHLVL=5
  HOME=/home/hadoop
  HADOOP_IDENT_STRING=hadoop
INFO redirectOutput to /mnt/var/log/hadoop/steps/s-29XVS3IGMSK1/stdout
INFO redirectError to /mnt/var/log/hadoop/steps/s-29XVS3IGMSK1/stderr
INFO Working dir /mnt/var/lib/hadoop/steps/s-29XVS3IGMSK1
INFO ProcessRunner started child process 20797 :
hadoop   20797  3347  0 15:54 ?        00:00:00 bash /usr/lib/hadoop/bin/hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit --deploy-mode cluster --master yarn --conf spark.yarn.submit.waitAppCompletion=false --num-executors 2 --executor-cores 2 --executor-memory 1g s3://projects/wordcount/wordcount.py s3://projects/wordcount/input/some_document.txt s3://projects/wordcount/output/
2018-01-24T15:54:09.956Z INFO HadoopJarStepRunner.Runner: startRun() called for s-29XVS3IGMSK1 Child Pid: 20797
INFO Synchronously wait child process to complete : hadoop jar /var/lib/aws/emr/step-runner/hadoop-...
INFO waitProcessCompletion ended with exit code 0 : hadoop jar /var/lib/aws/emr/step-runner/hadoop-...
INFO total process run time: 16 seconds
2018-01-24T15:54:24.072Z INFO Step created jobs:
2018-01-24T15:54:24.072Z INFO Step succeeded with exitCode 0 and took 16 seconds

Stderr log file:
18/01/24 15:54:12 INFO RMProxy: Connecting to ResourceManager at ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal/XXX.YY.YY.ZZZ:8032
18/01/24 15:54:12 INFO Client: Requesting a new application from cluster with 2 NodeManagers
18/01/24 15:54:12 INFO Client: Verifying our application has not requested more than the maximum memory capability of the cluster (11520 MB per container)
18/01/24 15:54:12 INFO Client: Will allocate AM container, with 1408 MB memory including 384 MB overhead
18/01/24 15:54:12 INFO Client: Setting up container launch context for our AM
18/01/24 15:54:12 INFO Client: Setting up the launch environment for our AM container
18/01/24 15:54:12 INFO Client: Preparing resources for our AM container
18/01/24 15:54:14 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
18/01/24 15:54:18 INFO Client: Uploading resource file:/mnt/tmp/spark-89654b91-c4db-4847-aa4b-22f27240daf7/__spark_libs__8429498492477236801.zip -> hdfs://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:8020/user/hadoop/.sparkStaging/application_1516806627838_0002/__spark_libs__8429498492477236801.zip
18/01/24 15:54:22 INFO Client: Uploading resource s3://projects/wordcount/wordcount.py -> hdfs://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:8020/user/hadoop/.sparkStaging/application_1516806627838_0002/wordcount.py
18/01/24 15:54:22 INFO S3NativeFileSystem: Opening 's3://projects/wordcount/wordcount.py' for reading
18/01/24 15:54:22 INFO Client: Uploading resource file:/usr/lib/spark/python/lib/pyspark.zip -> hdfs://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:8020/user/hadoop/.sparkStaging/application_1516806627838_0002/pyspark.zip
18/01/24 15:54:22 INFO Client: Uploading resource file:/usr/lib/spark/python/lib/py4j-0.10.4-src.zip -> hdfs://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:8020/user/hadoop/.sparkStaging/application_1516806627838_0002/py4j-0.10.4-src.zip
18/01/24 15:54:22 INFO Client: Uploading resource file:/mnt/tmp/spark-89654b91-c4db-4847-aa4b-22f27240daf7/__spark_conf__8267377904454396581.zip -> hdfs://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:8020/user/hadoop/.sparkStaging/application_1516806627838_0002/__spark_conf__.zip
18/01/24 15:54:22 INFO SecurityManager: Changing view acls to: hadoop
18/01/24 15:54:22 INFO SecurityManager: Changing modify acls to: hadoop
18/01/24 15:54:22 INFO SecurityManager: Changing view acls groups to:
18/01/24 15:54:22 INFO SecurityManager: Changing modify acls groups to:
18/01/24 15:54:22 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(hadoop); groups with view permissions: Set(); users  with modify permissions: Set(hadoop); groups with modify permissions: Set()
18/01/24 15:54:22 INFO Client: Submitting application application_1516806627838_0002 to ResourceManager
18/01/24 15:54:23 INFO YarnClientImpl: Submitted application application_1516806627838_0002
18/01/24 15:54:23 INFO Client: Application report for application_1516806627838_0002 (state: ACCEPTED)
18/01/24 15:54:23 INFO Client:
   client token: N/A
   diagnostics: N/A
   ApplicationMaster host: N/A
   ApplicationMaster RPC port: -1
   queue: default
   start time: 1516809262990
   final status: UNDEFINED
   tracking URL: http://ip-XXX-YY-YY-ZZZ.us-west-2.compute.internal:20888/proxy/application_1516806627838_0002/
   user: hadoop
18/01/24 15:54:23 INFO ShutdownHookManager: Shutdown hook called
18/01/24 15:54:23 INFO ShutdownHookManager: Deleting directory /mnt/tmp/spark-89654b91-c4db-4847-aa4b-22f27240daf7
Command exiting with ret '0'

A: It turns out that the problem was caused by the destination folder already existing (even though empty).  Deleting the output folder makes the example work.
I figured this out by reading the step logs in S3 rather than the instance logs in the EMR console -- in those logs I saw an org.apache.hadoop.mapred.FileAlreadyExistsException which clued me in.
A pre-existing S3 folder isn't a problem for other writing tasks I've done (e.g., PigStorage) so I wasn't expecting this.
I'm going to leave this question up in the (unlikely) event anyone else runs into this.

A: The following add-step worked for me, ran it from the master node:
aws emr add-steps --cluster-id yourclusterid --steps Type=spark,Name=SparkWordCountApp,Args=[--deploy-mode,cluster,--master,yarn,
--conf,spark.yarn.submit.waitAppCompletion=false,--num-executors,2,--executor-cores,2,--executor-memory,1g,s3://yourbucketname/yourcode.py,s3://yourbucketname/yourinputfile.txt,s3://yourbucketname/youroutputfile.out],
ActionOnFailure=CONTINUE


text:
Q: Adding constraint to an association Here is the deal I have a one to many relationship between User and Post
@Entity
public class User extends Model {
...
  @OneToMany(cascade = CascadeType.ALL, targetEntity = Post.class, mappedBy = "author")
  @OrderBy("createdAt DESC")
  public List<Post> posts;
...
}

@Entity
public class Post extends Model {
...
  public int privacy; // 0=public, 1=private
  @ManyToOne
  public User author;
...
}

Works beautifully... Now I want to retrieve the public posts from the users? Of course iterating over the result and deleting the private posts is not an option, I ultimately need to do some pagination, and that would become a headache. Is there some annotation that could help me out with that?

A: Something like this ?
User author = User.findById(1);
int pageNumber = 1;
int pageSize = 10;
Post.find("FROM Post WHERE author = ? AND privacy = 0", author).fetch(pageNumber, pageSize);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ignition 7.8 – Get Component Text From Text Area Within Container Via Scripting A Button with scripting is saving Component values to parameters for a SQL update. The calling button is one level above the Container that holds the Text Area. However, the set for the Text Area value using the recommended User Manual method is throwing the error "AttributeError: 'NoneType' object has no attribute 'text' "
Standard form not working:
Comments = event.source.parent.getComponent('textArea1).text

Also tried different attributes at the end of the call:
… .string , … .value , … .stringvalue
event.source.parent.parent.getComponent('textArea1).text

When looking at the Property Binding path on the Component, I am able to return "Root Container. ContainerName.textArea1.text". When I modified to be a GetProperty pull like below, I received a similar error mixed with an add on of Selected Property Not Found. I tried similar alternatives to those listed above.
Comments = event.source.parent.ContainerName.getComponent('textArea1).text

Any suggestions?

A: The solution is to call the Container component by name using the '.getComponent' method and then call the Text Area using the standard method. The combined code is below for setting to the Parameter Comments.
Comments = event.source.parent.parent.getComponent('ContainerName').getComponent('TextArea1').text

Retrieving a Component value from within a Container does not appear to be covered in the Ignition Manual.


text:
Q: Yet another: git svn not working on OS X Mavericks I've seen a lot of complaints about git-svn not working on Mavericks. I haven't seen my case discussed. I recently (involuntarily) upgraded from 10.7 to 10.9. Things worked fine until the upgrade.  Now git svn clone fails with this error:
W: Filesystem has no item: '/!svn/bc/8534/NavySpear' path not found at /Applications/Xcode.app/Contents/Developer/usr/share/git-core/perl/Git/SVN.pm line 153.

W: Ignoring error from SVN, path probably does not exist: (160013): Filesystem has no item: '/!svn/bc/100/NavySpear' path not found

The svn repository does exits, and I've been careful to avoid typos.
I've got:

*

*git version 1.8.5.2 (Apple Git-48)

*svn version 1.7.10 (r1485443)

*Xcode 5.1.1

Any ideas?
Update
I ended up trying Homebrew.  This worked without any of the tweaks suggested by Google searches.  I guess those tweaks applied to earlier versions.  One thing that I did have to figure out on my own was that by default OS X puts /usr/local/bin behind /usr/bin in the system PATH.  I don't understand the reasoning for that, but there probably is a reason.  At any rate, I had to put /usr/local/bin in front of /usr/bin.  There is more than one way to do that on OS X.  To do it only for yourself, fix it in ~/.bash_profile with
export PATH=/usr/local/bin:$PATH

or equivalent.
To fix it system-wide edit /etc/paths, and move /usr/local/bin from the bottom of the list to the top of the list.
Either way, after making the edits re-load .bash_profile:
source ~/.bash_profile

or open a new terminal session.
For the record, I now have
git version 2.1.0
svn version 1.8.10

A: You need the Xcode command line tools and a link that Apple seems to have forgotten to create:
sudo ln -s /Applications/Xcode.app/Contents/Developer/Library/Perl/5.16/darwin-thread-multi-2level/SVN /System/Library/Perl/Extras/5.16/SVN

Alternatively, you'll need to install SVN from CPAN using:
perl -MCPAN -e'install Git::SVN'

Best of luck and if you have further problems, do leave a comment.


text:
Q: How can I store data using loops I have an assignment

(Find the highest score) Write a program that prompts the user to enter the number
of students and each student's score, and displays the highest score. Assume that
the input is stored in a file named score.txt, and the program obtains the input from
the file.

However we haven't learned how to store data in a .txt file yet so the teacher told us to just treat it as inputs.
What I have so far:
grade = 0

students = eval(input("enter number of students: "))

for i in range(1, students + 1):
    grade = eval(input("enter student score: "))

I understand how to input number of students and store it in to a variable (students).
And I know how to write a loop to repeatedly ask for the input (student score) equal to the number of students
but I don't know how to store each students score separately other than doing it once under the for loop (grade).

A: students = int(input("enter number of students: "))
highest_grade = 0
for i in range(1, students + 1):
    grade = int(input("enter student score: "))
    if grade > highest_grade:
        highest_grade = grade

print("Highest score is {}".format(highest_grade))

I just run and tested. Its working fine

A: Well you can also try using dictionary. Store student names as well as their scores. Then check for the highest score. You code:
students=int(input ("Enter no of students: "))
scores={}
hg=0
for i in range(students):
    name=input("Enter name of student= ")
    score=int(input ("Enter score: "))
    scores[name]=score
    if score>hg:
        hg=score
print("Highest score is ",hg)

Explaination: we'll take input for both name as well as score from user and store it in dictionary. By default, we'll save hg(highest score) as 0. Then while taking user input for score, we'll check whether it greater than hg, if yes, update hg to new score and keep checking it until the loop terminates and finally print it
You do this stuff without dictionary and list, I just suggested dictionary because it can save data in more systematic way showing both name as well as score


text:
Q: Parsing Form action and input name and values using html agility pack I'm trying to parse the form action value and input name with value from the following HTML code:
            <form method="post" action="actionURL" autocomplete="" name="login_form" id="login_form" onsubmit="return hash2(this)">

            <input type="hidden" name=".tries" value="1">
            <input type="hidden" name=".src" value="ym">
            <input type="hidden" name=".md5" value="">
            <input type="hidden" name=".hash" value="">
            <input type="hidden" name=".js" value="">
            <input type="hidden" name=".last" value="">
            <input type="hidden" name="promo" value="">
            <input type="hidden" name=".intl" value="us">
            <input type="hidden" name=".lang" value="en">
            <input type="hidden" name=".bypass" value="">
            <input type="hidden" name=".partner" value="">
            <input type="hidden" name=".u" value="8013sg1858dp9">
            <input type="hidden" name=".v" value="0">
            <input type="hidden" name=".challenge" value="fUhehaaMq9c2lQjndCps_rNu1eSB">
            <input type="hidden" name=".yplus" value="">
            <input type="hidden" name=".emailCode" value="">
            <input type="hidden" name="pkg" value="">
            <input type="hidden" name="stepid" value="">
            <input type="hidden" name=".ev" value="">
            <input type="hidden" name="hasMsgr" value="0">
            <input type="hidden" name=".chkP" value="Y">
            <input type="hidden" name=".done" value="somevalue">
            <input type="hidden" name=".pd" value="ym_ver=0&c=&ivt=&sg=">
            <input type="hidden" name=".ws" id=".ws" value="0">
            <input type="hidden" name=".cp" id=".cp" value="0">
            <input type="hidden" name="nr" value="0">

            <input type="hidden" name="pad" id="pad" value="5">
            <input type="hidden" name="aad" id="aad" value="5">

                Yahoo! ID
                                    <input name='login' id='username' maxlength='96' tabindex='1' value=''>

(e.g. test)

                Password
                <input name='passwd' id='passwd' type='password' maxlength='64' tabindex='2'>

            <input type='checkbox' name='.persistent' id='persistent' tabindex='4' value='y' >

              Keep me signed in

              (Uncheck if on a shared computer)

        <button type='submit' id='.save' name='.save' class='secondaryCta' tabindex='5'>
          Sign In
        </button>

</form>

The above form contains, input type in direct children and beside children of children. While using sample here: https://stackoverflow.com/a/9890022/1007447 code trace on c# finds no elements or Descendants for name "form".
How to get the form action and all input types with value? (sometimes, I need to skip the username password part too)

A: This has been discussed a few times here on Stack Overflow.
The answer is in the same question you are referring to. You have to do:
HtmlNode.ElementsFlags.Remove("form");

var doc = ... //Load the document here

var nodes = doc.DocumentNode.SelectNodes("//form//input");

The key is on the line
HtmlNode.ElementsFlags.Remove("form")

and the explanation of why you need to add it can be found at the following pages:

*

*No child nodes for FORM objects

*How to get all input elements in a form with HtmlAgilityPack


text:
Q: Instagram liked API search with username and media_id I need to find out user has been liked specific media or not
Like I have username and media_id as well as tag, and I need to find user has liked that
media or not
I just wanted search in instagram database using username and media_id
Something like following

https://api.instagram.com/v1/media/555/likes?client_id=45b95681ac624228a40cddca1e087943&username=basedyl
https://api.instagram.com/v1/users/self/media/liked?access_token=38215261.f59def8.e202d307d1d64a70ac134b544eb8da3d&media_id=7007

As I looked into the liked API documentation, there no such option
http://instagram.com/developer/endpoints/likes/
OR
I have also tried https://api.instagram.com/v1/media/555/likes?client_id=ABC
As I see, I need to fetch whole data and then do the array search.. I think which not cool..
Is there any easy way to solve this problem?
thanks in advanced

A: After long trial n error got this:
As I have media_id which I want to checked it liked by user not
and currently logged user access_token, so using following user I am able to find user has like that media or not
Please check description of following params

max_like_id = $media_id //Media ID
count=1 //I just want fetch and check only one media
access_token={$insta_access_token} //it give current user access_token

        $is_liked_url = "https://api.instagram.com/v1/users/self/media/liked?access_token={$insta_access_token}&count=1&max_like_id={$media_id}";

Ref: http://instagram.com/developer/endpoints/users/
GET/users/self/media/liked

A: Just use this: https://api.instagram.com/v1/media/MEDIA_ID?access_token=ACCESS-TOKEN
This will return all information about that media including the user_has_liked key, then check if it is true. I did this is Javascript using ajax so I'm not sure what the php code would be.
http://instagram.com/developer/endpoints/media/

A: I think you need to use Symmetric infinity for doing this.
A sample source code from the above reference..
require 'restclient'
require 'json'
media_url = "https://api.instagram.com/v1/users/self/media/liked/?access_token=ACCESS_TOKEN"
urls = []

while media_url != nil
  response = RestClient.get(media_url)
  json = JSON.parse(response)
 media_url = json["pagination"]["next_url"]
  json["data"].each do |item|
urls << item["images"]["standard_resolution"]["url"]

end

  sleep 0.2

end

urls.each_with_index do |url, idx|
  image = RestClient.get(url)

 path = Dir.pwd + "/#{idx}.jpg"

  File.open(path, 'w') {|f| f.write(image) }

end


text:
Q: Using regular definitions in PLY When I use the following code snippet:-
t_ASD = r'(a|aa*)'

On input aaaaaaaa The output comes out to be:-
LexToken(ID,'aaaaaaaa',1,0)

Which is expected.
But when the same input is run on this code:-
ASD = r'(a|aa*)'
@TOKEN(ASD)
def t_ASD(t):
    return t

The output comes out to be
LexToken(ASD,'a',1,0)
LexToken(ASD,'a',1,1)
LexToken(ASD,'a',1,2)
LexToken(ASD,'a',1,3)
LexToken(ASD,'a',1,4)
LexToken(ASD,'a',1,5)
LexToken(ASD,'a',1,6)
LexToken(ASD,'a',1,7)

What can be the possible reason for this mismatch in output? And how to modify the second code to obtain the output:- LexToken(ID,'aaaaaaaa',1,0)

A: It's evident from the output from your first example that the token is being matched by the ID rule, not the ASD rule. Remember that patterns supplied as functions have priority over patterns supplied as variables. (See the Ply manual.)
Here's my almost minimal test case, without interaction with other rules, which shows that using a pattern variable has the expected result:
import ply.lex as lex
tokens = ['A']
ignore = ' \t\n'
def t_error(t):
    print("Bad char: '%s'" % t.value)
    t.lexer.skip()

t_A = r'(a|aa*)'

lexer = lex.lex()
lexer.input('aaaaaaa')
for token in lexer: print(token)

Output (same output with python2):
$ python3 lexorder.py
LexToken(A,'a',1,0)
LexToken(A,'a',1,1)
LexToken(A,'a',1,2)
LexToken(A,'a',1,3)
LexToken(A,'a',1,4)
LexToken(A,'a',1,5)
LexToken(A,'a',1,6)

It's the expected result because of the way Python regular expressions work. The Python regex engine does not implement longest-match semantics; it prefers earlier alternatives even if their match is shorter.


text:
Q: Jquery data-table : Filter/Search based on select box outside the table I'm using the dataTables jQuery plugin on a table, but I want to add a Filter Column drop-down box before the search box. I see documentation for adding drop-down boxes to individual columns but I want to add just one drop-down box which has all the column names. I am new to this and would greatly appreciate any help. I have added my code below.
HTML:
<select id='mySelector'>
   <option value="">Please Select</option>
   <option value='Name'>Name</option>
   <option value='Highlights'>Highlights</option>
   <option value='Area'>Area</option>
</select>

    @{int rowNo = 0;}

                Item

                @Html.DisplayNameFor(model => model.Name)

                @Html.DisplayNameFor(model => model.Highlights)

                @Html.DisplayNameFor(model => model.Area)

        @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i + 1 }))
        {
            rowNo++;

                    @rowNo.ToString("000")

                    @Html.DisplayFor(modelItem => item.Data.Name)

                    @Html.DisplayFor(modelItem => item.Data.Highlights)

                    @Html.DisplayFor(modelItem => item.Data.Area)

                    @Html.ActionLink("Edit", "Edit", new { id = item.Data.id}) |
                    @Html.ActionLink("Details", "Details", new { id = item.Data.id}) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Data.id})

        }

JS:
  $('#myTable').DataTable();

A: Try this, I add the dropdown option to select which column to search.
var table = $('#example').DataTable({
    dom : 'l<"#add">frtip'
})

$('').text('Search Column:').appendTo('#add')
$select = $('<select/>').appendTo('#add')

$('<option/>').val('All').text('All').appendTo($select);
$('<option/>').val('0').text('Seq').appendTo($select);
$('<option/>').val('1').text('Name').appendTo($select);
$('<option/>').val('2').text('Position').appendTo($select);
$('<option/>').val('3').text('Office').appendTo($select);
$('<option/>').val('4').text('Start Date').appendTo($select);
$('<option/>').val('5').text('Salary').appendTo($select);

$('input[type="search"]').on( 'keyup change', function () {
    var searchValue = $(this).val();
    var columnSearch = $select.val();

    if(columnSearch == 'All'){
        table.search(searchValue).draw();
    } else {
        table.columns(columnSearch).search(searchValue).draw();
    }
});

Here is the demo. for the code above.


text:
Q: Search bots creating issue in web service call through curl I implemented curl code to fetch to live inventory from the vendor web service when any user opens the product detail page.
But search engine bots are accessing the page and this results in curl call to web service 1000 times every second.
How to rectify this issue. I searched over the google but did not find accurate answer yet.

A: At least you should detect User-Agent and IP address when page called. If received arguments matched as bot's data, just don't call to web service and use permanent static data (only for bots).
In addition, you can use tool for human check (captcha etc.): if checking failed, don't call web service.
Also, you can use caching and call web service only for cache update (e.g., once every hour): if data updated less than an hour ago, page should use cached data.


text:
Q: How do I use the index function in Tkinter If I try to programatically reference the index
7.10
The natural round by python inhibits my ability to make reference to the position line 7
 position 10
How would I be able to do this programmatically?
 x = 7.10
output:
>>> 7.1

A: Could you make x a string:
x="7.10"

then split into a dictionary with line and position split out:
dict = {"line": x.split(".")[0], "position": x.split(".")[1]}

output:
{'line': '7', 'position': '10'}


text:
Q: Regex to remove prefix of a pattern (R) I have two strings, S and T. How do I use regex to remove copies of prefixes of T from the end of S?
More specifically, S consists of some characters followed by some copies of T, where the last one may be truncated. For instance, say T is abcdef and S is asdjb|ak.fvajfabcdefabcdefabcdefabc -- then what I would like to get is asdjb|ak.fvajf.
Additionally, S and T may contain characters with special meaning to regex engines, such as .[]*+()\. I'm working in R, but a solution in Java would be fine too.

A: I believe this does it. But it's really long.
S <- "asdjb|ak.fvajfabcdefabcdefabcdefabc"
T <- "abcdef"
want <- "asdjb|ak.fvajf"

sp <- strsplit(T, "")[[1]]
pat <- sapply(seq_along(sp), function(i){
                paste(sp[seq_len(i)], collapse = "")
            })
pat <- paste0("(", paste(pat, collapse = "|"), ")*$")

result <- gsub(pat, "", S)
identical(result, want)
[1] TRUE

If you want to process several vectors, rewrite the above as a function and then use sapply. (Or lapply.)
repl <- function(x, prefix){
    sp <- strsplit(prefix, "")[[1]]
    pat <- sapply(seq_along(sp), function(i){
                paste(sp[seq_len(i)], collapse = "")
            })
    pat <- paste0("(", paste(pat, collapse = "|"), ")*$")
    result <- gsub(pat, "", x)
    result
}

where <- rep(S, 10)
pref <- rep(T, 10)

sapply(seq_along(where), function(i) repl(where[[i]], pref[[i]]))

A: I think you want to do something like this
final String regex = "a(b|(bc|(bcd|(bcde|bcdef))))?$";
String string = "asdjb|ak.fvajfabcdefabcdefabcdefabc";

final Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
int length = 0;
while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    length += matcher.group(0).length();
    matcher = pattern.matcher(string.substring(0, string.length()- length));
}
System.out.println(string.substring(0, string.length()- length));

demo

Output : asdjb|ak.fvajf


text:
Q: Is there an equivalent to imagecolorset for GD from PHP in Perl? I have a transparent image and I would like to change it's color. In PHP this was done by using imagecolorset but I have read through CPAN's doc on GD and I am unable to comprehend how to do it in Perl. (Using fill does not preserve the transparency)
Thank you. :)

A: The nearest equivalent would seem to be colorAllocate.


text:
Q: Concatenating the columns in each row I have a selected range of cells. Need to concatenate all the columns in it and record the result in the first cell of the row (A first column in the selection). I'm trying to write following code
Dim row As Object
Dim col As Object
Dim cell_concat As String

For Each row In Selection
    cell_concat = ""
    For Each col In row
        cell_concat = cell_concat & col.Value
    Next col
    `How to record in first cell?
Next row

But this method unfortunately does not work and I can't figure out how to record cell_concat in the first cell of the row. What am I doing wrong and what to fix in the code?

A: This will concatenate the values into the first cell in each row chosen:
Dim rw As Range
Dim col As Range
Dim cell_concat As String

For Each rw In Selection.Rows
    cell_concat = ""
    For Each col In rw.Cells
        cell_concat = cell_concat & col.Value
    Next col
    rw.Cells(1, 1).Value = cell_concat
Next row


text:
Q: SCRIPT1010: Expected Identifier in IE11 Vuejs Nuxt I am using babel with nuxt js. However, my project not working in IE11. I think babel not transpile my code properly. When i open the developer console i am facing "SCRIPT1010: Expected identifier errors.
As far as i understand there is a spread operator transpile problem.
This is babel part of my nuxt.config.js:
    babel: {
      babelrc: true,
      configFile: './babel.config.js'
    },
    transpile: ['@nuxtjs/axios', 'bootstrap-vue', 'gsap'],

this .babelrc file:
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": [
            "> 1%",
            "not op_mini all"
          ],
          "node": "8"
        },
        "modules": false
      }
    ]
  ],
  "plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ],
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ],
    "@babel/plugin-syntax-dynamic-import",
    [
      "@babel/plugin-transform-runtime",
      {
        "helpers": false,
        "regenerator": true,
      }
    ],
    "@babel/plugin-proposal-object-rest-spread"
  ],
  "env": {
    "test": {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "node": "current"
            }
          }
        ]
      ],
      "plugins": [
        "@babel/plugin-syntax-dynamic-import",
        "dynamic-import-node-babel-7"
      ]
    }
  }
}

and this is babel.config.js file:
module.exports = function (api) {
    api.cache(true);
    return {
        sourceType: 'unambiguous',
        presets: ['@nuxt/babel-preset-app'],
        plugins: ['@babel/plugin-proposal-object-rest-spread']
    };
}

also dependencies:
     @babel/helper-plugin-utils": "^7.0.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.6.2",
    "@babel/polyfill": "^7.6.0",
    "@vue/cli-plugin-babel": "^3.11.0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^24.1.0",
    "babel-preset-env": "^1.7.0",
    "babel-register": "^6.26.0",

i installed almost everything about babel :(
Please help me...
EDIT:
When i back to the default config settings, there is no variance. Also i added screenshot below.


text:
Q: Enable DNS over HTTPS (DoH) when visiting a specific domain I am totally new with this new protocol that is already available in latest Firefox browser but I can not manage it to work on Chrome browser at least in a Windows PC. Now I totally had no idea where to put this question in SO so please understand.
Can I enable DoH feature automatically on Firefox or Chrome in Windows by just visiting a site?
If can not, then can I create a batch script or desktop app instead that will patch/enable DoH to the said browsers?

A: You can enable DNS over HTTPS (DoH) for Google Chrome like this:
1) Type this into address(URL) bar of Google Chrome: chrome://flags/#dns-over-https
2) You will see "Secure DNS lookups" in the opened tab: Click and change from the select box: Enabled/Disabled or Default
3) Done


text:
Q: How to open PDF Blob using browser's PDF viewer rather than downloading? I have an ArrayBuffer of data for a PDF file and I would like to open it using the built-in PDF viewer for the browser.
Here is the code I am using:
const blob = new Blob([pdfBuffer], { type: 'application/pdf' });
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.style.position = 'fixed';
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

This always results in the PDF file being downloaded to the downloads folder on the device rather than opening in a new tab with the PDF viewer in the browser. I have tested this in Chrome, Opera, and Firefox with the same results.
I have done this before when the PDF was actually downloaded from the server itself by just setting the Content-Disposition header in the response, but I am unsure how to do this with a client-side Blob like this.

A: Managed to do it very nicely in combination with pdfMake library.
//Preview PDF
export const previewDocument = (content) => {
  const pdfDocGenerator = pdfMake.createPdf(content);
  // Get PDF blob and open in new window
  pdfDocGenerator.getBlob((blob) => {
    let blobURL = URL.createObjectURL(blob);
    window.open(blobURL);
  });
}

A: You can use window.open() on the result of window.URL.createObjectURL(blob) to open the PDF in a new window instead of downloading it. For example:
var blob = new Blob([pdfBuffer], {type: 'application/pdf'});
var blobURL = URL.createObjectURL(blob);
window.open(blobURL);


text:
Q: this.platform.is("mobile") returning true for browser I am running a ionic project on browser
script
"browser": "ionic-app-scripts serve --sourceMap source-map --iscordovaserve --wwwDir platforms/browser/www/ --buildDir platforms/browser/www/build"

and running npm run browser
I am trying this piece of code in app.component.ts
if (this.platform.is('ios') || this.platform.is('android') || this.platform.is('mobile'))
//execute certain function only on mobile

Problem
this.platform.is('mobile') and this.platform.is('android') is returning true to me in case of browser which is weird behaviour.
So , how to obtain the condition so that on browser i want to disable certain feature and why is the above code not working as expected.
Thanks.

A: There are two approaches i got.
As suggested By Sergey
let isWebApp = this.platform.url().startsWith('http');

Found on the Ionic Forum
!document.URL.startsWith('http');

These are mainly used for development as development process is faster is in browser as changes are reflected instantly.

A: I really don't think you need this but you can use:
 if(this.platform.is('core') || this.platform.is('mobileweb')) {
        // In Browser
      } else {
        // In Mobile
      }

A: If you Enabled Toggle device toolbar from browser, It'll return mobile.
and if it is disabled then return desktop.

You can see it'll return desktop by disabling Toggle device toolbar from the browser:

You have to refresh(f5) the page after changing the state of Toggle device toolbar or it'll not work, because it was cached.

A: Thats some weird behavior of ionic platform. As per the documentation, platform.is('mobile') returns true only on a mobile device.
But
As Ionic is just gonna be used in the mobile devices, not in the browser, i don't think you need the logic to check whether the device is a mobile or not.

A: You can use other way to detect whether your app is web app or a cordova hybrid app:
let isWebApp = this.platform.url().startsWith('http');

In cordova (on device basically) depending on platform the app's "url" will start from "file://" or other but not http.


text:
Q: Can't Get ASP.NET MVC Form To Post I am having problems getting my form to Post to my Save method in a controller. I am new to MVC, and have followed several examples to try to get this to work. Here is my html markup:
    <form action="Edit/Save" method="post">
        <fieldset>
            <legend>Personal Information</legend>

                    First Name:
                    <input type="text" id="txtFirstName" value="<%=user.FirstName %>" name="FirstName" />

                    Last Name:
                    <input type="text" id="txtLastName" value="<%=user.LastName %>" name="LastName" />

                    NT Login:
                    <input type="text" id="txtNtLogin" value="<%=user.NtLogin %>" name="NtLogin" />

                    Hire Date:
                    <input type="text" id="txtHireDate" value="<%=string.Format("{0:d}",user.HireDate) %>" name="HireDate" />

        </fieldset>

        <fieldset>
            <legend>Job Information</legend>

                    Cost Center:
                    <%=Html.DropDownList("CostCenters")%>

                    Manager:
                    <%=Html.DropDownList("Managers")%>

                    Responsibility:
                    <%=Html.DropDownList("Responsibilities")%>

                    Department:
                    <%=Html.DropDownList("Departments")%>

                    Active:
                    <%=Html.CheckBox("Active",user.Active) %>

                    Hire Date:
                    <%=Html.TextBox("txtHireDate",string.Format("{0:d}",user.HireDate)) %>

                    Release Date:
                    <%=Html.TextBox("txtReleaseDate",string.Format("{0:d}",user.ReleaseDate)) %>

        </fieldset>
        <input type="submit" value="Save Changes" />
</form>

This form routes to a Save method in my EditController. Here is the code for my EditController's Save method:
    public class EditController : Controller
    {

        public ActionResult Save()
        {
//Save code goes here
          }

I have tried using the html form tag, and also the Html helper code:
using (Html.BeginForm("Save", "Edit"))

Here is the entry from my RegisterRoutes method in the Global.asax file:
    routes.MapRoute("EditSave", "{controller}/Save",
                    new { controller = "Edit", action = "Save" });

No matter what I do, the submit button does not trigger the Save method. Yet, if I manually key in the Url, The code breaks right into the Save method.
Edit:
Per Craig Stuntz's comment, I checked the source of the page. The page actually contains 2 forms, although only 1 is coded on the page by myself: Here is the HTML that appears prior to my form tag:
<form name="aspnetForm" method="post" action="44" id="aspnetForm">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjM3OTAyNTUzZGQrHhVn9+t78aHxN0vHvKUJ8DQWlQ==" />

                        Placeholder Link

                        Welcome, Test User

            <form action="Edit/Save" method="post">

I didn't think MVC generated viewstate or additional form tags. I am pulling data and populating it into this form using another method from the same controller. Am I doing something wrong here?

A: Ok, got the answer. And thanks Craig for having me look at the HTML again! My master page had generated a form tag in it without my knowing it, so I essentially had nested forms on the same page. After I removed the form from the Master Page, everything worked perfectly.


text:
Q: Functions Defined by Integrals of Non-Elementary Functions In calculus I, I encountered the function $e^{-x^2}$. The teacher told us that it was impossible to integrate. Curious, I graphed the function on my calculator, together with its integral. The integral appeared to be a perfectly ordinary function. I wondered whether this function's integral had any special properties as a function, apart from being impossible to define in terms of elementary functions.
Now, I have encountered many such impossible to integrate functions. Are there any such functions that have special properties apart from being impossible to integrate?

A: They are more or less ordinary functions. For example, consider the function $$f(x)=e^{x^2}\int_0^x{e^{-t^2}\,\mathrm{d}t}$$  Then $$f'(x)=2xe^{x^2}\int_0^x{e^{-t^2}\,\mathrm{d}t}+1$$ So $$f'(x)=2xf(x)+1$$ In other words, this functions is a solution to the differential equation $y'-2xy=1$. The function you mentioned also has the remarkable property that $$\int_{-\infty}^{\infty}{e^{-x^2}\,\mathrm{d}x}=\sqrt \pi$$ Aside from that, there is nothing remarkable per se about functions that cannot be expressed in terms of elementary functions. Many power series, for example, have the same property.


text:
Q: Which of this delete JTable row methods is better? I have two kind of methods to remove JTable selected row.
I create this methods in my GUI Class:
First:
    public void dellAction() {
    if (table.getSelectedRow() > -1) {
        int rowToDelete = table.getSelectedRow();
        int rowToModel = table.convertRowIndexToModel(rowToDelete);
        Object rowId = table.getValueAt(rowToModel, 0);
        try {
            Connection con;
            PreparedStatement ps = null;
            con = DriverManager.getConnection(...);
            ps = con.prepareStatement("delete from table where id=?");
            ps.setObject(1, rowId);
            if (ps.executeUpdate() == 1) {
                model1.removeRow(rowToModel);
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    } else JOptionPane.showMessageDialog(null, "Select A Row");
}

Second:
    public void delete(DefaultTableModel model, int modelRow) {
    if (table.getSelectedRow() > -1) {
        Object rowId = model.getValueAt(modelRow, 0);

        try {
            Connection con;
            PreparedStatement ps = null;
            con = DriverManager.getConnection(...);
            ps = con.prepareStatement("delete from table where id=?");
            ps.setObject(1, rowId);

            if (ps.executeUpdate() == 1) {
                model.removeRow(modelRow);
            }

        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    } else {
        JOptionPane.showMessageDialog(null, "Select A Row");
    }
}

A: The question depends on the context of your application.  In a perfect world, your  TableModel would be modelling data from some kind of factory/controller that was responsible for managing the data, which would read/write to some kind of data source.
This would allow your TableModel the opportunity to simply not care where the data was coming from or going to, only that it had some means of performing these actions.
The same would go for your JTable, it should have no idea about the source of the data, only that the TableModel provides the required contract it needs to fulfill its responsibility.
This, then, raises the question of, who should actually perform what jobs.
In this scenario, I would provide some means for the factory/controller to alert registered listeners to changes.  This would decouple the API in such away that any part of the program would then be able to modify the factory/controller without needing to know about everybody else who might be using that factory/controller, but still be able to react to those changes.
So, my answer would generally be neither...but...your second one comes closest to achieving this, but I'm concerned about the need to extract data from the model in this way, but that's me...
This is, of course, is just my opinion, based on the factory, observer, producer-consumer and model-view-controller patterns


text:
Q: Table: add a column inside a column I need to add one more column to the 4th column and 5th column so that I can put rmse train and rmse validation. Any hint?

This is my actual code:
 \begin{table}[H]
\begin{center}

    \label{tab:table1}
    \begin{tabular}{|c|c|c|c|c|} % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
        \hline
         &  & & \textbf{Movielens 100K} &\textbf{Movielens 1M   }  \\
         $\lambda$ & $\gamma$ & Epochs & rmse & rmse  \\
        \hline
        0.01 & 0.006 & 35 & 0.9385 & \\ \hline
        0.01 & 0.003 & 34 &  & 0.9078 \\
        \hline
    \end{tabular}
\caption{.}
\end{center}
\end{table}

My failed attempt:
    \begin{table}
\begin{center}

    \label{tab:table1}
    \begin{tabular}{|*{7}{c|}  % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
        \hline
        &  & & \textbf{Movielens 100K   } &\textbf{Movielens 1M }  \\
        $\lambda$ & $\gamma$ & Epochs & \multicolumn{2}{c}{ rmse }& rmse  \\
        \hline
        0.01 & 0.006 & 35 & 0.9385 & \\ \hline
        0.01 & 0.003 & 34 &  & 0.9078 \\
        \hline

    \end{tabular}
    \caption{}
\end{center}
\end{table}

A: It is to long for the comment .... Ii suspect that you looking for something like this

but I'm not sure. Please explain in comparison to above table, how should looks your table. MWE for above table is:
\documentclass{article}
\begin{document}
    \begin{table}
\centering
    \caption{}
    \label{tab:table1}
    \begin{tabular}{|*{7}{c|}}  % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
   \hline
            &   &   & \multicolumn{2}{c|}{\textbf{Movielens 100K}}
                            & \multicolumn{2}{c|}{\textbf{Movielens 1M }}  \\
    \cline{4-7}
$\lambda$   & $\gamma$  & Epochs&  rmse     &       & rmse  &   \\
        \hline
0.01        & 0.006     & 35    & 0.9385    &       &       &   \\
    \hline
0.01        & 0.003     & 34    &           & 0.9078&       &   \\
    \hline
    \end{tabular}
\end{table}
\end{document}


text:
Q: Get income call event via Bluetooth I have a phone and a simple site providing a list of numbers and names.
Is it possible to pair my phone with browsers via Bluetooth and pass an incoming number to the site in order to show the name of the caller? If the number isn't listed you have to fill it. So, I want to type using the Desktop browser and receive a call using a phone.
I'm using a web platform to store my client base. I tend to keep it on the web without coding Desktop API.

A: Typically, when you have something like a Bluetooth headset, the headset is a peripheral.
                    central -> peripheral
                  -----------------------
headset model     | phone   -> headset
desktop model (A) | phone   -> browser
desktop model (B) | browser -> phone

(A) is currently impossible with Web Bluetooth because, as of now, Web Bluetooth only supports using the web browser as a central, not a peripheral.
(B) may be possible, but it really depends on the mobile OS.  You would have to introduce special app to replace or augment the phone app on the mobile device so that it would act as a peripheral.


text:
Q: PersistenceUnitLoadingException - Error creating EntityManagerFactory I spent the last days searching for an error, but I'm not able to find it. I have to say that I'm a total newbie to JPA and that this is my first project, which I created following a tutorial but having an unexplained mistake.
I use Eclipse and Eclipselink and connected a runniny mySql-database
My code:
package com.tutorialspoint.eclipselink.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.Employee;

public class CreateEmployee {

    public static void main(String []args){
        EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("tutorialspoint_JPA_Eclipselink");
        EntityManager entitymanager = emfactory.createEntityManager();
        entitymanager.getTransaction().begin();

        Employee e = new Employee();
        e.setId(1201);
        e.setName("Gopal");
        e.setSalary(40000);
        e.setDegree("Technical Manager");
        entitymanager.persist(e);
        entitymanager.getTransaction().commit();
        entitymanager.close();
        emfactory.close();
    }

}

The persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence     http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="tutorialspoint_JPA_Eclipselink" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.tutorialspoint.eclipselink.entity.Employee</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/demo"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="removed"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        </properties>
    </persistence-unit>
</persistence>

And the error:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30005] (Eclipse Persistence Services -     2.6.0.v20150309-bf26070):         org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for     persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@1b1f1f12
Internal Exception: javax.persistence.PersistenceException: Exception         [EclipseLink-28018] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070):     org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [tutorialspoint_JPA_Eclipselink] failed.
Internal Exception: java.lang.NullPointerException
    at     org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSear    chingForPersistenceResources(PersistenceUnitLoadingException.java:127)
    at     org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(P    ersistenceProvider.java:111)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(Persi    stenceProvider.java:183)
    at     javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
    at     javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at     com.tutorialspoint.eclipselink.service.CreateEmployee.main(CreateEmployee.java:1    1)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-    28018]         (Eclipse Persistence Services - 2.6.0.v20150309-bf26070):     org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit     [tutorialspoint_JPA_Eclipselink] failed.
Internal Exception: java.lang.NullPointerException
    at     org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFaile    dPersistenceException(EntityManagerSetupImpl.java:2023)
    at         org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityMana    gerSetupImpl.java:2014)
    at     org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.callPredeploy(JPA    Initializer.java:100)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(P    ersistenceProvider.java:100)
    ... 4 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services -     2.6.0.v20150309-bf26070):     org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit     [tutorialspoint_JPA_Eclipselink] failed.
Internal Exception: java.lang.NullPointerException
    at     org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(E    ntityManagerSetupException.java:231)
    ... 8 more
Caused by: java.lang.NullPointerException
    at     org.eclipse.persistence.platform.server.NoServerPlatformDetector.checkPlatform(N    oServerPlatformDetector.java:28)
    at     org.eclipse.persistence.platform.server.ServerPlatformUtils.detectServerPlatform    (ServerPlatformUtils.java:44)
    at     org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.updateServerPlatform    (EntityManagerSetupImpl.java:973)
    at     org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityMana    gerSetupImpl.java:1718)
    ... 6 more

A: You probably misplaced the EclipseLink jar-file.
The NPE (NullPointerException) stems from line 28 in org.eclipse.persistence.platform.server.NoServerPlatformDetector (see the last Caused by in the error you posted). This line is shown on GrepCode here and shows:
PrivilegedAccessHelper.getClassLoaderForClass(NoServerPlatformDetector.class).toString();
and looking into the PrivilegedAccessHelper.getClassLoaderForClass method shows that the line can be re-written as:
NoServerPlatformDetector.class.getClassLoader().toString();
Now, getClassLoader can return null in which case toString() will cause the NPE. getClassLoader returns null if the EclipseLink jar-file was loaded using the bootstrap classloader (see this wiki-page about the bootstrap classloader). This makes me believe you placed the EclipseLink jar-file in the <JAVA_HOME>/jre/lib directory, or in Eclipse-terms, made it part of the "JRE System Library".
Right-click the project in Eclipse, select Properties, select "Java Build Path", open tab "Libraries", expand the "JRE System Library" (or something similar) and make sure the EclipseLink jar-file is NOT shown. Add the EclipseLink jar-file using the "Add (external) JARs" button (this should ensure the jar-file is loaded using the system classloader instead of the bootstrap classloader).
On a side node, the NoServerPlatformDetector causing the NPE is flawed: the next line shows if (loaderStr != null but this check is redundant since the toString() will never return null. In other words: the programmer was aware that getClassLoader can return null, but forgot that toString() will cause a NPE in this case.

A: thats the right solution. If you put the eclipselink.jar and/or the javax.persistence.jar in a User Library then eclipse cant find the EntityManagerFactory. So you have to remove the user library and put the jar files in the JRE System Library.
Right Click on project > Build Path > Configure Build Path > Java Build Path (Libraries) > Add external Jar > add eclipselink.jar under JRE System Library and voila...

A: In my case, the problem was generated by not using the "annotation" @  in the declarative of the class. In my case, the fields type DATE, dont take the "@Temporal(javax.persistence.TemporalType.DATE)" on the atribute  in the class Java.  When i put this annotation, the problem  finish.


text:
Q: what is the fastest way to join several tables matching specific column values in MySQL I have 3 tables that look like this:
CREATE TABLE big_table_1 (
 id   INT(11),
 col1 TINYINT(1),
 col2 TINYINT(1),
 col3 TINYINT(1),
 PRIMARY KEY (`id`)
)

And so on for big_table_2 and big_table_3. The col1, col2, col3 values are either 0, 1 or null.
I'm looking for id's whose col1 value equals 1 in each table. I join them as follows, using the simplest method I can think of:
SELECT t1.id
FROM big_table_1 AS t1
INNER JOIN big_table_2 AS t2 ON t2.id = t1.id
INNER JOIN big_table_3 AS t3 ON t3.id = t1.id
WHERE t1.col1 = 1
AND t2.col1 = 1
AND t3.col1 = 1;

With 10 million rows per table, the query takes about 40 seconds to execute on my machine:
407231 rows in set (37.19 sec)

Explain results:
+----+-------------+-------+--------+---------------+---------+---------+--------------+----------+-------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref          | rows     | Extra       |
+----+-------------+-------+--------+---------------+---------+---------+--------------+----------+-------------+
|  1 | SIMPLE      | t3    | ALL    | PRIMARY       | NULL    | NULL    | NULL         | 10999387 | Using where |
|  1 | SIMPLE      | t1    | eq_ref | PRIMARY       | PRIMARY | 4       | testDB.t3.id |        1 | Using where |
|  1 | SIMPLE      | t2    | eq_ref | PRIMARY       | PRIMARY | 4       | testDB.t3.id |        1 | Using where |
+----+-------------+-------+--------+---------------+---------+---------+--------------+----------+-------------+

If I declare index on col1, the result is slightly slower:
407231 rows in set (40.84 sec)

I have also tried the following query:
SELECT t1.id
FROM (SELECT distinct ta1.id FROM big_table_1 ta1 WHERE ta1.col1=1) as t1
WHERE EXISTS (SELECT ta2.id FROM big_table_2 ta2 WHERE ta2.col1=1 AND ta2.id = t1.id)
AND EXISTS (SELECT ta3.id FROM big_table_3 ta3 WHERE ta3.col1=1 AND ta3.id = t1.id);

But it's slower:
407231 rows in set (44.01 sec) [with index on col1]
407231 rows in set (1 min 36.52 sec) [without index on col1]

Is the aforementioned simple method basically the fastest way to do this in MySQL? Would it be necessary to shard the table onto multiple servers in order to get the result faster?
Addendum: EXPLAIN results for Andrew's code as requested (I trimmed the tables down to 1 million rows only, and the index is on id and col1):
+----+-------------+-------------+-------+---------------+---------+---------+------+---------+--------------------------------+
| id | select_type | table       | type  | possible_keys | key     | key_len | ref  | rows    | Extra                          |
+----+-------------+-------------+-------+---------------+---------+---------+------+---------+--------------------------------+
|  1 | PRIMARY     | <derived3>  | ALL   | NULL          | NULL    | NULL    | NULL |  332814 |                                |
|  1 | PRIMARY     | <derived4>  | ALL   | NULL          | NULL    | NULL    | NULL |  333237 | Using where; Using join buffer |
|  1 | PRIMARY     | <derived2>  | ALL   | NULL          | NULL    | NULL    | NULL |  333505 | Using where; Using join buffer |
|  4 | DERIVED     | big_table_3 | index | NULL          | PRIMARY | 5       | NULL | 1000932 | Using where; Using index       |
|  3 | DERIVED     | big_table_2 | index | NULL          | PRIMARY | 5       | NULL | 1000507 | Using where; Using index       |
|  2 | DERIVED     | big_table_1 | index | NULL          | PRIMARY | 5       | NULL | 1000932 | Using where; Using index       |
+----+-------------+-------------+-------+---------------+---------+---------+------+---------+--------------------------------+

A: INNER JOIN (same as JOIN) lets the optimizer pick whether to use the table to its left or the table to its right.  The simplified SELECT you presented could start with any of the three tables.
The optimizer likes to start with the table with the WHERE clause.  Your simplified example implies that each table is equally good IF there is an INDEX starting with col1.  (See retraction below.)
The second and subsequent tables need a different rule for indexing.  In your simplified example, col1 is used for filtering and id is used for JOINing.  INDEX(col1, id) and INDEX(id, col1) work equally well for getting to the second table.
I keep saying "your simplified example" because as soon as you change anything, most of the advice in these answers is up for grabs.
(The retraction) When you have a column with "low cardinality" such as your col%, with only 0,1,NULL possibilities, INDEX(col1) is essentially useless since it it faster to blindly scan the table rather than use the index.
On the other hand, INDEX(col1, ...) may be useful, as mentioned for the second table.
However neither is useful for the first table.  If you have such an INDEX, it will be ignored.
Then comes "covering".  Again, your example is unrealistically simplistic because there are essentially no fields touched other than id and col1.  A "covering" index includes all the fields of a table that are touched in the query.  A covering index is virtually always smaller than the data, so it takes less effort to run through a covering index, hence faster.
(Retract the retraction)  INDEX(col1, id), in that order is a useful covering index for the first table.
Imagine how my discussion had gone if you had not mentioned that col1 had only 3 values.  Quite different.
And we have not gotten to ORDER BY, IN(...), BETWEEN...AND..., engine differences, tricks with the PRIMARY KEY, LEFT JOIN, etc.
More insight into building indexes from Selects.
ANALYZE TABLE should not be necessary.

A: For kicks try it with a covered index (a composite of id,col1)
So 1 index make it primary composite. No other indexes.
Then run analyze table xxx (3 times total, once per table)
Then fire it off hoping the mysql cbo isnt to dense to figure it out.
Second idea is to see results without a where clause. Convert it all inside of join on clause

A: Have you tried this:
SELECT t1.id
FROM
(SELECT id from big_table_1 where col1 = 1) AS t1
INNER JOIN (SELECT id from  big_table_2 where col1 = 1)  AS t2 ON t2.id = t1.id
INNER JOIN (SELECT id from  big_table_3 where col1 = 1)  AS t3 ON t3.id = t1.id


text:
Q: Как изменить улучшить код? Есть игра, много персонажей. У каждого есть свои уникальные приемы, например
Бутылка шампанского

1. метнуть пробкой сквозь противника перекручиваясь через себя
2. залить пол алкоголем, заставив противника подскользнуться упасть

или
Варвар

1. Кинуть топор вверх, через секунду топор прилетит в голову сопернику
2. Усыпить соперника рогом шляпы в глаз

Для каждого персонажа для кастомных приемов есть свой класс, в котором есть три метода: beforeAttack, afterAttack, UpdateAttack. Где beforeAttack и  afterAttack вызываются лишь один раз до приема и после, а UpdateAttack обновляется 1 раз в кадр (то есть много). Эти классы наследуются от главного, который и контролирует процесс, примерно выглядит так:
abstract class CommonCustom {

    public virtual void beforeAttack() {}
    public virtual void afterAttack() {}
    public virtual void UpdateAttack() {}

    public virtual void ApplyAll() {
        // тут некое условие, чтоб этот метод вызывался лишь раз!
        beforeAttack();

        // вызывается много раз пока идет прием
        UpdateAttack();

        // тут некое условие, чтоб этот метод вызывался лишь раз!
        afterAttack();
    }
}

Суть проблемы: т.к. у меня есть три метода и у каждого персонажа может быть несколько приемов, то получается так, что в каждом методе я пишу switch/case, например:
class Test : CommonCustom {
    public virtual void beforeAttack() {
        switch attackType {
            case beerAttack: //do smth
                 break;
            case capAttack: //do smth
                 break;
            // и т.д.
        }
    }
    public virtual void afterAttack() {
        switch attackType {
            case beerAttack: //do smth
                 break;
            case capAttack: //do smth
                 break;
            // и т.д.
        }
    }
    public virtual void UpdateAttack() {
        switch attackType {
            case beerAttack: //do smth
                 break;
            case capAttack: //do smth
                 break;
            // и т.д.
        }
    }
}

Можно ли что-то как-то сделать, чтоб не писать в каждом методе swith, а как-то единообразить всё это дело? Может быть как-то добавить еще классы, которые надо имплементировать или еще что-то.

A: Я бы сделал интерфейс IAttack:
public interface IAttack
{
    public void PreAttack();
    public void Attack();
    public void PostAttack();
}

BeerAttack и другие реализуют этот интерфейс:
public class BeerAttack : IAttack
{
    public void PreAttack()
    {
        //специфическая логика пива
    }
    public void Attack()
    {
        //специфическая логика пива
    }
    public void PostAttack()
    {
        //специфическая логика пива
    }
}

Потом вот так:
class Test : CommonCustom {
    public virtual void beforeAttack(IAttack attack)
    {
        attack.PreAttack();
    }
    public virtual void afterAttack(IAttack attack)
    {
        attack.PostAttack();
    }
    public virtual void UpdateAttack(IAttack attack)
    {
        attack.Attack();
    }

A: При любом раскладе вам придется расписать эту пару сотен сценариев, в скриптах ли, классах, кейсах.. Ваша задача найти такой вариант, который будет максимально удобным, с минимумом повторений и возможностей ошибиться, с необходимой вам степенью кастомизации и масштабируемости. Напишите десять сценариев, вычлените все общее. Выберите вариант.

*

*Кейсы, и как их развитие - Полиморфизм
Сделать класс действия, отнаследовать от него классы действий (по типам). Использовать классы действий согласно типам действий прописанным в данных. Удобно кодить, но неудобно настраивать.

*Дата-дривен
Когда вы все действия пропишите в данных игры и будет один класс который будет их выполнять. Достаточно жесткая структура. Что-то среднее межды хардкодом и скриптами (см. ниже)

*Скриптовые языки,
типа Lua. Отличные возможности по моддингу игры и масштабируемости. Не нужно перекомпилировать чтобы изменить какую-то мелочь.


text:
Q: On click play a section of a mp3 I have many buttons playing many different sounds - each button plays a different mp3 when clicked.  Example code:
<audio src="1.mp3"  ></audio>1

For mobile devices I am trying to play all the different sounds from the same mp3 file, so I can preload 1 file and have more instant experience.
So I would need to set the starting point and end point of the mp3 to be played when clicked.
How do I do that using audio html5 or javascript?  Working in just chrome is enough...

A: If i got your question right, you want to play different time stamp of a audio file simultaneously or whenever you want
here is one example which you can use

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:00:00"
       >
</audio>Part 1

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:00:56" >
</audio>Part 2

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:01:00" >
</audio>Part 3

you can also give time in seconds instead of timestamp like

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=0"
       >
</audio>Part 1

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=56" >
</audio>Part 2

<audio id="audio2"
       preload="auto"
       src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t60" >
</audio>Part 3

A: I haven't tested this code, but this should work:
<audio src="1.mp3"  ></audio>1

var canPlay = false;
var audio = document.getElementsByTagName('audio')[0];

document.getElementById('audioTag1').addEventListener('click', function(){
    playAudio(15);
});

audio.addEventListener('canplay', function() { // listen for the `canplay`event, to make sure the file is loaded.
    canPlay = true; // Set a boolean to "true" once the audio has loaded.
});

function playAudio(time){
    audio.currentTime = time; // jump to 15 secs into the file
    audio.play(); // I'm not certain if this line is necessary.
}

Make sure you run the JS code in a onload event listener, so the audio tag is loaded when the code is executed.


text:
Q: Java console application Can you tell me if the console example (Java) below seems correct and how can I test it myself?
http://www.javapractices.com/topic/TopicAction.do?Id=79
I get about 8 errors, starting with:

"Severity and Description Path    Resource    Location    Creation Time   Id The
  method printf(String, Object[]) in the type Console is not applicable
  for the arguments (String, String)    JL1 Console6.java   line
  21    1345812238329   351"

for this line:
console.printf("Welcome, %1$s.", username);

I wrote a lot of applets, they all worked fine, up until I tried this.
Before this I tried a very simple console that read a few words until encountering the word 'bye', and it worked.
My Java version: 1.6.0_33
OS: Windows 7

A: The
main(String... aArgs)

seems to be incorrect.
You can try with
main(String args[])

You may still face problems . You can give the error messages for further answers.


text:
Q: Why is there a margin of the body and not the container? I am having a hard time figuring out why is the margin set on my nav element is being pushed down from the body and not from the parent element the container. In the code below I have a grey background, and white container. When I apply a top margin in my nav the white container gets pushed down and not my nav.
If anyone can help me understand this, I will really appreciate it. Thanks!

html,body{
    background-color: lightgray;
    margin: 0;
    height: 100%;
}
.container{
    background-color: white;
    width: 600px;
    margin: auto;
    height: 100%;
}
nav{
    margin-top:20px;
}

            Nav 1
            Nav 2
            Nav 3

A: This is happening because margins collapse. Similarly borders and padding too. To avoid this collapse you can use one of the following solution:
Solution : 1
Add overflow: auto; OR overflow: hidden; to the container class.
Plnkr DEMO:
http://plnkr.co/edit/9kpcNulpRYyRkUd3HFuJ?p=preview
Stack Snippet:

html,body{
    background-color: lightgray;
    margin: 0;
    height: 100%;
}

.container{
    background-color: white;
    width: 600px;
    margin: auto;
    height: 100%;
    overflow: auto; /* overflow */
}

nav{
    margin-top:20px;
}

            Nav 1
            Nav 2
            Nav 3

Solution : 2
Use Margin and Padding Reset:

html,body{
    background-color: lightgray;
    margin: 0;
    height: 100%;
}

.container{
    background-color: white;
    width: 600px;
    margin: auto;
    height: 100%;
    padding-top: 1px; /* padding and margin resets */
    margin-top: -1px;
}

nav{
    margin-top:20px;
}

            Nav 1
            Nav 2
            Nav 3

A: Your margin is not pushed down from the body but from the from the container with class .container
In the snippet below

*The div with class container has border blue and the nav has border red

* the nav is still in the div which is in the body
Snippet

      Nav 1
      Nav 2
      Nav 3

A: Probably your border is not defined Try defining the border of the container make it sth like
.container { border-style: solid;
 color: White;
 width: (your preferred width);
 height: (your preferred height );
 }

Try it and let me know if it worked. Also before you start your stylesheets it is advisable to use css resets.

A: This happens because sometimes the css rules are just dumb.
Here is a fix.
add this class in the css after your .container class:
 .container::before {
           clear: both;
           content: "";
           display:table;
        }

That should fix the problem. Have a look https://jsfiddle.net/e4k6L2nr/1/

A: I think a lot of people like to start off their style sheet with a css normalizer which I don't believe was explicitly covered here. I got turned onto it while doing some wordpress theme development using underscores.
* {
    margin:0;
}

That's basically all you need. It helps overwrite predefined styles users may have attached to their browsers or other rules you didn't know you set up.
Let me add, the * selector, selects everything. Sometimes I'll also use that area to remove text-decoration and establish a base font-size so I can use em or rem later.

A: From the tests I've done, it seems that the margin property is applied to the parent when the element is the first of the division.
I would encourage you to use the padding property instead.
You can find here some information on the differences between these properties.

A: Try this:

        html,body{
            background-color: lightgray;
            margin: 0;
            height: 100%;
        }

        .container{
            background-color: white;
            width: 600px;
            margin: auto;
            height: 100%;
        }

        nav{
            position: relative;
            top: 20px;
        }

        Nav 1
        Nav 2
        Nav 3


text:
Q: Does OS X have an equivalent to /dev/shm? Does OS X (Snow Leopard in particular) have an equivalent to (some versions of) Linux's /dev/shm , ie something where you can write to and read from a file without necessarily touching the hard drive?

A: You can create and mount a ram based disk as follows:

*

*Create a disk
hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))

hdiutil will return the name of the ramdisk.

*Format and mount the disk
diskutil eraseVolume HFS+ RAMDisk NAME_OF_DISK

*Access the disk under /Volumes/<diskname>
cd /Volumes/RAMDisk && touch testfile.txt && ls

Creating a 100MB ramdisk:
$ hdiutil attach -nomount ram://$((2 * 1024 * 100))
/dev/disk3

$ diskutil eraseVolume HFS+ RAMDisk /dev/disk3
Started erase on disk3
Unmounting disk
Erasing
Initialized /dev/rdisk3 as a 100 MB case-insensitive HFS Plus volume
Mounting disk
Finished erase on disk3 RAMDisk

Original source: http://www.frederico-araujo.com/2008/12/18/blazing-fast-firefox-using-osx-ramdisk/


text:
Q: Php Server: HTTP_X_FORWARDED_SSL usage In OpenCart i saw the following code:
    // Check if SSL
if ((isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) || (isset($_SERVER['HTTPS']) &&    $_SERVER['SERVER_PORT'] == 443)) {
    $_SERVER['HTTPS'] = true;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
    $_SERVER['HTTPS'] = true;
} else {
    $_SERVER['HTTPS'] = false;
}

What is $_SERVER['HTTP_X_FORWARDED_PROTO'] or $_SERVER['HTTP_X_FORWARDED_SSL']? I could't find them in PHP Manual.


text:
Q: HP SmartArray RAID5 recovery on linux This is a long time in the making, and I've finally got it working so I thought I'd share this with as many people as I can in case they're in a similar situation.
Long story short - HP SmartArray P410 failed, got another one (which worked for a while) then also failed. I also had a P200/ZM in there with another array (failed). I was sick of HP by that point, but I needed to recover my array's data - was not even going to consider getting another SmartArray card to copy it off with.
So. After much research, I found that HP employ some painful RAID5 algorithms (called Delayed Parity) that make normal RAID5 recovery methods very, very difficult.
So I wrote my own block driver. This driver (much like md-raid) takes the disks and translates them into a logical drive (array) taking into account HP's bastard algorithms. It's not a proper RAID solution - no paritiy calculations are done, but it should allow you to mount the array and copy it off (as I have now done).
Note: Some knowledge of C and compiling C required, see answers for the download.

A: The source tarball is available from: HERE


text:
Q: Comparison tool (but not monitoring tool !) My university has decided to switch from its CMS Jahia to Wordpress. It results of 40'000 new pages hosted on Wordpress. My work is to find/modify/create a tool to compare the old pages hosted on Jahia and the new ones on Wordpress, in order to find what is missing out.
I did many researchs but only found "monitoring tools", which is not what I'm looking for !
Do you have any recommandation ? Thanks !
(and sorry for my pretty bad english)


text:
Q: Can't convert time to GMT My problem is that I want to convert the local time to GMT. I am able to convert the actual time and save it to Parse but the problem is that Parse applies its own:

Wed Feb 24 10:00:00 GMT+05:30 2016

This is the date that I am getting after converting to GMT00:00 but the problem is the  GMT+05:30 that is actually false as my date is actually in GMT. Now when I put this date in the server it further decreases the time by 5:30 hrs. So how can we change this GMT+05:30 to GMT+00:00

A: We'll start with the current local time.
Calendar cal = Calendar.getInstance(); // automatically produces and instance of the current date/time

As I understand it, your local date is accurate to GMT but your time is 5:30 ahead of actual GMT.
In order to subtract 5:30 from your local time you can perform the following.
cal.add(Calendar.HOUR, -5);
cal.add(Calendar.MINUTE, -30);

System.out.println(cal.getTime());

Conversely, if you would like to add to the time field, you can simply use:
cal.add(Calendar.HOUR, 5); // note I have removed the minus(-) symbol
cal.add(Calendar.MINUTE, 30); // note I have removed the minus(-) symbol

System.out.println(cal.getTime());

A: If you are using java 8. you could utilize from the new time library.
As you tell it seems what you want, is to have a stamp in UTC which is GMT+00
more about time library here
This line:
System.out.println(Instant.now().toString());

gives

2016-02-25T17:54:55.420Z

Hope it makes thing more clear to you.


text:
Q: preparing data for vegan NMDS in R I'd like to run an NMDS and PERMANOVA on subsets of my data using vegan in R. My data contains a lot of zeroes and looks like this:
> str(invert)
'data.frame':   96 obs. of  67 variables:
 $ SampleID                       : Factor w/ 96 levels "11-1-E-1","11-1-E-2",..: 61 62 63 49 50 51 85 86 87 73 ...
 $ SampleDate                     : Factor w/ 8 levels "17-Aug-12","17-Oct-12",..: 1 1 1 6 6 6 2 2 2 4 ...
 $ Year                           : int  2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
 $ Month                          : Factor w/ 4 levels "August","July",..: 1 1 1 2 2 2 3 3 3 4 ...
 $ Habitat                        : Factor w/ 4 levels "epiphyte","pool",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ N                              : num  1429 143 1705 1147 212 ...
 $ S                              : int  6 2 8 9 4 5 6 8 5 5 ...
 $ Aeshnidae                      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Anax                : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Gynacantha          : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Oplonaeschna        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Anisoptera                     : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ant                            : num  0 0 0 0 0 0 0 0 0 0 ...

As you can see, there are four levels of "Habitat". I would like to analyse each habitat separately. I have tried subsetting, but this means I have to do it four times (one for each habitat). Is there a more efficient way of doing it?
This is how I subsetted for the pool habitat:
invert[6:67] <- lapply(invert[6:67], as.numeric)
pool <- subset(invert, Habitat=="pool")

ord <- metaMDS(pool[,7:67],
               k=2,
               trymax = 1000,
               autotransform = TRUE,
               expand = FALSE,
               plot = FALSE)

plot(ord$points[,2],ord$points[,1], type="n",
     main="Communities by month",
     xlab="NMDS 1",
     ylab="NMDS 2",
     xlim=c(-1.5,1.5),
     ylim=c(-1.5,1.5))
ordisymbol(ord, pool, factor="Month", cex=1.25, rainbow=T, legend=T)

#run PERMANOVA;
adonis(pool[,8:67] ~ pool$Month)

A: You should run all the species x sites in a matrix form for your nmds, and then create a group object specifying which rows are from which habitat.
For example, if the first 6 rows of my matrix came from urbanized areas and then the next 6 came from the rain forest I would create a grouping object like this:
habitattypes<-c(rep("Urbanized",16), rep("RainForest",16))
Permanova<-adonis(yourdata^0.25~habitattypes, permutations = 999, method = "bray")


text:
Q: Load object from xml, edit values in a dynamic UI and save back to xml I just read and applied it to the dynamic object on the panel for the container, the label for the title, the textbox for the contents.
but here I can't save it when I fill in the data in the textbox.
this is my deserialize xml code:
string Location= Path.Combine("D:\\Data\\Code.xml");
XmlDocument doc = new XmlDocument();
doc.Load(lokasiString);
foreach (XmlNode node in doc.DocumentElement)
{
    string name = node.Attributes[0].InnerXml;
    string value = node.InnerText;

    // create panel
    Panel panel = new Panel();
    panel.Name = "panelImages";
    panel.Size = new Size((int)(this.Width*0.9), 30);
    panel.Dock = DockStyle.Top;
    panel.BorderStyle = BorderStyle.FixedSingle;

    Label l = new Label();
    l.Text = name;
    l.Font = new Font("Serif", 12, FontStyle.Bold);
    l.ForeColor = Color.Black;
    l.Size = new Size((int)(this.Width * 0.2), 30);
    l.Dock = DockStyle.Left;
    TextBox tb = new TextBox();
    tb.Text = value;
    tb.Font = new Font("Serif", 12, FontStyle.Bold);
    tb.ForeColor = Color.Black;
    tb.Size = new Size((int)(this.Width * 0.9), 30);
    tb.Dock = DockStyle.Left;

    panel.Controls.Add(tb);
    panel.Controls.Add(lt);
    panel.Controls.Add(l);
    flowLayoutPanel1.Controls.Add(panel);
}

and this my Xml Code:
<resources>
    <string name="name">Tap Crush</string>
    <string name="mode">Slow</string>
    <string name="score">12345</string>
</resources>

I have no prior knowledge of parsing Xml with C#.

A: Define model classes and use databinding to edit the model, then you can break the problem to the following pieces:

*

*Defining a Model class containing a List<Resource> and each Resource having Title and Content.

*Write some logic to load model from xml or save model to xml.

*Write a piece of code to arrange UI and setup UI controls to use databinding to your mode.
Then you can easily Load data from xml, edit in the UI and Save data to xml.
Model classes
You can model classes like this:
public class Model
{
    public List<Resource> Resources { get; set; }
}
public class Resource
{
    public string Title { get; set; }
    public string Content { get; set; }
}

Setting up UI
There are different approaches to dynamically show a collection of controls in a form. Here I'll show how you can do that using a DataGridView as well as a TableLayoutPanel:
DataGridView

TableLayoutPanel

Create DataGridView
var dg = new DataGridView();
dg.Dock = DockStyle.Fill;
dg.BorderStyle = BorderStyle.None;
dg.GridColor = Color.Black;
dg.AutoGenerateColumns = true;
dg.EditMode = DataGridViewEditMode.EditOnEnter;
dg.DataSource = model.Resources;
dg.DataBindingComplete += (o, a) =>
{
    dg.RowHeadersVisible = dg.ColumnHeadersVisible = false;
    dg.AllowUserToResizeColumns = false;
    dg.AllowUserToResizeRows = false;
    dg.BackgroundColor = SystemColors.Control;
    dg.Columns[0].ReadOnly = true;
    dg.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    dg.Columns[0].DefaultCellStyle.ForeColor = Color.Black;
    dg.Columns[0].DefaultCellStyle.BackColor = SystemColors.Control;
    dg.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Black;
    dg.Columns[0].DefaultCellStyle.SelectionBackColor = SystemColors.Control;
    dg.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
};
this.Controls.Add(dg);

Create TableLayoutPanel
var tlp = new TableLayoutPanel() { ColumnCount = 2, AutoSize = true };
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
tlp.SuspendLayout();
foreach (var resource in model.Resources)
{
    tlp.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    var lbl = new Label() { AutoSize = true, Margin = new Padding(4) };
    lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
    lbl.DataBindings.Add(new Binding(nameof(Label.Text), resource, nameof(Resource.Title)));
    var txt = new TextBox();
    txt.DataBindings.Add(new Binding(nameof(TextBox.Text), resource, nameof(Resource.Content)));
    txt.Dock = DockStyle.Fill;
    tlp.Controls.AddRange(new Control[] { lbl, txt });
}
tlp.ResumeLayout();
this.Controls.Add(tlp);

Load and Save Model
You can create a class like this:
public class ModelFactory
{
    public Model FromXmlString(string xml)
    {
        return new Model()
        {
            Resources = XElement.Parse(xml).Elements()
                .Select(x => ResourceFromXElement(x)).ToList()
        };
    }
    public string ToXmlString(Model model)
    {
        return new XElement("resources",
            model.Resources.Select(x => ResourceToXElement(x)).ToArray())
            .ToString();
    }
    private Resource ResourceFromXElement(XElement element)
    {
        return new Resource()
        {
            Title = element.Attribute("name").Value,
            Content = element.Value
        };
    }
    private XElement ResourceToXElement(Resource resource)
    {
        return new XElement("string",
            new XAttribute("name", resource.Title),
            resource.Content);
    }
}

Then easily load and save model:
Model model;
ModelFactory modelFactory  = new ModelFactory();
private void loadButton_Click(object sender, EventArgs e)
{
    var xml = @"
    <resources>
        <string name=""name"">Tap Crush</string>
        <string name=""mode"">Slow</string>
        <string name=""score"">12345</string>
    </resources>";

    //Load model from xml
    model = modelFactory.FromXmlString(xml);

    //Setup UI
}

private void saveButton_Click(object sender, EventArgs e)
{
    //Save model to xml
    var xml = modelFactory.ToXmlString(model);
    MessageBox.Show(xml);
}


text:
Q: Is there any difference between "that is it" and "that is what it is" in the sense of it is a fact? Is there any difference between the phrases in the following context.

I couldn't pass the exam. That's what it is.
I couldn't pass the exam. That's it.

What I am trying to say that I didn't pass exam and that is a fact. Nothing can be changed about it.

A: Either phrase will work and generally get your meaning across. There is not any real difference in the meaning.
That said, I think maybe the phrase you are looking for is "it is what it is".

I couldn't pass the exam. It is what it is.

That is a colloquial way of relating that "nothing can be changed about it" (whatever it is). You can use the phrase as an informal way of conveying acceptance about some unfortunate thing that has happened.


text:
Q: How I get common values from two query in a table and join it with another table in MySql? I have two tables. One is orders and another is users. I want run two different query on orders table and want to get the common values and join it with users table.

    orders
    ======
    +----+---------+------------+------------+--------------+
    | id | user_id | receive_id | arrival_id | departure_id |
    +----+---------+------------+------------+--------------+
    | 1  |   1     |     1      |    null    |      5       |
    +----+---------+------------+------------+--------------+
    | 2  |   2     |     1      |      3     |      6       |
    +----+---------+------------+------------+--------------+
    | 3  |   3     |     1      |    null    |      7       |
    +----+---------+------------+------------+--------------+
    | 4  |   1     |     3      |      5     |    null      |
    +----+---------+------------+------------+--------------+
    | 5  |   3     |     3      |      6     |    null      |
    +----+---------+------------+------------+--------------+
    | 6  |   4     |     3      |      7     |    null      |
    +----+---------+------------+------------+--------------+
    | 7  |   1     |     4      |      7     |      9       |
    +----+---------+------------+------------+--------------+

    users
    =====
    +----+---------+
    | id |   name  |
    +----+---------+
    | 1  |  Shaon  |
    +----+---------+
    | 2  |  Rabu   |
    +----+---------+
    | 3  |  Asha   |
    +----+---------+

1st Query..
SELECT DISTINCT user_id from orders where receive_id = 1 and departure_id != 'null'

Its result will be..
1 2 3

2nd Query..
SELECT DISTINCT user_id from orders where receive_id = 3 and arrival_id != 'null'

Its result will be..
1 3 4

I want get common values form those queries

That is ..
1 3

When I Join it to users table then result will be
_id__name__arrival_id__departure_id
 1  Shaon    null           5
 3  Asha     null           7
But now I want to see..
_id__name__arrival_id__departure_id
 1  Shaon     5             5
 3  Asha      6             7
on arrival_id row the value from where
receive_id = 3 there's arrival_id as distinct user_id

I think code will be like bellow. But It's not working.

SELECT DISTINCT user_id from orders where receive_id = 1 and departure_id != 'null'
COMMON
SELECT DISTINCT user_id from orders where receive_id = 3 and arrival_id != 'null'
JOIN users on (users.id = orders.user_id)

A: You will get what you need by putting one query as a subquery for the other.
Something like this,
SELECT DISTINCT user_id from orders
JOIN users on (users.id = orders.user_id)
where receive_id = 1 and departure_id != 'null'
and user_id in (SELECT DISTINCT user_id from orders where receive_id = 3 and arrival_id != 'null')

Hope this helped.

A: SELECT DISTINCT user_id from orders JOIN
users on (users.id = orders.user_id) where receive_id = 3 and
arrival_id != 'null' AND user_id IN (SELECT DISTINCT user_id from
orders   where receive_id = 1 and departure_id != 'null');

You can use this query to fetch records

A: Try this query,
select orders.id, users.id from orders inner join users
on orders.user_id = users.id


text:
Q: LDAP User switches to local user mid session So, what's happening is I have an LDAP server and two clients:

*

*LDAP Server = Ubuntu 16.04 Headless

*Client 1 = Ubuntu Gnome 16.04

*Client 2 = Ubuntu 16.04 (XFCE, Gnome & Unity)

I have it all configured so both clients properly connect and authenticate with the LDAP server. However, during each session on either client, if I try and run something that requires a password prompt (ex: Clicking Unlock on the "Users" window to make changes) all of the sudden, the session is being run as the local admin user as opposed to the LDAP user. To get it to revert back to the LDAP user, typically I have to log out, but a reboot is more frequently required.
When I first login:

After I get password prompt:

I'm trying to understand what's causing the system to switch to the local user and no longer use the LDAP user.
So, the big question is, what's causing the LDAP user session to "end" and then migrate itself over to the local user?


text:
Q: Oracle/SQL -Sales broken out by Months Hello I have created the following query to pull total order by month for a salesMen. while this gets me the data I need for a single salesmen i need to run this for more than just one. what I would like to accomplish is a query that pull for several different salesmen and is broken out by month and the Months being the Columns names(Columns dynamic to months being pulled). Like below.
 SalesMen   -   10-2017     - 11-2017 - 12-2017 - 01/2018
------------------------------------------------------------
Salesmen_1   Month_total(5)    15       300       100
Salesmen_2       100          948       821       684

Current Code:
select (case when region_code in ('123','124') then 'SalesMen_1' else 'N/A' end)SalesMen, to_char(DATE_ENTERED, 'MM-YYYY') as MM_YYYY, Count(ORder_NO) as Month_Total
from ORDERS
where
REGEXP_like (ORder_NO, '^W|^E')
and DATE_ENTERED between ADD_MONTHS(TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, 2), 'YYYY') || '-01-01', 'YYYY-MM-DD'), -3) and TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM')|| '-01', 'YYYY-MM-DD') - 1
and region_code in ('123','124')
group by  to_char(DATE_ENTERED, 'MM-YYYY'),(case when region_code in ('123','124') then 'SalesMen_1' else 'N/A' end)
order by to_char(DATE_ENTERED, 'MM-YYYY') desc

Results:
Current Results Example


text:
Q: Outbound Message & Attachment Is it possible to send an uploaded file (attachment) to an Enterprise Server via an Outbound Message?

A: Even if you could add an attachment to the message you wouldn't be able to use anything in the standard UI to be able to find the appropriate file. Your best bet here would be to use Apex to make the callout to the remote service, activating it either via a trigger on attachment if that's what you're using, or possibly from a VisualForce page where you use an <apex:inputFile> element to facilitate the upload part.
I can't really be more specific without more details but hopefully this will get you headed in the right direction.


text:
Q: Using PHP's mail() - name.com hosting issue my site is hosted on name.com, and to test this I uploaded a simple file called contact.php with this at the top.
<?php

$to = '~~~~';
$subject = 'enquiry from ';
$name = $_POST['name'];
$email - $_POST['email'];
$message = $_POST['message'];

if ($_POST){
mail($to, $subject, $message, $header);
$feedback = "Sent";
}
?>

So, when I click the submit button it sends the mail. Inside a p tag I have echo $feedback, which shows up after I click submit.
The mail does not send? Anything I'm doing wrong here, or do I need to configure my cPanel in some way?

A: Since header is optional and is left undefined, removing it should resolve your issue.

A: You have not set header variable which is optional, there is a typo while setting $email variable, you've use - instead of =
your updated code,
<?php
    $to = 'a@a.com';
    $subject = 'enquiry from ';
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    if ($_POST){
        mail($to, $subject, $message);
        $feedback = "Sent";
    }
?>

A: Be aware that using the $_POST content directly into a email is a security risk for you!
THere are good email libraries that have tools to avoid abuses. (For example: ZendMail, PHPmailer)
Having said that, on your code you are missing the header and have a small mistake on $email = (not -) $_POST['email'];, you can use this:
$header = 'From: from@name.com' . "\r\n" .
'Reply-To: from@name.com' . "\r\n" .
'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
'X-Mailer: PHP/' . phpversion();


text: Q: Unity WebGL build to fullscreen on mobile devices Does anyone know if there is a way to have a working fullscreen button on a browser on mobile devices in WebGL Unity build? I've seen some topics here that it is not supported on mobile devices, but only on tablets. But anyway it is kinda a dealbreaker for us and we need to make this work. Thanks for any response!


text:
Q: Access Network Share folder from IIS 8.5 I am developing web application to access network share folder file and download the file. my application is working properly in development PC, once i publish to the IIS, cannot access the folder path and getting error  " Logon failure: unknown user name or bad password."
This is the sample code i have used to access the folder
WebClient request = new WebClient();
string Directroypath = @"\\192.168.1.20\Sacn_docs\Scan_Old\SCAN CR\";
request.Credentials = new NetworkCredential("admin","pwd","192.168.1.20");

i cant find the proper solution . please help me to solve the issue.


text:
Q: How to apply style to all elements on the same level? I have a table and I need to change the background color of the row after I click on it (as if it was selected). The problem is that I can't change the html, and currently I can change the background color of any .td using .td:focus, but not .tr.
So as a workaround - can I make it so that when selecting one .td:focus I also apply the same style to all .td elements at the same level (child elements of the same parent .tr element)? How can I achieve this?