text:
Q: subsonic - Offset and length were out of bounds for the array intermittent error inherited a website which uses subsonic 2.0 and gets an intermittent error of "Offset and length were out of bounds for the array" . If we were to restart the app or recycle the app pool, the issue would go away. I suspect it has something to do with subsonic caching the table schema based on the error log below. Has anyone experience this issue and can suggest a fix?
System.ArgumentException

Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
System.Exception: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
   at System.Array.BinarySearch[T](T[] array, Int32 index, Int32 length, T value, IComparer1 comparer)
   at System.Collections.Generic.SortedList2.IndexOfKey(TKey key)
   at System.Collections.Generic.SortedList`2.ContainsKey(TKey key)
   at SubSonic.DataService.GetSchema(String tableName, String providerName, TableType tableType)
   at SubSonic.DataService.GetTableSchema(String tableName, String providerName)
   at SubSonic.Query..ctor(String tableName)
   at G05.ProductController.GetProductByColorName(Int32 productId, String colorName) in C:\Projects\G05\Code\BusinessLogic\ProductController.vb:line 514

A: Strange that it's intermittent . How are the objects being generated? Is it using the .abp file? If so, I'd recommend running the files through the subcommander to hard generate the classes. That way the generation of the objects isn't ever executed on production environment.


text:
Q: Good way to filter list distincted by property and ordered by date I have very simple thing to do, i have list of persons like this:
[{
    name: John,
    date: 01-01-2018,
    attend: true
},
{
    name: Adam,
    date: 01-01-2018,
    attend: false
},
{
    name: Adam,
    date: 01-02-2018,
    attend: true
},
{
    name: JOHN,
    date: 01-02-2018,
    attend: false
}]

Result of this array should be: Adam (true), John (false)
So i need to return list of latest entries from users, in this case John first confirmed that he is attending, then he changed his mind and told that he is not attending so i'm returning his last entry (note that sometimes it's written JOHN and sometimes John but it is the same person, that is kind of tricky part)
My question what is best approach to filter out this kind of list, i was thinking applying "unique by property java stream" but first will need to order persons by date descending and names (to upper/lower case) and then i would need somehow to take latest entry.
Anyone have any good idea what is best approach to this ?

A: You can use Collectors.toMap to do the same as:
List<Person> finalList = new ArrayList<>(people.stream()
        .collect(Collectors.toMap(a -> a.getName().toLowerCase(),  // name in lowercase as the key of the map (uniqueness)
                Function.identity(), // corresponding Person as value
                (person, person2) -> person.getDate().isAfter(person2.getDate()) ? person : person2)) // merge in case of same name based on which date is after the other
        .values()); // fetch the values

Note: The above assumes the minimal Person class to be
class Person {
    String name;
    java.time.LocalDate date;
    boolean attend;
    // getters and setters
}

A: You could use the toMap collector:
Collection<Person> values = source.stream()
                    .collect(toMap(e -> e.getName().toLowerCase(),
                            Function.identity(),
                            BinaryOperator.maxBy(Comparator.comparing(Person::getDate))))
                    .values();

see this answer for an explanation as to how toMap works

A: Despite all answers until now are functionally correct, please consider this option:
final Map<String, Boolean> lastAttendResults =
            people
                .stream()
                .collect(
                    groupingBy(
                        Person::getName, // Define what is the property you are using to group people.
                        () -> new TreeMap<String, Boolean>(String.CASE_INSENSITIVE_ORDER), // Supply a map implementation that ignore name case.
                        collectingAndThen(maxBy(Comparator.comparing(Person::getDate)), // Foreach list of grouped people, select that with last date.
                            o -> o.get().isAttend()))); // As maxBy returns an Optional<Person> and we are sure that it exists, just get the Person and if he attends.

This implementation is interesting because it let be evident the concept of collection grouping. Although, in depth, it also uses a map, seems to me that use or not a map is not programmer problem, I mean, what we are looking for is how to group people by name and then get the last entry.
If you prefer receive a List of Person instead of a Map of name and attend, you can use:
final List<Person> lastAttendResults =
        new ArrayList<>(people
            .stream()
            .collect(
                groupingBy(Person::getName, // Define what is the property you are using to group people.
                    () -> new TreeMap<String, Person>(String.CASE_INSENSITIVE_ORDER), // Supply a map implementation that ignore name case.
                    collectingAndThen(maxBy(Comparator.comparing(Person::getDate)), // Foreach list of grouped people, select that with last date.
                        Optional::get // As maxBy returns an Optional<Person> and we are sure that is exists, just get the Person.
                        ))).values());

A: A compact way without streams:
Map<String, User> map = new LinkedHashMap<>();
users.forEach(u -> map.merge(
        u.getName().toLowerCase(),
        u,
        BinaryOperator.maxBy(Comparator.comparing(Person::getDate))));

Collection<User> result = map.values();

Or if you do need a List:
List<User> result = new ArrayList<>(map.values());

This code uses Map.merge, which puts the entry in the map if there's no entry with the same key (the lowercased user name), or, if the map already contains an entry for the key, it applies the merge function, which in this case chooses the User instance with the max date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas dataframe shifting values at certain row I'm currently working on a poorly DataFrame.
I am looping through each values in each columns and when a certain value is passed in, I am trying to shift values to the right. For example

this is the dataframe that I am working with and for the 5th column, if the string "Pubmed reference:" is passed I am trying to shift rest of values on the right to shift by certain amount. I saw there is a pandas shift function, but it seems like it moves whole column values by parameter value period.
and I would like to change it like this

what can I do to do this?

A: mask = df['ORIGINAL_COLUMN'] == "Pubmed reference:"
df.loc[mask, 'TARGET_COLUMN'] = "Pubmed reference:"
df.loc[mask, 'ORIGINAL_COLUMN'] = "NaN"

Be sure to replace the column names with your own.


text:
Q: Sharing Money Puzzle Nine boys and three girls agreed to share their cents equally.
Every boy gave an equal sum to every girl, and then every girl gave another equal sum to every boy. Each child then possessed exactly the same amount.
What was the smallest possible amount in cents that each child possessed after the sharing?
Note:
(1) Before the sharing, every boy had the same amount of money, which was
greater than 0. Every girl had the same amount of money, which was greater than 0 too. The money that each boy possessed and the money that each girl possessed were not the same before the sharing.
(2) The amount of money that each boy gave to each girl (which was greater than 0) and the amount of money that each girl gave to each boy (which was greater than 0) were not the same.
Here are some thoughts: Let $b$ the amount of money each boy has, and  let $g$ be the amount each girl has.
Let $x$ be the amount the each girl gets from the boys. So $x$ is a multiple of 9.
Let $y$ be the amount each boy gets from the girls. So $y$ is a multiple of 3.
So we have $9b-xg+yb=3g+xg-yb$, which gives use $(9+2y)b=(3+2x)g \implies (9+6y')b=(3+18x')g$
Now we want to find the smallest possible $b$ and $g$.
I still feel like I'm not understanding this question right. Please help.
Thank you!

A: Using your notation, each boy starts with $b$ and each girl with $g$.  Each boy gives $x$ to each girl and each girl gives $y$ to each boy.
Then, at the end of all the sharing, each boy has $$b-3x+3y=b-3(x-y)$$ coins and each girl has $$g+9x-9y=g+9(x-y)$$ coins.
These must be equal so $$b-3(x-y)=g+9(x-y)\quad \text {or}\quad b-g=12(x-y)$$
Thus $b-g$ is divisible by $12$.
Now, the rules appear to exclude $b-g=0$ so, as we are looking for minimal solutions, we need $|b-g|=12$.  Now, our goal is to minimize the total number of coins, which is $9b+3g$.  To do that, we aim for $b-g=-12$.  Noting that $b≥3$, so that the boys can at least give each girl one coin, the minimal solution is $(b,g)=(3,15)$.
We then require $x-y=-1$.  We can achieve that with $(x,y)=(1,2)$.
In the end each kid winds up with $$3-3(x-y)=\boxed {6}=15+9(x-y)$$
Note that the "official" solution fails since in that case the kids must start with the same number, counter to assumption.
Note:  an earlier version of this solution arbitrarily added the assumption that $b>g$.  This error was pointed out by @tomi in a comment.


text:
Q: Query Select group by last character in field I'm trying to do a query search on a table and return a count of rows that end in the same character.  For example, Cd312a, fdhEA and 42dA would be grouped together under 'A'.  Below is an example of the table and what I would like to see returned.
Table Tbl_Table
ID| _Name     |
1 | S033114A  |
2 | S033114B  |
3 | S033114B  |
4 | S033114K  |
4 | S033114K  |

Results
Type  | Count
  A   |  1
  B   |  2
  K   |  2

My Current Code
SELECT RIGHT(_Name,1) as Type, Count(Type) as Count FROM Tbl_Table

Anyone that can shed some light on my my query isn't returning what I am expecting would be helpful.  Thank you.

A: Before
SELECT RIGHT(_Name,1) as Type, Count(Type) as Count
FROM Tbl_Table

After
SELECT RIGHT(_Name,1) as Type, Count(*) as Count
FROM Tbl_Table
Group by RIGHT(_Name,1)
Order by RIGHT(_Name,1)

Edit
Removed "Type" from the Count function to address the "Unknown column 'Type' in 'field list'" problem.


text:
Q: Random selection in pandas dataframe I'm trying to solve this more complicated question. Here's a smaller problem:
Given df
a    b
1    2
5    0
5    9
3    6
1    8

How can I create a column C that is a random selection between the two elements of df['a'] and df['b'] of the same row?
So, given this dummy df, the random operator would choose from the pair (1, 2) for row #1, from (5, 0) for row #2...etc.
Thanks

A: import random

n = 2  # target row number
random.sample(df.iloc[n, :2], 1)  # Pick one number from this row.

For the whole dataframe:
>>> df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1)
0    [1]
1    [5]
2    [9]
3    [3]
4    [8]
dtype: object

Cleaning it up to extract the single values:
>>> pd.Series([i[0] for i in df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1)], index=df.index)
0    1
1    5
2    9
3    3
4    8
dtype: int64

Or taking advantage that column 'a' is indexed at zero (False) and column 'b' is indexed at 1 (True):
>>> [df.iat[i, j] for i, j in enumerate(1 * (np.random.rand(len(df)) < .5))]
[1, 5, 5, 6, 8]

A: No need to use a separate random module:
s = """a    b
1    2
5    0
5    9
3    6
1    8
"""

df = pd.read_table(StringIO(s),sep='\s+',engine='python')
df.apply(lambda x: x.sample(n=1).iloc[0],axis=1)
#output:
0    1
1    5
2    9
3    6
4    1
dtype: int64


text:
Q: How to implement secure remember username and password in react.js <Formik
    initialValues={LoginSchema}
    validationSchema={LoginSchemaValidation}
    onSubmit={(values, { setSubmitting, resetForm }) => {
      this.handleSubmit(values);
      setSubmitting(false);
      resetForm();
    }}
  >
    <Form>

        <Field name="username" type="email" className="form-control" placeholder="Email" />

              <FontAwesomeIcon icon={faEnvelope} />

        <ErrorMessage name="username" />

        <Field
          name="password"
          type="password"
          className="form-control"
          placeholder="Password"
        />

              <FontAwesomeIcon icon={faLock} />

        <ErrorMessage name="password" />

          <Field name="isRemember" type="checkbox"/> Remember Me

          <button type="submit" className="btn btn-yellow btn-block">
            Sign In
          </button>

    </Form>
  </Formik>

This is my react form for user input, i used spring boot as backend.
Now i want to implement remember me feature at front-end
Is it secure to store username and password in local storage?
If not then how should i implement this functionality?


text:
Q: Fabric8 Docker Maven plugin not working for compose.yml on Multi module project I trying to use Fabric8 docker-maven-plugin, though I was successful in configuring plugin for individual module and run docker:build docker:start Maven goal without using docker-compose.yml, however I needed externalize ports and link the different module, hence I intended to use docker-compose.yml. Below is my project structure.
--kp-parent
      |
      --- docker-compose.yml
      --- pom.xml
      |
      ---- rest1
      |       |
      |       -- .maven-dockerignore
      |       -- pom.xml
      |       -- Dockerfile
      ---- rest2
      |       |
      |       -- .maven-dockerignore
      |       -- pom.xml
      |       -- Dockerfile

Here are my configurations
Dockerfile[both rest1 and rest2 use identical file except the different port]
FROM openjdk:8-jdk-alpine
MAINTAINER 'Karthik Prasad'

ARG IMAGE_VERSION
ARG JAR_FILE
ENV JAVA_OPTS=""

LABEL version = IMAGE_VERSION

VOLUME /tmp
ADD /maven/${JAR_FILE}.jar app.jar

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
EXPOSE 8000

.maven-dockerignore[In both child modules identical file]
target/**

pom.xml [Both rest1 and rest2 pom files are same except the artifcatid and name of the project]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rest2</artifactId>
    <packaging>jar</packaging>

    <name>rest2</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.kp.swasthik</groupId>
        <artifactId>kp-docker-multimodule-fabric8-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- https://mvnrepository.com/artifact/io.fabric8/docker-maven-plugin -->
            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <configuration>
                    <skip>false</skip>
                    <images>
                        <image>
                            <external>
                                <type>compose</type>
                                <basedir>../</basedir>
                                <ignoreBuild>true</ignoreBuild>
                            </external>
                        </image>
                    </images>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

parent pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kp.swasthik</groupId>
    <artifactId>kp-docker-multimodule-fabric8-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>kp-docker-multimodule-fabric8-parent</name>
    <description>Microservice Parent Pom file</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <modules>
        <module>rest1</module>
        <module>rest2</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <docker.image.prefix>kp-ms</docker.image.prefix>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>io.fabric8</groupId>
                    <artifactId>docker-maven-plugin</artifactId>
                    <version>0.22.1</version>
                    <configuration>
                        <skip>true</skip>
                        <images>
                            <image>
                                <alias>${project.artifactId}</alias>
                                <name>${docker.image.prefix}/${project.artifactId}:${project.version}</name>
                                <build>
                                    <dockerFileDir>${project.basedir}</dockerFileDir>
                                    <assembly>
                                        <inline>
                                            <id>default</id>
                                            <fileSet>
                                                <directory>${project.build.directory}</directory>
                                                <outputDirectory>/</outputDirectory>
                                                <includes>
                                                    <include>*.jar</include>
                                                </includes>
                                            </fileSet>

                                        </inline>
                                    </assembly>
                                </build>
                            </image>
                        </images>
                        <buildArgs>
                            <IMAGE_VERSION>${project.version}</IMAGE_VERSION>
                            <JAR_FILE>${project.artifactId}-${project.version}</JAR_FILE>
                        </buildArgs>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

And finally docker-compose.yml
version: '2'
services:
  rest1:
    image: kp-ms/rest1:0.0.1-SNAPSHOT
    ports:
    - 8000:8000
  rest2:
    image: kp-ms/rest2:0.0.1-SNAPSHOT
    ports:
    - 8001:8001
    links:
    - rest1

When I run the docker:build docker:start I get below error.
[ERROR] Failed to execute goal io.fabric8:docker-maven-plugin:0.22.1:start (default-cli) on project rest1: I/O Error: Unable to pull 'kp-ms/rest2:0.0.1-SNAPSHOT' : repository kp-ms/rest2 not found: does not exist or no pull access (Not Found: 404) -> [Help 1]
[ERROR]

However If I remove rest2 section in docker-compose.yml, build goes fine and I'm able to find the container start successfully.
Another problem I noticed is that even if do not give image name in docker-compose.yml build fails with error image is null. However I'm not sure why I need to provide image can't the plugin map from plugin configuration as I had provided alias. As you can notice I'm trying to generate image name dynamically.


text:
Q: Graph Drawing with Tikz example error I have trouble making the Graph Drawing example on page 363 in the TikZ & PGF Manual work.
To this end, I've read the question asked ealier, errors - Layered Graph From TikZ Manual #291718 but have not had any luck using the code suggested by user @JP-Ellis.
I'm getting the same error on my local install (MikTex 2.9 Fully updated, TexStudio 5.6.2) and on Overleaf.com
Here is my code example:
% !TeX program = lualatex
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{graphs}
\usetikzlibrary{graphdrawing}
\usegdlibrary{layered}
\title{Tikz Graph Test}
\begin{document}
\tikz [nodes={text height=.7em,text depth=.2em,draw=black!20,thick,fill=white,font=\footnotesize},>=stealth',rounded corners,semithick] \graph [layered layout,level distance=1cm,sibling sep=0.5em,sibling distance=1cm] {"Femte" -> {"Sjette","Prise"};};
\end{document}

*

*Here is the log from TexStudio (pastebin)

*Here is the log from Overleaf (pastebin)

The main errors seem to be these:
./main.tex:10: Undefined control sequence.
\sa@placebox ->\newpage \global \pdfpagewidth
                                              =\wd \sa@box \global \pdfpageh...
l.10 ...tance=1cm] {"Femte" -> {"Sjette","Prise"};};

and this
! You can't use a prefix with `the character ='.
<to be read again>
=
l.10 ...tance=1cm] {"Femte" -> {"Sjette","Prise"};};


