text:
Q: How to return to the last used activity from another package. Android I have an application with 4 packages. I can start one of those packages with the actionbar. Inside all the packages is an alarmManager. The alarmManager start an Activity in his own package.  Lets say the Activity state is in the 3th activity from the first package. And the alarmManager of the second package is working, and opend the 4th Acitivy from (his) the second package. Now my question is how do I go back to my last used activity in the first package? I want this with an menu item in the action bar, and also an item to switch back to my last activity in the second package.  Without using the back button.
I have looked and tryed for hours, with intent flags, but can't find the right one.
Thanks in advance!

A: In the current activity, say you are in the activityThree of the package 3 and you want to go back to the activityFirst of the first package. In the activityThree you have to add this code to the click Listener to go to "activityFirst" activity.
Intent i = new Intent(getApplicationContext(), activityFirst.class);
StartActivity(i);

and in the manifest.xml you have  to add these lines
<activity android:name="com.example.package1.activityFirst"
    android:label="First Activity">

   </activity>

And One thing more you have to import the package1 (Package name of activityFirst ) name in the activityThree code like this import com.example.package1.activityFirst;
and inthe same way you can go back by adding this lines in activity activityFirst.


text:
Q: Getting python to answer "The total net amount of "Profit/Losses" over the entire period" I'm trying to get python to sum a column from a csv file that I imported.  The column includes both positive and negative numbers.  Every time I run my script, the output I get is 0 (zero).  I'm a noob at python so if you could point me in a direction, I would appreciate it.  I'm guessing I'm asking my code to calculate the wrong cells, but the numerous variations I've tried have all resulted in the same output.

A: Your csvreader iterator is already exhausted when you do:
row_count = sum(1 for row in csvreader)

so when you try to iterate over it again in:
for row in csvreader:

there's nothing to iterate over as the file pointer already reaches the end of file.
You should reset the file pointer the csvreader is associated with so that you can iterate over it again.
Add the following after row_count = sum(1 for row in csvreader):
csvfile.seek(0)
next(csvreader)

and your code would work.
But then again, there's no need to iterate over csvreader twice to begin with because all the first iteration does is to get the number of rows, which can easily be done in the second iteration by initializing row_count before the loop and incrementing row_count for each iteration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WIFI P2P REMOVE GROUP I want to connect from one device to different devices one by one. So what I do is check if my device is connected  if(myDevice.status == 0) and if so, I remove the group manager.removeGroup(channel, new ActionListener().
The problem here is that after a couple of times doing this, the method removeGroup() goes to onFailure() with this error: Disconnect failed. Reason :2 which means "BUSY".
How can I stop the framework from being BUSY? Is there any proper way of disconnection between two devices in order to start a new connection to a different one without any problem?

A: Wifi P2p creates a persistent group every time it creates a new group. So just removeGroup() won't work. You will have to use DeletePersistantGroup method (which is hidden). Use reflection to invoke a call on this method:
    private void deletePersistentGroups(){
    try {
        Method[] methods = WifiP2pManager.class.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("deletePersistentGroup")) {
                // Delete any persistent group
                for (int netid = 0; netid < 32; netid++) {
                    methods[i].invoke(manager, channel, netid, null);
                }
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Distribution of $\frac{X_1X_3+X_2X_4}{X_3^2+X_4^2}$
$X_1, X_2, X_3$ and $X_4$ are independent standard normal random variables. Find the distribution of $$T=\frac{X_1X_3+X_2X_4}{X_3^2+X_4^2}$$

I have found that $U=X_1X_3+X_2X_4$ follows standard Laplace distribution. And $V=X_3^2+X_4^2$, being the sum of squares of two independent standard normal random variables, follows Chi-square distribution with d.f. $2$.
But I don't know whether $U$ and $V$ are independent. Because I only have the marginal distributions of $U$ and $V$(i.e. standard Laplace and Chi-square, respectively), but not the joint distribution of $(U,V)$. So I cannot check whether they are independent by checking if their joint distribution is product of their marginal distributions. How can I know that $U$ and $V$ are independent, since both have common terms like $X_3$ and $X_4$? Is there any other way to check their independence?
Since I am not sure about their independence, I cannot proceed to find the distribution of $\frac{U}{V}$ by using Jacobian technique, because for that joint distribution of $(U,V)$ is necessary.
Please anyone help me clear this doubt. Thanks in advance.

A: Suppose $$Z=\frac{X_1X_3+X_2X_4}{\sqrt{X_3^2+X_4^2}}$$
Now conditioning $X_3=a,X_4=b$, we find that the above has a standard normal distribution, since
$$\frac{aX_1+bX_2}{\sqrt{a^2+b^2}}\sim N(0,1)$$
for any real $a,b$. As the conditional distribution does not depend on $a,b$, the unconditional distribution remains the same. That is, $Z\sim N(0,1)$.
Relating $Z$ and $T$ we have $$T=\frac{Z}{\sqrt{X_3^2+X_4^2}}=\frac{Z}{\sqrt 2\sqrt{(X_3^2+X_4^2)/2}}$$
As the distribution of $Z$ is independent of $X_3,X_4$, we can see that $$\frac{Z}{\sqrt{(X_3^2+X_4^2)/2}}\sim t_2$$
So I think $T$ is distributed as $\frac1{\sqrt 2}$ times a $t$ distributed variable with $2$ degrees of freedom.

A: Write $W = (X_1,X_2)$ and $Z = (X_3,X_4)$, which are i.i.d random vectors (with standard normal coordinates). Then using your notation, $U = W\cdot Z$ and $V = \|Z\|^2$ so $T= (W\cdot Z)/\|Z\|^2$. So using that $W$ and $Z$ are independent and law of total probability we have for any Borel $A$ that
\begin{align*}
P(T\in A) &= \int P\left(\frac{W\cdot z}{\|z\|^2}\in A\mid Z = z\right)P(Z=z)dz \\
&=
\int P\left(\frac{W\cdot z}{\|z\|^2}\in A\right)P(Z=z)dz.
\end{align*}
Since you know the distributions of $W$ and $Z$ individually you should be able to work out the distribution. (I haven't myself checked it so let me know if there is any difficulties).

A: The numerator and denominator of your random variable $T$ are, in fact, independent, since their parameters do not depend on each other. One of the ways to find the distribution of $T$ is by conditioning on $X_3, X_4$ as follows $$X_1X_3 + X_2X_4|X_3, X_4\sim \mathcal{N}(0, X_3^2 + X_4^2)$$ a.s. and hence $$\frac{X_1X_3 + X_2X_4}{\sqrt{X_3^2+ X_4^2}}|X_3, X_4\sim \mathcal{N}(0, 1).$$ Since the value of the term does not depend on the values of $X_3, X_4$, we can conclude that it is independent of $X_3$ and $X_4$. Moreover, we can conclude that the distribution of $T$ is a product of independent standard normal and a random variable $\frac{1}{\sqrt{W}}$ with $W$ being chi-squared with $df=2$, which is, in fact, a t-distribution with $df = 2$ multiplied by a  constant $\frac{1}{\sqrt{2}}$.


text:
Q: Где выполнять примеры кода к книге Thinking in Java Брюса Эккеля, если большинство IDE выдают ошибки? Скачал папку с кодом на Github, вставил в src в IntellijIDEA, выдалось несколько сотен ошибок компиляции. Не обратил на это внимание, удалил всё из src и просто качал по одному классу.
Потом на середине книги пришлось загрузить его пакет typeinfo, которая в IntellijIDEA не работает. Подскажите пожалуйста, есть ли какие-либо способы запустить этот код. Подача материала очень нравится и не хочется менять способ обучения.
Ссылка на код: https://github.com/BruceEckel/TIJ4-code/tree/master/examples

A: *

*Клонировать проект к себе на компьютер

*Открыть проект через кнопку open

и выбрать папку с названием проекта

*Установить плагин Ant Support. Для этого нужно будет Открыть File->Settings-Plugins-> Ищете Ant Support. Нажимаете установить, перезапускате idea

*Справа должна появится вкладочка Ant Build, на неё нужно нажать, там будет +
после чего нужно выбрать файл build.xml и импортировать лучше файл, с той дирректории, с которой будете работать, например TIJ4-code/examples/access/build.xml
(Осторожно тут указано в файле build версия java 1.5, чтобы запустить я исправлял на 1.7)

*После импорта нужно собрать его выбрав build и нажав зеленую стрелочку

*После корректной сборки, у вас справа появится список классов, который вы сможете выполнять


text:
Q: Find all possible combinations of words in given format I have 100 000 lines long dictionary:
w([w,o,r,d]).
w([h,a,p,p,y]).
w([q,u,e,s,t,i,o,n]).
...

Now I am working on a script that will return all possible words, that meet given format.
For example:
w([A,B,C]), w([B,C]), A \== B, A \== C, B \== C.

I've found the source that makes all variables different:
alldif([]).
alldif([E|Es]) :-
   maplist(dif(E), Es),
   alldif(Es).

So now I call:
w([A,B,C]), w([B,C]), alldif([A,B,C]).

Now I want that the variable A is one of [a,e,i,o,t,l]. I can do that using:
member(A, [a,e,i,o,t,l]).

But is it faster (?) using constraint programming with:
A in [a,e,i,o,t,l]

and
all_different([A,B,C]).

I am kind of stuck right now. The idea's been to generate all possible options in .txt file line by line.
I managed to concatenate words into statement using:
g([A,B,C], W1), g([B,C], W2), alldif([A,B,C]), buildStat([W1,W2], Statement).

Where:
g(Format, Word):-
    list_to_set(Format, Uniques),
    alldif(Uniques),
    w(Format),
    atomic_list_concat(Format, '', Atom), atom_string(Atom, Word).

insertSpaces([A], [A]).
insertSpaces([Word | Rest], OutWords):-
    insertSpaces(Rest, OutWordsRest),
    OutWords = [Word, " " | OutWordsRest].

buildStat(Words, Statement):-
    insertSpaces(Words, OutWords),
    with_output_to(atom(Statement), maplist(write, OutWords)).

But I don't know how to save all possibible Statements into file line by line.
Help would be appreciated.

A: One easy trick to emit all solutions is to force backtracking via false/0.
For example, assuming you have a predicate that yields all solutions on backtracking:

?- solution(S).

you can emit all solutions like this:

?- solution(S),
   print_solution(S),
   false.

where you have to define print_solution/1 as you want to yield the format you desire.
For example, you can print such solutions to standard output and then pipe the output to a file. The specifics for this depend on your Prolog system and could look like this:

$ prolog --goal 'ignore((solution(S),portray_clause(S),false)),halt' > output.txt


text:
Q: how to check what the value of Parameter in Oracle PLSQL Procedure I am in need of amending a procedure to include new data in which a parameter has been set. I need to check the value of the parameter so that I can test my code individually before it is implemented. below is portion of code which has parameter.
PROCEDURE Get_All_MT (i IN NUMBER)
AS
BEGIN
   INSERT INTO mrr_reten_mt_obp_cli (
     AMI_SCHEMA,
     UAN,
     PRODUCT_CLASS,
     POL_NO
   )
      SELECT a.ami_schema,
             a.uan,
             a.product_class,
             a.pol_no
        FROM mrr_retention_c_cover_item a,
             att_axa_uan agt,
             amt_structure str
       WHERE a.accident_date BETWEEN TRUNC (ADD_MONTHS (SYSDATE, i - 1), 'MONTH')
                                 AND TRUNC (ADD_MONTHS (SYSDATE, i), 'MONTH')
                                     - (1 / (60 * 60 * 24))

As you can see parameter "I" is been used in for accident_date range. I need to know what is the value of I so that it can be replaced while the code is been executed individually.

A: Log the value using DBMS_OUTPUT:
PROCEDURE Get_All_MT (i IN NUMBER)
AS
BEGIN
  DBMS_OUTPUT.PUT_LINE( i );
  INSERT INTO ...

A: I would create table log_params (param varchar2(30), value varchar2(200), log_time date); and procedure:
create or replace procedure log_param(param varchar2(30), value varchar2(200)) as
pragma autonomous transaction
begin
insert into log_params values (param, value, sysdate);
commit;
end;
/

And include in your code: log_param('i', i);. Then examinate results in table log_params


text:
Q: Sorting date m/y format in a data frame in R I am trying to sort date column which is in the format M/Y. I tried using several ways given in other posts but none helped. Please suggest.
For 2012 it shows correctly with all the months given with 2012 but then it changes the pattern. Thank you.
Here is how it looks like currently

A: That should work:
#let's add a column to your data.frame with a proper date
df$date_of_first_day <- as.Date(paste0("1/",monyear),format = "%d/%m/%y")
# then sort the data.frame
df <- df[order(df$date_of_first_day,decreasing = FALSE),]
# then get rid of this column
df$date_of_first_day <- NULL

A: 1) This converts DF (see Note) to a zoo time series whose first column is of class yearmon and which is sorted by that.
library(zoo)

z <- read.zoo(DF, FUN = as.yearmon, format = "%m/%y")

You may wish to keep it as a zoo object as above or to convert it back to a data frame:
fortify.zoo(z)

2) This is an alternative to read.zoo.  It also uses class yearmon.
library(zoo)

DF2 <- transform(DF, monyear. = as.yearmon(monyear., "%m/%y"))
DF2[order(DF2$monyear.), ]

Note: The above uses DF defined as:
library(tesseract)
u <- "https://i.stack.imgur.com/Szlhw.png"
DF <- read.table(text = ocr(u), header = TRUE, as.is = TRUE)

A: Using lubridate and dplyr:
library(dplyr)
library(lubridate)
df <- data.frame( monyear = c( "1/12", "10/13", "1/13", "2/10" ),
                  amount = 1:4,
                  prices = 1:4 )

Original Data:
  monyear amount prices
1    1/12      1      1
2   10/13      2      2
3    1/13      3      3
4    2/10      4      4

To sort by date:
df <- df %>%
      arrange( parse_date_time(monyear,"my") )

The function parse_date_time will read the format as "my" or "month year"
Output:
  monyear amount prices
1    2/10      4      4
2    1/12      1      1
3    1/13      3      3
4   10/13      2      2


text:
Q: Change button page link to a url I would like the change this code to redirect to a url google.com. How can I do this please?
echo '' . __( 'Home' ) . '';

Full code below:
add_filter( 'storefront_handheld_footer_bar_links', 'jk_add_home_link' );
function jk_add_home_link( $links ) {
    $new_links = array(
        'home' => array(
            'priority' => 10,
            'callback' => 'jk_home_link',
        ),
    );

    $links = array_merge( $new_links, $links );

    return $links;
}

function jk_home_link() {
    echo '' . __( 'Home' ) . '';
}


text:
Q: Can we bind the ManagedObject to View? I have prepared a object which by extending ManagedObject
and I have added these into the JSONModel of the view in controller as
var model = new JSONModel({
    data : someOne.getManagedObjects()
});

How to bind these to view? I have tried these
1: <List id="mainLayerList"
                    selectionChange="onSelectionChange"
                    mode = "MultiSelect"
                    items="{/data}">
2:
<List id="mainLayerList"
                    selectionChange="onSelectionChange"
                    mode = "MultiSelect"
                    items="{
                    path: '/data',
                    factory: '.dataListItemFactory'
                }">

