text:
Q: Python decorator class with members I want to write a class that will have member variables and member functions that will be used as decorators.
class decorator_class:
   def __init__(self, baseurl, username,password):
     self._baseurl = baseurl
     self._username = _username
     self._password = _password

   def decorator_get(self,arguments):
        def inner_function(function):
            @wraps(function)
            def wrapper(*args, **kwargs):
                url = self._url + argument
                if len(kwargs) > 0:
                    url+="?"
                    argseperator=""
                    for k,v in kwargs.items():
                        url+="{}{}={}".format(argseperator,k,v)
                        argseperator="&"
                    r = requests.get(url, auth=(self._username, self._password))
                    if r.status_code != 200:
                        raise Exception('Failed to GET URL: {}'.format(url))
                return function(args[0],json = r.json())
            return wrapper
        return inner_function

class usedecorator:
   def __init__(baseurl, self,user,password):
      self.dec = decorator_class(baseurl, self,user,password)

   @dec.decorator_get('/path/to/resource1')
   def process_output_resource1(self, json):
     do_something_with_json

The problem is that __init__ is being called after the class is loaded and at that time dec is undefined.
if I define the decorator_class globally it works, but then there is no way to pass the url, user and password to it at runtime.
Any suggestions?

A: Your decorator_get > innder_function > wrapper has the userdecorator's self.
Weird sentence but eh.
You have some weird namings, IDK why did you use self as a second argument for instance but, I tried to follow your naming.
def decorator_get(arguments):
     def inner_function(function):
         @wraps(function)
         def wrapper(self, *args, **kwargs):
             url = self._base_url + arguments
             if len(kwargs) > 0:
                 url+="?"
                 argseperator=""
                 for k,v in kwargs.items():
                     url+="{}{}={}".format(argseperator,k,v)
                     argseperator="&"
                 r = requests.get(url, auth=(self._username, self._password))
                 if r.status_code != 200:
                     raise Exception('Failed to GET URL: {}'.format(url))
             return function(self, json = r.json())
         return wrapper
     return inner_function

class usedecorator:
    def __init__(self, baseurl,user,password):
        self._base_url = baseurl
        self._username = user
        self._password= password

    @decorator_get('/path/to/resource1')
    def process_output_resource1(self, json):
        do_something_with_json

A: Indeed -to have a decorator for methods in a class, it must already be defined (i.e. ready to be used) when the method to be decorated is declared:  which means it have to be declared either at top-level or inside the class body.
Code inside methods, including __init__, however will only run when an instance is created - and that is the point where the class will get your connection parameters.
If this decorator is being used always in this model, you can turn it into a descriptor: an object which is a class attribute, but which has code (in a method named __get__) that is executed after the instance is created.
This descriptor could then fetch the connection parameters in the instance itself, after it has been created, and prepare way for calling the underlying method.
That will require some reorganization on your code: the object returned by __get__ has to be a callable which will ultimately run your function, but it would not be nice if simply retrieving the method name would trigger the network request - one will expect it to be triggered when the process_output... method is actually called. The __get__ method then should return your inner "wrapper" function, which will have all the needed data for the request from the "instance" attribute Python passes automatically, but for the payload which it gets via kwargs.
class decorator_class:
    def __init__(self, path=None):
        self.path = None
        self.func = None

    def __get__(self, instance, owner):
        if instance is None:
            return self
        def bound_to_request(**kwargs):
            # retrieves the baseurl, user and password from the host instance:
            # build query part of the target URL - instead of your  convoluted
            # code to build the query string (which will break ont he first special character,
            # just pass kwargs as the "params" argument)
            response = requests.get(instance._base_url, auth=(
                instance.user, instance.password), params=kwargs)
            # error treatment code
            #...
            return self.func(response.json())
        return bound_to_request

    def __call__(self, arg):
        # create a new instance of this class on each stage:
        # first anotate the API path, on the second call annotate the actual method

        new_inst = type(self)()
        if not self.path:
            if not isinstance(arg, str):
                raise TypeError("Expecting an API path for this method")
            new_inst.path = arg
        else:
            if not callable(arg):
                raise TypeError("Expecting a target method to be decorated")
            new_inst.func = wraps(arg)
        return new_inst

    def __repr__(self):
        return f"{self.func.__name__!r} method bound to retrieve data from {self.path!r}"

class use_decorator:
    dec = decorator_class()
    def __init__(self=, baseurl, user, password):
        # the decorator assumes these to be set as instance attributes
        self.baseurl = baseurl
        self.user = user
        self.password = password

    # <- the call passing the path returns an instance of
    #  the decorator with the path set. it is use as an
    #  decorator is called again, and on this second call, the decorated method is set.
   @dec.decorator_get('/path/to/resource1')
   def process_output_resource1(self, json):
       # do_something_with_json
       ...

In time, re-reading your opening paragraph, I see you intended to have more than one decorator inside your original class, probably others intended for "POST" and other HTTP requests: most important thing, the __get__ name here has nothing to do with HTTP: it is a fixed method name in the Python spec which is called automatically by the language when one will retrieve your method from an instance of use_decorator. That is, when there is code: my_instance.process_output_resource1(...), the __get__ method of the descriptor is called. Whatever it returned is then called.
For enabling the same decorator to use POST and other HTTP methods, I suggest you to have as a first parameter when annotating the path for each method, and then simply call the appropriate requests method by checking self.method inside the bound_to_request function.

A: I think you're going too far with the decorator approach. Let's break this down into a single question: What is the actual shared state here that you need a class for? To me, it looks like just the baseurl, user, and password. So let's just use those directly without a decorator:
from requests import Session
from requests.auth import HTTPBasicAuth

class UseDecorator: # this isn't a good name, but we will keep it temporarily
    def __init__(self, baseurl, user, password):
        self.baseurl = baseurl
        self.session = Session()
        # we've now bound the authentication to the session
        self.session.auth = HTTPBasicAuth(user, password)

    # now let's just bind a uri argument to a function to simply
    # send a request
    def send_request(self, uri, *args, **kwargs):

        url = self.baseurl + uri

        # you don't need to manually inject parameters, just use
        # the params kwarg
        r = self.session.get(url, params=kwargs)

        # this will check the response code for you and even handle
        # a redirect, which your 200 check will fail on
        r.raise_for_status()

        return r.json()

    # then just handle each individual path
    def path_1(self, *args, **kwargs):
        data = self.send_request('/path/1', *args, **kwargs)
        # process data

    def path_2(self, *args, **kwargs):
        data = self.send_request('/path/2', *args, **kwargs)
        # process data

Because we're leveraging the machinery offered to us by requests, most of your decorator is simplified, and we can boil it down to a simple function call for each path


text:
Q: Help with fractals Let $f(z)=z^2+4z+1$. Is the filled Julia set (denoted $F_f$) connected?
I'm not sure to show how its connected. The only thing I know how to do is verify whether a given point is in the set.

A: You only need to test the critical point, the root of the derivative $2z+4$, that is, $z=-2$. You'll find that the orbit of $z=-2$ is $-2,-3,-2,-3,\dots$, periodic of period 2. Since the critical orbit does not goes to infinity, the Julia set is connected.
Alternatively, you reduce $z^2+4z+1$ to the form $z^2+c$ by conjugation with a map $z\mapsto z+a$ for some $a$. For this, you need to find $a$ and $c$ such that $(z+a)^2+c-a=z^2+4z+1$. You'll find that $a=2$ and $c=-1$. So, the Julia set of $z^2+4z+1$ corresponds to the Julia set of $z^2-1$, which is connected.