text:
Q: Calling a method in a Fragment from an AlertDialog Could you please help with the below:
I am trying to call the method deletePlayer inside the fragment PlayersActivityFragment from the alertdialog NameAlertDialogFragment.
The code is below:
    public static class PlayersActivityFragment extends Fragment {

    ArrayList<Player> arrayPlayers;
    ListView listViewPlayers;
    //PlayerAdapter adapter;

    public PlayersActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        arrayPlayers = new ArrayList<Player>();

        View rootView = inflater.inflate(R.layout.fragment_activity_players, container, false);

        Button buttonAddPlayer = (Button) rootView.findViewById(R.id.button_addplayers);
        buttonAddPlayer.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view) {

                arrayPlayers.add(new Player("Player", 0));
                Player selectedPlayer = arrayPlayers.get(arrayPlayers.size()-1);
                ((PlayersActivity)getActivity()).showNameDialogFragment(selectedPlayer);

            }
        });

        listViewPlayers = (ListView) rootView.findViewById(R.id.listView_playername);

        return rootView;

    }

    public void deletePlayer(){
        arrayPlayers.remove(arrayPlayers.size()-1);
    }

}

void showNameDialogFragment(Player player) {
    mDialog = NameAlertDialogFragment.newInstance(player);
    mDialog.show(getFragmentManager(),"SCORE DIALOG");

}

// Class that creates the AlertDialog
public static class NameAlertDialogFragment extends DialogFragment {

    static Player selectedPlayer;

    public static NameAlertDialogFragment newInstance(Player player) {
        selectedPlayer = player;
        return new NameAlertDialogFragment();
    }

    // Build AlertDialog using AlertDialog.Builder
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        final View view = inflater.inflate(R.layout.alertdialog_name, null);

        final EditText editTextName = (EditText) view.findViewById(R.id.edittext_name);

        return new AlertDialog.Builder(getActivity())
                // Inflate and set the layout for the dialog
                // Pass null as the parent view because its going in the dialog layout
                .setView(view)

                .setMessage("Enter Player's Name:")

                //Set up Yes Button
                .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, int id) {
                        mName = editTextName.getText().toString().trim();
                        selectedPlayer.setName(mName);
                    }
                })

                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
                        //playersActivityFragment.deletePlayer();
                        //((PlayersActivityFragment)getTargetFragment()).deletePlayer();
                        NameAlertDialogFragment.this.getDialog().cancel();
                    }
                })

                .create();
    }
}

The two different ways I have tried to call the methods are commented out in the .setNegativeButton onClickListener:
PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
playersActivityFragment.deletePlayer();

and
((PlayersActivityFragment)getTargetFragment()).deletePlayer();

Thank you!

A: First of all, why are all of your classes static? Anyway, here's an answer that should work...
Try using an interface as a callback. For example:
First create an interface.
public interface NameAlertDialogListener {
    public void onNegativeClick();
}

Then have PlayersFragment implement NameAlertDialogListener.
public static class PlayersActivityFragment extends Fragment implements  NameAlertDialogListener

Next, in the PlayersFragment, create a method  called onNegativeClick.
@Override
public void onNegativeClick()  {
    //delete or whatever you want to do.
}

Create a member variable for the listener:
static Player selectedPlayer;
static NameAlertDialogListener mCallBack;

Next create a method in the dialog fragment called setListener.
public void setListener(NameAlertDialogListener callback) {
    try {
        mCallBack = callback;
    } catch (ClassCastException e){
        throw new ClassCastException(callback.toString() + " must implement NameAlertDialogListener" );
    }
}

Then, when you create the dialog fragment call the setListener method.
void showNameDialogFragment(Player player) {
    mDialog = NameAlertDialogFragment.newInstance(player);
    mDialog.setListener(this);
    mDialog.show(getFragmentManager(),"SCORE DIALOG");
}