Not getting the data on view.
Can we bind the ManagedObject to the view?

A: You can bind to any Javascript object. But you can only use attributes and properties on the bound objects. So you can't call functions like getName().
What do ManagedObjects do with the properties you declared in the metadata? It creates getXxx() and setXxx() methods and stores the data xxx somewhere inside a private object. Thats why you cant bind to {xxx} even though you have declared a xxx property on the ManagedObject.
As a workaround you could create getter properties and setter properties on your ManagedObject for all attributes you want to bind to:
get xxx()  { return this.getXxx();}
set xxx(value) { this.setXxx(value);}


text:
Q: How to make similar values in a column equal I have a dataframe like this:
Student_ID   Subject       Class_Feedback_question    Class_Feedback_Answer
100101       Physics       How was physics class?     Excellent: 5
100101       Physics       how was physics class:     very good:4
100101       Physics       How was the Presentation:  Good: 3
100101       Chemistry     How Much would you rate?   Excellent: 5
100102       Math          how much would you rate:   Excellent: 4
100102       Physics       how was presentation:      Good: 3

I want to make the similar row values in Class_Feedback_question column look equal, (e.g: making : as ? at end of questions or keeping one question as constant and replace the other similar questions with that, e.g: how was presentation: is replaced by  How was the Presentation: )
something like this:
Student_ID   Subject       Class_Feedback_question     Class_Feedback_Answer
100101       Physics       How was physics class?      Excellent: 5
100101       Physics       How was physics class?      very good:4
100101       Physics       How was the presentation:   Good: 3
100101       Chemistry     How Much would you rate?    Excellent: 5
100102       Math          How much would you rate?    Excellent: 4
100102       Physics       How was the presentation:   Good: 3

How can this be done in python Pandas?
Also, How can I create pivot table based on Class_Feedback_Answer?

A: To replace ':' by '?' you can use the apply method
df['Class_Feedback_question'] = df['Class_Feedback_question'].apply(x: x.replace(':', '?'))

and to rephrase questions you'll have to do it case by case, I would suggest using the map method
rephrasing = {'how was presentation': 'How was the presentation'}
df['Class_Feedback_question'] = df['Class_Feedback_question'].map(rephrasing)

For the pivot table please check pandas documentation because you are not giving enough information. It's really clear: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html?highlight=pivot#pandas.DataFrame.pivot


text:
Q: Arduino stepper I am building a system with the Arduino Uno, a power shield (REf to model) and a bipolar stepper motor.
I cannot initiate the motor using the stepper library from Arduino. I instantiate my stepper with
Stepper myStepper(motorSteps, motorPin1,motorPin2m motorPin3,motorPin4);

And keep on with the example code provided with the Arduino.
When I launch the code on the Arduino, the motor emits some sounds, but it does not turn.
How can determine the right motor pins to use? On the power shield, which mode is to be used, PWM or PLL?

A: As you suggest, the adafruit motor shield should fit the arduino stepper library, as it uses a L293D to drive the motor. It can drive 2 stepper with an current of 0.6A (good for most of little stepper you can find in printers, floppy/CD/DVD reader...).
Be careful, they seem to use their own library for this shield, you can find it here :
http://www.ladyada.net/make/mshield/download.html
And to know how to connect your stepper, look here :
http://www.ladyada.net/make/mshield/use.html
Sorry to answer your comment this way, but I don't have enough reputation to comment... so please, +1 my answer if you think it's a good answer :)

A: It's normal that the arduino sketch doesn't work. It drives the motor like this:

*

*PIN1 : coil 1, forward current

*PIN2 : coil 1, backward current

*PIN3 : coil 2, forward current

*PIN4 : coil 2, backward current

Your shield drives the stepper this way:

*

*PIN1 : current forward/backward

*PIN2 : current intensity with PWM

*PIN3 : current intensity with PWM

*PIN4 : current forward/backward

Not a good idea to drive a stepper motor, as you don't even need PWM to drive a stepper. It's to drive a DC motor. You may write your own sketch to drive a stepper with that shield, but you should find a shield that fit the arduino to drive a stepper. Look for something like "UL2003 stepper module", it costs few dollars.
Edit: I've got one of those modules and it works like a charm. Be careful about the power you need. Maybe you need something like a L298N module. I've got few of them too and they work fine.

A: If the motor emits some sound, this is good news. At least you have contact with it. Since it is just a sound but no movement, there might be three things laying underneath of this behavior;

*

*Wrong pin connections of the motor

*Insufficient current feeding from the motor driver.

*Step counts determined by the code using PWM might be
too less or too high as per the motor can handle.

I can offer this URL link to determine motor pin-outs;
How Can I Determine My Stepper Motor Wiring Without the Stepper Motor Pinout

A: In stepper motor how many wires you have? 4 or 6.
Your connection is faulty. That's why it makes such sound.
Test with multimeter. you find two wires give high resistance. other two give half from that. Connect the first two with motor driver out1 and second two with out2.
You didn't mention which motor driver you are using. Try with L298 motor driver shield.

A: I think the problem you are having is related to the kind of shield you are attempting to use. The power shield that you linked is designed for DC motors and you are attempting to use a stepper motor (see this website for an explanation of the difference).
I would recommend trying another shield (like the Sparkfun EasyDriver) that supports the use of a stepper motor.

A: The problem seems to be wrong connected motor pins.
Are you sure, you connect true windings to motor?
Measure the motor pins with ohmmeter. There should be two windings which have pins A1-A2 and B1-B2. Between these pins you should see some resistance value.
Then be sure you connect to shield with right order.

A: In mi projects I use a bipolar motor (a nema17), and you can drive it easy with a A4988 pololu  (or drv8825, more powerfull, and more expensive).
Those drivers has an H bridge inside, and allows you to control the motor by a simple:
while(1){
   digitalWrite(PIN_STEP, HIGH);
   delay(1000);
   digitalWrite(PIN_STEP, LOW);
   delay(1000);
//1RPM = 100 microsecond delay for a 1.8 degree angle motor (200 steps per
  turn)
  }


