text:
Q: Connect Multiple nodes for hadoop via ssh on ubuntu We are trying to set-up a two-nodes hadoop clusters on two different machines.
SSH to localhost without password have been setted up on both machines. And hadoop can run well as single node on each individual machine.
We are at the stage of use ssh to connect to each other's server and trying to copy the pub key to each other's .ssh folder.
But the problem is  it seems like we cannot even find the server via the ip :
Here is what I get when i am trying to ssh to the other machine:
ssh -v jingfang@hadoop-master

OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to hadoop-master [192.168.1.52] port 22.
debug1: connect to address 192.168.1.52 port 22: Resource temporarily unavailable
ssh: connect to host hadoop-master port 22: Resource temporarily unavailable

The other machine get similar response when trying to connect to me. We tried to ssh to other public servers like the server at school, we can log into.
When using putty, I can connect to my own machine by using the IP address I provided to the other side, but I cannot ssh to the other side. And the other side can putty to its own in the same way but cannt putty to my machine.
We think either b/c the ssh server configuration is not correct or the net configuration is wrong. Here is my ssh_config
    # This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

Host *
#   ForwardAgent no
#   ForwardX11 no
#   ForwardX11Trusted yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
   CheckHostIP yes
   AddressFamily any
#   ConnectTimeout 0
   StrictHostKeyChecking ask
   IdentityFile /home/hadoop/.ssh/id_rsa
#   IdentityFile /home/hadoop/.ssh/id_dsa
#   IdentityFile /home/hadoop/.ssh/id_ecdsa
#   IdentityFile /home/hadoop/.ssh/id_ed25519
   Port 22
   Protocol 2
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com
#   RekeyLimit 1G 1h
    SendEnv LANG LC_*
    HashKnownHosts yes
    GSSAPIAuthentication yes

And here is my sshd_config:
#       $OpenBSD: sshd_config,v 1.101 2017/03/14 07:19:07 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Port 22
AddressFamily any
ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin without-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
AuthorizedKeysFile      .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

Please suggest whether we should change any ssh/sshd config or network config. Thank you very much !


text:
Q: Scala constructor parameter modifiers I would like to clarify some concepts in scala
class Test(a:Int) {
 def print = println(a)
}

class Test1(val a:Int) {
 def print = println(a)
}

class Test2(private val a:Int) {
 def print = println(a)
}

val test = new Test(1)
val test1 = new Test1(1)
val test2 = new Test2(1)

Now when I try to access a in test, test1, test2.
Scala prints
scala> test.a
<console>:11: error: value a is not a member of Test

scala> test1.a
res5: Int = 1

scala> test2.a
<console>:10: error: value a cannot be accessed in Test2

I understand Integer a is a field of Test1 and Test2. But what is the relationship of Integer a and class Test? Apparently Integer a is not a field of class Test, but it is accessable in print function.

A: The best way to see what's going on is to decompile the resulting Java classes. Here they are:
public class Test
{
  private final int a;

  public void print()
  {
    Predef..MODULE$.println(BoxesRunTime.boxToInteger(this.a));
  }

  public Test(int a)
  {
  }
}

public class Test1
{
  private final int a;

  public int a()
  {
    return this.a; }
  public void print() { Predef..MODULE$.println(BoxesRunTime.boxToInteger(a())); }

  public Test1(int a)
  {
  }
}

public class Test2
{
  private final int a;

  private int a()
  {
    return this.a; }
  public void print() { Predef..MODULE$.println(BoxesRunTime.boxToInteger(a())); }

  public Test2(int a)
  {
  }
}

As you can see, in each case a becomes a private final int member variable. The only difference is in what kind of accessor is generated. In the first case, no accessor is generated, in the second a public accessor is generated and in the third it's private.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need to automatically switch a 12v 1amp dc pulse between 2 alternating outputs I have a control unit that produces two 12v 1amp dc pulses lasting about 200ms.
There is a gap of about 100ms between the pulses
I need to automatically switch these pulses between 2 outputs alternatly.
Any help would greatly appreciated

A: Use a D-flipflop like the HEF4013 to switch between channels.

With each pulse the high level switches between \$Q\$ and \$\overline{Q}\$ and back. AND each output with the input pulse signal. Use the AND gates' outputs to drive MOSFETs like the FDC855.
The HEF4013 is from the older CD4000 series, and normally I would suggest the 74HC74, but that one can't operate at 12 V. The HEF4013 can operate at a power supply voltage up to 15 V.
Don't forget the protection diodes across the solenoids.

A: One solution for this is using multiplexers. A multiplexer is a device that selects one of several analog or digital input signals and forwards the selected input into a single line.

For this i recommend use 74ls157. This is  Quad 2-to-1 Multiplexer.

The operation of the 74LS157, Quad 2 line to 1 line multiplexer is quite simple. It simply acts as four switches. When the A/B input is low, the A inputs are selected. E.g. 1A passes through to 1Y, 2A passes through to 2Y etc. When the A/B is high, the B inputs are selected.


text:
Q: calling web service very slow over https I have a web site from iis. When I call web service from the site it takes < 1 sec
but if i install certificate from global sign and run my site over https
the same web service method takes 40 second.
PS: The problem is not calling the service, the problem is returning data to back. I add some counter point to find out the bottleneck point.
Between call, reach and calculate the response are not important time, but the returning data to page is about 40 sec.

A: Ciphers differ in performance. Try using AES with 128-bit keys and also check if your web server supports AES-NI


text:
Q: EmbedScriptFromFile & RunScriptFromFile - QTP/UFT Please help me in using EmbedScriptFromFile & RunScriptFromFile for executing JS file in QTP/UFT.
I'm trying to fetch N number of values using JS file, and receive the same in QTP/UFT in an array. For which, I have got to know about EmbedScriptFromFile & RunScriptFromFile in QTP/UFT help section. But when I've tried to use the sample code, I couldn't make it as expected. Please help me in this issue
Java Script code I'm using:
function cloneArray(arr) {
          var ret = [];
          for (var i = 0; i < arr.length; ++i)
          ret.push(arr[i]);
       return ret;
 }

VB Script, I'm using:
Browser("Home").Page("Home").EmbedScriptFromFile "C:\Users\Gopi\Desktop\CloneArray.js" 'Call the function and run the script that returns the array'
Set cloned = Browser("Home").Page("Home").RunScriptFromFile("cloneArray(C:\Users\Gopi\Desktop)")

Getting some errors while executing these two line - for first line, I'm getting error as 'Object doesn't support this property or method'. And for the second line, I'm getting error as 'The parameter is incorrect'. Please help

15-Dec-2014: I have tried the suggestions below and it worked! But on top of that, I'm trying to get the array values too from JavaScript function.
Code to create an array:
function makeArray() {
    var myArray = new Array(4);
    for (var i = 0; i < myArray.length; i++){
        myArray[i] = i+1;
    }
    return myArray;
}

So exactly what I'm trying to achieve is, execute makeArray() function to create an array and create the QTP/UFT supporting array using cloneArray method by passing the makeArray() returning value/array as parameter to ConeArray(arr). But when I try to achieve this with following code, I couldn't make it.
Browser("Home").EmbedScriptFromFile "C:\Users\Gopi\Desktop\cloneArray.js"
'Set arr1 = Browser("Home").Page("Home").RunScriptFromFile "C:\Users\Gopi\Desktop\makeArray.js"
Set arr = Browser("Home").Page("Home").RunScript("cloneArray[C:\Users\Gopi\Desktop\makeArray.js]")
For i = 0 To arr.length - 1
    msgbox i & ": " & arr.item(i)
Next

EmbedScript & RunScript are working fine when I try separately, but not able to use while trying to pass another function as parameter.
I have tried to have both the functions in same JS file and call the functions, and tried with a few other possibilities too. But nothing helped, so please help.

A: First of all we should understand the RunScript and EmbedScript functions (and their FromFile variants).

*

*RunScript is a method of Page and Frame and it accepts a JavaScript and executes it, returning the result of the script (typically the last expression run).

*EmbedScript is a method of Browser and it means "make sure that this script is run on all Pages and Frames of this Browser from now on". This function returns no value since its main purpose is to run in the future (although it also runs immediately on the Page and existing Frames currently in the Browser). EmbedScript can be used in order to make a JavaScript function available for future RunScript use.

The plain versions of these functions accept some JavaScript script while the FromFile variation takes a file name (either on the file system or in ALM) and reads that file.
Regarding your question - on your second line you're preforming a RunScriptFromFile but aren't passing a file name, you seem to be passing a script (for this you should be using RunScript). Additionaly the parameter you're passing  to cloneArray is not an a valid JavaScript value.
If you want it to be a string you should put it in quotes, in any case it looks like you're expecting an array so perhaps you meant to do this:
Set cloned = Browser("Home").Page("Home").RunScript("cloneArray(['Users', 'Gopi'])")

In any case it's problematic to pass JavaScript arrays into VBScript, the .length property works fine but indexing into the array is a problem (perhaps due to the fact that JavaScript uses square brackets while VBScript uses parentheses).
A workaround for the array problem could be something like this
// wrapArray.js
function wrapArray(array) {
    return {
        length: array.length,
        item: function(index) {
            return array[index];
        }
    };
}

Then you can use the following in UFT/QTP.
Browser("B").EmbedScriptFromFile "C:\wrapArray.js"
Set arr = Browser("B").Page("P").RunScript("wrapArray(['answer', 42])")
For i = 0 To arr.length - 1
    Print i & ": " & arr.item(i)
Next

Output:

0: answer
  1: 42