Lastly, in your negative click listener:
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
        mCallBack.onNegativeClick() ;
        NameAlertDialogFragment.this.getDialog().cancel();
    }
})

A: I am not sure if this is the correct way of doing things, but I have come to a working solution.
First I moved ArrayList<Player> arrayPlayers; outside of the PlayersActivityFragment fragment.
Then I moved the method:
public void deletePlayer(){
    arrayPlayers.remove(arrayPlayers.size()-1);
}

outside of the PlayersActivityFragment fragment.
I then called the deletePlayer() method inside the alertdialog with the line ((PlayersActivity)getActivity()).deletePlayer();.

A: Actually, I have a little hack, it's not really good, but it's easy to implement: declare PlayersActivityFragment variable in your DialogFragment. Then change your constructor to:
public static NameAlertDialogFragment newInstance(Player player,PlayersActivityFragment fragment ){
 selectedPlayer = player;
 NameAlertDialogFragment test = new NameAlertDialogFragment();
 test.playerActivityFragment = fragment;
 return test;
}

Then you can call playerActivityFragment.deletePlayer() everywhere in your DialogFragment.
P/s: The best way is implement interface, but for lazy coder like me, the method above is better lol!


text:
Q: Why do descriptions of Hagrid's size vary so much throughout the books? As stated in this question (How Big is Hagrid?); descriptions of the size of Hagrid change throughout the books-

"He was almost twice as tall as a normal man and at least five times as wide."
  Harry Potter and the Philosopher's Stone - Chapter 1

And then in later books:

"About twice as tall as a normal man, and at least three times as broad"
  Harry Potter and the Goblet of Fire - Chapter 12

Did descriptions of Hagrid's size change due to how Harry perceived him?
Was it due to the portrayal of Hagrid in the films? Even so, Hagrid only appears to be taller than average in the films, not wider.

A: First, there isn't really a contradiction
Hagrid is indeed both "at least five times as broad as a normal man" and "at least three times as broad as a normal man," not to mention "at least as broad as a normal man." These merely specify a lower limit on his size, and the highest lower limit encompasses all the others (from a highly pedantic perspective).
It may be a matter of perception
Hagrid may have seemed broader when Harry first saw him (credit to CBredlow).
It might be mere exaggeration
If Hagrid's size is being exaggerated in any case, it doesn't particularly matter by how much.
Rowling may mean something different by "broad" than by "wide"
Maybe "broad" refers to the diameter, and "wide" refers to his girth (which would be about 3 times his diameter). Twice three is approximately equal to five.
He may have lost (significant) weight
(Credit to ibid)


text:
Q: Select wav files from a folder whose partial names are in a text file I have 500 wave files in a folder ABC which are named  like
F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100

all with extension .wav.
Also I have a text file which contains 3 digit numbers like

*

*001

*003

*098

*034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.
Expecting MATLAB or bash script solutions.
I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

A: for Matlab
1) Get all the file names in the folder using functions dir or rdir.
2) Using for loop go through every filename and add the last 3 digits of every filename to an array (array A). You will need str2num() here
3) Parse all 3 digit numbers to an array (array B)
4) Using function ismember(B, A) find which elements of B are contained in A
5) Load corresponding filenames

A: find . -name "*.wav" | grep -f <(awk '{print $0 ".wav"}' file)

grep -f will use the patterns stored in file, one per line, and look for them in your find result. But you want the three numbers to be at the end, so in the above command the last awk statement will provide a modified file with ".wav" appended at each line. So for the line 001, "0001.wav" will match but any file 0010.wav will not.
see: process substitution syntax and grep --help

A: function wavelist()

   wavefiles=dir('*.wav');   % loaded wave files
   myfolder='/home/adspr/Desktop/exps_sree/waves/selectedfiles'; %Output folder to store files

   for i=1: numel(wavefiles)  %for each wave file
      filename=wavefiles(i).name;
      [~,name,~] = fileparts(filename);  % found the name of file without extension
      a=name(end-2:end); %get the last 3 digits in the file name
      fileID = fopen('nameslist','r');

      while ~feof(fileID)
          b=fgetl(fileID); % get each line in the list file

          if strcmp(a,b) % compare
              movefile(filename,myfolder); % moved to otput folder

          end

      end
   fclose(fileID);

   end
end

I don't think this is a simple answer, thats why I asked here. Anyway, my problem solved, thats why I posted this as an answer.
Thank you all.


text:
Q: How to associate javascript objects with DOM nodes? Can I, and if so, how can I associate javascript objects with DOM nodes? My requirements:

*

*real objects, not just JSON-stringified-attributes or so

*shouldn't leak memory

*should also work in non-standard browsers like IE8 or so

I was thinking about doing it with a global array that holds the data and putting the indexes in attributes of the nodes, but that would leak memory because there's still a reference from the array to the data when the nodes aren't in th DOM anymore. It's for a web application, so that could be an issue.

A: Well, jQuery has the data system, which you could give a try. They say it's free from memory leaks.

A: Perfect use case for the WeakMap, assuming your targeting newer browsers (chrome 36, edge 12, IE 11, firefox 36, safari 7.1):
let map = new WeakMap();
let node = document.getElementById("unicorn");
let data = {};

window.map.set(node, data);

this wont leak since the keys of the WeakMap are weakly referenced.

A: Since tags doesn't mention jquery. Posting answer with Mootools.
http://mootools.net/docs/core/Element/Element#Element:store


text:
Q: Perl Regular Expression for Hash values I have hash values which looks like this:
   build -var ver=2.1.0.0 -var buildnum=WorkSet/2.1.0_suiteB_3o -var product=cisco6500 platform=NSA prodtype=Debug HOST=10.9.33.22 -var clist=

   build -var ver=2.1.0.0 -var buildnum=WorkSet/2.1.0_suiteB_3o -var product=juniper6700 platform=NSA prodtype=Prod HOST=10.9.33.22 -var clist=

I am trying to seperate out the hash value to create another hash such that it looks as below:
   My $list = {'2.1.0.0' => { 'branch' => Workset/2.1.0'
               'products' => [{product => 'cisco6500',
                                prodType => 'Debug'},
                                {product => 'juniper6700',
                                prodType => 'Prod'}]

}
}
I have written something like this:
    if ($cmd =~ m/ver=(\d.\d.\d.\d)/){
            $version = $1;
    }
    if ($cmd =~ m/buildnum=(\w+.\/\d.\d.\d)/){
            $branch = $1;
    }
    if ($cmd =~ m/product=(\s+)/){
            $product = $1;
    }

}
Now, I getting confused how to insert the hash in the hash and array simultaneously. Please if anyone can suggest something. Thank you.

A: The branch can be built without a problem:
$list->{$version}{branch} = $branch;

For products, you should push them onto the array that you have to dereference:
push @{ $list->{$version}{products} },
        { product  => $product,
          prodType => $prodtype,
        };

In recent versions of Perl, the dereference is not needed, so you can push directly to an array reference.


text:
Q: Implement a Java Iterator for a nested HashMap in which an element can be any of 1) an Integer or, 2) another nested HashMap or, 3) an empty HashMap As described in the title, how can we do this? I feel that it should be something similar to a tree traversal, but I cannot figure out how to do this.
    Map<Integer, Object> map = new HashMap<>();

    map.put(1, 1);
    map.put(2, 2);

    map.put(3, new HashMap<Integer, Object>());
    Map<Integer, Object> m1 = (Map<Integer, Object>)map.get(3);
    m1.put(4, 4);
    m1.put(5, new HashMap<Integer, Object>());
    m1.put(6, 6);

    Map<Integer, Object> m2 = (Map<Integer, Object>)m1.get(5);
    m2.put(8, 8);
    m2.put(9, 9);

    map.put(7, new HashMap<Integer, Object>());

In this example, the first two "values" are two Integers, and the third "value" is a nested HashMap which contains two Integers and one "deeper level" nested HashMap. Regarding key 7, I would like to express that the "value" can also be an empty HashMap -- because this is an interview question, I guess this possibility of having "empty value" may affect the next() or hasNext() implementation?

A: There are actually many different solutions to this.
By far the shortest one is this here, which uses Streams.
@SuppressWarnings("unchecked")
static <T> Stream<T> mapTraversalStream(Map<Integer, T> map) {
  return map.values().stream().flatMap(value -> {
    if(value instanceof Map) {
      return mapTraversalStream((Map<Integer, T>)value);
    } else {
      return Stream.of(value);
    }
  });
}

static <T> Iterator<T> mapTraversalIterator(Map<Integer, T> map) {
  return mapTraversalStream(map).iterator();
}

edit:
If you can't use Java 8 you could define your own map and flatten methods.
@SuppressWarnings("unchecked")
static <T> Iterator<T> mapTraversalIterator(Map<Integer, T> map) {
  return flatten(map(map.values().iterator(), new Function<T, Iterator<T>>() {
      public Iterator<T> apply(T value) {
        if(value instanceof Map) {
          return mapTraversalIterator((Map<Integer, T>)value);
        } else {
          return Collections.singleton(value).iterator();
        }
      }
  }));
}

interface Function<A, B> {
  B apply(A a);
}

static <A, B> Iterator<B> map(Iterator<A> iter, Function<A, B> op) {
  return new Iterator<B>() {
    public boolean hasNext() {
      return iter.hasNext();
    }
    public B next() {
      return op.apply(iter.next());
    }
  };
}

static <A> Iterator<A> flatten(Iterator<Iterator<A>> iter) {
  return new Iterator<A>() {
    private Iterator<A> next = null;

    public boolean hasNext() {
      while(iter.hasNext() && (next == null || !next.hasNext())) {
        next = iter.next();
      }
      if(next == null || !next.hasNext()) return false;
      else return true;
    }
    public A next() {
      if(!hasNext()) throw new NoSuchElementException();
      return next.next();
    }
  };
}


text:
Q: Adding parameters to Cloud Endpoint causes 404 GoogleJsonResponseException I have am having an issue where I completed the sample GCM Messaging (https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/GcmEndpoints)
and everything works fine until I want to add additional parameters to the registerDevice method in the the RegistrationEndpoint class. I've made sure that I added the @Named in before.
Before the change it looks like this:
@ApiMethod(name = "register")
public void registerDevice(@Named("regId") String regId) {
    if (findRecord(regId) != null) {
        log.info("Device " + regId + " already registered, skipping register");
        return;
    }
    RegistrationRecord record = new RegistrationRecord();
    record.setRegId(regId);
    //record.setUserName(name);
    //record.setUserProfId(profId);
    ofy().save().entity(record).now();
}