text:
Q: Inserting YouTube link in modern CV RE: Modern CV contact info - YouTube channel link
Hi,
I've tried repeatedly to include a link, in the upper-right-hand corner where my contact information is located a YouTube link to my channel, but to no avail.  I have a LinkedIn hyperlink using "\social" but cannot  seem to get the same for YouTube.  Any suggestions? I've attached a snapshot of the section but deleted the section I had for "\social[youtube]" because I kept getting errors. (I'm very new to LaTeX and am unsure how to upload the entire file otherwise).
Thanks so much!
Chris
\documentclass[11pt,a4paper]{moderncv}
\moderncvtheme[blue]{classic}
\usepackage[scale=0.8]{geometry}
\AtBeginDocument{\recomputelengths}
\firstname{John}
\familyname{Doe}
\mobile{}
\phone{}
\email{test@foo.bar}
\social[linkedin]{}

\usepackage[pdftex,
                   pdfauthor={},
                   pdftitle={CV for },
                   pdfsubject={Detailed CV for focusing on his previous training, employment and PhD research.},
                   pdfkeywords={These, are, keywords},
                   pdfproducer={ShareLaTeX},
                   pdfcreator={pdflatex},
                   pdfpagemode={UseOutlines},
                   bookmarksopen,
                   pdfstartview={FitH},
                   colorlinks,
                   linkcolor={blue},
                   citecolor={red},
                   urlcolor={blue}]{hyperref}

\begin{document}
\maketitle

% EDUCATION
\section{Education}
\cventry{2012--Present}{Some education}{University}{Prescott}{Arizona}{}  % arguments 3 to 6 can be left empty
\cventry{2008--2012}{MA (Hons)}{University}{Huntsville}{Texas}{}

\end{document}

A: According to this blog on the moderncv package there is a field called \homepage{} which will link to an internet page.
This gives a link to the an internet page above the social link.
In the MWE this can be added after the \social[]{} field
...
\social[linkedin]{}
\homepage{www.youtube.com}
\usepackage{pdflatex,
...


text:
Q: How to Compare Two Lists of Java Objects by Property Values I want to assert that two lists of objects of the same type are the same by the property values of that object. For example, I have two lists of Person objects which have first, last, and middle name properties. Each Person object has method setters and getters for each of these properties (java beans), and the constructor contains no parameters.
Let's assume here that I already have a list of two People called existingPersonList which has the following properties:
Existing person1: firstName = Bob, lastName = Smith
Existing person2: firstName = Sue, middleName = K., lastName = White
I want to compare the objects, so the approach I have taken is to create new ones to compare against:
Person person1 = new Person();
Person person2 = new Person();
List<Person> personList = new ArrayList<>();
person1.setFirstName("Bob");
person1.setLastName("Smith");
person2.setFirstName("Sue");
person2.setMiddleName("K.");
person2.setLastName("White");
personList.add(person1);
personList.add(person2);

What I'm currently doing is iterating through both lists with for loops and using the Hamcrest method samePropertyValue(personList.get(i)).matches(existingPersonList.get(j)) to find a match and assertTrue, however this is very inefficient for large lists.
Is there a better way to go about doing this? Or at very least directly compare the two lists instead of iterating through?

A: By overriding the equal and hash methods for your object,you can use the compare method of your lists as shows in the following sample:
this helps you to compare objects by as many as their proprieties as you want.
       import java.util.*;

    public class TestListConvert {

    public static void main(String[] args) {
        List<Obs> firstList = new ArrayList<>();

        List<Obs> secondList = new ArrayList<>();

        firstList.add(new Obs("1","2"));
        secondList.add(new Obs("1","2"));

        System.out.println(firstList.equals(secondList));

    }
    private static class Obs{
        private  String x;
        private String y;

        public Obs(String x, String y) {
            this.x = x;
            this.y = y;
        }

        public String getX() {
            return x;
        }

        public void setX(String x) {
            this.x = x;
        }

        public String getY() {
            return y;
        }

        public void setY(String y) {
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Obs obs = (Obs) o;
            return Objects.equals(x, obs.x) &&
                    Objects.equals(y, obs.y);
        }

        @Override
        public int hashCode() {
            return Objects.hash(x, y);
        }
    }
}


text:
Q: Array returns empty In the following example, my array returns empty. I need to get the (complete!) image link into my array.
This is my code:
<?php
    header('Content-Type: text/html; charset=utf-8');
    $url = "http://www.asaphshop.nl/epages/asaphnl.sf/nl_NL/?ObjectPath=/Shops/asaphnl/Products/80203122";
    $htmlcode = file_get_contents($url);
    $pattern = "/class=\"noscript\"\>(.*?)\<\/div\>/imU";
    preg_match_all($pattern, $htmlcode, $matches);
    //print_r ($matches);
    $image = ($matches[0]);
    print_r ($image);
?>

This is the part of the file I am using to try and get the (complete!) image link into my array:

          <img
           itemprop="image"
           alt="Jesus Remember Me - Taize Songs (2CD)"
           src="/WebRoot/AsaphNL/Shops/asaphnl/5422/8F43/62EE/D698/EF8E/4DEB/AED5/3B0E/80203122_xs.jpg"
           data-src-xs="/WebRoot/AsaphNL/Shops/asaphnl/5422/8F43/62EE/D698/EF8E/4DEB/AED5/3B0E/80203122_xs.jpg"
           data-src-s="/WebRoot/products/8020/80203122/bilder/80203122_s.jpg"
           data-src-m="/WebRoot/products/8020/80203122/bilder/80203122_m.jpg"
           data-src-l="/WebRoot/products/8020/80203122/bilder/80203122.jpg"
         />

A: First : you should never parse HTML with a regex, as HTML is too complex to be parsed like that. Have a look on this post.
For your question, your problem is that you're using multiline modifier instead of the singleline one. Change your regex for this one :
/class=\"noscript\"\>(.*?)\<\/div\>/isU

And if you want a cleanest result, use this one (with lookbehind/lookahead):
/(?<=class=\"noscript\"\>)(.*?)(?=\<\/div\>)/isU


text:
Q: how to change basic url into seo friendly url in opencart I had open the seo url in opencart 2.2.0 but it does not change the basic url into seo friendly url. when ever i click on any it shows the url something like that.
for index link --->
 http://homemartz.pk/index.php?route=common/home

product page link-->
http://homemartz.pk/index.php?route=product/product&path=76&product_id=105

and so on....
someone kindly help me to resolve this issue

A: Go into your admin then settings and store and click on the server tab and tick Yes for use SEO urls.
Next rename htaccess.txt on to .htaccess in the root of the shop.
Make sure all products have a unique seo keyword on the products add/edit page.

A: To set SEO URLS

*

*Add the SEO keywords to all products and categories (unique
keywords).

*To set SEO URLs - Go to System>Settings>Server>Use SEO URLs. You only
get this option on the DEFAULT store.

*In your main OpenCart directory, there should be a file called .htaccess.txt. Rename it to .htaccess. If you already have an .htaccess file, Edit the .htaccess file.

RewriteRule ^([^?]*) index.php?route=$1 [L,QSA]

Also, refer link Enable SEO friendly URLs in Opencart

A:
You can follow below link for SEO friendly url in opencart

http://docs.opencart.com/administration/seo/


text:
Q: Protecting siwi API routes for Next.js I have several API siwe/ironsession based Next.js routes, an example looks like this:
import { withIronSessionApiRoute } from 'iron-session/next';
import { NextApiRequest, NextApiResponse } from 'next';

import { ironOptions } from '../../lib/config';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const { method } = req;

  switch (method) {
    case 'POST':
      if (!req.session.siwe) {
        res.status(401).json({ message: 'You have to first sign_in' });
        return;
      }

      const address = req.session.siwe?.address;
      /** more code here **/
    default:
      res.setHeader('Allow', ['POST']);
      res.status(405).send(`Method ${method} Not Allowed`);
  }
};

export default withIronSessionApiRoute(handler, ironOptions);

Almost all of the API routes that required req.session.siwe follow this pattern.
What is an option, leveraging Next.js, to specify that a route that requires req.session.siwe goes through some shared logic so I do not have to repeat this code every time?


text:
Q: SQL query to find all rows with same timestamp + or - one second Row 3 in the following table is a duplicate. I know this because there is another row (row 5) that was created by the same user less than one second earlier.
row     record  created_by  created_dt
1       5734    '00E759CF'  '2020-06-05 19:59:36.610'
2       9856    '1E095CBA'  '2020-06-05 19:57:31.207'
3       4592    '1E095CBA'  '2020-06-05 19:54:41.930'
4       7454    '00E759CF'  '2020-06-05 19:54:41.840'
5       4126    '1E095CBA'  '2020-06-05 19:54:41.757'

I want a query that returns all rows created by the same user less than one second apart.
Like so:
row     record  created_by  created_dt
1       4592    '1E095CBA'  '2020-06-05 19:54:41.930'
2       4126    '1E095CBA'  '2020-06-05 19:54:41.757'

This is what I have so far:
SELECT DISTINCT a1.*
FROM table AS a1
    LEFT JOIN table AS a2
        ON a1.created_by = a2.created_by
            AND a1.created_dt > a2.created_dt
            AND a1.created_dt <= DATEADD(second, 1, a2.created_dt)
WHERE a1.created_dt IS NOT NULL
AND a.created_dt IS NOT NULL

This is what finally did the trick:
SELECT
    a.*
FROM table a
WHERE EXISTS (SELECT TOP 1
        *
    FROM table a1
    WHERE a1.created_by = a.created_by
    AND ABS(DATEDIFF(SECOND, a.created_dt, a1.created_dt)) < 1
    AND a.created_dt <> a1.created_dt)
ORDER BY created_dt DESC

A: You could use exists:
select t.*
from mytable t
where exists(
    select 1
    from mytable t1
    where
        t1.created_by = t.created_by
        and abs(datediff(second, t.created_dt, t1.created_dt)) < 1
)

A: How about something like this
SELECT DISTINCT a1.*
FROM @a1 AS a1
    LEFT JOIN @a1 AS a2 ON a1.[Created_By] = a2.[Created_By]
        AND a1.[Record] <> a2.[Record]
WHERE ABS(DATEDIFF(SECOND, a1.[Created_Dt], a2.[Created_Dt])) < 1

Here is the sample query I used to verify the results.
DECLARE @a1 TABLE (
    [Record] INT,
    [Created_By] NVARCHAR(10),
    [Created_Dt] DATETIME
)

INSERT INTO @a1 VALUES
(5734, '00E759CF', '2020-06-05 19:59:36.610'),
(9856, '1E095CBA', '2020-06-05 19:57:31.207'),
(4592, '1E095CBA', '2020-06-05 19:54:41.930'),
(7454, '00E759CF', '2020-06-05 19:54:41.840'),
(4126, '1E095CBA', '2020-06-05 19:54:41.757')

SELECT DISTINCT a1.*
FROM @a1 AS a1
    LEFT JOIN @a1 AS a2 ON a1.[Created_By] = a2.[Created_By]
        AND a1.[Record] <> a2.[Record]
WHERE ABS(DATEDIFF(SECOND, a1.[Created_Dt], a2.[Created_Dt])) < 1

A: I would suggest lead() and lag() instead of self-joins:
select t.*
from (select t.*,
             lag(created_dt) over (partition by created_dt) as prev_cd,
             lead(created_dt) over (partition by created_dt) as next_cd
      from t
     ) t
where created_dt < dateadd(second, 1, prev_created_dt) or
      created_dt > dateadd(second, -1, next_created_dt)


text:
Q: What is the difference between instance.let and instance?.let What is the difference between two line of codes:
1.
 viewHolderRef?.get()?.adapterPosition.let {

*

viewHolderRef?.get()?.adapterPosition?.let

I know that it can affect on the type of the argument that the lambda expression gets but in difference i mean, is there a situation when in one of the expression the let will run and in the second know (with refer to null issue)

A: v?.let means: if v is null, then just make the entire expression null (the let method won't even be called because it'll be terminated early), and if it's not null, then change the type of the expression to be non-nullable then keep going with the property chain. So, v?.let will only call the function if v is non-null.
On the contrary, v.let will always call let, regardless if v is null or not, so the parameter is nullable (since there's no guarantee it isn't null like with v?.let. The difference is best demonstrated with this code:
fun test(v: String?) {
    v.let { it: String? -> println("v.let: $it") }
    v?.let { it: String -> println("v?.let: $it") }
}

fun main () {
    test(null)
    println("----------")
    test("foo")
}

Playground link
This outputs:
v.let: null
----------
v.let: foo
v?.let: foo

As you can see, when calling it on a null output, only v.let runs and prints null, whereas on a non-null output, both let statements run. You can also see a difference in the types of the parameters: v.let takes in a String?, whereas v?.let takes in a String.


text:
Q: WCF REST JSON return dynamic list How can I return an object containing a dynamic list?
I've got a working REST service in which I want to return JSON data.
That works pretty well in most cases - except for one:
In that specific case I've got a List<Bla> which can contain objects of type Bla and Bla1 (which inherits from Bla).
As soon as I add a Bla1 to the list the result I get in my browser is an error.

Firefox: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://.../DoSomething. (Reason: CORS request did not succeed).
Chrome: GET https://.../DoSomething net::ERR_SPDY_PROTOCOL_ERROR

How can I return an object containing a dynamic list?
Classes
[DataContract]
public class Blibla
{
    [DataMember] public bool requestSuccess;
    [DataMember] List<Blubb> blubb;
    [DataMember] List<Bla> blas;

    public Blibla(bool success)
    {
        this.requestSuccess = success;
        blubb = new List<Blubb>() { new Blubb(11, "einser"), new Blubb(22, "zweier"), new Blubb(33, "dreier") };
        blas = new List<Bla>() { new Bla(11), new Bla1(22, 22) };
    }
}

[DataContract]
public class Bla
{
    [DataMember] public int id;

    public Bla(int id)
    {
        this.id = id;
    }
}

[DataContract]
public class Bla1 : Bla
{
    [DataMember] public int num;

    public Bla1(int id, int num) : base(id)
    {
        this.num = num;
    }
}

[DataContract]
public class Blubb
{
    [DataMember] public int ID;
    [DataMember] public string name;

    public Blubb(int id, string name)
    {
        this.ID = id;
        this.name = name;
    }
}

IService:
[Description("returns service's details")]
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
Blibla DoSomething();

Service:
public Blibla DoSomething()
{
    Message msg;
    DoHttpMethodTypeSpecific();

    Blibla bb = new Blibla(true);
    return bb;
}

EDIT
Abraham Qian's answer is exactly what I was looking for.
My service responds with a correctly serialized Bla1-object.
{
    "__type":"Bla1",
    "id":22,
    "num":22
}

If someone knows of a way to suppress the automatically added "__type":"Bla1"
please let me know...

A: According to your error and code, I have made a test and found that there is a serialization problem in the Bla class. When transferring the Bla class, WCF could not recognize the subclass(Bla1) and how to serialize them, So we should add the KnowType attribute to the base class.
[DataContract]
[KnownType(typeof(Bla1))]
public class Bla
{
    [DataMember] public int id;
    public Bla(int id)
    {
        this.id = id;
    }
}

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types


text:
Q: Primefaces p:fileUpload auto upload doesn't show the cancel option for invalid file Environment
JSF 2.0, Primefaces 3.4.2
File upload code is as below
<p:fileUpload fileUploadListener="#{myBean.handleFileUpload}" mode="advanced" update="messages11" auto="true" sizeLimit="1000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" rendered="#{myBean.fileUploadRendered}" ></p:fileUpload>

If I upload any invalid format then error message displays correctly that Invalid File type but after message it doesn't show the cancel option as shown in the example here. If I add correct format then It does get uploaded and I can access that file in myBean.
TIA

A: try to close the tag directly
<p:fileUpload
    fileUploadListener="#{myBean.handleFileUpload}"
    mode="advanced"
    update="messages11"
    auto="true"
    sizeLimit="1000000"
    allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
    rendered="#{myBean.fileUploadRendered}" />

that is the only difference you have to the showcase example

A: use auto="false" and shoud solve your problem.


text:
Q: Remove final characters from string recursively - What's the best way to do this? I am reading lines from a file one at a time and before i store each, i wanna modify them according to the following simple rule:

*

*if the last character is not any of, e.g., {'a', 'b', 'c'} store the line.

*if that is not the case, remove the character (pop-like) and check again.

What i currently have (felt like the obvious thing to do) is this:
bad_chars = {'a', 'b', 'c'}

def remove_end_del(line_string, chars_to_remove):
    while any(line_string[-1] == x for x in chars_to_remove):
        line_string = line_string[:-1]
    return line_string

example_line = 'jkhasdkjashdasjkd|abbbabbababcbccc'
modified_line = remove_end_del(example_line, bad_chars)
print(modified_line)  # prints -> jkhasdkjashdasjkd|

Which of course works, but the string slicing\reconstruction seems a bit too excessive to my untrained eyes. So i was wondering a couple of things:

*

*is there a better way to do this? like a pop type of function for strings?

*how is rstrip() or strip() in general implemented? is it also with a while?

*would it be worthwhile making rstrip() recursive for this example?

*Finally, how much better is the following:

def remove_end_del_2(line_string, chars_to_remove):
    i = 1
    while line_string[-i] in chars_to_remove:
        i += 1
    return line_string[:-i+1]

Any comment on any of the points made above would be appreciated ☺.
Note: the separator ("|") is only there for visualization.

A: Another nearly fast approach to re.sub albeit more intuitive (it sounds like the pop you're asking for) is itertools.dropwhile:

Make an iterator that drops elements from the iterable as long as the
  predicate is true;

>>> ''.join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]
'jkhasdkjashdasjkd|'

However, it appears rstrip was made and more suited for a task as this.

Some timings:
In [4]: example_line = 'jkhasdkjashdasjkd|abbbabbababcbccc'

In [5]: bad_chars = {'a', 'b', 'c'}

In [6]: %%timeit
   ...: re.sub(r'[%s]+$' % ''.join(bad_chars), '', example_line)
   ...:
100000 loops, best of 3: 5.24 µs per loop

In [7]: %%timeit
   ...: ''.join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]
   ...:
100000 loops, best of 3: 5.72 µs per loop

In [10]: %%timeit
   ....: remove_end_del(example_line, bad_chars)
   ....:
10000 loops, best of 3: 24.1 µs per loop

In [11]: %%timeit
   ....: example_line.rstrip('abc')
   ....:
1000000 loops, best of 3: 579 ns per loop

In [14]: %%timeit
   ....: remove_end_del_2(example_line, bad_chars)
   ....:
100000 loops, best of 3: 4.22 µs per loop

rstrip wins!

A: Not the direct answer to the question, but one alternative option would be to use regular expressions to remove the bad characters at the end of the string:
>>> import re
>>>
>>> example_line = 'jkhasdkjashdasjkd|abbbabbababcbccc'
>>> bad_chars = {'a', 'b', 'c'}
>>>
>>> re.sub(r'[%s]+$' % ''.join(bad_chars), '', example_line)
'jkhasdkjashdasjkd|'

The regular expression here is dynamically constructed from the set of "bad" characters. It would (or "could", since sets have no order) be [abc]+$ in this case:

*

*[abc] defines a "character class" - any of "a", "b" or "c" would be matched

*+ means 1 or more

*$ defines the end of the string

(Note that, if "bad" characters can contain a character that may have a special meaning in the character class (like, for example, [ or ]), it should be escaped with re.escape()).
The last statement though may prove that old saying about having more problems than initially.

A: Slicing creates lots of unnecessary temporary copies of string. Recursion would be even worse - copies would still be made, and on top of it function call overhead would be intruduced. Both approaches are not that great.
You may find an rstrip implementation in CPython source code. An iterative approach (similar to your last code snippet) is used there.
Py_LOCAL_INLINE(PyObject *)
do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj)
{
    Py_buffer vsep;
    char *s = PyBytes_AS_STRING(self);
    Py_ssize_t len = PyBytes_GET_SIZE(self);
    char *sep;
    Py_ssize_t seplen;
    Py_ssize_t i, j;

    if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0)
        return NULL;
    sep = vsep.buf;
    seplen = vsep.len;

    i = 0;
    if (striptype != RIGHTSTRIP) {
        while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
            i++;
        }
    }

    j = len;
    if (striptype != LEFTSTRIP) {
        do {
            j--;
        } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
        j++;
    }

    PyBuffer_Release(&vsep);

    if (i == 0 && j == len && PyBytes_CheckExact(self)) {
        Py_INCREF(self);
        return (PyObject*)self;
    }
    else
        return PyBytes_FromStringAndSize(s+i, j-i);
}