(image from http://www.math.cornell.edu/~lipa/mec/lesson5.html)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invalid Trigger Exception I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :
create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;

A: You have two errors:

*

*Your IF has no END IF

*Your SELECT INTO has no FROM
But the select is not necessary to begin with, you can simply assign the sequence value:
CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if :NEW.STAGING_REASON_ID is null then
      :NEW.STAGING_REASON_ID := STAGING_SEQ_ERROR_REASON.NEXTVAL;
   END IF; --<< missing
END;
/

Not sure how and where you ran your PL/SQL, but you typically also need a / at the end of a PL/SQL block.

A: In Oracle every SELECT statement should have a FROM clause. You should use at least
SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL INTO :NEW.STAGING_REASON_ID FROM DUAL;

A: You could use:
CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
BEFORE INSERT ON STAGING_ERROR_REASON REFERENCING NEW
AS NEW FOR EACH ROW
BEGIN
 if(:NEW.STAGING_REASON_ID is null) then
 :NEW.STAGING_REASON_ID := (SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL FROM dual);
 end if;
END;


text:
Q: Change file permission of com.apple.screensharing.plist file on mac I'm trying to change the file permission of a file.
I have tried chmod 777 on the file and nothing seems to work.
I even tried manually navigating to it and unocking and changing the permissions via the answers here (chmod unable to change permissions), I am at a loss for how to change the file permission so I can edit this file to allow screen sharing on a different port...

For anyone else that has a mac I'm trying to follow the instructions here, https://superuser.com/questions/148095/how-to-change-the-default-screen-sharing-vnc-port-number-on-mac-os-x
sudo vim /System/Library/LaunchDaemons/com.apple.screensharing.plist

This is the path to the file, but I can't edit it no matter what I do.  Even as super user!

A: I found the answer to this, there is a protection on the system file csrutil, you need to disable this by booting up into recovery mode and open the terminal program and run the command csrutil disable.
Make sure to reenable after making the change in recovery mode again!


text:
Q: Strange too few template-parameter-lists error set<unsigned int> setId;
vector<int> vecNode;
for (size_t i = 0,set<unsigned int>::iterator it = setId.begin(); i < vecNode.size() && it != setId.end(); i++,it++ ){}

the compiler report:
error: too few template-parameter-lists
but if I write like this:
set<unsigned int> setId;
vector<int> vecNode;
size_t i = 0;
for (set<unsigned int>::iterator it = setId.begin(); i < vecNode.size() && it != setId.end(); i++,it++ ){}

the compilation succeeds.
so why?

A: The same reason as why you cannot do
int i = 0, float j = 2.64f;  // ERROR!

With
size_t i = 0, set<unsigned int>::iterator it = setId.begin()

you are actually doing something like the above example, you are defining two variables but with different types, namely size_t and set<unsigned int>::iterator.
Where you can do
int i = 0, j = 1;  // OK

you are also allowed to do something like
for(size_t i = 0, j = 2; ...; ...) ...

in a for-loop statement. i and j in both examples both have the same type, int and size_t respectively.


text:
Q: In SAS how to print leading and lagging observations I am looking for a way to print the current, leading and lagging observation according to a flag variable. If an observation is flagged, I want to print that observation, plus its lagging and leading row.
Have:
    ID        VAR1        VAR2        Flag
    --------------------------------------
    ID1        1           15           .
    ID1        2           14           1
    ID1        3           13           .
    ID1        4           12           .
    ID2        5           11           .
    ID2        6           10           .
    ID2        7            9           1
    ID2        8            8           .
    ID2        9            7           .
    ID3        10           6           .
    ID3        11           5           1
    ID3        12           4           .
    ID3        13           3           .
    ID3        14           2           1
    ID3        15           1           .

Want:
    ID        VAR1        VAR2        Flag
    --------------------------------------
    ID1        1           15           .
    ID1        2           14           1
    ID1        3           13           .
    ID2        6           10           .
    ID2        7            9           1
    ID2        8            8           .
    ID3        10           6           .
    ID3        11           5           1
    ID3        12           4           .
    ID3        13           3           .
    ID3        14           2           1
    ID3        15           1           .

I have tried the Proc Expand functions, but since this procedure cannot deal with missing values, it is not appropriate in my working case.
Another approach is to order the dataset to the desired order and then create a variable numbering each row in order--printing current row +1,-1 on condition of the flag.
Is there a more direct way of achieving a dataset consisting of current, lagging and leading rows according to a flag?

A: Finding the previous value of FLAG is easy to do with the LAG() function. Finding the next value is a little harder.  Here is a method.
data want ;
  set have end=eof;
  by id ;
  if not eof then set have(keep=flag rename=(flag=lead_flag) firstobs=2);
  lag_flag=lag(flag);
  if first.id then call missing(lag_flag);
  if last.id then call missing(lead_flag);
  if flag or lead_flag or lag_flag ;
run;

A: you can use var1+1 and var-1 for flag = . as shown below.
     proc sql;
create table want as
select distinct a.* from
(select * from have)a
inner join
(select * from have
where flag = 1 )b
on a.var1 = b.var1
or a.var1 = b.var1-1
or a.var1 = b.var1 +1;

A: A more general scenario would be

*

*Within each group report each row meeting a fulcral condition as well as p rows before and q rows after

p and q would correspond to the concepts of lag-size and lead-size. A hash object can track a within group sequence number for the rows that should be output.  The double DOW technique is used to measure over the group (compute the seq number for output) and then evaluate the measure for each item in the group.
For example:
data have;
  do id = 'A', 'B', 'C', 'D';
    do seq = 1 to 36;
       rowid + 1;

       x = seq;
       if id = 'D' then x = floor(12*ranuni(123));

       flag = mod(x,7);
       output;
    end;
  end;
run;

%let lagsize = 2;
%let leadsize = 3;

data want;
  if _n_ = 1 then do;
    declare hash marks();
    retain __n .;
    marks.defineKey('__n');
    marks.defineData('__n');
    marks.defineDone();
  end;

  marks.clear();
  do __n = 1 by 1 until(last.id);
    set have;
    by id;
    if
      flag=0 /* fulcrum criteria checked for each row in group */
    then do;
      * computation is "store sequence number that would fall in the lag lead 'about' space";
      _n_ = __n;
      do __n = _n_ - &lagsize to _n_ + &leadsize;
        marks.replace();
      end;
      __n = _n_;
    end;
  end;

  do __n = 1 to __n;
    set have;
    if marks.check()=0 then output; * evaluate for each row in group;
  end;
run;

The technique can be extended to the case of wanting different 'about' sizes based on different fulcral conditions.


text:
Q: Apply regular expression repeatedly I've got text expressions like this:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'

I want to extract the following text pieces:
HIUPD:bla2bla2'

And
HIUPD:bla3bla3'

My Objective-C code for this looks like this:
-(void) ermittleKonten:(NSString*) bankNachricht
{
    NSRegularExpression* regexp;
    NSTextCheckingResult* tcr;
    regexp = [NSRegularExpression regularExpressionWithPattern:@"HIUPD.*'" options:0 error:nil];

    int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
    for( int i = 0; i < numAccounts; ++i ) {
        tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
        NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
        NSLog(@"Found text is:\n%@", HIUPD);
    }
}

In the Objective-C code numAccounts is 1, but should be 2. And the string that is found is "HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'"
I tested the regular expression pattern with an online tool ( http://www.regexplanet.com/simple/index.html ). In the online tool it works fine and delivers 2 results as I want it to be.
But I would like to have the same result in the ios code, i.e. "HIUPD:bla2bla2'" and "HIUPD:bla3bla3'". What is wrong with the pattern?

A: You're doing greedy matching with the .*, so the regular expression catches as much as it can in the .*. You should be doing .*?, or [^']*, so that the * can't match a '.


text:
Q: How can I choose a random conversation output in Python? I'm trying to get my script to choose between three options of conversation, labeled petconvo1, petconvo2, or petconvo3. The program asks what pet the user has and then picks a random thing to say about them.  Based on what tidbit the script picks, I want to continue the conversation there. My problem is that it just stops and doesn't keep going with the conversation. What's the best way to do this?
My code is below.
#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")

#Sets the input to lowercase
petlower = pet.lower()

#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")

#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]

#Compliments pet
print(random.choice(petconvolist))

#Continues the conversation
if petconvolist == petconvo1:
    time.sleep(1)
    print("Wouldn't you agree?")
else:
    if petconvolist == petconvo2:
        time.sleep(1)
        print("I think it's important for children to grow up with pets.")
    else:
        if petconvolist == petconvo3:
            time.sleep(1)
            foodbudget=input("Does it cost a lot to feed " + petlower + "?")
            time.sleep(.5)

        else: pass

The script stops after this bit:
print(random.choice(petconvolist))

Thanks in advance!

A: hmm first in the if statements you should use the elif statement. Afterwards you should use set the random selection to a var in order to check it. This code works for me.
#imports the random module
import random
#Asks what pet the user has
pet = input("What kind of pet do you have? ")

#Sets the input to lowercase
petlower = pet.lower()

#Sets tidbits of conversation about the pet
petconvo1 = ("Oh, I've heard that " + petlower + " is a good companion to have.")
petconvo2 = ("Oh, really? I had " + petlower + " when I was growing up.")
petconvo3 = ("Does it cost a lot to keep " + petlower + " fed?")

#Turns the tidbits into a list
petconvolist = [petconvo1, petconvo2, petconvo3]

#Compliments pet
convo = random.choice(petconvolist)
print(convo)

#Continues the conversation
if convo == petconvo1:
    time.sleep(1)
    print("Wouldn't you agree?")
elif convo == petconvo2:
        time.sleep(1)
        print("I think it's important for children to grow up with pets.")
elif convo == petconvo3:
            time.sleep(1)
            foodbudget=input("Does it cost a lot to feed " + petlower + "?")
            time.sleep(.5)


text:
Q: How do you manually tell Python which version to use in the script itself, across multiple operating systems? I have Python 2.7 and 3.3 installed on Windows, and Python 2.7 and 3.2mu installed on Linux.
How would I write a Python script that is able to be used on both Windows and Linux, using version 2.X or 3.X?
I'm looking for maybe a few lines of code that will check to see what the current operating system is, and use Python 3.X in whatever directory it's in for the rest of the script.
I was thinking somewhere along the lines of:
if operating_system == Windows:
    run rest of script with C:\python_directory3.X\python
elif operating_system == Linux:
    run rest of script with /usr/bin/python3.X

Does code like this exist, or will I have to make a different script for both operating systems?

A: On UNIX systems, Python commands should be named as prescribed in PEP-394, so using a shebang is the best solution:
#!/usr/bin/env python2

or
#!/usr/bin/env python3

As appropriate, at the top of your file.
Under Windows, it's a little less well defined. Since version 3.3, a launcher should be included with Python, as described in PEP-397. This, however, doesn't help older versions.
If you want to be sure under Windows, many people use py2exe, Cx_Freeze, or other similar tools to produce executables that include the interpreter. This may be a valid solution in some cases.
A good idea is to add a check to your code (checking the version of the interpreter), and give a clear, easy-to-understand message that they are using the wrong version of Python, perhaps with a link on how to solve that issue. This won't magically solve anything, but it means that if all else fails, the user gets a chance to understand what is going wrong.

A: You can identify the OS in which the script is running using os module or sys module. Both shows different results, but similar:
import os
os.name #"posix" for linux "nt" for windows
# or
import sys
sys.platform # "linux2" for linux


text:
Q: Updating javafx ChoiceBox when state of items changes I have a javafx project that uses a ChoiceBox. I am trying to get the ChoiceBox updated when the state of the ChoiceBox's item object changes.
I almost got it working but one problem persists. When an item's state changes the choicebox shows the updated item but it also shows the previous item's state. So I end up with two selections available for the single item.
When I restart the program only the updated selection is shown. Also, when I print choicebox's items to the console only the update item is shown.
My code snippets so far:
public class User {

   private ObjectProperty<Name> name;

   User(Name name) {
      this.name = new SimpleObjectProperty<>(name);
   }

   public Name getName() {
      return name.get();
   }

   public ObjectProperty<Name> nameProperty() {
      return name;
   }

   @Override
   public String toString() {
       return name.toString();
   }

   void setName(Name aName) {
     this.name.set(aName);
   }
}

Callback<User, Observable[]> extractor = (User u) -> {
        return new Observable[]{u.nameProperty()};
    };
users = FXCollections.observableArrayList(extractor);

I then pass reference to the unmodifiable version of the users list to the UI package and then use it in a choice box.
public ObservableList<User> getUsers() {
    return FXCollections.unmodifiableObservableList(users);
}

private ChoiceBox<User> climberChoiceBox;

climberChoiceBox.setConverter(new StringConverter<User>() {
        @Override
        public String toString(User aUser) {
            return aUser == null ? null : aUser.getName().toString();
        }

        @Override
        public User fromString(String string) {
            return null;
        }
    });

climberChoiceBox.setItems(model.getUsers());

Any ideas how to fix this.
Thanks.


text:
Q: Heavy Metal-ish animated picture with kidnapped princess I just saw scenes of this on another site, but without much information about it. A black-haired and scantily clad princess is left in her castle to learn about the elements when creatures similar to D&D-style orcs kidnap her. Somehow separated from the orcs (if that's what they are), said princess is found by a dim-witted troll-type being who takes her to his mother, a red haired witch. The red-haired witch learns the princess is sought by a guy named Necron (spell?).
Like I said in the header the film is animated, in colour, and while I didn't see any actual nudity it does strike me as adult-oriented.

A: This is almost certainly 1983's Fire and Ice. Plot summary from Google:

This fantastical animated movie by cult filmmaker Ralph Bakshi finds the villainous Nekron and his mother, Queen Juliana, attacking the human race from their frigid fortress. Creating mass destruction with huge glaciers, Nekron and Juliana incur the wrath of Larn, a warrior whose entire village was destroyed by ice. When Nekron's underlings kidnap the beautiful Princess Teegra, Larn sets out to rescue her, assisted by the fierce and enigmatic Darkwolf.

Here's Princess Teegra, she looks just as you recalled:


text:
Q: java.lang.NumberFormatException in Scala for mllib I just trying to develop a simple example of a K-Means algorithm, but I have a lot of problems loading and cleaning the data.
This my code:
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.clustering.KMeans
import org.apache.spark.sql.functions._

val crimeRDD = sc.textFile("/home/borja/spark/pruebas/AlgoritmoClusterizacion/filter_data1.csv")

val header = crimeRDD.first

val data = crimeRDD.filter (justData => justData != header)

//Spark doesn't allow more than 22 element
case class crimeReport (Record_ID: Int, Agency_Name: String, City: String, State: String, Year: Int, Month: String, Crime_Type: String, Crime_Solved: String, Victim_Sex: String, Victim_Age: Int, Victim_Race: String, Perpetrator_Sex: String, Perpetrator_Age: Int, Perpetrator_Race: String, Relationship: String, Victim_Count: Int)

val data_split = data.map(line => line.split(","))

val allData = data_split.map(p => crimeReport(p(0).trim.toInt, p(1).trim.toString, p(2).trim.toString, p(3).trim.toString, p(4).trim.toInt, p(5).trim.toString, p(6).trim.toString, p(7).trim.toString, p(8).trim.toString, p(9).trim.toInt, p(10).trim.toString, p(11).trim.toString, p(12).trim.toInt, p(13).trim.toString,p(14).trim.toString, p(15).trim.toInt))

val allDF = allData.toDF()
allDF.printSchema
//allDF.show(100)

val rowsRDD = allDF.rdd.map(r => (r.getInt(0),r.getString(1),r.getString(2), r.getString(3),r.getInt(4), r.getString(5), r.getString(6), r.getString(7),r.getString(8), r.getInt(9), r.getString(10), r.getString(11),r.getInt(12), r.getString(13),r.getString(14), r.getInt(15)))

rowsRDD.cache()

val features_vector = allDF.rdd.map(r => Vectors.dense(r.getInt(0)))

features_vector.cache()

val KMeansModel = KMeans.train(features_vector,2,40)

But I got this error
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 43.0 failed 1 times, most recent failure: Lost task 0.0 in stage 43.0 (TID 57, localhost, executor driver): java.lang.NumberFormatException: For input string: "Jersey"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.collection.immutable.StringLike$class.toInt(StringLike.scala:272)

I do not understand it because I am cleaning the white and the spaces with the function .trim, do I?
The point is the exception is throw because there is some String value when I do the .toInt, right? So how can I filter them because there are 65k rows.
Here a little set of data:
Record ID,Agency Name,City,State,Year,Month,Crime Type,Crime Solved,Victim Sex,Victim Age,Victim Race,Perpetrator Sex,Perpetrator Age,Perpetrator Race,Relationship,Victim Count
1,Anchorage,Anchorage,Alaska,1980,January,Murder or Manslaughter,Yes,Male,14,Native American/Alaska Native,Male,15,Native American/Alaska Native,Acquaintance,0
13504,Atlantic City,Atlantic,Jersey,1980,January,Murder or Manslaughter,Yes,Male,40,Black,Female,50,Black,Acquaintance,0
13505,Atlantic City,Atlantic,Jersey,1980,January,Murder or Manslaughter,No,Male,23,Black,Unknown,0,Unknown,Unknown,0
13506,Atlantic City,Atlantic,Jersey,1980,January,Murder or Manslaughter,No,Male,52,White,Unknown,0,Unknown,Unknown,0
13507,Atlantic City,Atlantic,Jersey,1980,March,Murder or Manslaughter,Yes,Male,35,Black,Male,23,Black,Unknown,0
13508,Atlantic City,Atlantic,Jersey,1980,March,Murder or Manslaughter,No,Male,25,Black,Unknown,0,Unknown,Unknown,0
13647,Jersey City,Hudson,Jersey,1980,October,Murder or Manslaughter,No,Female,50,White,Unknown,0,Unknown,Unknown,2
13648,Jersey City,Hudson,Jersey,1980,March,Murder or Manslaughter,Yes,Female,60,White,Male,36,White,Father,1
13649,Jersey City,Hudson,Jersey,1980,June,Murder or Manslaughter,Yes,Female,52,Black,Male,26,Black,Unknown,1
13650,Jersey City,Hudson,Jersey,1980,October,Murder or Manslaughter,No,Male,2,White,Unknown,0,Unknown,Unknown,2
13651,Jersey City,Hudson,Jersey,1980,January,Murder or Manslaughter,Yes,Female,68,Black,Male,0,Black,Unknown,0
13652,Jersey City,Hudson,Jersey,1980,January,Murder or Manslaughter,Yes,Female,22,Black,Male,23,Black,Unknown,0
13653,Jersey City,Hudson,Jersey,1980,January,Murder or Manslaughter,Yes,Female,16,White,Male,33,White,Acquaintance,0
13654,Jersey City,Hudson,Jersey,1980,January,Murder or Manslaughter,Yes,Male,34,White,Male,18,White,Acquaintance,0
13655,Jersey City,Hudson,Jersey,1980,February,Murder or Manslaughter,No,Male,29,Black,Unknown,0,Unknown,Unknown,0
13656,Jersey City,Hudson,Jersey,1980,February,Murder or Manslaughter,No,Male,42,White,Unknown,0,Unknown,Unknown,0

A: Yes, the error message is thrown when an object cannot be casted to an integer value.
Why don't you try Option or Try
for example
Option(p(0).trim.toInt) getOrElse 0

Or
Try(p(0).trim.toInt) getOrElse 0

That should be enough to avoid such casting error
And you mentioned in your code that case class only supports 22 elements. This limit has been removed in newer versions of spark.
I hope the answer helps
Edited:
Note : Option catches NullPointerException only, so the casting exception shall not be solved. Try handles almost every kind of Exception, so Try should be the option for casting exceptions.

A: You can use Try to handle the exception. You can use the old Java style try/catch or the functional way of Try in in scala. Below is the functional way of handling exception in scala.
Try(p(0).trim.toInt) match {
    case Success(result) => result
    case Failure (ex) => {
      ex.printStackTrace()
      //return a default value as you want i have returned 0
      0
    }
  }

Try returns Success if the statement is passed and returns Failure if the statement fails or exception occurs.
I hope this is more easier and understandable as well as functional.


text:
Q: How to use Twitter rest api with Backbone? I'm trying to build a simple Backbone app from this post Unable to fetch data from Twitter RESTful API using Backbone.js Collection . What I wanna do is adding a text box and a button. Every time a user press a button, my app will request to twitter and will search in twitter based on the textbox content (it will search the word 'NYC' as default).
My code is as follows.
My tweets collection
var Tweets = Backbone.Collection.extend({
    model: Tweet,
    url: 'http://search.twitter.com/search.json?q=NYC&callback=?',
    parse: function(response) {
        console.log('parsing ...')
        return response.results;
    }
});

My view.
var PageView = Backbone.View.extend({
    el: $('body'),
    events: {
    'click button#add': 'addItem'
    },
    initialize: function() {
        _.bindAll(this, 'render', 'addItem');
        this.tweets = new Tweets();
        this.counter = 0;
        this.render();
    },
    render: function() {
        $(this.el).append("<input id= 'search'type='text' placeholder='Write a word'></input>");
        $(this.el).append("<button id='add'>Search twitts</button>");
        $(this.el).append("

");
        return this;
    },
    addItem: function(item) {
        var subject = $('#search').val() || 'NYC';
        this.tweets.url = 'http://search.twitter.com/search.json?q=' + subject + '&callback=?';

        // never called ...
        this.tweets.bind('reset', function(collection) {
            console.log(collection.length);
            alert(collection.length);
        });

        $.each(this.tweets.fetch().models, function(index, tweet) {
            item = new Tweet();
            item.set({
                order: this.counter,
                info: tweet.attributes.text// modify item defaults
            });
            $('ul', this.el).append("
" + item.get('order') + " " + item.get('info') + "
");
        });

    }
});
var pageView = new PageView();

The thing is:

*

*First click (empty textbox) : twitter request is captured by parse
within Tweets collection. Nothing is appended to my ul element.

*Second click (with some word): twitter request is made with that
word. However, 'NYC' tweets from the previous call are printed.

*Third click (with some other word): 'Some word' from second click
are printed.
....
I realize that everytime I try to print my tweets I get the previous reply because Twitter hasn't replied me yet. I suppose that I could get my tweets in the parse callback and printed them, but it seems quite nasty.
On the other hand I've tried to get my tweets binding them to the reset event, but it doesn't work either.
Any ideas??.
Thanks in advance!!

A: Here's your example code done in a more idimatic Backbone pattern.
Basically:

*

*You have your Tweets collection

*You bind an event handler to the collection's reset event that does something with the newly populated collection

*In your view, you set up an event handler for your button-click event that calls collection.fetch() to get new data from the 'server'.

*When the fetch is completed, the reset event is triggered, calling the event handler bound to the reset event.

Code:
var Tweet = Backbone.Model.extend();

var Tweets = Backbone.Collection.extend({
    model: Tweet,
    url: 'http://search.twitter.com/search.json?q=NYC&callback=?',
    parse: function(response) {
        console.log('parsing ...')
        return response.results;
    }
});
var PageView = Backbone.View.extend({
    el: $('body'),
    events: {
        'click button#add': 'doSearch'
    },
    initialize: function() {
        _.bindAll(this, 'render', 'addItem');
        this.tweets = new Tweets();
        _this = this;
        // Bind an event handler for the reset event.
        this.tweets.bind('reset', function(collection) {
            // Clear any old tweet renderings
            _this.$('#tweets').empty();
            // For each tweet in the collection, we call addItem and
            // and pass the tweet.
            collection.each(function(tweet) {
                _this.addItem(tweet);
            });
        });
        this.counter = 0;
        this.render();
    },
    // This function is the event handler for the button click.
    // It tells the Tweets collection to fetch()
    doSearch: function() {
        var subject = $('#search').val() || 'NYC';
        this.tweets.url = 'http://search.twitter.com/search.json?q=' + subject + '&callback=?';
        this.tweets.fetch();
    },
    render: function() {
        $(this.el).append("<input id= 'search'type='text' placeholder='Write a word'></input>");
        $(this.el).append("<button id='add'>Search twitts</button>");
        $(this.el).append("

");
        return this;
    },
    addItem: function(item) {
        console.log(item);
        $('ul', this.el).append("
" + item.get('from_user_name') + ":  " + item.get('text') + "
");

    }
});
var pageView = new PageView();

Live example to play with:  http://jsfiddle.net/38L35/16/


text:
Q: Fetching image fails on expo on react native on android I use fetch sending image to a server.
On iOS everythin works as expected, but on android i get Request fialed.
The uri i get from expo image picker, on IOS everything works as expected.
const form = new FormData();
      form.append('file', {
        uri: imageUri,
        name: 'file.jpg',
        fileName: 'file',
      });

fetch(api,{
      method: 'post',
      body: form,
    })
      .then(response => response.text())
      .then(textResponse => {
      console.log(textResponse);
      Alert.alert(textResponse);
      if (textResponse){
        setAccuracyResponse(textResponse);
      }
      })
      .catch(error => {
        console.error(error)
      });

on android i get this response
Network request failed
- node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:383:16 in callTimers
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:416:4 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:109:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

Expo sdk v39
Expo version 3.28.5
node v14.15.0
npm 6.14.8

A: There were couple issues with this. First was that file picker in android would give imageUri value as
file:/user/.../path/to/file.jpg

whereas file picker in iOS would give imageUri value as
file:///user/.../path/to/file.jpg.

So the correct approach is to use file:// instead of file: in the formData in android.
The second issue is providing proper mime type in the form data, Ex: mime-type for .jpg file would be image/jpeg and for .png file would be image/png, so you can use a "mime" npm package for this.
So my final solution looks like this:
const imageUri = result.uri;
const newImageUri = Platform.OS === "android" ? "file:///" + imageUri.split("file:/").join("") : imageUri;
const form = new FormData();
  form.append('file', { //this prop can vary depends of your sever settings
    uri: newImageUri,
    type: mime.getType(newImageUri),
    name: newImageUri.split("/").pop(),
  });

The complete stack of this problem with a solution can be found here


text:
Q: how to control speed of worker thread(secondary thread) in android I am making a ECG graph display android application and extending  surfaceView class and implement SurfaceHolder. Callback and using  worker thread to lock canvas and and unlock as very common in game loop.
my class which extend surfaceView have draw function which draw line and this function is called by secondary thread to draw on lock canvas.
now my problem is that speed of drawing graph is so high. how i can control the speed of drawing .or can't we control control worker thread speed ?
thanks in advance.

A: I have worked on ECG sensor before and I am pretty sure you can set a sampling rate in the sensor. Try decreasing the sampling rate and your application will automatically behave as you want.
Otherwise you can also take a look at a thread.sleep() method or use timer class and timer.schedule() method to run some code in specific intervals.


text:
Q: gmail like account verification with phone call google recently(not very recently) started to verify new gmail accounts bt phone. when account is created and you are on the final step, a robot calls by phone and tell you the verification number. PHP-Side is OK but the calling section i have no idea. how can i do that? where to start?

A: A good place to start would be providing the user an input field for their phone number.


text:
Q: Are Maybe String and Maybe Int both Monoids in Haskell? I´ve gotten into a bit of confusion whether Maybe Int and Maybe String are both monoids in Haskell because i dont really know what functions you can apply to Int or String in terms of monoids with their neutral element and associativity rules! Can anybody help me out?

A: There is a Monoid instance for any Maybe a as long as a itself has a Monoid instance; the combination of two Just values simply combines the wrapped values according to their instance, while anything combined with Nothing is itself Nothing.
String has a Monoid instance by virtue of being an alias of [Char]; all lists are monoids via list concatenation with the empty list as the identity. As a result, Maybe String is a monoid as well.
> Just "Fo" <> Just "o"
Just "Foo"
> Just "Fo" <> Nothing
Just "Fo"

Maybe Int is not a monoid, because Int is not a monoid. This is because there are multiple choices for how to make Int a monoid, so no one choice is chosen as special. Instead, several new types are defined with distinct Monoid instances to clarify which operation you want to use.
> import Data.Monoid
> (3 :: Int) <> 5

<interactive>:8:1: error:
    • No instance for (Semigroup Int) arising from a use of '<>'
    • In the expression: (3 :: Int) <> 5
      In an equation for 'it': it = (3 :: Int) <> 5

-- (+) and 0
> Sum (3 :: Int) <> Sum 5
Sum {getSum = 8}

-- (*) and 1
> Product (3 :: Int) <> Product 5
Product {getProduct = 15}

> Just (Sum (3 :: Int)) <> Just (Sum 5)
Just (Sum {getSum = 8})
> Just (Sum (3 :: Int)) <> Nothing
Just (Sum {getSum = 3})

A: The Monoid instance for Maybe types has been defined as [src]:

instance Semigroup a => Monoid (Maybe a) where
    mempty = Nothing

it thus requires Int or String to be instances of the Semigroup type class. Since a String is the same as type String = [Char] and thus a list of Chars, this is the case, indeed we see [src]:

instance Semigroup [a] where
        (<>) = (++)
        {-# INLINE (<>) #-}

        stimes = stimesList

so it will append the two lists, and for a Maybe this means [src]:

instance Semigroup a => Semigroup (Maybe a) where
    Nothing <> b       = b
    a       <> Nothing = a
    Just a  <> Just b  = Just (a <> b)

    stimes = stimesMaybe

This thus means that for two Maybe Strings, the neutral element is Nothing and the binary operator will append the two strings wrapped in Just … data constructors if these are both Justs, the Just one if one of the two is a Just, or Nothing if both items are Nothings.
This is not the case for an Int, indeed. For integers there can be multiple Monoid instances, for example ⟨ℤ,+, 0⟩ or ⟨ℤ,×, 1⟩.


text:
Q: Replace regex submatched fields with extracts from email body First, Here is exactly what I want to do.

*

*Open outlook if it isn't already

*highlite an email from the quickview pane

*Run VBA code from an icon on the ribbon

*The code will pick up 3 items from the currently selected email using regular expressions.

*The 3 items will be used to fill in a form in my drafts folder with a specific subject.

*The previous items will be used to replace fields in the form that are enclosed in braces {} or curly brackets, I've heard them called both.

*The email will pop up but wait for me to send it.

Now, onto the code I've come up with so far.
Public Function GetIDsRegExp()

Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Set olApp = New Outlook.Application
Dim objRegExp As RegExp
Dim sString As String
Dim sBody As String
Dim objMatch As Match
Dim colMatches As MatchCollection

Set olMail = olApp.ActiveExplorer.Selection.Item(1)
'Debug.Print olMail.Body
    sString = olMail.Body

    Set objRegExp = New RegExp

    With objRegExp
        .Pattern = "(?:message|instrument)ID\s+:(\w+)"
        .IgnoreCase = True
        .Global = True
    End With

    If (objRegExp.Test(sString) = True) Then

        'Get the matches.
         Set colMatches = objRegExp.Execute(sString)   ' Execute search.

        For Each objMatch In colMatches   ' Iterate Matches collection.
            Debug.Print objMatch.SubMatches(0)

'      sBody = Replace(Template, "{MessageID}", objMatch.SubMatches(0))
'      sBody = Replace(Template, "{InstrumentID}", objMatch.SubMatches(0))
'      Debug.Print sBody

        Next

    End If

    Template = FindTemplate()
    Debug.Print Replace(Template, "{Date}", Now())

End Function

Function FindTemplate()
        Set objOutlook = GetObject("", "Outlook.Application")
        Set objDrafts = objOutlook.GetNamespace("MAPI").GetDefaultFolder(16)
        Set objItems = objDrafts.Items

        For Each objDraft In objItems
                If objDraft.Subject = "Environment : Prod International Trade Error" Then
                        FindTemplate = objDraft.Body
                        Exit Function
                End If
        Next
End Function

When I debug.print the code, I get exactly what I want. Now, I need to replace fields enclosed by {} in the template with the right submatched extracts. I'm stuck on 5 and 6.

A: Is it possible to change from {} to {adress} so you can do a string replace?
https://msdn.microsoft.com/en-us/library/bt3szac5%28v=vs.90%29.aspx
String = Replace(title, "something", "{adres}")

It should be also possible to compile an entire email from vba so you can bypass the draft folder (that's a step i don't fully get)?
https://msdn.microsoft.com/en-us/library/office/ff861332.aspx
Sub CreateMail()

 Dim myItem As Object

 Set myItem = Application.CreateItem(olMailItem)

 myItem.Subject = "Mail to myself"

 myItem.Display

End Sub


text:
Q: Apex Encryption to AMPscript Decryption I receive a string encrypted using the Apex function Crypto.encryptWithManagedIV() using AES256 as a url parameter, and I need to be able to decrypt this string on a marketing cloud landing page.
I have tried using the DecryptSymmetric() function, but I get an error saying "padding is invalid and cannot be removed".
The Apex code that generates the string is:
Blob cryptoKey = Blob.valueOf('I Am Thirty Two Bytes Long 12345');
Blob encryptedData = Crypto.encrypt('AES256', cryptoKey, Blob.valueOf('1234567890123456'), Blob.valueOf('Test123'));
String Output = EncodingUtil.base64Encode(encryptedData);
system.debug('Encrypted====== ' + Output);

The output of that code is:
Encrypted====== Crbyjxq+hJywMkfAky+SVw==

I have then taken that string and put it into the following AMPscript code to try and decrypt it:
%%[
set @string = "Crbyjxq+hJywMkfAky+SVw=="
/* Hex representation of 1234567890123456 */
set @iv = "31323334353637383930313233343536"

set @string = DecryptSymmetric(@string, "AES", @null, "I Am Thirty Two Bytes Long 12345", @null, "0", @null, @iv)
]%%

The padding used by the Apex method is pkcs5 and the default padding of the AMPscript method is pkcs7 which I have read should be compatible, so I do not understand the error message or what the problem is.
Any help would be greatly appreciated.


text:
Q: IllegalStateException: Same thread, different source (GUI) my problem is that I want to add the same ActionListener to 2 different components on my GUI program. One, when the user presses Enter Key in a JTextField, and the second when the user clicks on a JButton.  I am using the Netbeans IDE.
So I created a Thread, t1, and in the actionListener's actionPerformed method, I simply put t1.start(). Then I added the actionListener object to my JTextField and my JButton.
When I run the program, the first time I either click the button or press Enter, the program runs smoothly. But on the second time I click the button or press Enter, the program throws an IllegalStateException.
Here is my code:
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            //Do something
        }
     });
    public final ActionListener listener;

    public myClass () {    //Constructor
        this.listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                t1.start();
            }
        };
    InitComponents();
    JButton.addActionListener(listener);      //Adding listener object to JButton.
    JTextField.addActionListener(listener);   //Adding listener object to JTextField.
    }

I am thinking that the thread did not 'die' from the first time I clicked or pressed Enter, even though the run() method already exited. I tested the program at different points to make sure that the run() method did exit.
I am able to make program work if I create a thread in both the JButtonActionPerformed( and JTextFieldActionPerformed() methods, and start them inside these methods itself. But it's redundant since I am writing the same actions to be performed in 2 different methods.
Any help on why the IllegalStateException exception was thrown and on how to create a single ActionListener for both the JComponents using a thread is appreciated.
Thanks!

A: As the JavaDocs state...

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
  Throws:
  IllegalThreadStateException - if the thread was already started.

You can not start a Thread twice.  Instead, start with a Runnable and wrap a new Thread around it each time you want to run it


text:
Q: SQL Server: Where & Like Statements I'm fairly rusty with my SQL game. I have some code (see below) that checks on a database instance (instance001, instance002, etc), then looks for when the LAST_READ and LAST_WRITE fields are null, along with when it was last reset. Nothing too over the top.
The issue I'm having is how to execute this across multiple instances. You'll see I commented out a section. If I add in the appropriate OR statement (or inst_name like 'instance002'), it isn't getting the results I was seeking.
Example: instance001 yields 1 records. instance002 yields 60. If I use
where inst_name like 'instance001' or inst_name like 'instance002'
I get 210 records. How would I manipulate the SQL to provide 61?
declare @timeString nvarchar(50) = CONVERT(varchar(24), GETDATE(), 120)
select DB_NAME, INST_NAME, MIN([LAST_SRVR_RST]) AS MIN_SRVR_RST, LAST_READ, LAST_WRITE, LOG_DATE=@timeString
from CMS_DB_LAST_READ_WRITE     -- Targeted DB with data.
where inst_name                 -- Targeted instance(s)
    like 'instance001'
    /*
    like 'instance002'
    like 'instance003'
    like 'instance004'
    */
    and LAST_READ is null       -- Both read and write must be null
    and LAST_WRITE is null      -- to show no activity.
    --and [LAST_SRVR_RST] = MIN([LAST_SRVR_RST])
group by DB_NAME, INST_NAME, LAST_SRVR_RST, LAST_READ, LAST_WRITE

A: AND takes precedence over OR, you need to group the two conditions using parenthesis:
...
WHERE (inst_name = 'instance001' OR inst_name = 'instance002')
AND   LAST_READ  IS NULL
AND   LAST_WRITE IS NULL
GROUP BY ...

Note: I changed the usage from LIKE to =, as you are looking for an exact match, and it doesn't make much sense to use LIKE in that situation.
The reason for the grouping is due to the precedence order mentioned above. This order is:
Level   Operators
1       ~ (Bitwise NOT)
2       * (Multiply), / (Division), % (Modulo)
3       + (Positive), - (Negative), + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND), ^ (Bitwise Exclusive OR), | (Bitwise OR)
4       =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
5       NOT
6       AND
7       ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
8       = (Assignment)

What this means is, all of your AND statements will be evaluated first. After they have all been evaluated, then your OR statement is evaluated.
This makes your query look more like this to the compiler:
WHERE
(
        inst_name = 'instance001'
AND     LAST_READ  IS NULL
AND     LAST_WRITE IS NULL
)
OR      inst_name = 'instance002'

Which is why you were getting 210 results, as opposed to the expected 61, as it was pulling in all records in instance002, disregarding your other WHERE filters.
Rewriting the query grouping the two conditions as mentioned above would look like this to the compiler instead:
WHERE
(
        LAST_READ  IS NULL
AND     LAST_WRITE IS NULL
)
AND
(
        inst_name = 'instance002'
OR      inst_name = 'instance001'
)

Which should be the logical conditions you were expecting.

Another alternative way you can write this query without the AND/OR grouping altogether is by using an IN clause:
...
WHERE inst_name IN ('instance001', 'instance002')
AND   LAST_READ IS NULL
AND   LAST_WRITE IS NULL
GROUP BY ...


text:
Q: Android : Unchecked CheckBox during List View Scrolling I have a ListView with a CheckBox inside its. I had clicked some CheckBoxes and still scrolling - perfect, UNTIL I decided to Scroll back. At this time, the selected CheckBoxes aren't checked and others the wasn't checked had selected. I think that there are some bug at my code, please help me! From now I thank you! Following the code:
public class TableListAdapter extends
ArrayAdapter<String>
{
    private Context context;
    private int layoutId;
    private String[] numbers;
    private int btnColorId;
    public boolean[] listIsChecked;
    char activityOperation;

    int pos;

    public TableListAdapter(Context context, int layoutId,
     String[] numbers, int btnColorId, char activityOperation)
    {
        super(context, layoutId, numbers);
        this.context = context;
        this.layoutId = layoutId;
        this.numbers = numbers;
        this.btnColorId = btnColorId;
        this.activityOperation = activityOperation;

        listIsChecked = new boolean[numbers.length];
    }

    @Override
    public View getView(int position, View view, ViewGroup parent)
    {
        Holder holder;
        pos = position;

        if (view == null)
        {
            holder = new Holder();
            view = LayoutInflater.from(context).inflate(layoutId, null);

            holder.image = (ImageView) view.findViewById(R.id.practice_list_itemImageView);
            holder.button = (Button) view.findViewById(R.id.practice_list_itemButton);
            holder.checkbox = (CheckBox) view.findViewById(R.id.practice_list_itemCheckBox);
        view.setTag(holder);
        }
        else
        {
            holder = (Holder) view.getTag();
        }

                holder.image.setImageResource(R.drawable.ic_launcher);
        holder.button.setText(numbers[position]);
            holder.button.setBackgroundResource(btnColorId);

              holder.checkbox.setChecked(listIsChecked[position]);

     holder.checkbox.setOnClickListener(new CheckBox.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            listIsChecked[pos] = ((CheckBox)v).isChecked();
        }
    });

    holder.button.setOnClickListener(new Button.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(context, ShowTableActivity.class);
            intent.putExtra("activityOperation", activityOperation);
            intent.putExtra("number", pos);
            context.startActivity(intent);
        }
    });

    return view;
}