text:
Q: How do I deploy Activiti to Tomcat to use an MSSQL database and update the schema on startup? I am attempting to host an Activiti database in MSSQL 2012 via the MS JDBC sqljdbc4.jar driver.  I have setup Activiti 5.14 in JBoss, got fed up, and am starting over with 5.15.1 in Tomcat 7.  So upon deployment and start up of the activiti-explorer.war, it is attempting to upgrade the database schema of my 5.14 activiti database hosted in MS SQL.
The upgrade fails, and the errors show up in the catalina.out log file of the Tomcat server:
05:10:38,962 [localhost-startStop-1] INFO  org.activiti.engine.impl.db.DbSqlSession  - upgrading activiti engine schema from 5.14 to 5.15.1
05:10:38,962 [localhost-startStop-1] INFO  org.activiti.engine.impl.db.DbSqlSession  - Upgrade needed: 514 -> 515. Looking for schema update resource for component 'engine'
05:10:38,963 [localhost-startStop-1] INFO  org.activiti.engine.impl.db.DbSqlSession  - performing upgrade on engine with resource org/activiti/db/upgrade/activiti.mssql.upgradestep.514.to.515.engine.sql
05:10:38,977 [localhost-startStop-1] ERROR org.activiti.engine.impl.db.DbSqlSession  - problem during schema upgrade, statement alter table ACT_RU_TASK
add CATEGORY_ nvarchar(255)
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot find the object "ACT_RU_TASK" because it does not exist or you do not have permissions.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)

Logging in to the database, I see the ACT_RU_TASK table.
What MS SQL permissions does the Activiti database user need in order to perform an in-process database upgrade?  Or, how can I get the Activiti Explorer war to perform the upgrade?

A: Well, I figured it out, in case anyone needs to know the specific MS SQL details...
The MS SQL database user seems to get along just fine with db_datareader and db_datawriter membership in the Activiti database, if you have run the database create DDL scripts manually ahead of starting the Activiti engine for the first time.
Once the engine (apparently in the activity-engine.jar dependency of activiti-explorer.war) decides you need a database schema upgrade, and it has been configured to attempt such a change, the database user will need db_ddladmin membership in the database to perform the alterations.  (Apply base of palm to forehead).
Maybe there is a way to limit the privilege further, but it seems this is better than db_owner.  For production use, and considering zero-downtime change procedure requirements, I'll probably be turning the auto-upgrade feature off.


text:
Q: Convert Bigint to Date in PostgreSQL I have a BigINT column with value for example: 20140130. This needs to be converted to a date column 2014/01/30, so in format yyyy/MM/dd using PostgreSQL.
Please, how can this be done ?

A: Convert the value to a string and then use the to_date() function:
select to_date(20140130::text, 'yyyymmdd');

More details about the to_date() function in the manual: http://www.postgresql.org/docs/current/static/functions-formatting.html
More information about casting values in the manual:
http://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS

converted to a date column ... format yyyy/MM/dd