So to sum up, your intuition to use index-based parsing is correct. Main advantage is that no temporary strings are created and copying things in memory is significantly reduced.

A: I understand what you mean by excessive, but I think in general, it looks good. The alternative would be to work with indices, which is not very readable. (I also happen to think that regexes are not very readable either...)
You could, however, use a memoryview if you have a bytes object which may or may not be relevant:
https://docs.python.org/3/library/stdtypes.html#memoryview
1. pop function for strings
No there are no .pop method for str. You'd have to use list(line_string).pop(), where list(s) creates a list with each character of the string as an element.
2. (r)strip implementation
This is probably implemented with a while, yes.
It should be all C code though.
3. recursive rstrip
First of all, why would you need to make it recursive?
Second, I think that (recursiveness) would make the mental load unnecessarily high -- so, no.
4. Finally, how much better is the following:
Measure it! Surely it would be faster.


text:
Q: How to vertical align text next to radio button (on smaller screen)? When I put text next to my radio button, I want it to be vertically aligned, so the text isn't below my radio button. See this printscreen for example
This is the code I've used:

    <input type="radio" id="act41" name="action4" value="Geen vertraging, op tijd" onfocus="checkfocus()">
    Geen vertraging en tijd aangekomen

This is the CSS for the radio button:
input[type="radio"] {
    width: 25px;
    float: left;
    vertical-align: baseline;
}

Do you have any tips which CSS I should apply when I want the text to be vertically aligned?

A: You could use vertical-align: middle; in combination with display: inline-block; on both elements (the checkbox and the label next to it).
HTML:

    <input type="radio">
    Test
Test

CSS:
input[type=radio],
label {
  vertical-align: middle;
  display: inline-block;
}

Here is a jsFiddle, showing the result: https://jsfiddle.net/5a9fcu1n/1/

EDIT:
The former solution does not work properly for long label texts as mentioned in the comments. Another possibility is, to position the radio button absolutely next to the  and give the label a padding.
HTML:

  <input type="radio" id="radioBox">
  long text [....]

CSS:
.wrapper {
  position: relative;
}
.wrapper input[type=radio] {
  position: absolute;
  margin: 0;
  left: 0;
  width: 30px;

  top: 50%;
  transform: translateY(-50%);
  /* you could also drop transform and use top: 0; */
}
.wrapper label {
  display: block;
  padding-left: 30px;
}

Here is the according jsFiddle: https://jsfiddle.net/5a9fcu1n/3/

A: First, put the text in a  tag so we can target it. And because it's good practice
HTML:

    <input type="radio" id="act41" name="action4" value="Geen vertraging, op tijd" onfocus="checkfocus()">

         Geen vertraging en tijd aangekomen