class Holder
{
    ImageView image;
    Button button;
    CheckBox checkbox;
}
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@color/practice_list_item_auxiliar"
android:gravity="center">

<Button
    android:id="@+id/practice_list_itemButton"
    android:textSize="@dimen/main_button_text"
    android:textStyle="bold"
    android:layout_width="0dp"
    android:layout_height="70dp"
    android:layout_weight="3"
    android:textColor="@android:color/white"
    android:padding="@dimen/main_button_padding"/>

<ImageView
    android:id="@+id/practice_list_itemImageView"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:gravity="center">
    <CheckBox
        android:id="@+id/practice_list_itemCheckBox"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>

 public class MainPracticeActivity  extends Activity
 {
String[] nums = {"1","2","3","4","5","6","7", "8", "9", "10"};
ListView lv;
char activityOperation;

ImageButton imageButtonLinkeable;
ImageButton imageButtonChoiceable;
ImageButton imageButtonTypeable;
ImageButton buttons[] = new ImageButton[3];

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

    activityOperation = getIntent().getCharExtra("activityOperation", '0');

    lv = (ListView) findViewById(R.id.main_practice_ListView);
    TableListAdapter tbl = new TableListAdapter
    (this, R.layout.practice_list_item, nums, getMainColor(activityOperation), activityOperation);
    lv.setAdapter(tbl);

    imageButtonLinkeable = (ImageButton)findViewById(R.id.main_practice_imagebutton_linkable);
    imageButtonChoiceable = (ImageButton)
            findViewById(R.id.main_practice_imagebutton_choiceable);
    imageButtonTypeable = (ImageButton)
            findViewById(R.id.main_practice_imagebutton_typeable);
    buttons[0] = imageButtonLinkeable;
    buttons[1] = imageButtonChoiceable;
    buttons[2] = imageButtonTypeable;

    //Set the default drawable resources to the game's buttons
    unselectButtons(buttons);

    //ImageButtons
    imageButtonLinkeable.setOnClickListener(new ImageButton.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            unselectButtons(buttons);
            selectButton(v);
        }
    });

    imageButtonChoiceable.setOnClickListener(new ImageButton.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            unselectButtons(buttons);
            selectButton(v);
        }
    });

    imageButtonTypeable.setOnClickListener(new ImageButton.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            unselectButtons(buttons);
            selectButton(v);
        }
    });
}