And after the change it looks like this:
@ApiMethod(name = "register")
public void registerDevice(@Named("regId") String regId, @Named("name") String name, @Named("profId") String profId) {
    if (findRecord(regId) != null) {
        log.info("Device " + regId + " already registered, skipping register");
        return;
    }
    RegistrationRecord record = new RegistrationRecord();
    record.setRegId(regId);
    record.setUserName(name);
    record.setUserProfId(profId);
    ofy().save().entity(record).now();
}

Once I added those two parameters, the GCM request fails with the following error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found

at this line in my code (in an AsyncTask)
regService.register(Globals.REG_ID,"Test","Test").execute();

But when it the "Test","Test" is removed as in the original tutorial, it works fine!
In conclusion, I can't post to the datastore when I added my own parameters with fields I want. Any suggestions?

A: When you introduce new method in Google Cloud Endpoints you have to do:

*

*Upload new version to App Engine

*If you've changed the version name, you have to make it default one in the Developer Console

404 means there's no such method, so I assume you've not done yet one of the steps mentioned above.
If you done above steps just check if the method works using API Explorer
https://apis-explorer.appspot.com/apis-explorer/?base=https://appname.appspot.com/_ah/api

One more thing. Remember to check the parameters order. From my experience it will rather be (name, profId, regId), but I could be wrong:
regService.register("Test", "Test", Globals.REG_ID).execute();


text:
Q: call my script only after loading UI library? i want to add small effect (UI-jquery-draggable) to the navigation buttons in one of the WP slider plugins.
what i did:
1 I have installed the slider plugin
2 know that UI is allredy registerd in wordpress but i have to call it (am i right?)
so in my child theme functions.php,i added this:
   function my_enqueue() {
   wp_enqueue_script( 'jquery-ui-draggable' );
   }
   add_action( 'wp_enqueue_scripts', 'my_enqueue' );

   ?>

3 .the script itself is only one line so i included it directly in the my child theme page.php like this
       <?php if ( is_page(291) ) : ?>
       <script>
    jQuery( ".easingsliderlite-icon" ).draggable({ revert: true });
        </script>
       <?php endif; ?>