Then in the CSS we can use the calc function to make sure it's always next to the input.
CSS:
input[type="radio"]
{
     width: 25px;
     float: left;
     vertical-align: baseline;
     box-sizing: border-box;
     display: inline-block;
}
input[type="radio"] ~ label
{
     width: calc(100% - 25px);
     float: left;
     vertical-align: baseline;
     padding-left: 16px;
     box-sizing: border-box;
     display: inline-block;
}

Hope this helps

A: I put the radio button text in a label tag and by adjusting its width percentage I was able to get the wrapped text to vertically align correctly. Here's a picture.
HTML

    <input type="radio" id="act41" name="action4" value="Geen vertraging, op tijd" onfocus="checkfocus()">
    Geen vertraging en tijd aangekomen

CSS
label
{
   vertical-align: middle;
   display: inline-block;
   width: 70%;
}

jsFiddle: https://jsfiddle.net/5a9fcu1n/2/


text:
Q: NestJS background process which fetches data in 5 parallel actions I am working on a NestJS API which receives some article codes and saves them in a DB with status as queue and then i want to build a background process which searches for articles with queue status and fetches a website with that code and fills in the information about that article ID.
I want it to fetch codes in 5 parallel routines, each one should get a new code from the list as soon as it finished fetching the current code.
The way it's built right now, it gets 5 codes and uses Promise.all but what i don't like on this approach is that if one of the await is significantly slower than the other, they all way for the slowest one.
const promiseResult = await Promise.all(promiseList);

Which approach is the best one for me to learn in order to achieve what i am planning to do?

A: Basically you do your job when all the promises are fulfilled. You are correct when you say that you wait for the slowest one, as this is exactly what await Promise.all(promiseList) does.
Now you need to ask yourself the question whether you are able to process the quicker promises while you await for the slowest one. If so, then you can iterate your promises and define a .then() for them:
for (let promise of promiseList) {
    promise.then((value) => {
        //Do something
    });
}

This way all your promises have a then handler for the case when the promise is fulfilled and your Javascript flows normally, without waiting for any of the promises. Once each promise is fulfilled, the event loop will detect that an event happened and call your callback function (in the case of the example above, the arrow function inside the then call).
Note that the then callback should never assume that the other promises were also completed, but that shouldn't be a problem in your case, because you want to work when your promise list was only partially completed as well.


text:
Q: Exit valgrind on first error I want valgrind to stop on the first error it finds and exit.
Please do not suggest

*

*--vgdb-error=1: It does not exit valgrind. You have to connect gdb and kill from there.

*--db-attach: Deprecated and removed in a recent release

*--log-file=<filename>: It does not stop valgrind.

My intention is to save my time and get my shell back as soon as the first error is printed. The first error is all I care about.

A: --gen-suppressions=yes will pause on each error and ask you if you wish to continue.
In addition to that, you can specify --input-fd=<file descriptor> to provide an alternative to stdin (standard input) at the moment of interacting with the suppression menu.


text:
Q: On-Demand javascript I'm wondering if you guys can help me to perform on-demand javascript using AJAX? If you can help me with a simple example, I would really appreciate it.
my question is: how to get a javascript code from my server and execute it?
Thanks for the help

A: If you really want to use AJAX (as stated in the question) you can do so too. First, you download the javascript normally using XMLHttpRequest and when the download is finished you either eval() it or insert it inside a generated  tag.
function xhr_load(url, callback) {
  xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        callback(xhr.responseText);
      }
    }
  }
  xhr.open("GET", url, true);
  xhr.send(null);
}

// (1) download using XHR and execute using eval()
xhr_load('mylib.js', function(response) {
  eval(response.responseText);
});

// (2) download using XHR and execute as an inline script
xhr_load('mylib.js', function(response) {
  var script =
    document.createElement('script');
    document.getElementsByTagName('head')[0].appendChild(script);
    script.text = response.responseText;
});

Also, Steve Souders has done amazing job in this field and I can highly recommend watching his talk on this video.

A: I made the following function for being able to load JavaScript files programmatically:
Usage:
loadScript('http://site.com/js/libraryXX.js', function () {
  alert('libraryXX loaded!');
});

Implementation:
function loadScript(url, callback) {
  var head = document.getElementsByTagName("head")[0],
      script = document.createElement("script"),
      done = false;

  script.src = url;

  // Attach event handlers for all browsers
  script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      callback(); // execute callback function

      // Prevent memory leaks in IE
      script.onload = script.onreadystatechange = null;
      head.removeChild( script );
    }
  };
  head.appendChild(script);
}

I use a callback function argument, that will be executed when the script is loaded properly.
Also notice that the script element is removed from the head after it is loaded and I remove the load and readystatechange events by setting them to null, that is made to prevent memory leaks on IE.
Check an example usage here.

A: In fact, you don't even need to use AJAX for this. Simply append a new <script> element to your body.
Plain Old Javascript:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/scripts/example.js';

document.body.appendChild(newScript);

Here's the same code using jQuery:
// Traditional
$(document.body)
  .append('<script type="text/javascript" src="/scripts/example.js" />');

// Using getScript
$.getScript('/scripts/example.js');

Here's the same code using MooTools:
// Traditional
new Element('script', {type: 'text/javascript',
                       src: '/scripts/example.js'}
           ).inject(document.body);

// Using Assets (Recommended)
new Asset.javascript('/scripts/example.js');

A: I use this code to load-on-demand (using jQuery). Its blocking (but i need it) you can make it synchronous using async:true
(function(script) {
    var included_files = new Array();
    this.include = function(script) {
        var js_base = '/js/';
        if (_.indexOf(included_files, script) == -1){
            included_files.push(script);
            $.ajax({
                url: js_base+script.split('.').join('/')+'.js',
                type: 'get',
                dataType: 'script',
                async: false,
                global:false,
            });
        }
    };
})();

It uses jQuery and Underscore.js for .indexOf but you can ommit latter with your own indexOf function.
Good luck.

A: Get the JavaScript code from the server enclosed in  tags, append it into DOM and execute a function. The function name to execute could come with the same request or it can be predefined.
What do need this for? Perhaps if you could elaborate your goals, a more straightforward method could be found.

A: Javascript gets from the web server to the user's browser in a couple of ways:

*

*It is embedded in the web page along with the HTML in a <script> tag

*It is sent as a separate file along with the web page. The javascript file has a file name extension of .js. The code in the web page <script> tags can call the code in this separate .js file

*A combination of these can be used. The common javascript functions that are used on many web pages go in the .js file. Javascript that's only used on one web page goes on that page.

A: CMS has shown a solid (looking, haven't tested) library independent method.  Here's how you do it in Dojo.
dojo.require("namespace.object");

You may need to specifiy the path to your namespace (ie: root folder)
dojo.registerModulePath("namespace", "../some/folder/path");

See the doc for more info.


text:
Q: variable unable to increment ? I don't know why maybe it's a noob question, but I'm unable to understand why my variable "$numero_requete_en_cours_exe" is returning 0 instead of 3...
This is a global variable yet !
 $numero_requete_en_cours_exe = 0;

 affichagetypemessage(0);

 function affichagetypemessage($id_message_page){

     do{
    // operation with $id_message_page...
    $numero_requete_en_cours_exe++;
    } while ($numero_requete_en_cours_exe !=3);

 }

echo $numero_requete_en_cours_exe;


text:
Q: Trying to initialize multiple 'select' inputs inside a list item my first post at StackOverFlow ^_^ (So yeah, i'm a noob, be gentle)
I have searched and actually found several solutions to my question around the web, but for some reason none of them work for me.
So here it goes:
I have a list item, and inside it multiple 'select' inputs, as such:
<li id="langlevels">
   <select id="encombobox"></select>
   <select id="frcombobox"></select>
   <select id="hecombobox"></select>
   <select id="rucombobox"></select>
   <select id="arcombobox"></select>
   <select id="otcombobox"></select>
</li>

Now what i'm trying to do is: Using jQuery, initialize all of the 'select' inputs to values I have in an array:
var lang_levels = new Array("Native Level", "Good Level", "Amateur Level");
The way i'm trying (to no avail) to do this is:
    //Initializing language levels combobox values
    $("#langlevels > select").each(function () {
        for(var i=0; i<lang_levels.length;++i)
        {
            addOption($(this), lang_levels[i], lang_levels[i]);
        }
        */

    });

NOTE: addOption() is a method I know to be working because I use it to initialize other, un-nested 'select' inputs.
I would very much appreciate your help!
Thanks in advance :)

A: OK Got it!
The only problem was this:
addOption($(this), lang_levels[i], lang_levels[i]);
was supposed to be this:
addOption(this, lang_levels[i], lang_levels[i]);


text:
Q: Change an image dpi without changing it's pixal format Every time I try to change the image's dpi, the pixel format (Color scheme - RGB, CMYK and such...) seems to change.
The only time I did succeed in saving the pixel format, the dpi, on debug mode, seems to change, but after the process is complete, it is changed back to it's original settings.
the code I tried is as followed:
        using (var ms = new MemoryStream())
        {
            using (var bmpInput = Image.FromFile(path) as Bitmap)
            {
                using (var bmpOutput = (Bitmap)bmpInput.Clone())
                {
                    foreach (var id in bmpInput.PropertyIdList)
                        bmpOutput.SetPropertyItem(bmpInput.GetPropertyItem(id));
                    if (doResize)
                        bmpOutput.SetResolution(dpi, dpi);

                    bmpOutput.Save(ms, bmpInput.RawFormat);
                    return ms.ToArray();
                }
            }
        }

A: Application.DoEvents();

Try this before saving your Image in code.


text:
Q: How to select all parents of a child from a table I am using SQL Server.
My table is called Employees.
It looks like this:
EmpID   ManagerID   EmpName
-----   ---------   -------
1       NULL        Ali
2       1           Mike
3       1           Tom
4       2           Kim
5       2           Rob
6       3           Lay
7       5           Paul
8       7           Sam
9       6           Bin

I am trying to build a query that returns all parents of the children
So the query would return the parents of Bin and Sam are
Bin, Lay, Tom, Ali
Sam, Paul, Rob, Mike, Ali

I tried this but wasn't successful
SELECT *
FROM Employees A
LEFT OUTER JOIN Employees B ON A.ParentID  = B.EmpID
WHERE A.EmpID IN (8,9)

but this can only work for 1 parent
How can I get the whole list of parents (managers)?

A: Use recursive cte
WITH Parent AS
(
    SELECT *
        FROM Employees WHERE EmpID IN (8,9)
    UNION ALL
    SELECT emp.*
        FROM Employees emp JOIN Parent ON emp.EmpID = Parent.ManagerID
)
SELECT distinct * FROM Parent

A: Using recursive cte.
The solution would be finding the top hierarchy of each employee and grouping by them using string aggregate we can get all the employee names under each top manager in the order of thier level in hierarchy.
WITH Parent AS
(
    SELECT *,empid as top_hierarchy,0 as level
        FROM Employees  WHERE EmpID IN (8,9)
    UNION ALL
    SELECT emp.*, parent.top_hierarchy, level+1
        FROM Employees emp JOIN Parent ON emp.EmpID = Parent.ManagerID
)
SELECT STRING_AGG(EmpName,', ') within group(order by level)
FROM Parent group by top_hierarchy;

http://sqlfiddle.com/#!18/8e17b2/1/0


text:
Q: Register a Tenant in Azure I'm developing a multi-tenant application.  I've been developing for years, but i'm new to Azure development.  I'm trying to get pointed in the right direction regarding a specific area.
I have a requirement to Register a Tenant.  For example, a potential customer comes to my website and decides they want to purchase services from us.  I provide a link that takes them to a page on my site that allows them to enter their information and sign up.
I'm trying to understand how that information gets setup on the Azure side using .net.  This would also include getting them setup in Windows Azure Active Directory (WAAD).


text:
Q: Print variables, excluding ones that are zero Let's say I have five int variables that are prompted for user input. User keys in the five value and two of those values are 0. I would like to ONLY print out values that are greater than zero.
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;

I would like to write a dynamic print statement that would exclude the int variables with Zero value.
Currently, my print statement displays all values:
System.out.printf("%s %d%n%s %d%n%s %d%n%s %d%n%s %d%n","V1;","v1","V2:","v2","V3:","v3","V4:","v4","V5:","v5");

I tried writing if-else statements but that became very cumbersome.

A: Create a new method printNonZeroVars(Integer... ints).
public static void main(String[] args) {
  int v1 = 1;
  int v2 = 30;
  int v3 = 0;
  int v4 = 37;
  int v5 = 0;
  printNonZeroVars(v1, v2, v3, v4, v5)
}

public void printNonZeroVars(int... ints) {
  for (int i = 0; i < ints.length; i++) {
     if (ints[i] > 0) {
          System.out.printf("V%d%d%n", i, ints[i]);
     }
  }
}

A: I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.

A: So a simple way of achieving this would be to use some sort of Array/List.
ArrayList<Integer> list = new ArrayList<Integer>()
// Or as pointed out by David a better way would be to declare the list as
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
....

Once you have the list you can use a loop to loop through the list and do relevant checks - something like this
String str = "";
for(int i=0; i<list.size(); i++) {
   if(list.get(i) == 0) {
       continue;
   }
   str += "v"+i + ":" + Integer.toString(list.get(i));
}
System.out.println(str);

Its pseudo but should give you a good head start :)