private int getMainColor(char activityOperation)
{
    int colorId = -1;

    switch(activityOperation)
    {
        case '+':
            colorId = R.color.add;
            break;

        case '-':
            colorId = R.color.subtract;
            break;

        case '*':
            colorId = R.color.multiply;
            break;

        case '/':
            colorId = R.color.divide;
            break;
    }
    return colorId;
}

private int getSelectedBackground(char activityOperation)
{
    int backgroundId = -1;

    switch(activityOperation)
    {
        case '+':
            backgroundId = R.drawable.circle_button_add_selected;
            break;

        case '-':
            backgroundId = R.drawable.circle_button_subtract_selected;
            break;

        case '*':
            backgroundId = R.drawable.circle_button_multiply_selected;
            break;

        case '/':
            backgroundId = R.drawable.circle_button_divide_selected;
            break;
    }
    return backgroundId;
}

private int getDefaultBackground(char activityOperation)
{
    int backgroundId = -1;

    switch(activityOperation)
    {
        case '+':
            backgroundId = R.drawable.circle_button_add_default;
            break;

        case '-':
            backgroundId = R.drawable.circle_button_subtract_default;
            break;

        case '*':
            backgroundId = R.drawable.circle_button_multiply_default;
            break;

        case '/':
            backgroundId = R.drawable.circle_button_divide_default;
            break;
    }
    return backgroundId;
}