A date column does not have "a format". Any format you see being applied to a date (or timestamp) column is done by the client application (e.g. psql or any other SQL client).
The result of the to_date() function is  a date which can be formatted to any display you like using the to_char()` function.
select to_char(to_date(20140130::text, 'yyyymmdd'), 'dd.mm.yyyy');
select to_char(to_date(20140130::text, 'yyyymmdd'), 'yyyy/mm/dd');

But formatting dates is better left to the frontend and should not be done in SQL.
You should also seriously consider to fix your table design and use a proper date date column rather than an "encoded" bigint value.


text:
Q: what are the react native libraries that helps you to display some statistics Is there a library for React Native that will help us to see the numbers of how many people for example swiped down until most bottom of FlatList in Newsfeed module or how many times login button is pressed by x users or how many minutes or seconds did people stay in their profile tab ?
Is there any implementation or library that can help us to display these kind of statistical results for React Native apps ?

A: You can use Firebase Analytics. Examine this link.
Basically, after install and import that, create an Analytics object:
let Analytics = firebase.analytics();

Now, you can use any event whatever you want. Just write a code on your onPress method like this:
Analytics.logEvent('EventName','Parameters'}


text:
Q: How to diagnose Windows 7 boot problems? Is there a way in Windows 7 to see some log file on why the system is trying to boot, then after some time reboots itself?

A: As it's not clear what you've tried already, I'll suggest this to start:

*

*Start Windows 7 in Safe Mode

*Check the logs in the Windows Event Viewer for pertinent information
Hope that helps get you going.


text:
Q: What sensor to choose to track human presence indoors? This is a hobby project about home automation. The idea is that of distributed system of cheap microcontrollers that take measurements, communicate, output data and control appliances.
One important task that this system should perform is detect at every room if there are humans inside (awake or asleep distinction would be a over-the-top bonus :) ). I am still at a loss if this is feasible. PIR-s? Webcameras? Microphones? Optical counters at the doors? Ultrasound?
Available processing power per sensor output: 5MIPS of avr instructions (8-bit RISC) for 3 seconds = 15 million instructions.
Typical usage scenario would be:

*

*The apartment is empty (the system should know that).

*The door opens and a group of 4 people enters the hallway. (the system should know that someone is in the hallway).

*Two go to a room (the system should track their path by room, with a lag of no more than several seconds, plus know that there is still someone in the hallway).

*, one of them returns, the other sits on a chair, (the first one is to be tracked. the system should also know in which room is the sitting person).

*In the meantime the rest two wander randomly in a 2 x 2 meter area in the hallway (taking shoes off, hanging coats) (the system should know they are still in that area).

*One goes to another room, turns the radio on and goes to sleep (the system should know that there is a sleeping person there).

*Someone leaves the apartment and returns 10 minutes later (here the only requirement is that the system know that there are still persons inside).

*The three leave (the system should know that there is still someone inside).

*Much later, the sleeper gets up, wanders around for half an hour and then leaves the apartment (the system should track his position by room with a lag no more than several seconds, and know when he leaves that there is now no one inside).

I have no pets.

The same question has been asked and received some nice answers on a sister SE: the question.

A: PIR is good at detecting moving humans.
 If you have a number of them per room you can infer the presence of non mobing humans with reasonable success by tracking people and deciding where they are when they vanish "off the RADAR".
Doppler RADAR modules once common for door openers and now largely replaced by PIRs make excellent movement detectors. You can make your own with relative ease. They also detect moving cats and dogs and flapping curtains etc.
 Detection can be limited to humans by bandpass filtering the output. I'm told that human joints produce articulation frequencies which are unique - especially not found at the same frequency in cats and dogs. I was told tat this is a very reliable people detector.
Ultrasound is liable to be less good than PIR's or RADAR
Other systems you mention may be able to be triggered in a beam counter type role but lack the actual person detection capability of PIR and RADAR.

A: For the extra points: a sleeping person can be detected with a cheap DIY force sensor. Take two stripes of aluminium foil, crumple them a bit. Then roll them to form a capacitor. Use a plastic bag or foil as insulator/dielectric.
Squeeze this under the full weight of the bed/couch base or foot. Then measure the capacity. E.g. make it part of an oscillator circuit and count interrupts, or count the CPU cycles needed to charge it.
It's good enough to detect a pillow being added or removed. It will drift over time, but can detect events reliably: weight added, weight removed, weight shifting around. (Yes I actually do have a log of my sleeping hours.) It won't help if someone decides to sleep on the floor, but it's a start.

A: Especially for a home hobby project I'd probably start with PIR (Passive InfraRed) sensors.  They are cheap and very effective at detecting something warm like a human body moving around.
However, PIR sensors will not detect static warm objects like someone sleeping or sitting still on the couch.  With enough PIR sensors around the place, you can probably infer where people are motionless by where you know there was movement and in what direction.  PIR sensors don't inherently give you direction, but enough of them activated in sequence does.  For example three sensors triggered in sequence in a hallway is a strong clue someone is walking down the hall in that direction.  If you saw motion of someone entering a room and then motion in the room, but nothing at the doorway, then you can make a good guess the person that entered is still inside but motionless.
This system isn't foolproof, but PIR sensors are cheap and remarkably sensitive, so with enough of them I think you can get to quite a useable level.
One thing to keep in mind is that other warm moving things will trigger PIR sensors too, like pets moving about.  If you have a dog, then aiming the sensors so they only see motion a few feet off the floor helps.  Cats jump around a lot, but are smaller, so maybe there is a way to not trigger on cats.  This system will be a lot easier if you know the only warm moving things are humans though.

A: PIRs. I've tested Matsushita/Panasonic NaPiOn PIRs on my previous job, also for home automation, and they worked well. Those were motion detectors, which reacted on changes in the receiver's signal, but you can use presence detectors, which also give a signal if the detector receives a static signal.
I tested with different types of clothing, like a coat over a pullover, and it always detected me from several meters distance, so apparently the radiation from head and hands was already sufficient. So I guess a person sleeping under a blanket will be detected as well (unless maybe she's completely covered by it).

A: I believe that producing a radio signal in the KHz range and latter measuring the interference on the signal detected in a long sensing antenna might work much better and easier!
You may even detect where the human body is through some quadracture signal applied to a trasmit antenna with know resistivity.

A: My solution stands alone as the most simple minded of all possible solutions. I have a motion detecting software package installed on my computer called: Yawcam. This little puppy takes pictures of anything that moves in my apartment through my HP 5210 web camera. Next, I have a barking dog microwave motion detector pointed out my front door.
As a final touch I pasted a small sticker / shipping label on the outside of my front door that reads: Surveillance Camera Inside.

A: Olin Lathrop's answer should be enough but if you add some sound detection sensors with your project this can increase your human presence detection rate.
Try to to detect human voice with sound detection sensors, this can be made another sign of presence detection in a room or hall.
Cheap and sensitive sound detection sensors are available over internet.

A: I was thinking is a good way to detect prescence is using a some electronic design that have the capacity to detect the weight or deformation of the floor in the room to detect the people (obiously diference is some big like 50 kg avrg), only adjusting the room weight before prescence of humans and that would be the master measure comparing with when a human access to the room and then detect by the diference of weight.

A: i think about a scanner , which can count the number of people in a location. we can use a wi-fi scanner for that.
if we want to know , whether there is anybody in a room, place the wi-fi detectors in the corners of the room. scan the area within the detectors using the wi-fi scanner with us, . then it will sence the humans in the room and display the number.


text:
Q: how can i isolate the number from str in the same data set My list
a=['100Dollar','200Dollar','100Euro','300Euro','184pounds','150pounds','10rupee','30rupee']

My code
def data_table(data=a)

    for row in a:
        value=[]

      if 'Dollar' in row:
            print(row[0:])
            price, currency =row.split('D')
            currency=currency.replace('ollar','Dollar')
        value.append(int(price))

A: import re

re.match( '([0-9]+)(.*)','100Dollar').groups()

gives:
('100', 'Dollar')

You can extend this to your list:
[ re.match( '([0-9]+)(.*)',i).groups() for i in a ]

gives:
[('100', 'Dollar'),
 ('200', 'Dollar'),
 ('100', 'Euro'),
 ('300', 'Euro'),
 ('184', 'pounds'),
 ('150', 'pounds'),
 ('10', 'rupee'),
 ('30', 'rupee')]


text:
Q: MySQL - Retrieve last update per day per user I have a hypothetical table "users" with the columns

*

*user_id (auto incremented)

*name

*foo

*bar

*last_updated

This table is updated multiple times per day. How can I query to get the last update, per user, per day, going back X days?
Example Data
1 John a b "2013-01-31 02:01:12"
2 Rich c d "2013-01-31 22:41:12"
3 John e f "2013-01-31 22:01:15"
4 Rich g h "2013-02-01 16:01:12"
5 John i j "2013-02-01 22:21:12"
6 Rich k m "2013-02-01 22:21:12"

Desired Return Set:
2 Rich c d 2013-01-31
3 John e f 2013-01-31
5 John i j 2013-02-01
6 Rich k m 2013-02-01

I am able to get the last updated per user overall with the following query, it's applying it to each day that I am struggling with.
SELECT u1.*
FROM users u1
    LEFT JOIN users u2
    ON (u1.name = u2.name AND u1.user_id < u2.user_id)
WHERE u2.user_id IS NULL

A: Do this by summarizing the data at the date level and then joining back:
select u.*
from users u join
     (select u.nanme, DATE(last_updated) as thedate, MAX(last_updated) as maxlastupdated
      from users u
      group by u.name, DATE(last_updated)
     ) usum
     on u.name = usum.name and
        u.last_updated = usum.maxlastupdated

A: First of all the table name users is very confusing, since these aren't the users but the logins.
Beyond that you're on the right way. You just need to add a comparison on the date in the join.
SELECT u1.*
FROM users u1
    LEFT JOIN users u2
    ON (u1.name = u2.name AND date_format(u1.last_updated, '%Y-%m-%d') = date_format(u2.last_updated, '%Y-%m-%d') AND u1.user_id < u2.user_id)
WHERE u2.user_id IS NULL

See it work in this SQL fiddle.


text:
Q: Invalid LazyInitializationException on collections I've run into a truly frustrating problem and spent several hours trying every which way to sort out. When a collection is lazy loaded on some objects it throws a LazyInitializationException stating there is no session or the session is closed. After taking out the code into a clean console app for testing - I'm convinced the session simply cannot be closed! Here is the code:
    private static ISessionFactory _sessionFactory;

    static void Main(string[] args)
    {
        _sessionFactory = BuildFactory(@"*<ThisIsMyConnectionString>*");
        using (var session = _sessionFactory.OpenSession())
        {
            var allContacts = session.Query<Contact>().Where(x=>x.EmployeeId.HasValue);
            foreach (var contact in allContacts)
            {
                var allServices = contact.EmployeeServices.ToArray();
            }
            session.Dispose();
        }
    }

    private static ISessionFactory BuildFactory(string connectionString = null)
    {
        return Fluently.Configure()
                       .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
                       .Mappings(m =>
                           {
                               m.FluentMappings.Conventions.AddFromAssemblyOf<TableNameConvention>();
                               m.FluentMappings.AddFromAssemblyOf<KioskAdapterConfigMapping>();
                           })
                       .BuildConfiguration().BuildSessionFactory();
    }

And here is my (fluent) mappings:
public ServiceMapping()
    {
        Table("tblServices");
        Id(x => x.Id, "ServiceId");
        Map(x => x.Name);
    }
public ContactMapping()
     {
         Table("tblContacts");
         Id(x => x.Id, "ContactId");
         Map(x => x.EmployeeId);
         HasManyToMany(x => x.EmployeeServices)
             .Table("lnkEmployeeService")
             .ParentKeyColumn("EmployeeId")
             .PropertyRef("EmployeeId")
             .ChildKeyColumn("ServiceId")
             .NotFound.Ignore();
     }

How on earth is the session closed? Some database records do not have any records in the "lnkEmployeeService" table, but all foreign keys are in place and valid. Also the link table does have extra columns and is actually a composite key with other columns, but I don't care about rest of the data.

A: The problem is hidden in the fact, that the EmployeeServices collection is mapped to the Contact by the not-unique value "EmployeeId".
Other words, let's assume three contacts
ContactId, EmployeeId
1        , 1
2        , 2
3        , 2

Now, we instruct NHibernate be ready, to load 3 collections. They will/should/must be unique, for each of the contacts. So in the ISession, they could be kept by their unique identifier. In case of NOT property-ref mapping they would be like:
CollectionId - Collection
1            - the first collection of all Services related to contact with ID 1
2            - the first collection of all Services related to contact with ID 2
3            - the first collection of all Services related to contact with ID 3

But we do have a problem here, because our unique identifier for our collections is
CollectionId - Collection
1            ...
2            ...
2            - here we go... this (collection) or the previous
               must now be removed from a session...
               no way how to load/handle it any more

The key, must be unique, that's the point, even if this is the property-ref. On a bit different place of the documentation, we can see 5.1.10. many-to-one:

The property-ref attribute should only be used for mapping legacy data
  where a foreign key refers to a unique key of the associated table
  other than the primary key.

While this is not explained for <bag> mapping the logic is still the same

A: I think the problem is that you're calling Dispose on an IDisposable that's wrapped in a using block. The using block is the equivalent of writing
var myDisposable = new SomeIDisposableImplementation();
try { ... }
finally
{
    if(myDisposable != null) myDisposable.Dispose();
}

In your code Dispose is called twice. My guess is that's causing the problem but I wasn't able to duplicate the exception in a simple test.


text:
Q: Ionic 2 HTTP.post not send data I has a problem, When I post data to my api server.
My api server didn't get any data, It send from ionic app.
This is my api providers.
import { Injectable } from '@angular/core';
import { HTTP } from 'ionic-native';
import 'rxjs/add/operator/map';

@Injectable()
export class APIProvider {

  constructor() {}

  getProduct(){
    return new Promise(resolve => {
      let header = {"Content-Type": "application/json"}

      let body = {
        "data_1": "1234567890123",
        "data_2": "125615"
      }

      HTTP.post('https://ex.com/api/somethig', JSON.stringify(body), header)
      .then(data => {
        console.log(data.status);
        console.log(data.data); // data received by server
        console.log(data.headers);
        resolve(data);
      })
      .catch(error => {
        console.log(error.status);
        console.log(error.error); // error message as string
        console.log(error.headers);
        resolve(error);
      });
    });
  }
}

In api server (PHP), I try vardump($_POST);/ But it return array(0) {}
Console log
[15:20:15]  console.log: 200
[15:20:15]  console.log: array(0) { }
[15:20:15]  console.log: [object Object]

System information:

*

*Cordova CLI: 6.5.0

*Ionic Framework Version: 2.0.0

*Ionic CLI Version: 2.2.1

*Ionic App Lib Version: 2.2.0

*Ionic App Scripts Version: 1.0.0

*ios-deploy version: Not installed

*ios-sim version: Not installed

*OS: macOS Sierra

*Node Version: v6.9.5

*Xcode version: Xcode 8.2.1 Build version 8C1002

A: Ahhhh, I found the answer.
Just changed "Content-Type": "application/json" to "Content-Type": "application/x-www-form-urlencoded".

A: Try using '@angular/http'.
import { Http, Headers } from '@angular/http';

constructor(public http: Http) {}
let body = { data_1: "1234567890123", data_2: "125615" };

return new Promise((resolve, reject) => {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  this.http.post('https://ex.com/api/somethig', JSON.stringify(body), {headers: headers})
    .subscribe(res => {
      resolve(res);
    }, (err) => {
      reject(err);
    });
});


text:
Q: How to sort attribute options in Magento 2 alphabetically For example, if you have thousands of colors (options) in the color attribute, it becomes a pain to use the drag & drop sorting functionality.
I'd like to override the default sorting (based on option position) to sort by attribute label alphabetically for all attributes.
I did some digging around in core files, but couldn't locate the class or function which does this.
Any ideas where this functionality is inside Magento's core?

A: you can download this module https://github.com/nhutnguyenvu/alphabet-option. It allows you can sort any attributes by alphabet (desc, asc) or position

A: So I have had a development done to make the usability of product attributes with "many" options a lot simpler.
Essentially I have added Sort button, see below.
It takes the list of items and resorts in Alphabetical order.
Before Change

After Selecting Button

After the list is resorted, just hit the save button.
If your interested in code, just message me to work something out.
Regards


text:
Q: Get remote image using cURL then resample I want to be able to retrieve a remote image from a webserver, resample it, and then serve it up to the browser AND save it to a file. Here is what I have so far:
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "$rURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$out = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

$imgRes = imagecreatefromstring($out);
imagejpeg($imgRes, $filename, 70);

header("Content-Type: image/jpg");
imagejpeg($imgRes, NULL, 70);
exit();

Update
Updated to reflect correct answer based on discussion below

A: You can fetch the file into a GD resource using imagecreatefromstring():

imagecreatefromstring() returns an image identifier representing the image obtained from the given data. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

from there, it's pretty straightforward using imagecopyresampled().
Output it using imagejpeg() or whichever output format suits you best.
Make one output with a file name:
imagejpeg($image_resource, "/path/to/image.jpg");

then send the same resource to the browser:
header("Content-type: image/jpeg");
imagejpeg($image_resource);

depending on the image's format, you may want to use the imagepng() or imagegif() functions instead.
You may want to work with different output formats depending on the input file type. You can fetch the input file type using getimagesize().
Remember that you can adjust the resulting JPEG image's quality using the $quality parameter. Default is 75% which can look pretty crappy.


text:
Q: Css visibility hidden I'm trying to create a toggle button through javascript without a button ID and the css element visibility hidden, I have been trying to google it but can't find any good answers, I can only found how you toggle by using style.display but that doesn't work when I use visibility hidden in css. The button name for the toggle button is button2 and the hidden button has Hbutton as the ID.
document.querySelector(button8).addEventListener(click, function () {
  document.querySelector("hiddenbutton").style.visibility = "visible";
});

A: Get the current style, and use a conditional.
document.querySelector(button8).addEventListener(click, function() {
  const button = document.querySelector("hiddenbutton");
  let current = getComputedStyle(button).getPropertyValue("visibility");

  button.style.visibility = current == "visible" ? "hidden" : "visible";
})

A: You can use the computed style to determine whether or not the element is visible.

document.querySelector("button").addEventListener("click", function(){
  let p = document.querySelector("p");
  let visibility = getComputedStyle(p).visibility;
  if(visibility == "hidden")
    p.style.visibility = "visible";
  else
    p.style.visibility = "hidden";
});
p
{
  visibility: hidden;
}

I will disappear

<button>Toggle</button>

A: You can actually do this by toggling through classes which is more simple! Just create a class e.g. .hide and set the visibility to hidden. Whenever you click on the button, the selected button's class will be toggled through the given class(.hide).

document.querySelector('.toggle').addEventListener('click', () => {
  document.querySelector('.myBtn').classList.toggle('hide');
});
.hide {
  visibility: hidden;
}
<button class="myBtn">You See Me!</button>
<button class="toggle">toggle</button>

A: It is very simple:
document.querySelector(button8).addEventListener(click, function () {
  var element = document.querySelector("hiddenbutton")
  if (element.style.visibility == "visible") {
    element.style.visibility = "hidden"
  } else {
    element.style.visibility = "visible"
  }
});


text:
Q: React.js with XUL for Firefox development React.js was designed to work with HTML. How about XUL, sort of HTML? When I tried to run them together I got an error:
Target container is not a DOM element.
Basically I don't see the reason why React.js shouldn't work with XUL. I would like to hear some opinions or suggestions for this subject.

A: React.js tests for the DOM as follows:
var canUseDOM = !!(
 typeof window !== 'undefined' &&
 window.document &&
 window.document.createElement
);

whereas XUL works as follows:

You can get a Window object from a document using document.defaultView.
Assume you have a document loaded in a <tabbrowser>, <browser>, or <iframe> element inside your document. You can use browser.contentDocument to access that document and browser.contentWindow to access the Window object of that document.

References

*

*ReactMount.js

*ReactDOM.js

*geMarkupWrap.js

*ReactDOMComponent.js

*ExecutionEnvironment.js

*MDN: Inner and Outer Windows

*MDN: Working with Windows in Chrome code


text:
Q: NSPredicate subquery over all values of dictionary I have an object with the following layout:
@interface Contact : NSObject
@property (nonatomic, strong) NSString *username;
@property (nonatomic, strong) NSDictionary *emails;
@end

As you can see the emails are modeled by a dictionary with keys which are the email tag and values for the emails themselves (i.e. @{@"home" : @me@home.com"}).
I'm trying to filter a bunch of these by partial match on either username or an email out of potentially many emails each contact might have. But the email subquery is not returning any matches, even if I type in an exact email. I'm not sure where am I messing up the query.
My query looks like this:
NSPredicate *userName = [NSPredicate predicateWithFormat:@"self.username contains[cd] %@", self.searchFieldText];
NSPredicate *email = [NSPredicate predicateWithFormat:@"SUBQUERY(self.emails.allValues, $x, $x contains[cd] %@).@count > 0", self.searchFieldText];
self.activeFilter = [NSCompoundPredicate orPredicateWithSubpredicates:@[userName,email]];

Any thoughts?

A: My belief is you're missing an at-sign: emails.allValues -> emails.@allValues
NSPredicate *userName = [NSPredicate predicateWithFormat:@"username contains[cd] %@", self.searchFieldText];
NSPredicate *email = [NSPredicate predicateWithFormat:@"SUBQUERY(emails.@allValues, $x, $x contains[cd] %@).@count > 0", self.searchFieldText];
self.activeFilter = [NSCompoundPredicate orPredicateWithSubpredicates:@[userName, email]];

A little testing indicates that it should work once that's fixed.


text:
Q: Showing both sides of a coin being flipped using Android standard animation I'm very close to getting a "coin flipping" animation to work, but due to the limitations (bugs?) in the current Animation system - I cannot find a way to show BOTH sides of a coin flipping in the air.
For example, I have the following Animation .XML:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
        <scale
            android:repeatCount="17"
            android:repeatMode="reverse"
              android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:fromXScale="1.0" android:toXScale="1.0"
            android:fromYScale="1.0" android:toYScale="0.0"
            android:pivotX="50%"     android:pivotY="50%"
            android:fillEnabled="true"
            android:fillAfter="true"
            android:duration="60"
        />
        <scale
            android:repeatCount="1"
            android:repeatMode="reverse"
              android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:fromXScale="1.0" android:toXScale="2.0"
            android:fromYScale="1.0" android:toYScale="2.0"
            android:pivotX="50%"     android:pivotY="50%"
            android:fillEnabled="true"
            android:fillAfter="true"
            android:duration="800"
        />
        <translate
            android:repeatCount="1"
            android:repeatMode="reverse"
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:fromXDelta="0%"
            android:toXDelta="0%"
            android:fromYDelta="0%"
            android:toYDelta="-150%"
            android:fillEnabled="true"
            android:fillAfter="true"
            android:duration="800"
        />
</set>

This "fakes" a flipping animation by scaling the coin on the Y-axis and reversing it on a loop.  In combination to this, there's a scale to make the overall animation bigger, while also translating it up and down.  But it is only ever gonna show the one side of the coin.
I tried having two of these animations, each side of the coin, running at the same time, but I cannot find a way to stagger them due to the REPEATCOUNT not working when applied to an AnimationSet.  Otherwise I could introduce some kind of delay after one anim (and before the other one) so they alternate, giving the illusion of a coin flipping.
Does anyone know any way I can tweak this to get the desired result?
I had thought of giving up and doing a frame-based anim (pre-render the flip as frames), but it appears you can't mix Frame & Tween anims, so I'd lose the flip "height" and "distance" effects.
(I have another issue when it comes to the coin landing - e.g. the final result is random, but I'm hoping I can switch in the actual result at the end?)
Thanks in advance!

A: I recently wanted to implement something like this for a project. I finally came up with a solution and the result was good enough. Hope it helps someone else who is trying to achieve the same animation.
I uploaded the result as a gist on GitHub.
For a preview of the animation click here.
For the full android studio project visit our CoinToss repository.

A: I was looking for something like this myself, even with the scaling of the image so it appears the imageview is getting closer to the screen.
I combined your animation with this solution to do exactly what you wanted and its fairly lightweight, missing out the need for multiple views.
https://github.com/Lojko/Booty/blob/master/src/game/booty/BootyGameActivity.java
Changed Location of the Original Link: http://www.jasoncavett.com/2011/05/changing-images-during-an-android-animation/#comments
See the FlipCoin class and how its used, I have an animation already existing (created in the same way as detailed by the link)

A: This code shows the same procedure
http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html


text:
Q: Styling arrow in Select Box I'm creating a dropdown menu box and arrow. It looks good except one thing. I used :focus so when user is on select the box, it will turn to green. Yes, box is turning to green but when I do the same thing for arrow icon, it is not changing. Can someone help me with this?
All help will be appreciated.
I have searched some solution on the internet but could not fix the problem.

input[type=text],
input[type=tel],
input[type=email] {
  width: 100%;
  padding: 5px 5px;
  height: 40px;
  box-sizing: border-box;
  border: 2px solid #A9A9A9;
}

/* user input and dropdown turning to green color when active */

input[type=text]:focus,
input[type=tel]:focus,
input[type=email]:focus,
select:focus,
textarea:focus {
  width: 100%;
  padding: 5px 5px;
  height: 40px;
  box-sizing: border-box;
  border: 2px solid #42AC82;
}

/* dropdown box styling */

select {
  width: 100%;
  padding: 5px 5px;
  height: 40px;
  box-sizing: border-box;
  border: 2px solid #A9A9A9;
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
}

select::-ms-expand {
  display: none;
}

.select-container {
  position: relative;
}

select:-moz-focusring {
  color: transparent;
  text-shadow: 0 0 0 #000;
}

.select-arrow {
  color: #A9A9A9;
  right: 0px;
  top: 7px;
  width: 30px;
  position: absolute;
  display: block;
  z-index: 10;
  margin: 0 0 0 0;
  pointer-events: none;
}

select:required:invalid {
  color: gray;
}

select[value=""][disabled] {
  display: none;
}

Is desicion maker?

      <select name="options" required>
        <option value="" disabled selected>Select an option
        </option>
        <option value="1">yes</option>
        <option value="2">no</option>
      </select>

  </div

A: The reason why you're not seeing the arrow color change is that the arrow icon is not a children or next sibling of select element and there's no CSS selector for previous/ parent element. The way I see it you have two options there:
1) Move you arrow icon after select:
          <select name="options" required>
             <option value="" disabled selected>Select an
             option</option>
             <option value="1">yes</option>
             <option value="2">no</option>
          </select>

Which should you allow to use + (next sibling) selector
select:focus + .select arrow { color: #42AC82 }

2) Use JS to detect select element focus and toggle class select-container element what would allow you to style all child elements as you need

A: Try add some of your css like this part:
input[type=text]:focus ~ span ,
input[type=tel]:focus ~ span ,
input[type=email]:focus ~ span ,
select:focus ~ span ,
textarea:focus ~ span {
    color: red;
}

And transfer your span with icon after select tag like this:

    <select name="options" required>
         <option value="" disabled selected>Select an option</option>
         <option value="1">yes</option>
         <option value="2">no</option>
         </select>


text:
Q: import excel file in JTable using java I want that when button is clicked using JFileChooser, filedialog need to be opened and when excel file is selected it need to be loaded in JTable
can anyone please help how to import excel file into jtable?

A: Here are some use useful links/tutorial for you to use.
Importing Excel (.xls) in Java Swing application
blog
There are a couple of open source libraries which you can use to read an excel file such as Apache POI.
Once you've read your excel file into some data structure, this can be written into a DataModel for a JTable. Alternatively, you could write a custom DataModel which will read dynamically from the excel file, but I'd take the two steps separately and build up the complexity once you understand the excel file reading library you choose.


text:
Q: Using Apache CXF to set up a Soap endpoint - how to get message as simple XML? I am trying to set up a simple SOAP endpoint that can take the SOAP request and put the body on a camel route as XML without making it into a POJO or doing any other conversions.   Everything I have read indicates that PAYLOAD will bring in the payload as a string, but it is actually an
org.apache.camel.component.cxf.CxfPayload

Is there some syntax that will simply bring in a soap body as XML into a camel route?
    from("cxf:?dataFormat=PAYLOAD")
    .to("testBean");

@Handler
public void testThis(Exchange exchange, Message message) {
    System.out.println("here I am");
    String thisBody = message.getBody(String.class);
    System.out.println(thisBody);
}

Error during type conversion from type:
java.lang.String to the required type: java.lang.String with value
org.apache.camel.component.cxf.CxfPayload@3138546a
due java.lang.IllegalStateException: StAXSource(XMLStreamReader) with
XMLStreamReadernot in XMLStreamConstants.START_DOCUMENT or
XMLStreamConstants.START_ELEMENT state

Note that exchange.getIn().getBody() does the same thing - brings in a CfxPayload which I cannot convert to a string without marshal / unmarshal.  I do not want this to be tied to some object, I really just want the XML string. -
My architecture:
embedded Tomcat
Camel 2.16
Spring 4.1.8


text:
Q: Eclipse does not detect Android device Eclipse is not detecting my phone. It's a Samsung Galaxy S2 HD LTE, Android version 4.0.4. Working in Windows 7. I have enabled USB debugging and updated the driver for it, but when I go into Eclipse Run --> Run Configurations --> Target it is not listed.
Not sure if this is relevant but I heard in another thread that the build target for your project has to be <= to the version of your device. If this is the case, all the options here are higher and there doesn't seem to be a way to add another so I'm not sure what to do. Also checked the manifest file to see what the min SDK is. It's 8 (which corresponds to android version 2.2) so that is fine.

I'm wondering if it has to do with "Android" being listed under Other Devices in the Device Manager (as per image below). I'm not even sure what this is. The phone itself says it's already updated, but when I try to update Android it can't find the driver software.
Another issue could be that when I connect the phone to my PC, it lists it as a camera instead of a mobile device, and displays the message "Connected as a camera" on the phone itself. The first time I connected, it also showed some error message about how device was not installed properly, but I haven't seen this message again and so not sure what to do about that, or that stupid Autoplay window that pops up every time I connect.

If you have any ideas please let me know!

A: Check if your Android Composite ADB Interface is correctly installed.
You can refer OEM USB Drivers and Debugging on real device for more details.


text:
Q: Android register for location updates in activity I have a singleton for retrieving location updates in my Android project.
This works fine for when I want to use getters to get values I need.
However, for one of my activities, I need to retrieve location updates as they happen. Is there anyway to "tap" into the singleton to retrieve location updates, and process them as I need to inside of the activity? Or is there someway to broadcast that the location has been updated, and register for broadcast updates similar to what I would do in iOS?
Here is what I have for my singleton:
public class LocationSingleton implements LocationListener {
    //Instance
    private static LocationSingleton mInstance = null;
    private static Context appContext;

    private LocationSingleton(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, MINIMUM_DISTANCE, this);
    }

    public static LocationSingleton getInstance(Context context) {
        if (mInstance == null) {
            appContext = context.getApplicationContext();
            mInstance = new LocationSingleton(appContext);
        }

        return mInstance;
    }

    /*
     ** Location methods
     */
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Log.d("Location", "Provider disabled");
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Log.d("Location", "Provider enabled");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

A:
Is there any way to "tap" into the singleton

Extend your LocationSingleton (bad name btw :) with i.e. listeners so any external code can hook in when it needs live updates. When you receive new location, you just call your listeners. Alternatively (which would be perhaps
cleaner and require less code to write by you) would be to use event bus (like OTTO, GreenRobot's). Your LocationSingleton would then emit event on each location update. If any other code would like to know about that, it'd just subscribe to the bus for particular event and that's mostly it. If unsure, go
with Event Bus solution.


text:
Q: Ignore certain links in the html magnific-popup I need Magnific-popup to bind to only certain links in the HTML. This is so when one linked is clicked it will link out to another website. If the other link is clicked it will enlarge the image.
Right now the link the being clicked that is not wrapped in an image the popup is initialized.
This is the HTML

      Google

This is the jquery
 $(context).find('.field--name-field-gallery-items').once('mfp-processed').each( function() {
        $(this).magnificPopup({
          delegate: 'a',
          type: 'image',
          gallery: {
            enabled: true
          },
          image: {
            titleSrc: function (item) {
              return item.img.attr('alt') || '';
            }
          }
        });
      });

      $(context).find('.field--name-field-gallery-items .field--name-field-url a').each().unbind('click');

How do I stop magnificPopup from binding to the second link?

A: The solution is the following:
$(context).find('.field--name-field-gallery-items').once('mfp-processed').each( function() {
        $(this).magnificPopup({
          delegate: '.mfp-field a',
          type: 'image',
          gallery: {
            enabled: true
          },
          image: {
            titleSrc: function (item) {
              return item.img.attr('alt') || '';
            }
          }
        });
      });

I should have read the api properly


text:
Q: How to retrieve data from an Object in an Array in Vue.js I have an Array with an Object with multiple Objects in them with the use of Vue.js.
See it like this:
tree: [{
  stick: {
    leaf:{
      name: "Vincent"
    },
    sheet:{
      name: "Charles"
    },
    paper:{
      name: "Harry"
    }
  }
]}

Now my question is: How do I reach the name of a leaf?

A: This could not work. You set the leaf property multiple times which is not supported. I assume you would do something like:
var myvar = {stick: [
  {leaf: {name: "Vincent"}},
  {leaf: {name: "Charles"}},
  ...
]};

console.log(myvar.stick[0].leaf.name);

A: You'd want tree[0].stick.leaf.name with the data you have.


text:
Q: How do I get the dereferenced type of a pointer type in a template? Like this:
template <typename Tptr>
struct Test
{
    Test(Tptr) {}
    typedef decltype(*Tptr) T;
    T dereferencedType;
};

int i;
Test t(&i); // t.dereferencedType is type int

I'm looking to get the type of *Tptr dereferenced.


text:
Q: Null values inside FOREACH loop in R I need a help to fix errors in my code. Below I provide the reproducible example. The first problem is that all entries of xySL are null. However, the same code works fine if I use simple for loop. The second problem refers just to this example (I don't have this issue in my original code) - data cannot be extracted from data[[i]]$x.
  library(sp)
  library(maptools)
  library(foreach)
  library(doParallel)

  x1 <- c(1,4,5,3,2)
  y1 <- c(2,5,3,6,7)
  x2 <- c(4,4,6,3,2)
  y2 <- c(8,5,2,6,1)

  data<- vector(mode = "list", length = 2)
  data[[1]] <- cbind(x1,y1)
  data[[2]] <- cbind(x2,y2)

  xySL <- vector(mode = "list", length = 2)
  foreach(i=1:2, .packages = "sp") %dopar% {
    xy <- cbind(data[[i]]$x,data[[i]]$y)
    xy.sp = sp::SpatialPoints(xy)
    spl <- sp::SpatialLines(list(Lines(Line(xy.sp), ID=i)))
    xySpatialLines <- vector(mode = "list", length = 2)
    xySpatialLines[[1]] = spl
    spl90 <- maptools::elide(spl, rotate=90)
    xySpatialLines[[2]] = spl90
    xySL[[i]] <- xySpatialLines
 }

  print(xySL[[1]]) # NULL !!!


text:
Q: Create master-detail page using PHP I want to create a master-detail page using PHP. Rather than getting data from a MYSQL database, I want to get the data from an associative array. Is this possible?
The data will first be obtained from the mysql database table and stored inside an associative array for some processing. Now I want to create a master detail page based on the data inside the associative array alone. Anyone with Ideas?

A: It's just impossible, due to PHP nature.
PHP script being run for a fraction of second and then dies. With all it's variables and associative arrays and other stuff.
That's why a database intended to be data storage between distinct HTTP calls.
Thus, don't pretend to be a smartmass, let the things go natural way:

*

*one page that queries database for the list of data, with typerlinks to detail page, passing unique record id via HTTP GET query string

*one details page that queries database for the details, based on passed id.

here is a very basic example of such application, using templates, to give you an idea:
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
  $name = mysql_real_escape_string($_POST['name']);
  if ($id = intval($_POST['id'])) {
    $query="UPDATE $table SET name='$name' WHERE id=$id";
  } else {
    $query="INSERT INTO $table SET name='$name'";
  }
  mysql_query($query) or trigger_error(mysql_error()." in ".$query);
  header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
  exit;
}
if (!isset($_GET['id'])) { //listing part:
  $LIST=array();
  $query="SELECT * FROM $table";
  $res=mysql_query($query);
  while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
  include 'list.php';
} else { // form displaying part:
  if ($id=intval($_GET['id'])) {
    $query="SELECT * FROM $table WHERE id=$id";
    $res=mysql_query($query);
    $row=mysql_fetch_assoc($res);
    foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
  } else {
    $row['name']='';
    $row['id']=0;
  }
  include 'form.php';
}
?>

details page template called form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>">

<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit">

Return to the list
</form>

and main page template called list.php
Add item
<? foreach ($LIST as $row): ?>

<a href="?id=<?=$row['id']?>"><?=$row['name']?>
<? endforeach ?>

this is example of admin page, letting you add and edit records.
however, the page tat just shows the data will be pretty much the same.

A: If you are, for example, displaying a list of summary data and you want to dynamically show the details for a particular record, you can use javascript (jQuery is a nice library that makes dealing with javascript easier).
Depending on the number of records you display on your summary page, you can either

*

*pull all the data (master and detail) from the database, output it with PHP and then hide the detail with javascript

*pull only the master data from the database, output it with PHP, and  then do an AJAX request for the detail data when the user asks for it.

In neither case will you maintain all your data in memory.


text:
Q: python + parse.com upload data if broken internet connection I use a script with an infinite loop to upload sensor data to parse.com. I use
batcher.batch_save(myDataPoints)

to upload the data.
The problem is if the computer where the script runs (a raspberry pi) looses the internet connection, the scipt will exit on an error because the batcher can't reach the parse api.
how can I avoid this? If there is no internet connection, I would like the program to execute some code and keep looping, but NOT to exit on an error.
thanks.

A: def spinner(newList):
    count = 0
    while connection_is_bad:
        count +=1
    x= uploader(newList)

If your data is a list I think it gets easier
def uploader(someList):
    last_value = ''
    while connection_is_good:
        for item in someList:
            do some uploading
            last_value = item

        return something
    newList = someList[someList.index(last_value) + 1:]
    x = spinner(newList)

Here is my thought about some pseudo-code.  I can imagine a number of ways to keep track of the data being transferred but not completely sure until I saw how it was collected

A: If you just want to keep going after you get an error you can just use try...except, e.g.
while True:
    try:
        upload_function()
    except Exception:
        pass

This should catch your exception and instead of exiting out of your while loop, just continue on. You can put whatever you want to do there, you don't have to just leave it as pass.


text:
Q: Send 10 message through send() while receive more message through recv() server.c
if (retSize == -2)
{
    if (send(client_sock, buf, BUF_SIZE, 0) == -1)
    {
        close_socket(client_sock);
        close_socket(sock);
        fprintf(stderr, "Error1 sending to client.\n");
        return EXIT_FAILURE;
    }
    printf("You have sent %d msg\n", ++cntOfMsg);
    printf("The msg is:\n %s\n", buf);
    printf("------------\n");
}
else
{
    if (send(client_sock, ret, BUF_SIZE, 0) == -1)
    {
        close_socket(client_sock);
        close_socket(sock);
        fprintf(stderr, "Error2 sending to client.\n");
        return EXIT_FAILURE;
    }
    printf("You have sent %d msg\n", ++cntOfMsg);
    printf("The msg is:\n %s\n", ret);
    printf("------------\n");
}

client.c
while ((bytes_received = recv(sock, buf, BUF_SIZE, 0)) > 1)
{
    buf[bytes_received] = '\0';
    printf("You have received %d msg\n",++cnt);
    fprintf(stdout, "Received:\n%s\n", buf);
    printf("-----------\n");
    memset(buf,0,sizeof(buf));
}

Part of the output is as shown below:

NOTICE:
output like "Can't write error_log" or "syntax error" have nothing to do with the problem.Your can  believe the code I show is the only place where send or recv.

A: TCP send can segment the data however it wants.  If you send small buffers, TCP can group them and send them as a single packet after a timeout or a pending ack is received.  If you send large buffers, TCP can break them into a series of smaller packets, favoring TCP segmentation over IP fragmentation.
TCP recv can theoretically return only 1 byte, even if you think there should be more data waiting.
When using TCP to send records, you need to use a record layer that prepends each record with its length (say, a 32-bit integer in big-endian order).  The receiver must then accumulate a length (which could theoretically dribble in 1 byte at a time), and then accumulate the record content described by that length.  The receiver ping-pongs between accumulating a length and accumulating record content.
In a line-oriented protocol, you could use a newline character to delineate record boundaries.  It's really up to you to decide how to indicate boundaries within the TCP byte stream.

A: On each recv(), you are just incrementing the cnt variable and printing, it doesn't represent the number of bytes received. Try printing the bytes_received instead.
In the same way, in the send() part, print the return value of send() call instead of cntOfMsg


text:
Q: Splitting up a Spring Controller by mapping a sub-path to a different controller I am trying to split up a spring controller that has become rather bloated.  The main controller, FooController, is mapped to "/foo".  As FooController has grown, several handlers to the sub mapping "/foo/bar/" have emerged.  It feels like these "/foo/bar" calls should be handled by a different controller because of all the features being added.
I am using spring 4 and here's a code example of what I am trying to do:
@Controller
@RequestMapping(value="/foo/")
public class FooController {
// ...
}

@Controller
@RequestMapping(value="/foo/bar"")
public class BarController {
// ...
}

I am not able to receive requests to /foo/bar/.  Is this not possible with spring, or I am missing something?
I have set up the spring-servlet to be able to scan the BarController.
Because of backwards compatability issues with mobile clients, I am not able to simply add a BarController mapped to "bar/".  I can of course do so with future APIs, but I'd love to group all the APIs together if possible.

A: You can have nested URL's in the same FooController
@Controller
@RequestMapping(value="/foo")
public class FooController {

    @RequestMapping(value = {"/bar"}, method = {RequestMethod.POST})
    public ModelAndView someOperation(....){

    }
}


text:
Q: Problems working with decimal type in .NET I'm having a bit of a curious problem with .NET and working with the decimal type. My web application uses the following globalization settings:
<globalization culture="auto" enableClientBasedCulture="true"/>

With that in mind, consider the following: the decimal value 123.00 becomes £123.00 in GBP, and EUR 123,00 (note the comma). The problem I'm having appears when I want to go from a decimal value of 123,00 (EUR) back to GBP again, as it becomes 123,000 - which is a huge problem.
In this scenario, my application has consults a look up table based on the detected culture and shows prices in that currency. The problem only arises when the user has made a selection and the data is prepared for sending to our payment gateway, which convers the EUR 123,00 to 123,000.
Any ideas how I can overcome this?

A: Maybe this could help you
        NumberFormatInfo ni = new NumberFormatInfo();
        ni.NumberDecimalSeparator = '.';

usage i.e.
        Double.Parse(MyString, ni)

-rAyt
Don't know any better way to detect the format, but take a look at this
    static void Main(string[] args)
    {
        // German Format (EUR)
        CultureInfo ci_de = new CultureInfo("de-DE");

        // English Format (GBP)
        CultureInfo ci_gb = new CultureInfo("en-GB");

        string test_de = "1.234.567.890,12";
        string test_en = "1,234,567,890.12";

        double result_de = 0.0;
        double result_en = 0.0;

        try
        {
            result_de = Double.Parse(test_en, ci_de.NumberFormat);
        }
        catch (FormatException ex)
        {
            Console.WriteLine("Number isn't a german format " + ex.InnerException);
        }
        try
        {
            result_en = Double.Parse(test_en, ci_gb.NumberFormat);
        }
        catch (FormatException ex)
        {
            Console.WriteLine("Number isn't a english format " + ex.InnerException);
        }

        Console.WriteLine(result_de.ToString());
        Console.WriteLine(result_en.ToString());

        Console.ReadLine();
    }

A: The decimal data type basically just holds a number--there is no formatting implicitly applied to it. The value of a number won't change just because it's being displayed in a different format.
Likely, the problem that you're likely having is when you receive the input as a string from a web page, you are parsing it incorrectly.

A: Thanks to everyone who offered their experience and suggestions.
Implementing a custom-type/structure for holding my own Decimal values wasn't really what I was after, and wouldn't really give me the functionality I needed (I can already display decimal values in the appropriate local currency/format, I just couldn't convert them back into UK format when required).
The problem was this line in the web config:
<globalization culture="auto" enableClientBasedCulture="true"/>

Setting culture = "auto" was allowing .NET to set the locale according to the values provided by the browser (incidentally, by the way, 'enableClientBasedCulture' is not implemented, according to MSDN - so you can omit it). Hence, if a visitor from France (with language 'fr-FR' configured in their browser) visited our site, all the number formatting would work perfectly (correct decimal separator and currency symbol) but I'd have a problem later when trying to conver that number from it's European format to the UK/US format I required.
It's odd, but converting "123.00" to the 'fr-FR' locale produces a FormatException because "123.00" is not valid in the French locale (it expects "123,00"). But, converting "123,00" (fr-FR) to the UK/US 'en-GB' or 'en-US' format does NOT produce an error, but instead the value becomes "123,000". I believe this should throw a FormatException because it is not acceptable to add another zero.
The solution I implemented was as follows:

*

*Set culture="auto" to culture="en-GB" in  web.config.

*Use Decimal.ToString("c", ni) - where 'ni' is custom NumberFormatInfo class.

Since my existing code connects to our data source to retrieve the correct decimal values dependant on country, all I had now was a formatting issue. So, to format a number according to the 'fr-FR' locale, you can do:
NumberFormatInfo ni = Globalization.CultureInfo.GetCultureInfo("fr-FR").NumberFormat;
Decimal.ToString("c", ni);

In this setup, all my decimal values (internally) are always treated as en-GB decimals, and thus in the format I require. In other words, my application did not require the flexibility of being able to change the settings that apply to the entire current thread; rather just the opposite: I only cared about formatting the values differently.

A: rAyt has offered a good start, but if you are working with a variety of cultures, it could become very difficult to automatically detect which culture a decimal number is. To ensure that you always know, it might be best to create a simple wrapper type around decimal that includes the culture. You would need to update your data store to also store the culture code (i.e. en-US) so that when reconstituting data you don't "forget" what culture the data was saved as. Any entities you have would use your decimal wrapper type, rather than decimal directly, and that type could have an overridden ToString method to automatically render in the correct format:
public struct CulturedDecimal
{
    public decimal Value;
    public CultureInfo Culture;

    public override ToString()
    {
        return Value.ToString(Culture);
    }
}

public class SomeEntity
{
    public int ID { get; set; }
    public CulturedDecimal MonetaryValue { get; set; } // Was 'decimal' before
}


text:
Q: How to restrict an any type inside a choice group in XML schema? I want to redefine/restrict a complex type from the Oasis XML DSig schema.
xmldsig-core-schema.xsd
<complexType name="TransformType" mixed="true">
   <choice minOccurs="0" maxOccurs="unbounded">
      <any namespace="##other" processContents="lax"/>
      <!-- (1,1) elements from (0,unbounded) namespaces -->
      <element name="XPath" type="string"/>
   </choice>
   <attribute name="Algorithm" type="anyURI" use="required"/>
</complexType>

I only want to allow one explicit element type from an ##other namespace.
xmldsig-restricted.xsd
(1) This does work:
<xs:redefine schemaLocation="xmldsig-core-schema.xsd">
   <xs:complexType name="TransformType">
      <xs:complexContent>
         <xs:restriction base="ds:TransformType">
            <xs:choice minOccurs="1" maxOccurs="1"> <!--diff-->
               <xs:element name="XPath" type="xs:string"/>
           <!--<xs:any namespace="##other" processContents="lax"/>-->
            </xs:choice>
            <xs:attribute name="Algorithm" type="xs:anyURI" use="required"/>
         </xs:restriction>
      </xs:complexContent>
   </xs:complexType>
</xs:redefine>

(2) This does also work:
<xs:redefine schemaLocation="xmldsig-core-schema.xsd">
   <xs:complexType name="TransformType">
      <xs:complexContent>
         <xs:restriction base="ds:TransformType">
            <xs:choice minOccurs="0" maxOccurs="unbounded">
           <!--<xs:element name="XPath" type="xs:string"/>-->
               <xs:any namespace="##other" processContents="lax"/>
            </xs:choice>
            <xs:attribute name="Algorithm" type="xs:anyURI" use="required"/>
         </xs:restriction>
      </xs:complexContent>
   </xs:complexType>
</xs:redefine>

(3) This does NOT work:
<xs:redefine schemaLocation="xmldsig-core-schema.xsd">
   <xs:complexType name="TransformType">
      <xs:complexContent>
         <xs:restriction base="ds:TransformType">
            <xs:choice minOccurs="1" maxOccurs="1"> <!--diff-->
           <!--<xs:element name="XPath" type="xs:string"/>-->
               <xs:any namespace="##other" processContents="lax"/>
            </xs:choice>
            <xs:attribute name="Algorithm" type="xs:anyURI" use="required"/>
         </xs:restriction>
      </xs:complexContent>
   </xs:complexType>
</xs:redefine>

Error:
cos-particle-restrict.2: Forbidden particle restriction: 'choice:all,sequence,elt'.

(4) This (the desired definition) does also NOT work:
<xs:redefine schemaLocation="xmldsig-core-schema.xsd">
   <xs:complexType name="TransformType">
      <xs:complexContent>
         <xs:restriction base="ds:TransformType">
            <xs:choice minOccurs="1" maxOccurs="1"> <!--diff-->
           <!--<xs:element name="XPath" type="xs:string"/>-->
           <!--<xs:any namespace="##other" processContents="lax"/>-->
               <xs:element name="InclusiveNamespaces" type="ec:InclusiveNamespaces"/> <!--diff-->
            </xs:choice>
            <xs:attribute name="Algorithm" type="xs:anyURI" use="required"/>
         </xs:restriction>
      </xs:complexContent>
   </xs:complexType>
</xs:redefine>

Error:
rcase-RecurseLax.2: There is not a complete functional mapping between the particles.

(1) shows that the restriction of choice is OK
(2) shows that the usage of only the any type is OK
(3) shows that there must be a special behavior when any and choice are combined, maybe regarding the namespaces?
(4) looks like the given element is not a subset of the any type (which is not true)
The behavior of (3) is also implied by the original schema which has these comments for choice and sequence:
<choice minOccurs="0" maxOccurs="unbounded">
   <any namespace="##other" processContents="lax"/>
   <!-- (1,1) elements from (0,unbounded) namespaces -->
</choice>

<sequence>
   <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
   <!-- (0,unbounded) elements from (1,1) external namespace -->
</sequence>

So what does this mean and how has the restriction to be defined?
EDIT
(2)/(3) The restriction is also OK, when setting choice to either minOccurs=0 maxOccurs=1 or minOccurs=1 maxOccurs=unbounded. But why is "exactly one" not a valid restriction of "any number"? Still, when not using an any type, we have (1).

A: Found a partial answer...
(4) was resolved by removing an import of another schema document I wrote. I wanted to make restricting redefinitions of several targetNamespaces in multiple files and chain them together. I assume that how I did it was not a legal composition of schema documents and it resulted in some kind of circular dependency referencing(?). I re-created the document standalone and it works just the way I wrote it.
However, the main question shown in (3) still remains (see EDIT).


text:
Q: SetWindowIcon error: must be in R8G8B8A8 pixel format - raylib c++ So I am trying to make a window icon for the game and when I load the icon.png image, it says this: WARNING: GLFW: Window icon image must be in R8G8B8A8 pixel format and here is my icon:  Finally, here is the code snippet:
Image icon = LoadImage("pong.png");
SetWindowIcon(icon);

Thanks for all answers!

A: Your icon PNG has a bit depth of 24 which means it's missing the alpha channel (the A8 from R8G8B8A8).
Edit the image to save it with the alpha channel. You can check the bit depth in the file properties (should be 32 for RGBA).


text:
Q: Dynamic Conditional Formatting With VBA Macro I'm fairly new to VBA. I want to conditionally format the cells of the column of the ActiveCell so that they are highlighted blue if they are not present in the column which is 4 columns to the right of the ActiveCell. I recorded a macro which performed this for one particular set of columns but I am having trouble changing it so that it works for arbitrary sets of columns based on the position of the ActiveCell. The recorded code is given below
    Range("Y8").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=COUNTIF(AC:AC, Y8)=0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 15773696
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
ActiveWindow.SmallScroll Down:=0

Could anyone please tell me how to alter this so that Y8 is the ActiveCell and AC:AC is the column 4 columns to the right of the ActiveCell. Thank you.

A: If you want a VBA solution then use R1C1 references in your posted code for the COUNTIF bit like:
"=COUNTIF(C[4], R[]C[])=0"
These are relative references and Excel will automatically work out and convert them into the right A1 style references for you.
Alternatively,
If the sole purpose of your macro is to get those cells coloured then you don't need a macro for this.
Select your data in the first column with cell A1 as the active cell within your selection (I call it column A below, and the 4 column offset as column E) and go to Conditional Formatting.
Add a new 'conditional format based on a formula'
Type in as the formula
=ISERROR(MATCH(A1,E:E,0))
And then choose your desired format.
Note that as the cell references are relative, you can very easily copy and paste the format to any arbitrary column and it will still check to 4 columns to the right of the new column.


text:
Q: `make` failed with exit code: 2 at ChildProcess.onExit (/usr/share/node-gyp/lib/build.js) I have certain application which exposes about 100 Soap Web Service Services and I need to "facade" them as Rest Service using NodeJs. In other words, I will create a rest service that will recieve the parameters as json and I will send them to certain Soap Service (same parameters in xml format) and I will transform the answer from xml to json.
It is not part of this question discuss about alternatives for NodeJs neither discuss alternatives to change the client consumer approach to parse soap.
I "googled" a bit and I found a very interesting project at https://github.com/vpulim/node-soap and another at https://github.com/23/node-soap, all of them seeming that depends on same API. Nevertheless, when I tried to install it (npm install soap), I get the error in my question subject.
PS. I using Linux Mint 18.1 Serena
PS2. same error happens when I tried npm i easysoap
demetrio@nodejs ~/movie-collection $ sudo npm install soap
npm WARN deprecated node-uuid@1.4.7: use uuid module instead

> ursa@0.9.4 install /home/demetrio/movie-collection/node_modules/ursa
> node-gyp rebuild

make: Entering directory '/home/demetrio/movie-collection/node_modules/ursa/build'
  CXX(target) Release/obj.target/ursaNative/src/ursaNative.o
make: g++: Command not found
ursaNative.target.mk:92: recipe for target 'Release/obj.target/ursaNative/src/ursaNative.o' failed
make: *** [Release/obj.target/ursaNative/src/ursaNative.o] Error 127
make: Leaving directory '/home/demetrio/movie-collection/node_modules/ursa/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/share/node-gyp/lib/build.js:269:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.4.0-59-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /home/demetrio/movie-collection/node_modules/ursa
gyp ERR! node -v v4.2.6
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:ursa@0.9.4 ursa@0.9.4 install: `node-gyp rebuild`
npm WARN install:ursa@0.9.4 Exit status 1
movie-collection@0.0.1 /home/demetrio/movie-collection
└── soap@0.18.0  extraneous

demetrio@nodejs ~/movie-collection $


text:
Q: Android and achartengine: resetting chart values for multiple uses I have an application that draws a dynamic chart and when it's done it saves some data and lets the user exit. (So there are multiple activities). Once the user exits, I want them to be able to come back and let the charts dynamically redraw themselves from 0. But for some reason, the chart always continues from the value where it left of.
Here's what I tried:

*

*Clearing the XYSeries by calling clear(). Also, removed the series from my XYMultipleSeriesDataset, and cleared the Text Labels on my XYMultipleSeriesRenderer. Still, the graph continues where it left off.

*Calling onDestroy() to get rid of all saved data. This worked to clear the chart, but when the user chose to exit, the app crashed because for some odd reason, the activity I was killing tried to recreate itself. When I tried onDestroy() together with finish(), there was no crash, but the graph saved it's data from the last run.

*Calling super.onCreate(null) to avoid the savedInstanceState. The graph still saved it's data.
Can anyone help me please? Let me know if I need to post my code or anything else!
Thank you in advance!

A: I solved this problem by removing the view and then adding he view again.
Each time I build a new XYSeries and new dataset:
mDataset = new XYMultipleSeriesDataset();  //mDataset in my case is global
XYSeries series = new XYSeries("My Series Title");

series.add((double)y,Weight); //call this function several times if you want several points in the same series.

mDataset.addSeries(series);
mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);  //mChartView is also global

layout.removeAllViews();  //This remove previous graph
layout.addView(mChartView); //This loads the graph again

I don't know if this is the best way, but it works great and with almost no delay (I only have to update the graph when coming back from other activity, or the user enters data).
Hope this is useful.
BR,
Adrian.

A: You can have a method that does that each time you launch a new graph
private void removeGraph(){
    //View item = lineChartLayout;
    lineChartLayout.removeAllViews();
    //((ViewGroup) item.getParent()).removeView(item);
}

Since the lineChartLayout is a Layout, then it is a ViewGroup, hence we can remove all attached views on it by calling the removeAllViews method on the layout and all views attached on it will be removed.
Cheers


text:
Q: Sunspot solr pagination not working with kaminari The controller Actions
def search_leads
            @search = Sunspot.search(Lead) do |searcher|
                searcher.all do
                    fulltext params[:email], :fields => :email
                    fulltext params[:name], :fields => [:first_name, :last_name]
                end
                searcher.paginate(:page => params[:page], :per_page => 10)
            end
            @leads = @search.results

            respond_to do |format|
                if (params[:email].present? || params[:name].present? ) and (current_user.credits > 0)
                    format.html { redirect_to search_leads_path }
                    format.js { }
                else
                    format.html { redirect_to new_search_path }
                end
            end
        end

search_leads.js.erb
$(".search_results").html("<%= escape_javascript(render :partial => 'search/search_results') %>");
$('#paginator').html('<%= escape_javascript(paginate(@search.hits, :remote => true).to_s) %>');

HTMl
<div id="paginator">
      <%= paginate @search.hits, remote: true %>
</div>

Pagination buttons appear in results, but i am not able to scroll through pages. When clicking on next pages, no call goes to solr.

A: Everything is ok, the issue is remote: true on paginate, just update like below
Remove remote: true from paginate and it will be on the partial e.g search_results.html.erb
<%= paginate @search.hits %>

and the main file e.g search_leads.html.erb add this script
<script type="text/javascript">
    $(document).ready(function() {
        $('.pagination > a').attr('data-remote', 'true');
    });
</script>

the .pagination > a is selector if this not working then just find the selector from browser console then use this.
I think this line does not require, remove this
$('#paginator').html('<%= escape_javascript(paginate(@search.hits, :remote => true).to_s) %>');

and on the search_leads.js.erb this script also OK
$(".search_results").html("<%= escape_javascript(render('search/search_results')) %>");


text:
Q: Tornado https proxy outputs 405 WARNING I tried to make proxy server by tornado in Python. The simple http proxy server has worked well, but the https proxy has some problem.
Part of my programs which might have problem are below.
import tornado.ioloop
from tornado.web import RequestHandler, Application
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.httpserver import HTTPServer

class HTTPSHandler(RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        print self.request.host, self.request.method
        def handle_request(response):
            if response.error and not isinstance(response.error, tornado.httpclient.HTTPError):
                print "Error:", response.error
            else:
                self.write(response.body)
            self.finish(" ")#in case of response.body == None

        request = self.request
        req = HTTPRequest(url=request.uri, method=request.method,
                          headers=request.headers, body=request.body,
                          allow_nonstandard_methods = True, follow_redirects = False,
                          validate_cert=True)

        http_client = AsyncHTTPClient()
        try:
            http_client.fetch(req, handle_request)
        except Exception as e:
            print e

    @tornado.web.asynchronous
    def post(self):
        return self.get()
    @tornado.web.asynchronous
    def head(self):
        return self.get()
    @tornado.web.asynchronous
    def delete(self):
        return self.get()
    @tornado.web.asynchronous
    def patch(self):
        return self.get()
    @tornado.web.asynchronous
    def put(self):
        return self.get()
    @tornado.web.asynchronous
    def options(self):
        return self.get()

if __name__ == "__main__":
    app2 = Application([(r"https:.*", HTTPSHandler),])
    httpsServer = HTTPServer(app2, ssl_options = {
            "certfile": "./server.crt",
            "keyfile": "./server.key",
            })
    app2.listen(444)
    tornado.ioloop.IOLoop.instance().start()

It outputs a WARNING like below (when I access to https://www.google.com and https://github.com)
WARNING:tornado.access:405 CONNECT www.google.co.jp:443 (127.0.0.1) 0.69ms
WARNING:tornado.access:405 CONNECT github.com:443 (127.0.0.1) 0.58ms

Finally, web pages which use https protocol could not be displayed with browser error.
ERR_TUNNEL_CONNECTION_FAILED

I guess, this is caused by the tornado's requestHandler because it does not support CONNECT method.
My question is how can I use the CONNECT method?

A: I have noticed the way to fix this problem.
At first, SUPPORTED_METHOD should be written in HTTPSHandler class.
This can solve the 405 WARNING and browser error.
class HTTPSHandler(RequestHandler):
    SUPPORTED_METHODS = ("CONNECT", "GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS")
    @tornado.web.asynchronous
    def get(self):

This is written in official document as follows.
If you want to support more methods than the standard GET/HEAD/POST, you
should override the class variable ``SUPPORTED_METHODS`` in your
`RequestHandler` subclass.

Moreover, to handle and process the CONNECT method request, additional method is needed in HTTPSHandler class.
@tornado.web.asynchronous
def connect(self):
    print "some specific processings here"

Finally, I took stupid mistakes in regular expressions and ssl_option.
app2 = Application([(r"https:.*", HTTPSHandler),]) # not correct
app2 = Application([(r".*", HTTPSHandler),])       # correct
httpServer = HTTPServer(app2)                      # ssl_options is not needed

A: In theory you should be able to implement the CONNECT method in the same way that WebSocketHandler works, by hijacking the underlying connection's IOStream.  But be warned that this is uncharted territory; the HTTP proxy protocol has some differences from plain HTTP and I don't know how well it will work to implement a proxy on top of a normal application-level HTTP service.


text:
Q: why my java program get terminated after printing "address" in the below code? is there is something with the read()and readline()method please tell me the flow of this code I am not understanding what happening after the char s2=(char)br.read();
  import java.io.*;

  class demo
  {

  public static void main(String[]arg) throws IOException

  {

InputStreamReader i=new InputStreamReader(System.in);
 BufferedReader br=new BufferedReader(i);

 System.out.println("enter name");
 String s1=br.readLine();

 System.out.println("enter gender");
 char s2=(char)br.read();

 System.out.println("enter adress");
 String s3=br.readLine();

  System.out.println("name"+s1);
  System.out.println("gender"+s2);
  System.out.println("address"+s3);
  }
 }

A: Issue is with your br.read(). Basically, you could have entered M and press enter. Then, this function call only pass M to gender, however, the new line character is still available in br, hence address will come as black. That is why program continues and completes successfully.
You can change from br.read() to br.readLine() for gender, and convert string to char accordingly (after validating input) to fix this problem.


text:
Q: Can One Time Passwords be used as identifiers? If I have bunch of OTPs mixed and if I know all of their generation seeds (the OPT URI) can I group by source URI?
I have a  use case there I need the system to be 100% blind to the data relationships that its passing around.
For example: Users enter OTPs from their smartphones instead of their logins it should become very difficult identify entries by one user. As data is exported of the system that has OPT seeds is it possible to reestablish entry's ownership?

A: That's possible, but with a big complexity. You will need to generate codes for all seeds you have and then find if there is any match.
Also, there is a chance to receive the same code for different seeds at some moment. To avoid this problem you can ask a user for several consecutive codes, this significantly decreases the possibility of codes matching just by case.


text:
Q: Apache, 20+ long running connections with little memory usage I have a small server, 2 GB memory (an AWS t2.small) that I would like to run cron jobs on. These crons run by specific URLs getting hit (an AWS setup I can't change), and take maybe 1 – 2 minutes each to complete.
At some points during the day there are ~20 crons that run at exactly the same time. Predictably, this is causing memory usage to spike and shut things down. I reduced MaxClients to 6, which fixed the memory usage spike problem, but this is causing some crons to silently not be run.
From my understanding of MaxClients, these crons are silently failing because only 6 connections are allowed at one time? Is there any way my little server can handle these spikes of 20 connections and keep memory usage stable? It seems like my goal would be "allow 20+ connections, but only allocate a small amount of memory to each".
Thanks for your help


text:
Q: How to select data of the specified 'createBy' I want to execute the SELECT command to find the data of the specified 'createBy', and the dao.xml is as follows (some fields are omitted for simplicity):
<select id="findList" resultType="ChenminIndicator">
    SELECT
        <include refid="chenminIndicatorColumns"/>
    FROM chenmin_indicator a
    <include refid="chenminIndicatorJoins"/>
    <where>
        a.del_flag = #{DEL_FLAG_NORMAL}
        <if test="createBy != null and createBy.id != null and createBy.id != ''">
            AND a.create_by = #{createBy.id}
        </if>
        <if test="updateBy != null and updateBy.id != null and updateBy.id != ''">
            AND a.update_by = #{updateBy.id}
        </if>
        <if test="icode != null and icode != ''">
            AND a.icode = #{icode}
        </if>
    </where>
    <choose>
        <when test="page !=null and page.orderBy != null and page.orderBy != ''">
            ORDER BY ${page.orderBy}
        </when>
        <otherwise>
            ORDER BY a.update_date DESC
        </otherwise>
    </choose>
</select>

I write the dao.java like this:
public List<T> findList(T entity, @Param("createBy") User createBy);

but Mybatis throws exception:
Parameter 'updateBy' not found. Available parameters are [0, createBy, param1, param2]

and if I write dao.java like:
public List<T> findList(T entity);

it works and return the total data, how can I select the data of one specified 'createBy'?


text:
Q: 'NoneType' object has no attribute 'append' Llevo tiempo intentando solucionar este error pero no lo entiendo.
Estoy trabajando en python con las librerías de openpyxl y pandas, para trabajar dataframes y Excel, lo que intento hacer es pasar los datos que se encuentran dentro del dataframe al excel mediante openpyxl (no mediante pandas), lo hice siguiendo la documentación de openpyxl, pero al momento de ejecutarlo me tira el error --> 'NoneType' object has no attribute 'append'
Mi código es el siguiente:
import pyodbc
import pandas as pd
import openpyxl as opx
from openpyxl.utils.dataframe import dataframe_to_rows

#Conexion BBDD
conexion = pyodbc.connect('DRIVER={SQL Server}; SERVER=srv;DATABASE=BD;Trusted_Connection=yes;')

#Query a la BBDD
query = "SELECT top 3 * FROM contratos"
pd_query = pd.read_sql_query(query, conexion)

#Creacion del Dataframe
df = pd.DataFrame(pd_query)

#Creacion de Workbook
wb = opx.Workbook('Prototipo.xlsx')
ws = wb.active

for r in dataframe_to_rows(df, index=False, header=True):
    ws.append(r)

wb.save('path')

El error viene del FOR en la parte del append.
Espero que alguien me pueda ayudar a solucionar este error, se lo agradecería mucho.