text:
Q: Don't run JS in Web Browser c# I try to show a web site in Form using web browser, but when I run my project the web browser don't run JS files, this files are from web site.
this is my code in Form class:
public Form1()
{
    InitializeComponent();
    web_content.Navigate(urlString: "www.mywebsite.com");
}

thanks.

A: Try to set property of browser component.
web_content.ScriptErrorsSuppressed = true;


text:
Q: How does spring-ldap bypass OpenLDAP's "unique" overlay? And how do I stop it from doing this? I have an OpenLDAP deployment with uniqueness constraints on certain attributes (created with the "unique" overlay), which I have tested using ldapadd and confirmed to be working properly. But when I add a conflicting entry using the "bind" method of org.springframework.ldap.core.LdapTemplate, the entry is saved without being validated.
Is this supposed to happen, or is there something buggy about one of my environments? And if it is supposed to happen, how do I get spring-ldap to stop sneaking past the uniqueness constraint?

A: This could possibly be due to a known issue with OpenLDAP, if spring isn't explicitly adding the RDN attribute when it adds the entry:
http://www.openldap.org/lists/openldap-bugs/201210/msg00065.html

A: Spring LDAP uses JNDI for communication with the LDAP Server. By default JNDI sends ManageDsaIT control. If set the OpenLDAP Server ignores the unique overlay.
You can disable this behaviour by setting the following environment variable:
java.naming.referral=throw

When using a spring boot service you can set:
spring.ldap.base-environment:
  java.naming.referral: "throw"


text:
Q: Constrain grid width to width of columns It's great that grids are automatically responsive, i.e. the number of columns will adjust based on the width available.
Unfortunately, it seems to be only the columns themselves that respond, the width of the grid itself takes up all the available space. Is it possible to limit the width of a grid to the total width of its columns (plus any gaps and padding)?
For instance, if I define my grid as:
grid-template-columns: repeat(auto-fit, 300px);
gap: 10px;

I would like my grid to have an inner width of 610px when it displays two columns, or 920px when it displays three columns. It should be constrained to this width, and not fill its parent's available width.
Please see this example to see what I'm talking about.


text:
Q: jsdoc тип данных Как в jsdoc указать, что функция возвращает тот же тип данных, что был ей передан?
/**
 *
 * @param {*} data
 * @returns {???}
 */
function random(data) {
    // ...
    return data;
}

A: Generic Types
/**
 * @template T
 * @param {T} data
 * @returns {T}
 */
function random(data) {
  // ...
  return data;
}


text:
Q: Xcode 6 Storyboard Size Classes there´s the new function called size classes to design once for every device. So i designed my Views in Compact Width and Regular Height, to support all iPhones in Portrait mode.

But what if i want to have one thing different on 3.5 inch devices?! How can i do that?I already tried to change the size class, but there´s no class especially for 3.5 inch devices...

A: Size classes are for categories of devices, not individual devices themselves. This means that you can't design specifically for 3.5-inch screens by using a size class.
You will have to use something like the following to check if your app is running on a 3.5-inch screen:
#define IS_IPHONE_4  ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )480 ) < DBL_EPSILON )

...and then update the position of your desired view - either by settings its frame or updating its constraints.


text:
Q: How do you pass html input text into a javascript function as a parameter? My code is below. I would like the player to input their name into the html form and for this value to be submitted into the javascript scorecard class so that this.players = "name". How would I best do this? I have been trying to use jquery but am having no success.
HTML:

  <form class='name' action=''>
    <input type="text" name="name" placeholder="NAME">
    <input type='submit' name='submit'>
  </form>

JAVASCRIPT:
var Scorecard = function() {
    this.players = 0;
};

Scorecard.prototype.addPlayer = function(name) {
  this.players = name
};

A: The jQuery solution is nice, but a bit overdressed for the occasion.
Plain JavaScript:
You aren't really accustomed to JavaScript I guess:
var Scorecard = function() {
    this.players = 0;
};

Scorecard.prototype.addPlayer = function(name) {
   this.players = name
};

This code does two things:

*

*It creates a constructor function called Scorecard. With this function you can create instances (simply put copies) of Scorecard.

*You add a function to the Scorecard master object by using the prototype. Everything added via prototype will be shared by all instances of Scorecard
To sum this up. This isn't the way to go for the functionality you want. Consider this:
var Scorecard = function() {
    this.players = 0;
    this.playerList = [];  //create a new Array() using shorthand [];
    this.addPlayer = function(name)
    {
        this.players++; //add one to the player count.
        this.playerList.push(name); //add a player to the playerlist using array.push().
    }
};

What is this code doing:

*

*It creates a master object called Scorecard.

*A public variable is assigned called this.players. Public because it can be called upon outside the function Scorecard.

*The same is done for the array: this.playerList.

*A public method is added. Note this function only applies to the instance and is not shared with all instances.

*The method addPlayer does two things. It takes name as argument. First it adds one to the public variable this.players by using ++, which means add one. Secondly it adds a player to the array list by using the method push. Which appends an item to an array.

Now we need to create a submit event. When the user submits the form, a player is added to the Scorecard.
var scorecard = new Scorecard(); //first create an instance of Scorecard
document.querySelector("form").addEventListener("submit", formAddPlayer, false);

function formAddPlayer(e)
{
   e.preventDefault(); //e is the submit event. preventDefault stops it from actually posting the form, causing the page to reload.
   var name = e.target.querySelector("input[name='name']").value //get the value from the input element.
   scorecard.addPlayer(name);

   //show the results
   alert("Player amount: " + scorecard.players + "\nPlayers: \n -" + scorecard.playerList.join("\n -") ); //show the results
}

What is the code doing:

*

*It creates a new instance (copy) of Scorecard named scorecard.

*That instance has two properties: players and playerList and one method: addPlayer.

*Attach an onsubmit event to the form. I used document.querySelector for this. Since your page only has one form, we can select the first form that the querySelector function comes across. We use addEventListener to attach the event. When the submit button is clicked the function formAddPlayer will fire. Note that formAddPlayer is passed as a reference not as a function call.

*The actual formAddPlayer function: the argument e refers to the event. In this case a submit event. The actual submitting is cancelled using e.preventDefault(). The we use querySelector on the form element (retrieved using the target, which is the form, of the submit event). We select the input element with the name : name and retrieve it's value using value. We pass this value to the method addPlayer of the instance scorecard.

Al together:
function Scorecard() {
  this.players = 0;
  this.playerList = []; //create a new Array() using shorthand [];
  this.addPlayer = function(name) {
    this.players++; //add one to the player count.
    this.playerList.push(name); //add a player to the playerlist using array.push().
  }
};

var scorecard = new Scorecard(); //first create an instance of Scorecard

function formAddPlayer(e) {
  e.preventDefault(); //e is the submit event. preventDefault stops it from actually posting the form, causing the page to reload.
  var name = e.target.querySelector("input[name='name']").value //get the value from the input element.
  scorecard.addPlayer(name);

  //show the results
  alert("Player amount: " + scorecard.players + "\nPlayers: \n -" + scorecard.playerList.join("\n -")); //show the results
}
document.querySelector("form").addEventListener("submit", formAddPlayer, false);

  <form class='name' >
    <input type="text" name="name" placeholder="NAME">
    <input type='submit' name='submit'>
  </form>

http://jsfiddle.net/55u2b81j/

A: With jQuery:
var aScorecard = new Scorecard();

$('form.name').on('submit',function(e){
    e.preventDefault();
    var name = $(this).children('input[name="name"]').val();
    aScorecard.addPlayer(name);
});


text:
Q: Access Denied Creating a folder or item in Onedrive I am getting this error:

{"error":{"code":"accessDenied","message":"Access Denied"}}

everytime i am using the onedrive api
the scopes i use are:
wl.signin,wl.offline_access, onedrive.readonly, onedrive.readwrite, onedrive.appfolder
I am able to login, logout, edit and delete items and folders, retrieve the files for each and every folders but why can't I add a folder?
This is the api url I used to try to add the folder:
https://api.onedrive.com/v1.0/drive/items/{{THE PARENT ID}}/children?nameConflict=fail
I use curl post, body is json encoded:
$data = json_encode(array("name"=>"".$title,"folder"));