private void unselectButtons(View...buttons)
{
    for(View cb : buttons)
    {
        ((ImageButton)cb).setBackgroundResource(getDefaultBackground(
        activityOperation));
    }
}

private void selectButton(View button)
{
    ((ImageButton)button).setBackgroundResource
    (getSelectedBackground(activityOperation));
}
 }

A: I think the problem might be the pos variable you're using inside your CheckBox click listener.
Imagine that getView() is called for position 0, then position 1, then position 2, etc (enough to fill up the list with all the visible positions). Once that's done, pos is equal to (let's say) 10. What happens when you click the CheckBox at position 3? I believe you will wind up setting listIsChecked[10] = true.
You should get rid of the pos variable and just use the position argument passed to getView(). You can make it be final if the compiler says it can't use a non-final variable in the click listener.
@Override
public View getView(final int position, View view, ViewGroup parent)
{
    // ...

    holder.checkbox.setOnClickListener(new CheckBox.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            listIsChecked[position] = ((CheckBox)v).isChecked();
        }
    });

    // ...
}


text:
Q: Открыть страницу в браузере и перейти по ссылке Нужно открыть браузер, перейти на определенную страницу (www.site.com), затем найти определенную ссылку (www.site.com/*link.html) и перейти по той ссылке именно со страницы сайта.
Подскажите, пожалуйста, возможно ли такое осуществить посредством VBScript? Подойдут любые варианты.

A: Открыть браузер и перейти по ссылке можно так:
Dim objShell
Set objShell = CreateObject("Shell.Application")

iURL = "www.google.com"

Call objShell.ShellExecute("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", iURL, "", "", 1)

Предварительно вы можете скачать страницу и найти нужную вам ссылку.


text:
Q: How to draw an arrow from a parent div to all children divs? I have a reusable React list component that can have nested children and I want to draw an arrow from the parent div to all direct children divs like the picture below.
List Component Image
Here is an example of a nested list component:
import React from 'react';
import ListElement from './ListElement.js';

const List = () => (
  <>
    <ListElement>
      <ListElement>
        <ListElement>
          <ListElement />
          <ListElement>
            <ListElement />
          </ListElement>
        </ListElement>
        <ListElement />
      </ListElement>
      <ListElement />
    </ListElement>
    <ListElement />
  </>
);

export default List;

The ListElement component looks something like this:
    import React from 'react';

    const ListElement = props => {
      const indentationStyle = { paddingLeft: `${3 * props.indent}rem`,
      position: 'relative'};

      const lineStyle = {
        left: `${2 + 3 * (props.indent - 1.2)}rem`,
      };

      const tile = (

          {props.indent > 0 ? (

          ) : null}

            I am a ListElement

      );

      const getChildren = () => {
        let elements = React.Children.toArray(props.children);

        // increase indent prop of each child and assign what number child it is in the list
        elements = elements.map((element, index) => {
          return React.cloneElement(element, {
            ...element.props,
            indent: props.indent + 1,
            childNumber: index,
          });
        });
        return elements;
      };

      const childTiles =
{getChildren()}
;

      const arrowStyle = {
        backgroundPosition: `${1.3 + 3 * (props.indent - 1)}rem`,
      };

      return (
        <>

              {tile}

            {props.children ? childTiles : null}

        </>
      );
    };

    ListElement.defaultProps = {
      childNumber: 0,
      indent: 0,
    };

    export default ListElement;

and the css looks like this:
ul.no-bullet {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.arrow-line {
  border-left: 2px solid #6a6969;
  content: "";
  position: absolute;
  height: 65%;
}

li.arrow {
  background: url("./arrow.png") no-repeat;
}

li.no-arrow {
  display: block;
}

Currently, I am creating the list with
 elements and changing the bullet to an image of the arrow. I want to draw the lines from the parent and attach them to the arrows at each child. I am struggling with calculating the correct height of the line and the position for the top of the line. Any suggestions are appreciated.
Here is a link to the Plunker: https://plnkr.co/edit/GFrriWfJyeur7MRh?open=Hello.js&deferRun=1&preview

A: I managed to find a solution by only drawing one line at the last child and using offsetTop and getBoundingClientRect().height to calculate the position and height of the arrow-line. Working solution here: https://plnkr.co/edit/SFzgiZi1dckRa79C


text:
Q: When release NSXMLParser? I am using NSXMLParser like this :

- (BOOL)parseXMLData:(NSData *)inData
{
 provisioningParser = [[NSXMLParser alloc] initWithData: inData]; // defined if .h
 [provisioningParser setDelegate:self];
 [provisioningParser setShouldProcessNamespaces:NO];
 [provisioningParser setShouldReportNamespacePrefixes:NO];
 [provisioningParser setShouldResolveExternalEntities:NO];

return [provisioningParser parse];
}

My question is when should I release NSXMLParser?
I believe it is automatically released when parsing is finished; is this true?
If yes, instruments indicate there is a leak.
Do you have an idea ?
Thanks

A: Since you alloc'd it, you'll need to release it.  Just release it after calling parse:
BOOL rval = [provisioningParser parse];
[provisioningParser release];
return rval;

Also, from the looks of your code, it looks like you might be saving this in a member variable.  Is there a reason for doing that? If not, make it a local variable.  If so, you'll probably want to release it in the dealloc() method of your class instead of after calling parse().

A: The correct thing to do is to release it within the dealloc method since it's an instance variable. But your code is wrong for that scenario. Imagine calling parseXMLData: twice in a row. provisioningParser will be overwritten the second time, making it impossible to release it within your dealloc.
If you want it to be local, declare it local, and end the method with
return [[provisioningParser autorelease] parse];

You could allocate it with NXSMLParser 'parserWithData:' and not have to do any of this (still should move it local to the method though).


text:
Q: How to group data and create line for each data object? I currently have the below canvas with axis implemented. However, I am new to D3 and could not find enough information on how to make the line start at 0 and hit the data point which each placement's 'y' value. The line I am looking for is a curve. Also each placement should have their own line. How to make sure to group each data object to one line that will start at 0 or from the beginning of 'y'?
https://jsfiddle.net/Gereltuya/xby3j6k6/
var data=[
  {
    "placement_name": "BAN1",
    "alpha": 140.3,
    "beta": 0.0000386,
    "max_x_val": "28,675.00",
    "spend": 29919,
    "y": 93.93621404
  },
  {
    "placement_name": "BAN2",
    "alpha": 115.31,
    "beta": 0.0000208,
    "max_x_val": "32,302.00",
    "spend": 28367,
    "y": 56.39370495
  },
  {
    "placement_name": "BAN3",
    "alpha": 91.9,
    "beta": 0.0000507,
    "max_x_val": "19,740.00",
    "spend": 16972,
    "y": 58.10382629
  },
  {
    "placement_name": "ADJ4",
    "alpha": 91.8,
    "beta": 0.000029119,
    "max_x_val": "25,855.00",
    "spend": 27112,
    "y": 48.56107812
  },
  {
    "placement_name": "ADJ5",
    "alpha": 90.3,
    "beta": 0.0000281,
    "max_x_val": "25,793.00",
    "spend":23883,
    "y": 46.55407367
  },
  {
    "placement_name": "ADJ6",
    "alpha": 88.8,
    "beta": 0.0000178,
    "max_x_val": "25,263.00",
    "spend": 28401,
    "y": 32.12792707
  },
  {
    "placement_name": "ADJ7",
    "alpha": 47.3,
    "beta": 0.000100787,
    "max_x_val": "10,226.00",
    "spend": 12428,
    "y": 30.4244956
  },
  {
    "placement_name": "ADJ8",
    "alpha": 47.3,
    "beta": 0.0000254,
    "max_x_val": "25,669.00",
    "spend": 21899,
    "y": 22.65738987
  },
  {
    "placement_name": "ADJ",
    "alpha": 43.98,
    "beta": 0.00018458,
    "max_x_val": "6,928.00",
    "spend": 9068,
    "y": 31.73686214
  }
];

 var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 1000 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

xScale = d3.scale.linear().range([margin.left, width - margin.right]).domain([d3.min(data, function(d) {
    return d.spend;
}), d3.max(data, function(d) {
    return d.spend;
})]),

yScale = d3.scale.linear().range([height - margin.top, margin.bottom]).domain([d3.min(data, function(d) {
    return d.y;
}), d3.max(data, function(d) {
    return d.y;
})]),

color = d3.scale.category10()
    .domain(d3.keys(data[0]).filter(function(key) { return key === "placement_name"; })),

xAxis = d3.svg.axis()
    .scale(xScale)
    .tickFormat(d3.format('d'))
    .orient('bottom'),

yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left"),

vis = d3.select(".jumbotron").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

vis.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + yScale(0) + ")")
      .call(xAxis);
vis.append("g")
      .attr("class", "y axis")
      .call(yAxis);

vis.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.call(xAxis);
vis.selectAll(".y line")
      .attr('class', 'grid')
      .attr("x2", width);

  vis.selectAll(".x line")
      .attr('class', 'grid')
      .attr("y2", height)
      .attr("transform", "translate(0," + (-yScale(0)) + ")");

  vis.selectAll(".x text")
      .attr("transform", "translate(-5, -4)");

 var lineGen = d3.svg.line()
                        .x(function(d,i) {
                            return xScale(i);
                        })
                        .y(function(d,i) {
                            return yScale(d);
                        })
                        .interpolate("basis");
  var people = vis.selectAll(".people")
      .data(data)
    .enter().append("g")
     .attr("class", "people");

 people.append("path")
      .attr("class", "lineGen")
      .attr("d",lineGen(data))
      .style("stroke", function(d) { return color(d.placement_name); });

  people.append("text")
      .datum(function(d) { return {name: d.placement_name,value: d.spend}; })
      .attr("x", 0)
      .attr("dy", ".35em")
      .text(function(d) { return d.placement_name; });


text:
Q: How to use TextResponse, HtmlResponse and XmlResponse? I see there are several types of responses, but how do I signal Scrapy to return an HtmlResponse?
I think the goal would be to implement def parse(self, response: HtmlResponse):. Or is this supposed to be used some other way? Is there an usag example?
This is the example from Scrapy tutorial. How would I use HtmlResponse here instead of the default?
import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'https://quotes.toscrape.com/page/1/',
            'https://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = f'quotes-{page}.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log(f'Saved file {filename}')

A: Scrapy tries to identify the type of response it gets and calls parse with a specific type. As far as I can tell, parse is never called with the base type Response. The Response identification is done in `scrapy/responsetypes.py by a sort of methods: mimetype, body, headers, etc.
Here's the mimetype identification map:
CLASSES = {
    'text/html': 'scrapy.http.HtmlResponse',
    'application/atom+xml': 'scrapy.http.XmlResponse',
    'application/rdf+xml': 'scrapy.http.XmlResponse',
    'application/rss+xml': 'scrapy.http.XmlResponse',
    'application/xhtml+xml': 'scrapy.http.HtmlResponse',
    'application/vnd.wap.xhtml+xml': 'scrapy.http.HtmlResponse',
    'application/xml': 'scrapy.http.XmlResponse',
    'application/json': 'scrapy.http.TextResponse',
    'application/x-json': 'scrapy.http.TextResponse',
    'application/json-amazonui-streaming': 'scrapy.http.TextResponse',
    'application/javascript': 'scrapy.http.TextResponse',
    'application/x-javascript': 'scrapy.http.TextResponse',
    'text/xml': 'scrapy.http.XmlResponse',
    'text/*': 'scrapy.http.TextResponse',
}

Since parse is called with one of the subclasses, devs have access to it directly in the response parameter. One way to use it is like this:
   def parse(self, response):
       if isinstance(response, HtmlResponse):
           ...


text:
Q: Opencart change default value of list I have a list where you can choose an option. I need to change default value to my own. Is it possible in Opencart?

   Choose
      <select name="option[227]" id="frmdocumentsForm-r1" class="form-control" wtx-context="0128A83E-7CFB-40AA-836C-8D17569841BF">

                    <option value=""> --- Please choose an option --- </option>
                                    <option value="17">AAAA</option>
                                    <option value="18">BBB</option>
                                    <option value="19">CCC</option>
                                    <option value="44">DDD</option>
                                  </select>

I need to change value "17" -> "AAA"
Thanks

A: change  attribute value  with loop . If you need replace only 1st value 17 check for if condition.

$( "select > option").each(function() {
$(this).attr('value',$(this).text());
});

<select>
<option value=""> --- Please choose an option --- </option>
<option value="17">AAAA</option>
<option value="18">BBB</option>
<option value="19">CCC</option>
<option value="44">DDD</option>
</select>


text:
Q: Simplification - Boolean Algebra using DeMorgan law
Can somebody please help me simplify this expression using DeMorgan law.
$\lnot{(A\land B)}+\lnot{(\lnot{A}\land B)}$
Thank you.

A: Present for the day:
$\overline{AB}+\overline{{\bar A}B} = \bar{A} + \bar{B} + A + \bar{B} = A + \bar{A} +\bar{B}= 1+\bar{B} = 1$


text:
Q: Python Bokeh imports logic In Python Bokeh it is possible to import certain classes with 2 different paths, for instance:
from bokeh.plotting import ColumnDataSource

works, as well as:
from bokeh.models import ColumnDataSource

What is the logic behind it? I just find it not neat/nice to be always surprised by how the import paths are (as they are always different) when using the examples from the documentation.

A: You'll find that bokeh.plotting imports ColumnDataSource from bokeh.models. The behavior is a consequence of how classes get imported into different namespaces. Your best course of action is the import from the package that ColumnDataSource is defined in, which in this case is bokeh.models.

A: In this case, to avoid clashes you would do. If you are lucky there are referencing the same classes anyway, in worst case you might have some nasty problem.s
from bokeh.plotting import ColumnDataSource as pcd
from bokeh.models import ColumnDataSource as mcd

In this case, they are both the same:
print pcd.__mro__
print mcd.__mro__

'bokeh.models.sources.ColumnDataSource'>, 'bokeh.models.sources.DataSource'>, 'bokeh.model.Model'>, 'bokeh.core.properties.HasProps'>, 'bokeh.util.callback_manager.CallbackManager'>,


text:
Q: Extract a number with sed Given
1  = 1.093691
how can I extract just 1.093691 with sed?
[\d\.]{2,} will match the number, but how do I do the opposite, i.e., get rid of everything else?
I tried using ^ but couldn't figure it out.
Maybe awk?

A: this grep line works for your example input:
grep -oP '[\d.]+(?=\s*$)'

or sed works for your given example too.
sed  's/.*//;s#.*##'

same idea with gnu awk:
awk -F'</?strong>' '{$0=$(NF-1)}7'

A: This worked:
sed -E 's:.*([0-9.]+).*:\1:g'


text:
Q: Are raring arm packages available someplace? I neglected to update my ARM system from raring to saucy in time. Now I can't install update-manager-core; things are missing.
Is there a way to manually update sources.list to point to some sort of archive so that I can get the update to saucy?


text:
Q: Angular 2 - Template? Em uma estrutura como esta:

   div1: <router-outlet></router-outlet>
   div2: <router-outlet></router-outlet>
   div3: <router-outlet></router-outlet>

Eu tenho essa estrutura no meu app.componente.html. Ocorre que as minhas rotas (paginas), terão elementos (outras divs, inputs, table, etc) que irão compor partes diferentes do templates (div1, div2, div3,div4, etc..) Consegui ser claro?
Como monto essa estrutura no angular? Consigo montar esta estrutura no Laravel utilizando as Session.


text:
Q: C# not recognizing a string sent to powershell somehow I want to remove an email alias from a mailbox which is selected by the user.
string removeAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{remove=\"" + textBox2.Text + "\"}";

However, this does not work and I am not getting any error. Also, the following code works to add an email alias:
string setAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{add=\"" + alias + "\"}";

I still cant figure out why this does not work. Any help would be really appreciated.

A: for any one facing such trouble. There was a whitespace in my alias string and so Powershell was not accepting it. I used the following to get rid of whitespaces:
selectedAlias = Regex.Replace(selectedAlias, "[\n\r\t]", "");


text:
Q: Rails check_box inside fields_for I have a nested form
- f.object.buttons.build if f.object.buttons.blank?
- f.object.buttons.each do |button|
  = f.fields_for :buttons, button, index: nil do |button|
    .control-group
      = button.label :url, 'Url'
      = button.text_field :url, {type: 'url'}

    .control-group
      = button.label :active, 'Active'
      = button.check_box :active

    # ...

When I check check_box and save this form, something weird happened: in the params hash I can see, that instead of one button with checked params 'active' form sends two buttons:
..., "buttons"=>[{"label"=>"site", "url"=>"http://example.com", "active"=>"0"}, {"active"=>"1"}]}

A: you have two variables named button in your fields_for scope


text:
Q: Hadoop reuse Job object I have a pool of Jobs from which I retrieve jobs and start them. The pattern is something like:
    Job job = JobPool.getJob();
    job.waitForCompletion();
    JobPool.release(job);

I get a problem when I try to reuse a job object in the sense that it doesn't even run (most probably because it's status is : COMPLETED). So, in the following snippet the second waitForCompletion call prints the statistics/counters of the job and doesn't do anything else.
    Job jobX = JobPool.getJob();
    jobX.waitForCompletion();
    JobPool.release(jobX);

    //.......

    Job jobX = JobPool.getJob();
    jobX.waitForCompletion(); // <--- here the job should run, but it doesn't

Am I right when I say that the job doesn't actually run because hadoop sees its status as completed and it doesn't event try to run it ? If yes, do you know how to reset a job object so that I can reuse it ?

A: The Javadoc includes this hint that the jobs should only run once

The set methods only work until the job is submitted, afterwards they will throw an IllegalStateException.

I think there's some confusion about the job, and the view of the job.  The latter is the thing that you have got, and it is designed to map to at most one job running in hadoop.  The view of the job is fundamentally light weight, and if creating that object is expensive relative to actually running the job... well, I've got to believe that your jobs are simple enough that you don't need hadoop.
Using the view to submit a job is potentially expensive (copying jars into the cluster, initializing the job in the JobTracker, and so on); conceptually, the idea of telling the jobtracker to "rerun " or "copy  ; run ", makes sense.  As far as I can tell, there's no support for either of those ideas in practice.  I suspect that hadoop isn't actually guaranteeing retention policies that would support either use case.


text:
Q: Check if an user exist in my database with Node and MySQL This is my sandbox in the server folder there is the back-end while the front-end is in the src one. I'm using React.js and Node.js.
Let's go to the point, I use Auth0 for authentication,I want to use Auth0's user_id to register users in my database in order to retrieve and update their information: e-mail, name, surname.
With Auth0 sub claim it's used to get the user_id. I would like to first check if the sub property is present in my MySQL database if true update user info with that sub else create new user record.
For example. johnsmith@gmail.com with sub: id1234 submit form
if(id1234 exist in database) {
update info;
} else {
create new user record;
}


text:
Q: How to align datepicker icon appearing below the datepicker textbox properly? I have a datepicker and I want the datepicker icon to appear just after the datepicker. However, the datepicker icon appears below the datepicker. I have attached a JSFiddle. Fiddle for datepicker

      $(document).ready(function() {
        $("#datepicker").datepicker({
          changeMonth: true,
          changeYear: true,
          yearRange: "-100:+0",
          showOn: 'button',
          buttonText: 'Show Date',
          buttonImageOnly: true,
          buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif',
          dateFormat: 'dd/mm/yy',
          maxDate: 0
        });
      });

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css">

  <form>

        DOB :

        <input class="form-control" name="dob" value="" id="datepicker" type="text">

  </form>

I tried getting the datepicker button aligned to the textbox in many ways but failed. I have to get the datepicker button aligned to the textbox.
It works perfectly on JSFiddle. However, if you run it on Chrome. You will notice that datepicker button appears below the text box. How to align it to text-box?

A: input.hasDatepicker {
    display: inline-block;
    margin-right: 5px;
    width: -webkit-calc(100% - 21px);
    width: -moz-calc(100% - 21px);
    width: -o-calc(100% - 21px);
    width: -ms-calc(100% - 21px);
    width: calc(100% - 21px);
}

Add the above css

$(document).ready(function() {
        $("#datepicker").datepicker({
          changeMonth: true,
          changeYear: true,
          yearRange: "-100:+0",
          showOn: 'button',
          buttonText: 'Show Date',
          buttonImageOnly: true,
          buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif',
          dateFormat: 'dd/mm/yy',
          maxDate: 0
        });
      });
input.hasDatepicker {
  display: inline-block;
  margin-right: 5px;
  width: -webkit-calc(100% - 21px);
  width: -moz-calc(100% - 21px);
  width: -o-calc(100% - 21px);
  width: -ms-calc(100% - 21px);
  width: calc(100% - 21px);
}

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css">

  <form>

        DOB :

        <input class="form-control" name="dob" value="" id="datepicker" type="text">

  </form>

A: Just change below CSS
.form-control {
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
  color: #555;
  display: inline;
  font-size: 14px;
  height: 34px;
  line-height: 1.42857;
  margin-right: 10px;
  padding: 6px 12px;
  transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s  ease-in-out 0s;
  width: 90%;
}

A: Adding this to style did the job..
display: inline-block;
vertical-align: middle;
width: 90%;
margin: 0 5px 0 0;


text:
Q: Import code coverage calculated from sonarqube dashboard on TFS dashboard I have visual studio and code in c# .net, and using TFS for code check in. Now I am using sonarqube to find out code coverage and bugs etc parameters for my code. So I am able to see them on my sonarqube dashboard, now I want to import that statistics on my TFS dashboard from sonarqube dashboard. How can I do that. Can anyone guide me please. Thanks in advance.

A: There isn't the built-in widget to import sonarqube code coverage result in TFS dashboard. You can try to build a custom extension with SonarQube Web Service API to get the related report and show in that extension.
A related thread about get code coverage through Sonaqube API: Sonarqube API single class test coverage


text:
Q: Multi processamento/Multithread não está a funcionar Quero tentar resolver o problema de quando o cliente não consegue se conectar com o servidor(falha de ligação, servidor em baixo, etc).
Na minha classe principal está a ligação ao servidor e eu quero que no caso de dar erro apanhado pelo try ... catch(ConnectException ex) lançar um JDialog a informar o cliente que ainda não está conectado...

Algo deste género, o JDialog é criado mas só é desenhado quando a operação acaba, isto é enquanto a thread principal tenta se conectar nao desenha nada, só quando consegue a conexão é que desenha tanto o JDialog como o frame principal.
Código para conectar ao server:
public Socket connect() {
    try {

        this.socket = new Socket("localhost", 5555);
        this.output = new ObjectOutputStream(socket.getOutputStream());

    } catch (ConnectException ex) {
                waitinng();//crio o frame mas ele só aparece quando o servidor está conectado
                System.out.println("tenta conectar");
                connect();//volto a chamar a função até que se consiga conectar
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownHostException ex) {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return socket;
}

Para aparecer o JDialog já tentei:
Criar uma class normal, mas nao funcionou;
Criar uma thread que cria o JDialog, também não deu
Agora por ultimo estou a tentar com o swingworker, mas com alguns problemas...
Perguntas:

*

*O swingWorker é o caminho que devo seguir?

*O que devo inserir como parametros de entrada SwingWorker<Integer,
Integer>

*É no doInBackground que devo criar o JDialog ou no construtor?

EDIT
Tenho serias duvidas se o meu problema está no multithread ou na maneira como o java processa o que quero fazer...
Esboço:

nao sei se ajuda esta edição...

A: Você pode fazer com Thread, fiz um exemplo simples tem o JFrame a thread principal e um botão que quando você clica inicia outra Thread que exibe o jDialog você pode por esse seu código dentro do método run() e passar por referencia os Sockets, você precisa por todo código necessário para executar em paralelo, criar apenas o jDialog em uma Thread não vai funcionar
Classe Frame - Thread principal
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class Frame extends JFrame {

    private JButton botao;
    private JDialog dialog;

    public Frame() {

        botao = new JButton("OK");
        botao.addActionListener(new BotaoEvento());
        this.add(botao);
        botao.addActionListener(null);
        this.setSize(400, 400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public class BotaoEvento implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            Thread thread = new Thread(new Dialog(dialog));
            thread.start();
        }

    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
    }

}

Classe Dialog - Thread Extra
import javax.swing.JDialog;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

public class Dialog implements Runnable {

    JDialog dialog;

    public Dialog(JDialog dialog) {
        this.dialog = dialog;
    }

    public void run() {
        dialog = new JDialog();
        dialog.setSize(200, 200);
        dialog.setLocationRelativeTo(null);
        dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
        //operações que você deseja executar
    }

}


text:
Q: Is there a graphical intuition behind the Vieta's substitution for reduction of a depressed cubic to a quadratic? Like for the first substitution from a general cubic equation to a depressed cubic, a substitution is made so that the inflection point of the cubic equation changes to the y axis, so that it represents a depressed cubic, similarly is there a graphical institution for Vieta's sub ($x=w-\frac{p}{3w}$ for $x^3 + px+q=0$)?
One of the ways I know the sub was thought of was to just convert into a "perfect cube" but I think it's more algebra sided and would like a more visual approach.


text:
Q: How to change the UI on specific url/websites in Firefox? What i'am trying to do is to remove, or at least hide the horizontal scrollbar in Firefox when i visit a specific website/url. I found code which hides the bottom scrollbar, but on all websites:
:-moz-any(#content,#appcontent) browser{
 margin-bottom:-17px!important;
 overflow-x:scroll;
}

All i did so far is to create the chrome folder, created the userChrome.css and pasted in the above code. So far so good. Since i have literally no idea how to bind this customisation to a specific website/url i just tried to replace the first line with the following code:
@document url("https://www.example.com/"){

or
:-moz-any(#content,#appcontent), domain("https://www.example.com/") browser{

or
@-moz-document url-prefix("https://www.example.com/"){

What iam searching for is more or less a "if-condition" when the url of the website contains "xyz.com/" (like the url-prefix(): "Matches if the document URL starts with the value provided") then remove/hide the bottom scrollbar. I know this is super rude to ask something like this, but i think i just need the correct syntax to add the website/url condition in the code. And to go though hours and hours of tutorial material to find the correct syntax i though i just ask here.