now what happens is that this line of script is loaded before the UI jquery library,when I look at the page in the browser (source code)  the UI library is at the buttom of the page meaning its probebly loading after my script
so the script doesnt work:(
4 i know you can create dependencies but only with wp-enqueue and only in function.php not for single line of script in page.php (am i correct?) ,

A: Enqueue your script instead of putting it in your template, you can enqueue your code as is, or put your code in an actual file.
The benefit of doing this is you gain control over output, as you can see there is a $priority parameter for add_action.
add_action( $hook, $function_to_add, $priority, $accepted_args );

Futhermore  wp_enqueue_script comes with two parameters which can alter output, which are $deps and $in_footer.
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

So with the above 3 settings you can surely change the way the scripts load.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
http://codex.wordpress.org/Function_Reference/add_action

A: When you use wp_enqueue_script you can tell wordpress what the script depends on so the loading can be done in the right order.
What you need to do here is something like (didn't try it):
wp_enqueue_script( 'jquery-ui-draggable', false, array('jquery-core','jquery-ui-core' ));

You don't have to put this in functions.php, you should be able to put it in the top of page.php (before wp_head()). Then you must add your oneliner of code somewhere after wp_head.
Now when I wrote this I suspect that the problem with your code is not the dependencies but maybe you put your oneliner too early in the code. You can put it in the bottom of page.php.
Also, you can make a specific template for this page. Just copy page.php and call it page-291.php (or you can call it page-{slug}.php)


text:
Q: jQuery .click() .animate() not working The events called inside of $('.transparent-close').click(function(){ ...}); don't seem to be working. Is it possibly because it is inside of another .click() event?
$('#featured-top').click(function(){
    $(this).animate({'top':'-318px'}, 600, 'easeOutBounce');
    $('#featured-top-container').animate({'margin':'260px 0 0 117px'}, 600, 'easeOutBounce');
    $('#wrap').animate({'margin-top':'365px'}, 600, 'easeOutBounce');

    //Add transparent background for click out
    $(document.body).append('

');
    $('.transparent-close').click(function(){
        $('#featured-top').animate({'top':'-318px'}, 600, 'easeOutBounce');
        $('#featured-top-container').animate({'margin':'260px 0 0 117px'}, 600, 'easeOutBounce');
        $('#wrap').animate({'margin-top':'365px'}, 600, 'easeOutBounce');
        $(this).remove();
    });
});

A: I would use:
$('body').append(
    $('

')
        .addClass('transparent-close')
        .on('click',function(){
            //...
        });
);

I had yet problems using click function as an event listener, even if I don't know exactly why.


text:
Q: How to reverse iterate output from subprocess in python? I have a python code which iterates logs from journalctl as below, currently it print
log 1
log 2
log 3
but what I want is
log 3
log 2
log 1
How can I do this
import sys
import subprocess
import select
from re import search

substring = "Modem works in"

args = ['journalctl', '--lines', '100', '|', 'tail', '-n','100']
#, '_SYSTEMD_UNIT=myservice.service']

for line in subprocess.check_output(args, shell=True, universal_newlines=True).split('\n'):
    print(line)
    if search(substring, line):
        print(line)

A: Many different ways of doing this. Here are two:
for line in reversed(subprocess.check_output(args, shell=True, universal_newlines=True).split('\n')):
...

and
for line in subprocess.check_output(args, shell=True, universal_newlines=True).split('\n')[::-1]:
...

A: One other way can be
log_list=[]
for line in subprocess.check_output(args, shell=True, universal_newlines=True).split('\n'):
    log_list.append(line)
    print(line)
    if search(substring, line):
        log_list.append(line)
        print(line)

print(" ".join(log_list.reverse()))

A: your_list = [1,2,3,4]

*

*using range method:
print( [i for i in range(10,1,-1)] )

*reversed method:
print([i for i in reversed( your_list )])

*extended slicing list
print( your_list[::-1] )
All of them will print:
[5, 4, 3, 2, 1]


text:
Q: Modify code contains in variable using JQuery. Remove attribute and wrap by div I have html in that i have a variable and try to modify it and apply after but after i change it code doesn't change.
So basiclly i have a code with table and i what to remove attribute and wrap by div.
let paste = editor.node.innerHTML;
    //console.log(paste);

    console.log($(paste).filter("table"))
    $(paste).filter("table").each(function(i, item){

        console.log($(this).attr('width'))
        $(this).removeAttr('width');
        console.log(item)
    })

    editor.node.innerHTML = paste
    console.log(paste)
});

I successfully get that width but after loop i made log and it the same as it was before loop and attribute is still there
Give me an advice please

A: Your code
$(paste)

creates a jquery object, this then has the.filter/.each applied to - ie to the jquery object.  Not to the source string.  The original paste variable is unchanged.
To update your variable, you need to reassign the result of your manipulation, ie:
paste = $(paste)
            .filter("table")
            .each(function(i, item) {
                ...
            })
            .html();


text:
Q: React Router Displaying only Blank Page - No data Showing I am new to React. It's My First Program with React - Router When I Am Using React-Router I Don't get any data displaying on the window. It only Shows Blank Page.
My code -
profile.js
import React from 'react'
 function Profile()
 { return (

profile

 ) }

export default Profile

about.js file
import React from 'react'

function About() {
    return (

about

    )
}

export default About

App.js
import About from './Container/about'
import Profile from './Container/profile'
import {BrowserRouter, Route} from 'react-router-dom'
function App() {
 return (

<BrowserRouter>
<Route element={About} path='/about' />
<Route element={Profile } path='/profile' />
</BrowserRouter>

);
}

export default App;

If anybody Know any Solution Please Reply
I Checked some websites for results but I Don't get any solution from them. I watched some Youtube videos. but they code the same as mine and they got results but I didn't.

A: if you use older version import Switch from react-router-dom
import About from "./Container/about";
import Profile from "./Container/profile";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function App() {
  return (

      <Router>
        <Switch>
          <Route component={About} path="/about" />
          <Route component={Profile} path="/profile" />
       </Switch>
     </Router>

);
}

export default App;

if you using latest version ..import Routes from react-router-dom
App.js
import Routes
    import About from './Container/about'
    import Profile from './Container/profile'
    import {BrowserRouter as Router,Routes, Route} from 'react-router-dom'
    function App() {
     return (
      <Router>

         <Routes>
          <Route exact path='/about' element={<About />}  />
          <Route exact path='/profile' element={<Profile /> }  />
         </Routes>

      </Router>
      );
      }

     export default App;

A: You can use Switch from react-router-dom which renders the route exclusively.
Your code would be like this.
import About from "./Container/about";
import Profile from "./Container/profile";
import { BrowserRouter, Route, Switch } from "react-router-dom";
function App() {
  return (

      <BrowserRouter>
        <Switch>
          <Route component={About} path="/about" />
          <Route component={Profile} path="/profile" />
        </Switch>
      </BrowserRouter>

  );
}

export default App;

Check this  sandbox where react-router-dom is implemented with dynamic params as well as components.


text:
Q: Convert hierarchical dictionary to HTML nested dropdown I have a list of dicts like this,
but we may have more depth and so more id and pids ...
WIDGETS = [
    {"id": 1, "pid": 0, "url": "/upload"},
    {"id": 2, "pid": 0, "url": "/entry"},
    {"id": 3, "pid": 0, "url": "/report"},
    {"id": 4, "pid": 3, "url": "/reppremium"},
    {"id": 5, "pid": 4, "url": "/reppremiumsum"},
    {"id": 6, "pid": 4, "url": "/reppremiumfull"},
    {"id": 7, "pid": 3, "url": "/repcommission"},
    {"id": 8, "pid": 7, "url": "/repcommissionsum"},
    {"id": 9, "pid": 7, "url": "/repcommissionfull"},
    {"id": 10, "pid": 3, "url": "/repportions"},
    {"id": 11, "pid": 10, "url": "/repportionssum"},
    {"id": 12, "pid": 10, "url": "/repportionsfull"},
    {"id": 13, "pid": 0, "url": "/adduser"},
    {"id": 14, "pid": 0, "url": "/exportdb"},
    {"id": 15, "pid": 0, "url": "/importdb"},
]

and i want to convert it to a HTML nested / multilevel dropdown like this:
main menu -> /upload
             /report -> /reppremium    ->  /reppremiumsum
                                       ->   /reppremiumfull

                     -> /repcommission ->  /repcommissionsum
                                       ->  /repcommissionfull

                     -> /repportions   ->  /repportionssum
                                       ->  /repportionsfull
             /adduser
             /exportdb
             /importdb

i have tried some codes , but it doesnt work properly , as i know it needs a recursive function...
def get_widgets(widgets,text='',pid=0,text_m=''):
    childs = get_childs(pid,widgets)
    for child in childs:

        pidn = child['id']
        n = get_childs(pidn,widgets)
        print(n,'for id',pidn)

        if len(n) != 0:
            text += f'''

                { child['url'] }

            '''
            pid_new = child['id']
            get_widgets(widgets,text,pid_new)
            text += '

'
            print(text)
            text_m += text
        else:
            #print(n,'n')
            text += f'''

                { child['url'] }

            '''
            text_m += text

        text = ''

    return tex

i expect the code to show an html multilevel dropdown ... but populated by WIDGETS...

A: As you've guessed this should be done recursively and there are several approaches to solve it.
Here is the complete code:
WIDGETS = [
    {"id": 1, "pid": 0, "url": "/upload"},
    {"id": 2, "pid": 0, "url": "/entry"},
    {"id": 3, "pid": 0, "url": "/report"},
    {"id": 4, "pid": 3, "url": "/reppremium"},
    {"id": 5, "pid": 4, "url": "/reppremiumsum"},
    {"id": 6, "pid": 4, "url": "/reppremiumfull"},
    {"id": 7, "pid": 3, "url": "/repcommission"},
    {"id": 8, "pid": 7, "url": "/repcommissionsum"},
    {"id": 9, "pid": 7, "url": "/repcommissionfull"},
    {"id": 10, "pid": 3, "url": "/repportions"},
    {"id": 11, "pid": 10, "url": "/repportionssum"},
    {"id": 12, "pid": 10, "url": "/repportionsfull"},
    {"id": 13, "pid": 0, "url": "/adduser"},
    {"id": 14, "pid": 0, "url": "/exportdb"},
    {"id": 15, "pid": 0, "url": "/importdb"},
]

def build_HTML(d, text=""):
    for (id_, url), children_list in d.items():
        text += f"
{url}"

        if children_list:
            text += "
"
            for dd in children_list:
                text += build_HTML(dd, "")
            text += "
"

        text += "
"

    return text

def set_recursive(obj, d):
    for (id_, url), children_list in d.items():
        if obj["pid"] == id_:
            children_list.append({(obj["id"], obj["url"]): []})
            return
        else:
            for item in children_list:
                set_recursive(obj, item)

root = {(0, "/main-menu"): []}
while WIDGETS:
    d = WIDGETS[0]
    set_recursive(d, root)
    del WIDGETS[0]

print(f"
{build_HTML(root)}
")

output:

/main-menu

/upload

/entry

/report

/reppremium

/reppremiumsum

/reppremiumfull

/repcommission

/repcommissionsum

/repcommissionfull

/repportions

/repportionssum

/repportionsfull

/adduser

/exportdb

/importdb

Explanation:
In set_recursive() function, we basically create another data structure in form of:
{(0, '/main-menu'): [{(1, '/upload'): []},
                     {(2, '/entry'): []},
                     {(3, '/report'): [{(4, '/reppremium'): [{(5, '/reppremiumsum'): []},
                                                             {(6, '/reppremiumfull'): []}]},
                                       {(7, '/repcommission'): [{(8, '/repcommissionsum'): []},
                                                                {(9, '/repcommissionfull'): []}]},
                                       {(10, '/repportions'): [{(11, '/repportionssum'): []},
                                                               {(12, '/repportionsfull'): []}]}]},
                     {(13, '/adduser'): []},
                     {(14, '/exportdb'): []},
                     {(15, '/importdb'): []}]}

This is now a dictionary of elements which keeps track of every sub-elements. The way it works is that for every element, it recursively checks the data structure to see if it can find its "parent". If it finds, it belongs to that list. After we handle that we just delete it from the records.
In build_HTML() function you create your string in its most compressed form(browser's parser doesn't care).
The main point in this function is that you need to open
 before entering to the children_list and close it after that.
Note: This solution works properly because your data is sorted in the way that for appending every child, it's parent is already appended.
If you render that string:

<!DOCTYPE html>

/main-menu

/upload

/entry

/report

/reppremium

/reppremiumsum

/reppremiumfull

/repcommission

/repcommissionsum

/repcommissionfull

/repportions

/repportionssum

/repportionsfull

/adduser

/exportdb

/importdb

The beautified version of that string is:

/main-menu

/upload

/entry

/report

/reppremium

/reppremiumsum

/reppremiumfull

/repcommission

/repcommissionsum

/repcommissionfull

/repportions

/repportionssum

/repportionsfull

/adduser

/exportdb

/importdb


text:
Q: Finding duplicates across range and summing it up I have a list of agents who are working on OT, but the challenge is that they have 2 entries for OT per day, and when i need to work on this data with another sheet i have to sort out the data and remove duplicates manually in order not to cause issues with vlookup.
I need the end result to be like this:
if any agents works OT 2 times a day then sum it up and place in one raw with the date.
i have made helpers columns to show the duplicates but the i got stuck with the next steps
here is the sheet for the example:
https://docs.google.com/spreadsheets/d/1rdqylI9Rr4CxPIJcffEsqfoHx0loPVrqi2UJAQ30Sos/edit#gid=0

A: use:
=QUERY(A2:C, "select A,B,sum(C) where C is not null group by A,B label sum(C)''")

and vlookup from it...


text:
Q: PlistBuddy on Windows I'm in the process of moving our Xamarin build infrastructure to be Windows based and I've hit a problem in that our build scripts currently use PlistBuddy to read from and write to the Info.plist file of an app.
Obviously PlistBuddy won't run on Windows.
Has anyone seen any other solution for interacting with Plist files on Windows? I've seen a few that use a GUI but we would need this to have a CLI.

A: You can force the Build Agent to run arbitrary commands on the Mac via tying into any generic Task/Target(You can look in the Xamarin.iOS .targets files for a better idea here) that runs across the SSH connection. This is currently available in another method by using the <Exec> Task with a SessionId of your $(BuildSessionId). Here's an example of how you might do this:
<Exec Command="..." SessionId="$(BuildSessionId)" />

If the SessionId is null/empty, then that means we are not connected to the Mac. If it's not null/empty, then we are connected to the Mac.
We can then force this condition to always run on the Mac via:
<Exec Command="..." SessionId="$(BuildSessionId)" Condition=" '$(BuildSessionId)' != '' " />

Please note that the following built-in tasks are exposed for remote execution:

*

*Copy

*Delete

*Exec

*MakeDir

*Move

*RemoveDir

*Touch

Source: https://github.com/xamarin/xamarin-macios/blob/fc55e4306f79491fd269ca2495c6a859799cb1c6/msbuild/Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets#L74-L80
You can then invoke the PlistBuddy Command via this method.
EX:
  <Target Name="_SayGoodbye">
    <Exec Command="plistbuddy ..." SessionId="$(BuildSessionId)" Condition=" '$(BuildSessionId)' != '' "/>
  </Target>

If you wanted to go about a MSBuild custom Task way, You can see examples of previous built Tasks here:
https://github.com/xamarin/xamarin-macios/tree/fc55e4306f79491fd269ca2495c6a859799cb1c6/msbuild/Xamarin.iOS.Tasks.Core/Tasks
EX Plist in Use:
https://github.com/xamarin/xamarin-macios/blob/fc55e4306f79491fd269ca2495c6a859799cb1c6/msbuild/Xamarin.iOS.Tasks.Core/Tasks/MTouchTaskBase.cs#L608
EX Tests with Plist:
https://github.com/xamarin/xamarin-macios/tree/fc55e4306f79491fd269ca2495c6a859799cb1c6/msbuild/tests/Xamarin.iOS.Tasks.Tests/TaskTests/GeneratePlistTaskTests
This is more of a MSBuild customization at this point, but it's definitely possible to do what you're trying to do using these items.


text:
Q: Volume of a ball intersected with a submanifold I am given a smooth Riemannian submanifold of dimension $d$ embedded in $\mathbb{R}^D$ with condition number $1/\tau$ (a formal definition of condition number is on Page 3 of this paper http://people.cs.uchicago.edu/~niyogi/papersps/NiySmaWeiHom.pdf).
I would like to know how to calculate an upper bound on the $d$-dimensional volume of a ball (of radius $r \ll \tau$) around a point on the manifold intersected with the manifold. Lemma 5.3 in the paper referenced above gives a lower bound on this volume.
Proposition 6.3 gives a bound on the geodesic distance $d_M$ between any two points that are a distance $r$ apart in $\mathbb{R}^D$ as $$d_M(p,q) \leq \tau - \tau \sqrt{1 - \frac{2r}{\tau}} := d_{\max}$$
if $r < \frac{\tau}{2}$.
I think a valid upper bound is given by
$$\mathrm{vol}(B(r,p) \cap M) \leq v_d d_{\max}^d$$
where $v_d$ is the volume of a unit ball in $\mathbb{R}^d$. How would I go about proving this (or an equivalent statement)?


text:
Q: hashtable from input to output I would like to implement hashtable and so far I have reading from file and something not working when I want to write first string to Tabh. Code compile without errors but nothing appears in console. Can someone help me with that? I think that I wrong implement: if (Tabp[ite].substr(0) == "a"){...}
#include <iostream>
#include <fstream>

using namespace std;

void Add(string T[], int r, long k, string w);
//void print();
//void delete();
//void stop();

int main()
{
   string linie;
   int licznik = 0;
   ifstream policz("test.txt");
   while(getline(policz, linie))
         licznik++;
   policz.close();

   string * Tabp = new string[licznik];
   fstream plik;
   plik.open("test.txt");
   string wiersz;

   for (int b =0; b<licznik; b++)
   {
         getline(plik, wiersz);
         Tabp[b] = wiersz;
   }

   string iloscprzypadkow = Tabp[0].substr(0);
   int n = stoi(iloscprzypadkow);

   string rozmiarstring = Tabp[1].substr(5,7);
   int size = stoi(rozmiarstring);
   string * Tabh = new string[size];

   for (int ite=2; ite<licznik; ite++)
            if (Tabp[ite].substr(0) == "a")
            {
               string temp = Tabp[ite].substr(4,5);
               long klucz = stoi(temp);
               string wartosc = Tabp[ite].substr(7,14);
               Add(Tabh, size, klucz, wartosc);
            }
          //if (wyrazenie == "p")
          //{
          //}
          //if (wyrazenie == "d")
          //}
          //{
          //if (wyrazenie == "s")
          //{
          //}

}
void Add(string Tabh[], int rozmiar, long klucz, string wartosc)
{
cout<<rozmiar<<klucz<<wartosc;
int indeks = klucz%rozmiar;
Tabh[indeks] = wartosc;
cout<<indeks<<" "<<klucz<<" "<<wartosc;
}

-------------------------
input:
1
size 10
add 13 ala
print
add 23 ola
print
delete 13
print
stop

A: The one parameter version of substr returns a substring starting at the given index thru the end of the string. So your call to Tabp[ite].substr(0) will return a copy of Tabp[ite]. To get a substring of one character, you need to specify that using two parameter version, where the second parameter is the length of substring that you want (not the end index, as it appears you're doing elsewhere in your code).
So you'd want to use Tabp[ite].substr(0,1) == "A". Or, since it is just one character, just check that single character with Tabp[ite][0] == 'A'.


text:
Q: Meteor Router + PhantomJS My Meteor application uses Meteor router for navigation and Spiderable plugin to get pages indexed by search engines. Spiderable calls phantomjs to get page content. This approach works ok for most pages except home page.
   '/': ->
    'home'
  '/otherurl': ->
    'otherpage'

I did some debugging and found that the callback of page.evaluate in spiderable.js always returns false in the case when home page was requested
...
setInterval(function() {
  var ready = page.evaluate(function () {
    if (typeof Meteor !== 'undefined' && typeof(Meteor.status) !== 'undefined' && Meteor.status().connected) {
      Meteor.flush();
      return Meteor._LivedataConnection._allSubscriptionsReady();
    }
    return false;
  });
...

Any suggestions?


text:
Q: Translating {{ model.name }} data dynamically in django template Can anyone suggest shortest way to translate {{ model.name }} type of data in django template?

A: Templates aren't supposed to do buisiness logic in django,
in a good way you need to pass already translated data in your template.
Although if you actually in need to do it, you can use django filters:
Link to django documentation
Code may look like this:
new_filter.py
from django.template.defaulttags import register

@register.filter
def translator_filter(string_to_translate):
    translated_string = #do logic with translation here
    return translated_string

any_page.html
<p>{{ model.name|translator_filter }}</p>


text:
Q: Best way to get data from another collection when rendering documents in Firestore? I have a Person collection in Firestore that has an array with ids that refer to another collection called tasks.
The tasks collection contains all the tasks that exist and the array in Person has specific tasks belonging to that person.
Person collection from a specific person:
Firestore-root
     |
     --- person (collection)
          |
          --- personId (document)
                 |
                 --- taskDoing (field) - Array type
                        |
                        --- (tasksId) 0 - FEFEveDoZOv7WFsQLQvP
                                      1 - DEDSFgefeOv7WFsQLQvP
                                      2 - Wffw3f3333f7WFsQLQvP

Task collection:
Firestore-root
     |
     --- task (collection)
          |
          --- taskId (document)
                 |
                 --- title (field) - String type

So in Person collection I have an array with tasksIds and I want to retrieve task data from one specific Person, such as the title from the Task collection from only those ids.
How can I retrieve data?
I looked at the reference field but it can only specify one reference value at a time. What also might work is instead of storing only the id in Person, perhaps I could store the reference in the array?
Like:
task/FEFEveDoZOv7WFsQLQvP/

A: If you want your app to display a person with their current tasks and all you want to display is the name of the task, for example, then I would most likely put that "dressing data" (the task name) into the person document so that I could render this screen with one network call. However, if you ever want to change the name of a task, this would be relatively expensive, because you'd have to change every person document that contained it. But if task names are permanent then I would almost certainly do this.
If there is lots of dressing data then you have to do some number crunching to see if it's more economical (in terms of engineering and dollar cost) to pack it all into the listing documents (the person document) or to fetch them separately. Just remember with Firestore (and NoSQL in general), your biggest costs will be read and write operations, not the size of documents.


text:
Q: Web scraping with request/selenium/cloudscraper return empty values I'm trying to collect information from a cloudflare-protected website I believe. I've tried three alternatives and they all return empty values. So, I don't know if the site has any blockages or if I'm doing something wrong.
--Update
The solution proposed by F.Hoque works, however, when I try to use it in Colab, I only get an empty value.
Using request
import requests
import re
import pandas as pd
from bs4 import BeautifulSoup

url = 'https://www.portaldoholanda.com.br/assaltante-surra/com-pedacos-de-madeira-populares-dao-surra-em-homem-assalt'

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")

soup.find('h1',class_="noticia titulo").text # I tried with select too (soup.select('[class="noticia titulo"]'))

Using cloudscraper
import cloudscraper

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
soup = BeautifulSoup(scraper.get(url, headers=headers).content, "html.parser")

soup.find('h1',class_="noticia titulo").text

Using selenium
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import InvalidSessionIdException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

river = webdriver.Chrome(options=options, executable_path='/usr/bin/chromedriver')
print("Current session is {}".format(driver.session_id))

driver.get(url)
html = BeautifulSoup(driver.page_source)
innerContent = html.find('h1',class_="noticia titulo").text

A: Yes,the website is using cloudflare protection.
https://www.portaldoholanda.com.br/assaltante-surra/com-pedacos-de-madeira-populares-dao-surra-em-homem-assalt is using Cloudflare CDN/Proxy!

https://www.portaldoholanda.com.br/assaltante-surra/com-pedacos-de-madeira-populares-dao-surra-em-homem-assalt is using Cloudflare SSL!

Here is the working solution using cloudScraper instead of requests.
Script:
import cloudscraper
from bs4 import BeautifulSoup
scraper = cloudscraper.create_scraper(delay=10,   browser={'custom': 'ScraperBot/1.0',})
url = "https://www.portaldoholanda.com.br/assaltante-surra/com-pedacos-de-madeira-populares-dao-surra-em-homem-assalt"
req= scraper.get(url)
#print(req)

soup = BeautifulSoup(req.content, "html.parser")
txt=soup.find('h1',class_="noticia titulo").text
print(txt)

Output:
Com pedaços de madeira, populares dão surra em homem em Manaus; veja vídeo


text:
Q: Having trouble getting JSON object to work when passed to SCEditor I am using SCEditor and I am trying to set my own custom emoticons according to the emoticons option specified on this page.
So I called it like so:
$(document).ready(function() {

    $(".sceditor").sceditor({
        // Other options
        emoticons: $.getJSON('../../images/emoticons/default/emoticons.json'),
        emoticonsRoot: '../../images/emoticons/default/'
    });

})

Then in my emoticons.json file I have this:
{
    dropdown: {
        ':)': 'emoticons/smile.png',
        ':angel:': 'emoticons/angel.png',
        ':angry:': 'emoticons/angry.png'
    }
}

However it is not working. I have checked the NET panel in my browser and I have confirmed it is fetching the .json file fine, however when I click to open the smiley window in the editor it is blank (all I see is the "more" link).
Am I doing something wrong here?

A: Json lint show above text in json file is invalid.
Try putting this in your json file
{
    "dropdown": {
        ":)": "emoticons/smile.png",
        ":angel:": "emoticons/angel.png",
        ":angry:": "emoticons/angry.png"
    }
}

I tried this in php
$a = '{
    "dropdown": {
        ":)": "emoticons/smile.png",
        ":angel:": "emoticons/angel.png",
        ":angry:": "emoticons/angry.png"
    }
}' ;
print_r(json_decode($a));

Output
Array
(
    [dropdown] => Array
        (
            [:)] => emoticons/smile.png
            [:angel:] => emoticons/angel.png
            [:angry:] => emoticons/angry.png
        )

)

A: I have tried by your link.
The follows is my code:
$(function() {
        // Replace all textarea's
        // with SCEditor
        $("textarea").sceditor({
            plugins: "bbcode",
            style: "plugins/SCEditor/development/jquery.sceditor.default.css",
            emoticons: {
                // Emoticons to be included in the dropdown
                dropdown: {
                    ":)": "emoticons/smile.png",
                    ":angel:": "emoticons/angel.png"
                },
                // Emoticons to be included in the more section
                more: {
                    ":alien:": "emoticons/alien.png",
                    ":blink:": "emoticons/blink.png"
                },
                // Emoticons that are not shown in the dropdown but will still
                // be converted. Can be used for things like aliases
                hidden: {
                    ":aliasforalien:": "emoticons/alien.png",
                    ":aliasforblink:": "emoticons/blink.png"
                }
            },
            emoticonsRoot: "plugins/SCEditor/"
        });
    });

Above this, you may kown why your code is wrong.
Accross from jQuery.getJSON, $.getJSON returns JQXHR,not a Json object. So, It is not possible to show your emoticons.

A: As per WhiteWater's answer the reason it wasn't working was because it was returning a JQXHR object and not a JSON object, so I had to work out how to get it to return a JSON object whilst the editor loading not being dependent on the emoticons existence.
So we have the solution below with credit to jeremysawesome for his answer to this question:
// create a variable to store the results
var emoticons = false;

$.getJSON('../../images/emoticons/default/emoticons.json')
.done(function(result){
    emoticons = result;
})
.always(function(){
    // always initialize the sceditor
    $('.my-selector').sceditor({emoticons: emoticons});
});

This will load the emoticons but will always load the sceditor instance, even if the emoticons fail for some reason.


text:
Q: Bottom aligning div without specifying parent container height I have some html like this

Text

Long text wrapped over multiple lines

Text

See this fiddle:  http://jsfiddle.net/LmZYE/
What I would like is to have the two "Text" div's align to the bottom of the gRow div.
I don't know the height of gRow at render time as the text changes with selected language. I have tried positioning gRow relative and my inner div's absolute, bottom:0 but in vain.
Can I do what I'm trying to do or do I need to know the height of the gRow div?

EDIT: Forgot one thing: I would like to have a right border going all the way from the top to the bottom of gRow.
Thanks in advance!

A: If you need to do this using divs rather than a table you can use the css for display:table to make your divs respond like a table would:
html

Text

Long text wrapped over multiple lines

Text

css
.table {display:table; border-right: 1px solid red;}
.row {display:table-row;}
.cell {border-left: 1px solid red; display:table-cell; width:33%;}

Then you can keep adding rows and cells as you please.
You are also able to take advantage of the vertical-align property for if you want to align text to the middle or bottom of the div
http://jsfiddle.net/LmZYE/6/

A: If I've understood the question right, this is what you're looking for.
HTML

Long text wrapped over multiple lines

Text

Text

CSS
.gRow {
    width:400px;
    overflow: hidden;
    position: relative;
    border: 1px solid #d3d3d3;
    padding-bottom: 20px;
}
.bottomRow {
    position: absolute;
    bottom: 0;
    width: 100%;
}
.c7, .c8, .c9 {
    width:80px
}
.right {
    float: right;
}
.cell {
    border-left: 1px solid red;
}


text:
Q: Jquery: how to create double .not() statement? I have 3 layers of nested menus in
s, eg:

enu Item

Menu Item 2

Menu Item 3

I want to use Jquery to replace the href attribute of the first level of uls with #, but keep the href attributes on the 2nd and 3rd a tags.
Ive created this script which works for 2nd level uls but not the third level.
$("#menu ul li a").not("#ctamenu ul li ul a").attr("href", "#");

I have tried this:
$("#menu ul li a").not("#menu ul li ul a").not("#menu ul li ul li a").attr("href", "#")

But this doesnt work - the 3rd layer still has href='#'
Is there a way to do a "double not" statement?

A: The third level is nested in yet another ul that you are missing, but it would be easier to use the child selector:
#menu > ul > li > a

A: Depending on your situation, you might find it helpful to create add class="first-level" on the first level anchor tags.  Then you could use $('.first-level'), which is more maintainable as the logic for your menu becomes more level dependent.


text:
Q: How to disable magic searching after I move targets of shortcuts in Windows Server 2003? When I move or delete the target of a shortcut and click the shortcut afterwards windows kindly starts searching and guessing.
How to disable this on Windows Server 2003? I'd prefer a quick error condition.
How to do the same on windows xp, maybe there is no difference?
Edit: For windows shortcuts see http://en.wikipedia.org/wiki/Symbolic_link#Microsoft_Windows

Windows shortcuts maintain their
  connection even when the target is
  moved, unlike symbolic links. Windows
  XP will search for a broken link's
  target before offering to delete it.

Edit2: From the accepted answer:
Quoted from http://www.tomstricks.com/how-to-disable-the-ntfs-file-system-tracking-of-broken-shortcut-links-in-windows/ :
Navigate to this registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\Current Version\Policies\Explorer
Add a new DWORD value and name it NoResolveTrack, set the value to 1.
Will only be effective after the next reboot. Applies only to target files on NTFS partitions. FAT partitions do not have this ID tracking and search capability.
You can also do this for NTFS at a Group Policy level by selecting Do not use the tracking-based method when resolving shell shortcuts  in the UserConfiguration\AdministrativeTemplates\Start Menu & Taskbar group policy branch.

A:
How To Disable the NTFS File System Tracking of Broken Shortcut Links
SUMMARY
If you disable a shortcut, the NTFS File System in Windows XP and
  Windows 2000 automatically attempts to locate the shortcut destination
  by searching all paths that are associated with the shortcut. This
  step-by-step article describes how to prevent this behavior from
  occurring.
Disable the Tracking of Broken Shortcuts
WARNING: If you use Registry Editor incorrectly, you may cause serious
  problems that may require you to reinstall your operating system.
  Microsoft cannot guarantee that you can solve problems that result
  from using Registry Editor incorrectly. Use Registry Editor at your
  own risk.
To prevent the NTFS file system from tracking alternate paths for a
  broken shortcut link, make the following changes in the registry:

*

*Start Registry Editor (Regedit.exe).

*Navigate to the following key:
  HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer

*On the Edit menu, click New, and then click DWORD value.

*Type NoResolveTrack for the Value name, and then press ENTER.

*Double-click the new value, and then set it to 1.

*Click OK.

*Quit Registry Editor.

  You can also prevent this behavior at a Group Policy level by
  selecting the Do not use the tracking-based method when resolving
  shell shortcuts check box in the following location:
User ConfigurationAdministrativeTemplatesStart Menu and Taskbar group
  policy

Source: How To: Disable The NTFS File System Tracking Of Broken Shortcut Links In Windows.

A: I found this: http://ss64.com/nt/shortcut.html

Shortcut: NTFS file system tracking
If a shortcut to a file breaks because
  the destination file has moved, then
  by default Windows will attempt to
  automatically locate the shortcut
  destination by performing a search
  (this only applies to NTFS
  partitions). To turn this off - add a
  DWORD value of 1 to the registry:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer NoResolveTrack=1


text:
Q: Depth Search in Spark Scala I've a following data which has user and supervisor relationship.
user |supervisor |id
-----|-----------|----
a    |   b       | 1
b    |   c       | 2
c    |   d       | 3
e    |   b       | 4

I want to explode the relationship hierarchy between the user and supervisor as below.
user |supervisor |id
-----|-----------|----
a    |   b       | 1
a    |   c       | 1
a    |   d       | 1
b    |   c       | 2
b    |   d       | 2
c    |   d       | 3
e    |   b       | 4
e    |   c       | 4
e    |   d       | 4

As you see, for the user 'a', the immediate supervisor is 'b' but again 'b' has 'c' as its supervisor. So indirectly 'c' is supervisor for 'a' as well and so on. Such as, my aim is to explode the hierarchy at any level for a given user. What is the best way to implement this in spark-scala ?

A: Here is an approach using dataframes. I show doing one level of hierarchy, but it can be done multiple times by repeating the step below:
val df = sc.parallelize(Array(("a", "b", 1), ("b", "c", 2), ("c", "d", 3), ("e", "b", 4))).toDF("user", "supervisor", "id")
scala> df.show
+----+----------+---+
|user|supervisor| id|
+----+----------+---+
|   a|         b|  1|
|   b|         c|  2|
|   c|         d|  3|
|   e|         b|  4|
+----+----------+---+

Let's enable cross joins:
spark.conf.set("spark.sql.crossJoin.enabled", true)

Then join the same table:
val dfjoin = df.as("df1").join(df.as("df2"), $"df1.supervisor" === $"df2.user", "left").select($"df1.user", $"df1.supervisor".as("s1"), $"df1.id", $"df2.supervisor".as("s2"))

I use an udf to combine two columns into an array:
import org.apache.spark.sql.functions.udf
val combineUdf = udf((x: String, y: String) => Seq(x, y))
val dfcombined = dfjoin.withColumn("combined", combineUdf($"s1", $"s2")).select($"user", $"combined", $"id")

Then the last step is to flatten the array to separate rows and filter rows that did not join:
val dfexplode = dfcombined.withColumn("supervisor", explode($"combined")).select($"user", $"id", $"supervisor").filter($"supervisor".isNotNull)

The first level hierarchy looks like this:
scala> dfexplode.show
+----+---+----------+
|user| id|supervisor|
+----+---+----------+
|   c|  3|         d|
|   b|  2|         c|
|   b|  2|         d|
|   a|  1|         b|
|   a|  1|         c|
|   e|  4|         b|
|   e|  4|         c|
+----+---+----------+


text:
Q: Suppose F is a subset of the first category in metric space X, and E is a subset of F. Prove that E is of the first category in X. I know that a subset of a nowhere dense subset is still nowhere dense. But since being of the first category doesn't imply nowhere dense, I couldn't use that fact directly. How should I proceed here?

A: $F=\cup _n F_n$ where each $F_n$ is nowhere dense. Now $E=\cup_n (E \cap F_n)$ and $E \cap F_n$ is a subset of a nowhere dense set , so it is nowhere dense.


text:
Q: How can disallow su - I am a system administrator and I do not want users to use su - $appuser and try entering the password of the app user
rather
use sudo su - $appuser and enter their own password.
Some naïve users who are not aware try to do su - $appuser and enter an incorrect password, by doing this the application user gets locked after 3 unsuccessful attempts (defined by the AD team; cannot be changed). We want to force users to use sudo su -
Can this be achieved ?

A: Well, you could always use the traditional BSD-route...
Create a group - wheel is the traditional name...
Add users allowed to use su into this group - in your case, none (maybe except root, but root is allowed anyway).
Set the group-ownership of su to wheel
Take away others execution-rights for su
By the end, su should have root:wheel ownership, and it's permission should be: rws--x---  (ie. chmod u=rwxs,g=x,o= su) (or even better; --s--x--- ; ie. chmod u=xs,g=x,o= su)
This will prevent anybody but root and members of wheel from executing su.  Since using sudo effectively makes any user root, sudo su ... should also work.

A: If you're on a system that uses PAM (e.g., almost all Linux systems), then you have a few more options.

*

*Edit /etc/pam.d/su and add a line like su      auth     required       pam_wheel.so before your LDAP/AD/etc. authentication. This gives you the wheel group, through PAM instead of file ownership. You can also do much more flexible things using pam_succeed_if.

*Edit the same, and either change auth sufficient pam_rootok.so (which lets root use su) to auth required pam_rootok.so (to let only root use su), or alternatively put auth required pam_deny.so at some point.

*Same file, you could do something like auth required pam_succeed_if.so uid ne $appuser to just block su to the app user.

I apologize in advance I haven't tested any of those.


text:
Q: Two PCs through one WiFi bridge, cannot be on simultaneously I recently purchased a TP-link WiFi extender, which I mostly use as a WiFi bridge for the wired devices in my bedroom since the other solutions I tried (such as homeplugs) simply weren't appropriate for this house.
I have one Desktop PC for working on, and one HTPC hooked up to my TV. This is done using an 8-port ethernet switch. It works wonderfully, my internet connection is reliable and fast, I can stream Plex down to the living room from the Desktop.
However, something strange happens as soon as I try to have both the Desktop and the HTPC switched on together, (which I sometimes need since I use the Desktop as a beefier machine for streaming Steam games to the TV).
If I have the Desktop on, and switch the HTPC on, the internet connection is completely lost. All sorts of issues, from the Default Gateway being unavailable to the DNS not responding. As soon as I switch the HTPC off again, the internet is back on the Desktop.
This is the first time I tried it, but yesterday I switched the HTPC on first and had no issues.
I have tried playing around with the DHCP settings on the TP Link device, manually setting the DNS servers (standard Virgin Media servers:  to use, telling it to use the router as the default gateway... But this doesn't seem to matter.
The router I am using is a Virgin Media Superhub, which actually seems to set its own IP as the DNS server for devices to use...
Any ideas what is happening? There doesn't seem to be any IP Clash between the PCs, which is the only thing my limited Networking knowledge could think of.
Could it be that the extender is acting as its own DHCP? Maybe that is messing with the router?


text:
Q: Let C18 throw a compiler error Is there a way to let the C18 compiler throw an own, customized error message during compiling?
For example, consider a situation with two user-defined settings:
#define SETTING_A 0x80
#define SETTING_B 0x3f

Assume these settings can't be both 0x00. Is there a way to let the compiler throw an error (or at least a warning) when the user sets both settings to 0x00?

A: Consider using #if and #error:
#if (SETTING_A == 0) && (SETTING_B == 0)
#error SETTING_A and SETTING_B can't both be 0!
#endif

A: I don't know what C18 does or doesn't support, but you should try the #error directive.


text:
Q: React 16. alert event in setState callback is called before the graphical rendering is performed I work with react js 16.
var time = this.state.time;
this.setState({time: time + 1}, function(){alert("hello, time is updated");} );

but the alert pops up before the time is graphically updated.
Any idea how to trigger the alert but ONLY when setState is completed ?? (I want the view updated BEFORE the alert pops up...)

A: When updating state based on existing state, you should always use callback function as React waits if there are any other state updates before it renders. So your code should look like this:
this.setState(
   (prevState) => ({time: prevState.time + 1}),
   () => {alert("hello, time is updated");}
);

In another words, whenever your new state dependens on previous state, you should use state callback method.


text:
Q: Как добавить двумерный список в массив Numpy? Имеется двумерный список s1=[[2,3],[4,5,6]] и двумерный список s2=[[7,8,9],[10,11],[12,13]]. Необходимо в массив a=np.array([]) добавить данные списки таким образом, чтобы во время итерации по массиву a выбирался целиком список s1 и целиком список s2. Аналог данному результату c использованием обычных списков будет выглядеть так:
s1=[[2,3],[4,5,6]]
s2=[[7,8,9],[10,11],[12,13]]
s3=[]
s3.append(s1)
s3.append(s2)
for i in s3:
    print(i)
    #[[2, 3], [4, 5, 6]]
    #[[7, 8, 9], [10, 11], [12, 13]]

Если использовать функцию np.append, то граница между списками s1 и s2 в массиве a стирается и все списки и подсписки записывается подряд в одномерный массив:
import numpy as np
s1=[[2,3],[4,5,6]]
s2=[[7,8,9],[10,11],[12,13]]
a=np.array([])
a=np.append(a,s1)
a=np.append(a,s2)
for i in a:
    print(i)
    #[2, 3]
    #[4, 5, 6]
    #[7, 8, 9]
    #[10, 11]
    #[12, 13]

Таким образом, мне необходим результат как в первом варианте кода, только чтобы данные списков s1 и s2 содержались в массиве. Проще говоря, добавить двумерные списки в массив numpy.

A: Я думаю, что нашел решение своей проблемы в англоязычной версии похожего вопроса: https://stackoverflow.com/a/47071845/17715435
s1=[[2,3],[4,5,6]]
s2=[[7,8,9],[10,11],[12,13]]
s1=np.array(s1)
s2=np.array(s2)
a=[s1,s2]
a=np.array(a)
for i in a:
    print(i)
    #[list([2, 3]) list([4, 5, 6])]
    #[list([7, 8, 9]) list([10, 11]) list([12, 13])]

A: В официальной документации
Function: Numpy.vstack()


text:
Q: Build standalone app from React native projects How do i create a standalone app for iOS (*.ipa) so that i can distribute it to friends / testers?
Is there a way to do this without paying 99$/annum to Apple?
I tried the solution where you have to create a directory called "Payload", archive it and then rename it to *.ipa. But, this did not work.

A: Expo has created a great solution to this problem.  It's also great for development.  They have a huge community on their slack channel.  Download the expo app, and you can test on your own device, and send your app to your friends.
https://expo.io/

A: You could ask your friends to install the Expo App to test it
If you ask your friends to install the Expo app and you keep your Expo XDE open with your host selected as tunnel it should work. But if you switch of you xde the app will not work anymore. This is the only way.
The android apk can still be circulated to your friends without the license but for ios you will need to get the developers certificate and upload your app/get approval and only then can you ask people to test it out.


text:
Q: Excel Embeded If Statements In excel is it bad to have about 1000 embedded if statements? I have about 1000 options that I want to pre-populate in other excel fields, what is the best way to do this other then inefficient if statements?

A: Yes, it is bad.
Excel is not a good tool to use for complex programs. It would be better to buy Resolver One which gives you a spreadsheet interface, but actually generates Python code under the hood. That way you can audit and test the code for correctness, and you are less tempted to create awfully complex, and often buggy, spreadsheets.
There is a group called the European Spreadsheet Risks Interest Group that holds an annual conference about the risks inherent in complex buggy spreadsheets. A lot of the papers presented at this conference are available on their website.

A: only 7 if statements can be embedded in one another in older versions of excel. 2007 allows more, but it gets unwieldly after that.
A better option may be to build a table with all your different options, then use the VLOOKUP formula to pull the result.
Whether you use Excel or another tool, the important thing is to design it well with a good flow of information that is easy to follow. Excel works great for large spreadsheet projects as long as they are well designed. The additional benefit to a well designed Excel file is that more people can open them.


text:
Q: Python/Pandas: Conditional summing of columns In python I have a pandas data frame similar to the one below:
           | AUG12               | UNDERLYING | VOL |
           |---------------------|            |     |
           | 45  | 49  | 50 | 55 |            |     |
====================================================|
2012-11-14 | 1   | 1   | 2  | 3  | 49         | ?   |
...          ...   ...   ...   ...

The task is: For each row, find column names which are greater than UNDERLYING (49), sum the values (2+3) and put the result in to VOL (5). How can I accomplish this in python? Many thanks in advance!

A: You could use DataFrame.apply function
def conditional_sum(row):
    underlying = row['UNDERLYING'][0]  # extra '[0]' is required due to multi leve index in column names
    return row.loc['AUG12'].apply(lambda x: 0 if x < underlying else x).sum()

df.apply(conditional_sum, axis=1)


text:
Q: Codeigniter div tag around anchor can we use div tag inside anchor function?
I have this div
#first{ opacity:0; }

Then I want to put it into my anchor. Here it is:
<?php

    if(is_array($databuku)){

        echo '

';
        $i = 1;
        foreach($databuku as $key){
            $judul = '
'.$key->tbl_name.'

                         ' .$key->index_no. ' / ' .$key->id. '

                         '.anchor('perpustakaan/koreksi_buku/'.$key->id, 'Edit').' |

                         // I want to put the div #first in 'Delete' function below //
                         '.anchor('perpustakaan/konfirm_hapus_buku/'.$key->id, 'Delete').'

';
             echo $judul;
        }
        echo '
';
    }

?>

I want to put the div #first in anchor -> delete. How can I do that?

A: This will work
 anchor('perpustakaan/konfirm_hapus_buku/'.$key->id, '
Delete
')

A: As the div opacity is 0 in your CSS, so that the div content is not visible to you and if you want to add the div#first in your anchor tag then try,
...anchor('perpustakaan/konfirm_hapus_buku/'.$key->id, '

Delete')....


text:
Q: Having trouble to understand circular declaration Hi i'm trying to create a factory method, that returns a derived class of class A, I'm having trouble understanding circular declaration, I hope you can help me solve this.
Thanks.
AChildOne.cpp

#include "AChildOne.h"

AChildOne.h

#ifndef ACHILDONE_H
#define ACHILDONE_H
#include "A.h"

class A_CHILD_ONE : public A {
};

#endif

A.cpp

#include "A.h"

void A::a(){
    Factory::fact();
};

A.h

#ifndef A_H
#define A_H

#include "Factory.h"

class A {
    public:
      static void a();
};

#endif

Factory.cpp

#include "Factory.h"
A *Factory::fact(){
    return new A_CHILD_ONE;
}

Factory.h

#ifndef FACTORY_H
#define FACTORY_H

#include "A.h"
#include "AChildOne.h"

class Factory {
    public:
     static A *fact();
};

#endif

Compilation error
g++ A.cpp Factory.cpp AChildOne.cpp -o test
In file included from Factory.h:5:0,
                 from A.h:4,
                 from A.cpp:1:
AChildOne.h:5:30: error: expected class-name before '{' token
 class A_CHILD_ONE : public A {
                              ^
In file included from A.h:4:0,
                 from A.cpp:1:
Factory.h:9:10: error: 'A' does not name a type
   static A *fact();
          ^
A.cpp: In static member function 'static void A::a()':
A.cpp:4:2: error: 'fact' is not a member of 'Factory'
  Factory::fact();
  ^
In file included from A.h:4:0,
                 from AChildOne.h:3,
                 from AChildOne.cpp:1:
Factory.h:9:10: error: 'A' does not name a type
   static A *fact();
          ^

A: In Factory.h you try to include A.h; in A.h you try to include Factory.h.
Including Factory.h into A.cpp and removing from A.h should help.
Factory declaration depends on A interface. A declaration doesn't depend on Factory declaration but A definition does.
Also, Factory.h doesn't need to know about AChildOne.h but Factory.cpp does. So move #include AChildOne.h to Factory.cpp.


text:
Q: TYPO3 Media-Emelent own field is it possible to extend the media type in my typo3 extension?
Default fields are alternative, title, desription.
How can i add a own field?
$GLOBALS['TCA']['tt_content']['types']['my_slider'] = [
        'showitem'         => '
                --palette--;' . $frontendLanguageFilePrefix . 'palette.general;general,
                --palette--;' . $languageFilePrefix . 'tt_content.palette.mediaAdjustments;mediaAdjustments,
                pi_flexform,
            --div--;' . $customLanguageFilePrefix . 'tca.tab.sliderElements,
                 assets
        ',
        'columnsOverrides' => [
            'media' => [
                'label'  => $languageFilePrefix . 'tt_content.media_references',
                'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('media', [
                    'appearance'    => [
                        'createNewRelationLinkTitle' => $languageFilePrefix . 'tt_content.media_references.addFileReference'
                    ],
                    // custom configuration for displaying fields in the overlay/reference table
                    // behaves the same as the image field.
                    'foreign_types' => $GLOBALS['TCA']['tt_content']['columns']['image']['config']['foreign_types']

                ], $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext'])
            ]
        ]
    ];

A: if you analyze the datastructure of your TYPO3 database you will find: those fields (title and alternative) are not fields in the table sys_file but in sys_file_metadata (and in sys_file_reference for overwriting them on a specific usage)
With that knowledge you can add your fields to these tables and give them a proper rendering and behaviour.

Adding the fields to sys_file_metadata will make them available for every file as default values if the fiel is used anywhere.
If you want these fields appear only at special usage you need to set the fields only for the table sys_file_reference which is used only for relations between a file and it's usage. AND you need to set conditions to show the fields only if your content elements use a file. This condition might be a litte complicated. if you use inidvidual tables the condition could be used the usage of this foreign_table, if you use tt_content records you also need to include the CTypeof the record in the condition. Probably you will need an userfunc.
Or you have an unique fieldname?