Please help me resolve my issue. :(

A: I just have to create the data to be passed to url as a string and not as an array. That solved my problem. Thanks everyone.


text:
Q:  <ice:outputMedia player="flash" source="... /ICEfaces_Flash.swf"
                style="width:300px;height:250px;">
<f:param name="play" value="true"/>
<f:param name="menu" value="true"/>
</ice:outputMedia>

Above Code plays the flash file but doesnt show the controls !

A: For Flash you get access to the controls via the context menu only.

A: Yes, the context menu (aka right-click menu) will have the play, pause button.
<param name="menu" value="true"> with a normal html page will do the trick, but it seems not to be working with icefaces (when using f:param) like u did.
Actually the icefaces docs says it should be done this way. Maybe it's a bug so i would recommend to add a thread on the icefaces forum.


text:
Q: MySQL and PHP advanced product sales: check multiple fields Sorry for the title, I don't know how to properly explain, I'll try here.
I have 4 tables:

*

*products(id, season_id(FK), year(4), brand_id(FK), price, ...)

*seasons(id, name)

*brands(id, name)

*sales(id, season_id(FK), year(4), brand_id(FK), value(INT))
As you already guessed season_id and brand_id are FK where there is _id.
Now, depending on the sales table, products will have a price that will be calculated. My problem is that there can be any combinations of the sales table to calculate the price.
I'll quickly make an example to be clearer.
Table products rows:

*

*id: 1, season_id: 3, year: 2013, brand_id 3, price: 100.00

*id: 2, season_id: 3, year: 2015, brand_id 4, price: 100.00

*id: 3, season_id: 4, year: 2014, brand_id 5, price: 100.00

*id: 4, season_id: 5, year: 2014, brand_id 5, price: 100.00
Table sale rows:

*

*season_id: 3, year: 2013, brand_id: 3, value: 5%

*season_id: 3, year: 2014, brand_id: null, value: 10%

*season_id: 4, year: 2015, brand_id: null, value: 15%

*season_id: null, year: null, brand_id: 5, value: 20%
(all fields are optional, but if there is a season there must be a year)
Given that example

*

*first product's price will be 100 - 5% ( season 3 + 2013 + brand 3 )

*second product's price will be 100 ( matches season but not year )

*third product's price will be 100 ( matches season but not year )

*fourth product's price will be 100 - 20% (any season + any year + brand 5)
So to wrap up, I need a way to know for each product what sale to apply. The priority is:
SeasonYearBrand > SeasonYear > Season > Year > Brand

Now I have a query that fetches all products and another one for all sales. Inside a foreach I loop through all products and here again another foreach where I loop through all sales and finally I check what sale to apply.
I know is very confusing but I want to know if there is a better way of doing it. Each page has 25 products and I have 20 rows in the sales table so you can see how easily things get heavy.

A: You can do this with SQL. Use a subquery to get the best matching sales record. Candiadates are all sales records where the three fields match or are null. You order by match quality. I rank a year match highest, then season then brand using some math where I use MySQL's feature to evaluate boolean expressions to 1 f0r TRUE and 0 for FALSE. So a year macth with no brand is better than a brand match with no year. Then take the first record, i.e. the best match. I expect a value of 5% to be stored as 0.5? Else you would have to change the formula. At last, if no records match at all, I multiply the price with 1, thus keeping the price.
select
  id,
  season_id,
  year,
  price *
  coalesce
  (
    (
      select 1 - s.value
      from sales s
      where coalesce(s.season_id, p.season_id) = p.season_id
      and coalesce(s.year, p.year) = p.year
      and coalesce(s.brand_id, p.brand_id) = p.brand_id
      order by
        (s.year is not null) * 4 +
        (s.season_id is not null) * 2 +
        (s.brand_id is not null) * 1 desc
      limit 1
    ), 1
  ) as calc_price
from products p;


text:
Q: TypeError: unhashable type: 'list' when using nltk.FreqDist on Pandas Series I am trying to get the word frequencies for terms within each tweet contained in a dataframe.
Using this code the tweets are all treated like one word:
import pandas as pd
import numpy as np
import nltk
import string
import csv
import collections
from collections import Counter
nltk.download('stopwords')

data= pd.read_csv('C:/Users/leska/Desktop/tweets.csv.zip', compression='zip')

print (data.columns)
print (len(data.tweet_id))
tweets = data.text
sw= set(nltk.corpus.stopwords.words ('english'))
punctuation = set (string.punctuation)
tweets_filtered = [w.lower() for w in tweets if w.lower() not in sw and w.lower() not in punctuation]
words = nltk.FreqDist(tweets_filtered)
print(len(words))
df_fdist = pd.DataFrame.from_dict(words, orient='index')
df_fdist.columns = ['Frequency']
df_fdist.index.name = 'Term'
print(df_fdist)
df_fdist.to_csv('C:/Users/leska/Desktop/Tweets2.csv')

So I tried tokenizing the words within the text column of the dataframe so each word would be counted:
import pandas as pd
import numpy as np
import nltk
import string
import collections
from collections import Counter
nltk.download('stopwords')
sw= set(nltk.corpus.stopwords.words ('english'))
punctuation = set (string.punctuation)
data= pd.read_csv('C:/Users/leska/Desktop/tweets.csv.zip', compression='zip')

print (data.columns)
print (len(data.tweet_id))
tweets = data.text
test = pd.DataFrame(data)
test.column = ["text"]
# Exclude stopwords with Python's list comprehension and pandas.DataFrame.apply.
test['tweet_without_stopwords'] = test['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (sw)]))
print(test)
chirps = test.text
splitwords = [ nltk.word_tokenize( str(chirps) ) for chirps in chirps ]

tweets2 = pd.Series(splitwords)

words = nltk.FreqDist(tweets2)

print(len(words))
df_fdist = pd.DataFrame.from_dict(words, orient='index')
df_fdist.columns = ['Frequency']
df_fdist.index.name = 'Term'
print(df_fdist)
df_fdist.to_csv('C:/Users/leska/Desktop/Tweets2.csv')

This gives me the following error:
TypeError: unhashable type: 'list'
Here is the full traceback:
Traceback (most recent call last):
File "", line 1, in
    runfile('C:/Users/leska/.spyder-py3/temp.py', wdir='C:/Users/leska/.spyder-py3')
File "C:\Users\leska\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)
File "C:\Users\leska\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/leska/.spyder-py3/temp.py", line 32, in
    words = nltk.FreqDist(tweets2)
File "C:\Users\leska\Anaconda3\lib\site-packages\nltk\probability.py", line 108, in init
    Counter.init(self, samples)
File "C:\Users\leska\Anaconda3\lib\collections__init__.py", line 568, in init
    self.update(*args, **kwds)
File "C:\Users\leska\Anaconda3\lib\site-packages\nltk\probability.py", line 146, in update
    super(FreqDist, self).update(*args, **kwargs)
File "C:\Users\leska\Anaconda3\lib\collections__init__.py", line 655, in update
    _count_elements(self, iterable)
TypeError: unhashable type: 'list'
I am stumped as I have converted the list to a series.
In the end I need the word frequency for each tweet to save to a .csv file.
I am very new to using both Python and Pandas so I am stumped. What am I doing wrong or missing?


text:
Q: How to access window class extra memory without a window handle? I need to register a window class, and right after that set some data in it's extra memory section (the one cbClsExtra refers to) before any window of the class is being created. The problem is that SetClassLong expects a HWND in order to identify the class, instead of the class's name or atom.
What's the way to acheive this?

A: Why can't you just create a dummy window of that class, set the data and destroy the window?


text:
Q: BigQuery is not supporting split function on dataframes to expand column into multiple columns To insert data in BigQuery, I am loading csv file to bigquery. To create csv file I am using dataframes then converting them to csv file. After creating one dataframe, I am using split function to expand some columns(suppose I have 6 columns and I want to expand each column into 21 columns i.e total of 6*21) but when I am applying split function on more than one column of dataframe, it's giving me error.
Then I also tried other methods like creating multiple dataframes then using merge, concat function to join them but it didn't work.
For example: data in one column is : '11.7_16.1_20.6_25.0_29.4_33.9_38.3_42.7_47.1_51.6_56.0_60.4_64.8_69.3_73.7_78.1_82.5_87.0_91.4_95.8_100.2' and now we want to split this into separate 21 columns, similarly for other 5 columns.
If anyone here can help me with this would be appreciated. Trying to solve this from past 3 days.

A: I would use a combo of stack/unstack :
out = df.stack().str.split("_", expand=True).unstack()

NB : For the sake of the output, I divided your column into 2 (#len(df.columns)=2).

Output :
print(out)

      0               1           2           3           4           5           6           7           8           9
   col1      col2  col1  col2  col1  col2  col1  col2  col1  col2  col1  col2  col1  col2  col1  col2  col1  col2  col1   col2
0  11.7  56.060.4  16.1  64.8  20.6  69.3  25.0  73.7  29.4  78.1  33.9  82.5  38.3  87.0  42.7  91.4  47.1  95.8  51.6  100.2


text:
Q: Urban Airship: custom icon for default status bar notification Urban Airship recommends creating a custom notification with CustomPushNotificationBuilder if you want to make any modifications to the status bar notification, including trivially changing the icon.
Unfortunately, using a RemoteView for notifications carries many unwanted implications with it related to custom manufacturer and/or platform-specific skins, including text colors and references to private resources (for instance @*android:drawable/notify_panel_notification_icon_bg_tile on Honeycomb/ICS).
There must be a simple way to swap the icon without using RemoteView. How?

A: I found that by overriding BasicPushNotificationBuilder, I can set the icon quite trivially:
BasicPushNotificationBuilder nb = new BasicPushNotificationBuilder() {
    @Override
    public Notification buildNotification(String alert,
            Map<String, String> extras) {
        Notification notification = super.buildNotification(alert,
                extras);
        // The icon displayed in the status bar
        notification.icon = R.drawable.notification;
        // The icon displayed within the notification content
        notification.contentView.setImageViewResource(
                android.R.id.icon, R.drawable.notification);
        return notification;
    }
};
// Set the custom notification builder
PushManager.shared().setNotificationBuilder(nb);

A: I know this is an old question, but UrbanAirship get's updated quite often, so I decided to help others who might reach this page. As of version 6.0.1 there's no BasicNotificationBuilder no more. In order to customize your notification with icon and color and whatnot, you need to extend the NotifcationFactory class, and override the createNotification method.
Like shown in the example below:
public class MyNotificationFactory extends NotificationFactory {

public MyNotificationFactory(Context context){
    super(context);
}

@Override
public Notification createNotification(PushMessage pushMessage, int i) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
            .setContentTitle(getContext().getResources().getString(R.string.app_name))
            .setContentText(pushMessage.getAlert())
            .setSmallIcon(R.drawable.your_icon_here)
            .setColor(getContext().getResources().getColor(R.color.your_color_here))
            .setAutoCancel(true);

    return builder.build();
}

@Override
public int getNextId(PushMessage pushMessage) {
    return NotificationIDGenerator.nextID();
}

}
At last you must set this as UrbanAirship's new notification factory in your application class or wherever you initialized UA:
UAirship.shared().getPushManager().setNotificationFactory(new MyNotificationFactory(getApplicationContext()));

A: We provide a lot of functionality in our default notification factory such as big styles (inbox, text, image), lollipop features (privacy, priority), and interactive notification buttons. If you are only trying to set the icon and maybe the accent color, I recommend the following:
    UAirship.takeOff(this, new UAirship.OnReadyCallback() {
        @Override
        public void onAirshipReady(UAirship airship) {
            // Perform any airship configurations here

            // Create a customized default notification factory
            DefaultNotificationFactory defaultNotificationFactory = new DefaultNotificationFactory(getApplicationContext());
            defaultNotificationFactory.setSmallIconId(R.drawable.ic_notification);
            defaultNotificationFactory.setColor(NotificationCompat.COLOR_DEFAULT);

            // Set it
            airship.getPushManager().setNotificationFactory(defaultNotificationFactory);
        }
    });

Full docs on the class can be found here - http://docs.urbanairship.com/reference/libraries/android/latest/reference/com/urbanairship/push/notifications/DefaultNotificationFactory.html


text:
Q: Don't display how many times the badge was earned for badges earned at max once
Possible Duplicate:
Clarify wording on badge page for post-associated badges that you can only earn once

If you look e.g. on Tumbleweed badge of someone you see:

Jinka earned this badge 1 time

which is quite confusing because it suggests that the badge could have been earned more times. But this badge can be earned only once. So my suggestion would be to change that message  to something like:

*

*Jinka earned this badge

*Jinka earned this badge (awarded only once)

*...

Also the question is whether it lists all the questions for which this badge applies or only the first one.


text:
Q: Computing an map of minimum distance to a number of points Given a list of points obstacles (given as a list of row, column matrix coordinates, an ndarray of shape (n, 2)), return a map of size size (where size is the shape of the 2D NumPy array) in which the value of r, c is the Euclidean distance to the closest "obstacle."
def gen_distgrid(size, obstacles):
    n_obstacles = obstacles.shape[0]
    distgrids = np.zeros((n_obstacles + 4, size[0], size[1]))
    for layer in range(n_obstacles):
        for i in range(size[0]):
            for j in range(size[1]):
                distgrids[layer, i, j] = np.linalg.norm(obstacles[layer,:] - [i,j])
    for i in range(size[0]):
            for j in range(size[1]):
                distgrids[n_obstacles + 0, i, j] = i
                distgrids[n_obstacles + 1, i, j] = (size[0] - i)
                distgrids[n_obstacles + 2, i, j] = j
                distgrids[n_obstacles + 3, i, j] = (size[1] - j)
    distgrid = np.min(distgrids, axis=0)
    return distgrid

My method is really slow, and I feel like there should be a better one.

A: Here is a solution to a similar problem using a KD-tree with Numpy and SciPy. Just insert your obstacles into the KD-tree and query the tree for each grid point to get its nearest neighbor.

A: I ended up using a KD-tree from SciPy. It has a very easy distance function.
from scipy.spatial import cKDTree as KDTree
def gen_distgrid(obstacles):
    n_obstacles = obstacles.shape[0]
    obstacles = np.vstack((obstacles, [0,0], [0, size[1] - 1], [size[0] - 1, 0], [size[0] - 1, size[1] - 1]))

    distgrid = np.zeros((size[0], size[1]))
    obs_tree = KDTree(data=obstacles)

    i_v = np.arange(size[0])
    j_v = np.arange(size[1])

    coordmat = np.dstack(np.meshgrid(i_v, j_v, indexing='ij'))
    obs_dists, obs_locs = obs_tree.query(coordmat)

    top_dists = np.repeat(i_v, size[1]).reshape(size)
    bottom_dists = np.repeat(size[0] - i_v, size[1]).reshape(size)
    left_dists = np.repeat(j_v, size[0]).reshape(np.transpose(size)).T
    right_dists = np.repeat(size[1] - j_v, size[0]).reshape(np.transpose(size)).T

    dists = np.min([obs_dists, top_dists, bottom_dists, left_dists, right_dists], axis=0)
    return dists


text:
Q: Explorer seems to time out for ~ 2 min. when opening files I have an odd problem.  I have a farm of 8 Citrix terminal servers, running Server 2003 Std x86.  The hardware on all servers is identical and all servers were built from the same image.  Late last week, one the servers started having a problem where any file, when opened by double-clicking, seems to lock explorer.exe for about 2 minutes (I've timed it multiple times, anywhere from 2:09 to 2:40) after which point the file eventually opens.  The file can be .txt, .doc, .xls, .jpg, etc.  HOWEVER, if I open the required program first (notepad, Excel, whatever) and go to File/Open the file opens without incident.
I've tried running ProcessMonitor while the explorer 'lock' is occurring and I can't find a smoking gun (it's possible that it's there, but with 18,000+ lines it'll take a while to track it down even using filters).
I've started the server in Safe Mode and files open normally (without the lock).  Subsequently I've tried stopping every service I can (while started normally) without success.
I've uninstalled AV (Symantec EAP 11) without any positive impact.  The event logs are clean and none of the other servers are experiencing this problem.
Does anyone have any thoughts?

A: Okay, I figured it out and thought I'd post the answer here in case anyone finds this post thought a search.
Last week I replaced Adobe Reader on the Citrix farm with Foxit Reader.  Before doing so I did some testing using an old Citrix server that's not part of the production farm.  At some point I noticed that the Foxit install just consisted of an execuatable, and you could click the executable from anywhere on the network.  At some point I clicked on the Foxit executable from the server which later became inflicted with this problem.
Late last week that old Citrix (testing) server failed and it wasn't restarted.
Justin's comment to use Wireshark showed multiple attempts on the part of the afflicted server to contact the failed test server.  I searched the registry for that servername and found that the open, print and printto registry keys set to the foxit executable on the failed test server, rather than the local copy of Foxit.exe
These keys:
HKEY_CLASSES_ROOT\Applications\Foxit Reader.exe\shell\open\command
HKEY_CLASSES_ROOT\Applications\Foxit Reader.exe\shell\print\command
HKEY_CLASSES_ROOT\Applications\Foxit Reader.exe\shell\printto\command
Changing these keys to point to the local copy of Foxit.exe fixed the problem.  Thanks Justin, for pointing me in the right direction.

A: Every time I've seen explorer hang it was because of an inaccessible mapped drive.

A: I would disable the Netbios protocol altogether (temporarily ) and see if that improves performance.   By removing the protocol completely, you can narrow down the problem.    Also, disabling the network adapter (temporarilty) would accomplish the same thing probably.


text:
Q: How to launch Fuzzy Logic? I'm trying to launch the Fuzzy Logic addin in Excel, using VBA.
I have got the addin, and have used the macros recording tool to try and see how it is done.
However, the macros recording does not show the launch of the Fuzzy Logic or the setting of the parameters.
Any suggestions on how to launch the addin?

A: From the Readme.docx file included with the add-in:

Can I call Fuzzy Lookup from VB or C#?
Programmatic access is not presently available.

The comments on this blog post seem to also indicate that this is not possible at this time.
The closest I can come is the following:

*

*Add the launch icon to the quick access toolbar

*Add VBA SendKeys "%5" (where 5 is the position of the icon in the quick access toolbar)

*The VBA should make sure that the Excel spreadsheet is displayed before using SendKeys (it won't work if you displaying the VBE)

Tabbing around on the Fuzzy Logic pane gets stuck about halfway through the controls.
In VBA, you can create a reference to the pane:
Dim cb as CommandBar
Set cb = Application.CommandBars("Fuzzy Lookup")

You can display the caption of the pane.
MsgBox cb.controls(1).caption

You can't modify the visible property of the CommandBar nor the CommandBarControl. For comparison, you can display the Selection Pane quite easily with the following:
Application.CommandBars("Selection").visible = true


text:
Q: Setting up common classes for access from other projects I'm trying to set up two Java projects to have access to classes in another Java project.
So far, the situation is visible in the following image:

(source: shrani.si)
However, I can't seem to import any classes from the Common project.

(source: shrani.si)

I could just have multiple packages in a single project, but as far as I know only 1 jar can be compiled per project.
Any help is greatly appreciated.

A: You need to add your "Common" project to libraries of project where you need to use classes from "Common" project.
For example right-click on "Clinet" project then "Properties"
In right menu choose "Libraries" and press button "Add Project..." and double-click on project "Common".
After that you can add import common.Item;
Also try to clean and build all your projects.


text:
Q: Swagger-ui Validation issue with REST API I am trying to integrate Swagger in my existing application for REST APIs.
While running on localhost I am getting the expected result in Swagger UI.
But when I deploy my .war file on DAP and try to access it is not able to read the JSON from the URL.
{"schemaValidationMessages":[{"level":"error","message":Cant read from file..

I suppose this is a validator issue.
I cannot make the link public as I work for a bank and it has to be private and secure at any cost.
Alternately I tried to bypass the validator.
I have already tried setting validatorUrl = null in my index.html.
Also i have set validatorUrl = null in my swagger-ui.js file.
Both these don't seem to work.
Can any one please guide me on how can I go about doing this as this is really important and critical.


text:
Q: compare sum of column values in python I have a csv file loaded in a python object. 15 of the columns contains binary values. I have several thousands rows.
I want to count the sum of the binary values of each of the columns and sort the result ascendingly.
I only made it to:
sum1=sum(products['1'])
sum2=sum(products['2'])
sum3=sum(products['3'])
....
...
sum15=sum(products['15'])

and process the result manually. Is there a programmatic way to achieve this?

A: you will find the solution here :
with open("file.csv") as fin:
headerline = fin.next()
list_sum_product=[]
for i in range(15):
    total = 0
    for row in csv.reader(fin):
        total += int(row[i])
    list_sum_product.append(total)
print sorted(list_sum_product)

A: How about this:
sorted_sum = sorted([sum(products[i]) for i in range(1, 16)])

sorted_sum is the sorted list of column sums. However, I believe the index should run from 0 to 14, not 1 to 15.


text:
Q: TypeError: key must be a string, a buffer or an object at typeError with GCP file exists I'm trying to simply test for an existence of a file on our Google Cloud Platform (GCP) storage. I'm using GCP buckets on express js servers. Below is essentially a very simple exampled copied off of https://googleapis.dev/nodejs/storage/latest/File.html#exists
EDIT: This is how I authenticate the GCP key:
const { Storage } = require('@google-cloud/storage');

const storage = new Storage({
    projectId: 'my-cloud',
    keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
});
const bucketName = 'my-ci';

(With small changes, I realise you are supposed to return data[0])
const bucket = storage.bucket(bucketName);
const file = bucket.file(path);
const exists = await file.exists().then(data => {
    return data
})

But when I try run this, I get the error:
[nodemon] starting `node --inspect server/server.js`
Debugger listening on ws://127.0.0.1:9229/9a677766-4a93-4499-b57c-55f5f05096d7
For help, see: https://nodejs.org/en/docs/inspector
Server listening on port 4000!
/opt/node_modules/jwa/index.js:115
return new TypeError(errMsg);
^

TypeError: key must be a string, a buffer or an object
at typeError (/opt/node_modules/jwa/index.js:115:10)
at checkIsPrivateKey (/opt/node_modules/jwa/index.js:61:9)
at Object.sign (/opt/node_modules/jwa/index.js:147:5)
at Object.jwsSign [as sign] (/opt/node_modules/jws/lib/sign-stream.js:32:24)
at JWTAccess.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/jwtaccess.js:87:31)
at JWT.getRequestMetadataAsync (/opt/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:51)
at JWT.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/oauth2client.js:238:37)
at GoogleAuth.authorizeRequest (/opt/node_modules/google-auth-library/build/src/auth/googleauth.js:593:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Since the error message did not give a useful traceback, I did some digging on my own. Through putting console.log statements everywhere, I narrowed it down to the line
const exists = await file.exists().then(data => {
    return data
})

and tried various approaches from removing the .then(...) clause, to removing the await (which, does work until the promise is resolved). None of these seemed to have worked.
What may be potential causes of this?

A: Eventually figured it out - it was due to the GCP key being an older version of the key. If you get an error like above, try to check that your key is correct.