text:
Q: How to make 100 divided by 110 equal a decimal in Java / Android I'm trying to use the follow code to produce a decimal number, but the evaluation of l divided by h (low by high) always comes out to be 0.
How can I correct this? Thanks!
EditText marketValLow = (EditText) findViewById(R.id.marketValLow);
            EditText marketValHigh = (EditText) findViewById(R.id.marketValHigh);
            String valLow = marketValLow.getText().toString();
            String valHigh = marketValHigh.getText().toString();
            int l = Integer.parseInt(valLow);
            int h = Integer.parseInt(valHigh);

            if (valLow.trim().equals("") || valHigh.trim().equals("")) {

                Toast.makeText(CurrentMarketValue.this, "You need to enter a high AND low." + valLowIndex, Toast.LENGTH_SHORT).show();

            } else if ((l / h) < .9) {

                Toast.makeText(CurrentMarketValue.this, "The range between your value cannot be more than 10%." + (l / h), Toast.LENGTH_SHORT).show();

            }

A: (int / int) will result in a int.
Instead do: double result = ((double)l) / ((double) h); and instead of checking on (l / h) do a check on result instead.

A: double val = ((double)l)/h

A: You're doing integer division. Force one of the operands of / to be a double.
((double)l / h)

A: it is a basic part of many type languages. Integer division shows the results of whole divisions. In your case you could make it 1.0 / h or typecast one of the numbers to float or double.

A: Just by way of contrast to all the other answers:
if ((l * 10) < (h * 9))

Not saying its better (in fact if l or h has the possibility of being greater than about 200 million it's bad), just different.

A: It would appea ryou're using an integer where a float or double would be better.

A: I think JeremyP is right. TomTom why do you say it's wrong?
The following are all equivalent, by properties of inequalities (multiplying both sides by the same positive amount... assuming h >= 0):
(l / h) < .9
l < (.9 * h)
(l * 10) < (h * 9)

The latter also has the nice property of not throwing an exception when h = 0.


text:
Q: How to use a spinner within a fragment in Android studio I'm getting the error code I've printed below. I'm trying to use fragments and on my first fragment, i want to give users a choice of options using a spinner. To me it seems most logical to have this within my fragment1 class. However it doesn't seem to work. Furthermore at the moment my code works by calling the fragment 1 straight away, like my main activity.xml isn't shown (i'm not sure if this is correct or not, i'm a newb when it comes to android app development).
I'm getting the error on the ArrayAdapter call, marking 'this' as the culprate.
Fragment
public class Page1Fragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
                savedInstanceState) {

            View view = inflater.inflate(R.layout.page1_fragment, container, false);

            Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, //this is where the error is called
                    R.array.planets_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
            spinner.setAdapter(adapter);

            return view;

        }

    }

Main Activity
package provider.ac.stir.ac.uk.finallab;

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
                tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

    }
}

Error
Wrong 1st argument type. Found: 'provider.ac.tir.ac.uk.finallab.Page1Fragment', required: 'android.content.Context

A: ArrayAdapter.createFromResource expects a Context, and Fragment is not a Context, so try with its Activity. Simply change:
ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);`

To:
ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);`

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I unpack a map in spark sql? I have a spark data frame and one of the columns have values packed like this:
Map(a -> 123, name -> rover, type -> london)

How do I extract the value london and put it into a new column called type?
I tried
%sql

select map_field["type"] as type from myDF

A: You just select the column and add the key like the following:
import org.apache.spark.sql.functions.col
df.select(col("mapColumnName")("keyName"))


text:
Q: React 0.13 class method undefined So i've started with React and ES6 and got stuck with very basics. Really appreciate some help.
handleClick() throws an error:
Uncaught TypeError: Cannot read property 'handleClick' of undefined

code follows
export default class MenuItems extends React.Component {

  constructor(props) {
    super(props)
    this.state = {active: false}
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState({ active: !this.state.active });
  }

  render() {
    let active = this.state.active
    let menuItems = [{text: 'Logo'}, {text:  'promo'}, {text:     'benefits'}, { text: 'form'}]
    return (

        {menuItems.map(function(item) {
          return
{item.text}
;
        })}

    );
  }
}

A: {menuItems.map(function(item) {
  return
{item.text}
;
})}

Because your code is in strict mode (modules are always in strict mode),  this is undefined inside the function you pass to .map.
You either have to explicitly set the context by passing a second argument to .map:
{menuItems.map(function(item) {
  // ...
}, this)}

Or use an arrow function:
{menuItems.map(
     item =>
{item.text}

)}

A: react.js:18794 Warning: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See BlueBall
so just like this:
{
  menuItems.map(
     item =>
{item.text}

)}


text:
Q: Is there a way to renew a DHCP lease for another client? I am looking for a way to renew a DHCP lease for ANOTHER client, that the one making the request. I know how to do this for the requesting client using dhclient or arping, but I have this old router that does not have static ip per mac address setting, and a network printer that changes an ip with each reset...

A: If I am understanding your question correctly, you wish to have a client execute a DHCP LEASE RENEWAL from a trigger sent by another client.  In terms of security, clients shouldn't be allowed to control other clients on the network.  The DHCP server could send a FORCERENEW message to all clients but that would force all clients to renew and few DHCP Servers even support this.  https://www.ietf.org/rfc/rfc3203.txt.

*

*Targeting a specific client from another client can be accomplished using exploitation techniques such as  MITM attack, DHCP Server Spoofing, etc.. to perform Remote Code Execution or Denial of Service for the specific client.
https://www.whitewinterwolf.com/posts/2017/10/30/dhcp-exploitation-guide/

*I take it that the old router you are using is also serving as the DHCP server.  A simple solution would be to lower the Default Leas Time and/or Max Lease Time as doing so would have the client request the Renewal after the time specified.

*Being that your router is old, another solution would be to replace the router firmware with one capable of assigning static IP addresses to MAC addresses such as DD-WRT, OpenWRT, Tomato, etc...
https://dd-wrt.com/
https://openwrt.org/docs/start
http://www.polarcloud.com/tomato


text:
Q: How to find the latest account in a chain of old and new accounts? I have a dataframe with three columns, old account, new account and date. For every account, I want to trace the path through each row of the dataframe to the find the latest account on record, and write it to a new column.
Simple example:
df1 = pd.DataFrame({'new_account': ['A1', 'B1', 'A2', 'B2'],
                'old_account': ['A0', 'B0', 'A1', 'B1'],
               'date': ['Jan 2019', 'Feb 2019', 'Mar 2019', 'Apr 2019']},
             index=[0, 1, 2, 3])

    new_account     old_account       date
0   A1              A0              Jan 2019
1   B1              B0              Feb 2019
2   A2              A1              Mar 2019
3   B2              B1              Apr 2019

This shows that account A0 went into A1, and then A1 went into A2, B0 went into B1, which eventually went into B2.
I want to end up with a situation looking like this:
df2 = pd.DataFrame({'new_account': ['A1', 'B1', 'A2', 'B2'],
                'old_account': ['A0', 'B0', 'A1', 'B1'],
                'date': ['Jan 2019', 'Feb 2019', 'Mar 2019', 'Apr 2019'],
                'latest_account': ['A2', 'B2', 'A2', 'B2']},
             index=[0, 1, 2, 3])`

    new_account     old_account       date           latest_account
0   A1              A0              Jan 2019               A2
1   B1              B0              Feb 2019               B2
2   A2              A1              Mar 2019               A2
3   B2              B1              Apr 2019               B2

A: Construct a mapping table (pandas series) from old_account to new_account and use Series.map to conduct mapping. In the case of no map, use new_account data.
old_to_new_map = df1.set_index('old_account')['new_account']

df1['latest_account']=df1['new_account'].map(old_to_new_map).fillna(df1['new_account'])


text:
Q: Maven release perform files injection I use the maven release plugin within CI/CD pipeline based on Gitlab.
Everything works fine but I try to inject some sensitive data directly to a file using runner during the pipeline run:
simply echo $var > file
yet before running maven plugin - it works fine but running maven release perform in one of its steps is branch checkout which means that all uncommitted files will be skipped. Of course, as they are sensitive ones I don't wanna keep them directly at the repo level and finally as a result I have an artifact without necessary data
Maybe someone knows how to inject/add such a file running maven release plugin? Worth to add that I'm fully aware of fact that it's not a secure way to keep sensitive data in the artifact - it's only a temporary solution.


text:
Q: Python: Global name 'info' is not defined Buen día, realmente yo no tengo taaaanta experiencia programando en Python (Soy un estudiante, en realidad) lo que pasa es lo siguiente: Tengo una asignacion en la que debo de poner en practica el uso de listas enlazadas, creando nodos.
Y pues eso, creo los nodos con una clase definida para ellos y les agrego valores, pero a la hora de imprimirlos me arroja el siguiente error:

Traceback(Most recent call last): File "clase.py", line 62, in
   print(c.getInfo()) File "clase.py", line 24, in getInfo
  return str(info.getTitulo()) NameError: Global Name 'info' is not
  defined

El codigo es el siguiente:
class Nodo():
    def __init__(self,pos):
        siguiente = ''
        self.pos = pos
        elemento = ''
        info = NodoInfo(self.pos)

    def getSiguiente(self):
        return self.siguiente

    def setSiguiente(self,n):
        self.siguiente = n

    def getPos(self):
        return pos

    def setElemento(self,a):
         elemento = a

    def getElemento(self):
        return elemento

    def getInfo(self):
        return str(info.getTitulo())

class NodoInfo():
    def __init__(self,pos):
        self.titulo = "Numero de nodo: "+str(pos)
        self.desc = "Este nodo puede almacenar datos."
        self.detalle = "Especificamente, almacena datos de tipo Object (Amplio espectro de TDA's)."

    def getTitulo(self):
        return self.titulo

    def getDesc(self):
        return self.desc

    def getDetalle(self):
        return self.detalle

pos = 1
seguir = 1
n = Nodo(pos)
c = Nodo(pos)

x = raw_input("Ingrese su primer dato: ")
n.setElemento(x)
while(seguir):
    pos = pos + 1
    opc = raw_input("Desea ingresar otro dato? S/N ")
    if(opc == 'S'):
        a = Nodo(pos)
        n.setSiguiente(a)
        a.setElemento(raw_input("Ingrese el otro dato: "))
        if(c.getSiguiente==''):
            c=n
        n=a
    else:
        seguir = 0

for i in range (1,pos):
    print(c.getInfo())
    print("El nodo almacena: "+c.getElemento())

Les agradeceria su ayuda! =)


text:
Q: Footer fixed bottom with header and Bootstrap I'm using Twitter Bootstrap 3.3.1, with the template "Jumbotron".
Here, my page :

On the browser, the header (the div with role "navigation" + div with class "jumbotron") has  a 290px size.
When I'm trying to push the footer at the bottom with all what I found, I have always the same problem. The "root" and "main" div will always be longer than the screen display because of the header, I guess.
A lot of internet's solutions don't include a header... :(
I don't want to fix the footer with a "position:fixed", I realy want to push it at the bottom with CSS only.
To be more specific, my footer has to stay at the bottom of the page with or without content. If the content is sorter than the screen, the footer will be at the bottom of the screen. If the content is longer than the screen, the footer will be at the end of the page.
EDIT: I don't want to do it WITH Bootstrap. I just want some CSS to do it without Bootstrap if Bootstrap can't do it !
I hope it's clear enough.
If someone has an idea, it'll make my day!
Thanks.

A: Bootply Example
Did you try this?

Also if this isn't what you're looking for, edit your question and try to be more detailed.
EDIT
OP is looking for the navbar-static-bottom, which renders the footer at the very bottom of the page REGARDLESS* of page content/height. The only issue is, this class has not yet been added to bootstrap. It's in the list of commits, but has yet to be reliably implemented.
Commit Log for Bootstrap
See this document on the status of navbar-static-bottom class. As of right now, there is not reliable way to do this in Bootstrap.

A: In bootstrap you can style your footer with the class of
   navbar-fixed-bottom

A default footer might look something like this:

    ...

A: Have you looked into these examples?
http://getbootstrap.com/examples/sticky-footer/
or
http://getbootstrap.com/examples/sticky-footer-navbar/

A: This is my favorite:
http://www.cssstickyfooter.com/
It's been working like a charm for years.
Hope this helps!

A: So you want to keep the footer at the bottom of the page with css, you could just do:
html {
    position: relative;
    min-height: 100%;
}
body {
    margin: 0 0 100px; /* bottom = footer height */
}
footer {
    position: absolute;
    bottom: 0;
}


text:
Q: texlive: Personal "texmf.cnf" I was wondering what is the official way to add personal configurations to texmf.cnf.
I specifically want to add my own settings for this reason:
Avoid linebreaks in LaTeX console / log output
But the answer there tells you to modify /usr/local/texlive/2017/texmf.cnf, which is not right.  Each time you install a new version of texlive, each time you reinstall texlive, each time you acquire a new machine, each time you wipe out your system disk, you would have to modify texmf.cnf.
All personal configurations should reside under the user's home directory.
I've heard of the environmental variable TEXMFCNF and searched the net for how to use it, but I haven't found what exactly it does and how to use it to solve the particular problem I have.

A: The TEXMFCNF environment variable tells TeX (or rather, the kpathsea library used by TeX in typical distributions) where to look for the texmf.cnf file. (You can type kpsewhich texmf.cnf to see the location of the texmf.cnf file that will get picked up.)
For me, by default, kpsewhich texmf.cnf shows /usr/local/texlive/2017/texmf.cnf. But if I set TEXMFCNF to something else:
% export TEXMFCNF='/tmp'
% kpsewhich texmf.cnf
warning: kpathsea: configuration file texmf.cnf not found in these directories: /tmp.

However, if I instead export TEXMFCNF='/tmp:' then kpathsea searches in /tmp first, and then the default system directories (like /usr/local/texlive/2017/ or whatever).
The documentation for all this is in the kpathsea manual, sections Path searching > Path sources > Config files, and Path searching > Path expansion > Default expansion (for the stuff about the colon).

So the answer to your question, of how to maintain a local texmf.cnf file inside your user's home directory, is:

*

*Create a file called texmf.cnf, in some place inside your home directory, say in ~/tex_config_dir. Put whatever config changes you'd like, into this file.

*Somewhere in your shell config (.bashrc or .zshrc or whatever you use), set the environment variable TEXMFCNF to point to that directory, ending with a colon. For example:
export TEXMFCNF='~/tex_config_dir:'

*In any new shell (for example, after restarting your terminal), type echo $TEXMFCNF to confirm that it's set correctly, and kpsewhich texmf.cnf to confirm that your config file is the one getting picked up. Enjoy.

A: TEXMFCNF is an environment variable saying where to find texmf.cnf. But there are some quirks:

*

*TEXMFCNF does not point to texmf.cnf itself, but the dir containing it.

*Its value can have a : in the end, which means keep searching if not found here.
An example TEXMFCNF setting (on unix-like system) is:
export TEXMFCNF=$HOME/.texlive:

This will search for $HOME/.texlive/texmf.cnf (then search other places if not found there).
I suggest using kpsewhich --all texmf.cnf to test if your settings are successful.

A: There are a lot locations where kpathsea will look for texmf.cnf and it will use all it can find: values in earlier texmf.cnf overrides the values from later texmf.cnf.
The main texmf.cnf is in texlive/2017/texmf-dist/web2c. This should never be changed.
The one in texlive/2017 can be used for personal changes (open it to see the comments). But if you don't trust the location you can use the web2c folder of other texmf trees, e.g. texmf-local. A list of all possible location can be shown with kpsewhich -show-path=cnf.
You can also set the variable TEXMFCNF to a specific folder with the texmf.cnf but normally I don't think that it is needed.


text:
Q: Invalid form of an argument Modus ponens, that is [(A→B) and A, therefore B], is a valid argument.
If we use the form (1) [(A→B) and B, therefore A], the argument is no longer valid because for the assignment [A = False, B = True], we have the premises (A→B) and B both true but the conclusion A false.
It is said that propositional logic must hold only for the form of the arguments, not for the meaning of the propositions.
But try using A = "Today is Saturday", B = "Tomorrow is Sunday".  The assignment [A = False, B = True], which makes the argument invalid, is not possible, because A and B can only be both true or both false. So argument (1) becomes valid? It seems like a small question but if you think about it, it is fundamental.

A: The validity of an argument gauges not the truth of the conclusion, but whether a false conclusion can result from premises that are all true. If yes, the argument is deemed invalid; otherwise—since there is no case whereby all the premises are true yet the conclusion is false—its corresponding conditional must be logically valid (in propositional calculus, this means a tautology).
Argument (1)—its form is called "affirming the consequent"—is invalid, because its corresponding conditional $((A\rightarrow B)\land B)\rightarrow A$ is not a tautology, since it is false for $A$ False and $B$ True.
The fact that when $A$ and $B$ are "Today is Saturday" and "Tomorrow is Sunday", respectively, the conditional $((A\rightarrow B)\land B)\rightarrow A$ is true (weaker than tautologically true, i.e., true regardless of interpretation of $A$ and $B$) is just a peculiarity of this tautologically-equivalent choice of $A$ and $B.$ However, this doesn't affect argument (1)'s validity, which, as you correctly observe, depends on its form, not its atomic propositions' meanings.


text:
Q: How to disable JQuery keypress event for just one element? On my site I have registered a keypress event handler for the whole document.
$(document).keypress(myhandler);

And I handle the 'space' key to scroll a list.
Trouble is, there is an <input type='text' /> element, and I don't want 'space' keypress to scroll the list when it is entered in the input.
I couldn't find any information in the "event" object passed by JQuery to the handler, to identify where the source of the event is.

A: you're looking for event.target.id, which will be the id of the element that the event was raised on. So inside myhandler you would need something like the following
function myhandler(e) {
    if (e.target.id !== 'id of input') {
        /* rest of event handler */
    }
}

A: Alternatively, you could attach another event handler to the input field, and in this handler stop the propagation of the event:
jQuery('#input-field-id').bind('keypress', function(e) {
    e.stopPropagation();
});

This way, you can leave the global event handler as it is. Might be cleaner.

A: See the QuirksMode docs about event order, and especially about how to turn off the events, which is browser-specific. Quote:
For a complete cross-browser experience do
function doSomething(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}


text:
Q: Is there a "universal LYM inequality?" This question is based on a blog post of Qiaochu Yuan.
Let P be a locally finite* graded poset with a minimal element, and w be a weight function on the elements of P. Suppose that the total weight of the elements of rank k is bounded by 1. Then is the total weight of any antichain bounded by 1, or some constant c (independent of P or w?) The answer, of course, is no, and it's not hard to construct a counterexample. So what are the minimal conditions on P and/or w needed for such a result?
Note that this should specialize to several well-known theorems. Taking the poset to be a Boolean lattice and w to be 1/(n \choose k), we obtain the LYM inequality, hence the question title. Taking the poset to be the set of finite-length binary words with X \leq Y if X is a prefix of Y, and w to be 1/2^k, we get back Kraft's inequality. And finally, for arbitrary P and setting w to be the constant function 1, we get back (half of a special case of) Dilworth's theorem.
A secondary question: assuming such a result exists, is there a probabilistic proof of it, similar to the probabilistic proofs of Kraft and LYM?
Edit 4: Most of the counterexamples I've constructed thus far have had trees as the underlying poset (i.e., if X \leq Z and Y \leq Z, then either X \leq Y or Y \leq X). This subcase seems to simplify the analysis somewhat, so it might be worth considering only trees.
In fact, here's a toy problem which itself seems rather difficult: Can we characterize the weight functions on the infinite rooted binary tree, with the weight of each graded part equal to 1, that satisfy the strong property that the weight of any antichain is at most 1?
*Edit: Actually we want something somewhat stronger than local finiteness, namely that every element is covered by finitely many elements, so that there are are only finitely many elements of any given rank.
Edit^2: Of course we also want the weight function to be nonnegative, or else scary bad things can start happening.
The obvious restriction on the weight function requires it to be dependent only on the rank; interestingly, this is neither necessary nor sufficient for the strong form of the conjecture (i.e. the maximal weight of any antichain \leq the maximal weight of all the elements of rank k) to hold. (Counterexamples available upon request.) I'm still searching for a counterexample in this situation to the weak form of the conjecture (Edit^3: Counterexample found.), where every rank has bounded total weight but there are arbitrarily heavy antichains.

A: An approach to the strong form of the property, based on a probabilistic proof of the LYM inequality (apparently due to Bollobas, can be found in Tao and Vu, Ch. 7):
Consider a graded poset P and let G be a compact topological group that acts on P. Construct a weight function as follows. Fix a distinguished (saturated) chain C of P, and for each X, let S(X) be the set of elements in G that take X into C. Then w(X) is the normalized Haar measure of S(X).
It's clear that the total weight of every graded part is 1; now if A is an antichain of P, no automorphism of P can take two elements X, Y \in A to C simultaneously. So the sets S(X) are distinct for all elements X \in A, and the total weight is therefore at most 1.
The only obvious problem with this approach is that I don't see why the sets S(X) should be measurable. However, if P is finite, no such difficulty arises, and in particular this answers Qiaochu's question (from the comments) in the affirmative, at least for finite posets.
This also specializes, for finite posets, to the examples already discussed. Does every weight function on a finite poset with the strong property arise in this way?

A: I'm going to write some of my thoughts on the question as separate answers to add a degree of threading.
The first thing to note is that it seems that any weight function that doesn't depend in a rather deep way on the specific properties of P isn't going to work generically. So we might ask: can we find an (infinite) poset such that every weight function fails?
Well, no. Even if we require that the sum of every graded part is 1, we can simply take an infinite chain and take the weight of the elements in that chain to be 1, and the weight of the other elements to be 0. And, in fact, I believe that small-enough perturbations of this weight function will also satisfy at least the weak form of the conjecture.
So the question is: how can we even ask for a "maximally bad" poset? One approach might be to disregard weight functions that have "high correlation" with the characteristic function of a chain, but it's still not clear how to make this rigorous...

A: Don't know if you are aware of this, but there is an LYM-style inequality for the partition lattice, published in Advances In Applied Mathematics 19, pp 431-443, 1997.
Can be found here-
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.109.5191&rep=rep1&type=pdf
This is useful for me in the context of generating exactly the partitions that satisfy some simple characteristics.


text:
Q: Getting the error "Unable find module with ID" with Aurelia Router I'm trying to configure routes in Aurelia using aurelia-router, but it throws an error that it can't find the moduleId(route to file) of my route.
I configure my routes in two files router.js and app.js, router file only contains an array with all the routes. app file is the main file of my project.
Project Structure:

Router.js:
export default [
  { route: ['', '/', 'home'], name: 'home', title: 'Inicio', layoutView: 'components/common/layout/layout.html', moduleId: 'components/home/home' }
]

App.js
import routes from 'router'
import {RouterConfiguration, Router} from 'aurelia-router';

export class App {

  configureRouter(config, router){
    config.options.root = '/';
    config.title = 'La Tatuadora';
    this.router = router;
    config.map(routes);
  }
}

Error

A: Aurelia provides PLATFORM.moduleName("moduleId") to resolve modules, it comes with the aurelia-pal package.
In use it looks like this:
{ moduleId: PLATFORM.moduleName("components/home/home") }


text:
Q: How do I modify a library in flutter? I'm using a library that draws barcodes and under them it drows the barcode number, however it draws text just in black color. I found the code that chooses the color during this operations, however when I try to change this code library from Colors.black to Colors.white and I save it, it doesn't save for some reason. So I suppose there is a different way to modify code from library, but I don't know how.

A: @Gabriel, You can easily copy .dart files from the package/library you're using to your project and modify the code to your liking. For e.g. if you are using https://pub.dev/packages/toggle_switch, then you can access the source code from the GitHub location of the package in pub.dev and download it from GitHub,

You can then copy .dart files from <project>/lib to your <project>/lib and modify them accordingly. Make sure you add reference in the source code to credit the original developers and add their GitHub link.
Good luck!


text:
Q: Javascript is submitting a simple request but not getting proper feedback I have the following setup where Javascript sends an AJAX request and it gets executed fine. The problem is that the AJAX submission is not getting the reply from server to display in the UI. console.log(msg) works but all the rest does not behave at all. How can I make sure every single output from PHP is received in Javascript?
ajax.php:
<?php
    $cmd = $_POST['command'];
    echo shell_exec("/usr/local/software/bin/cli -x '{$cmd}'");
?>

javascript.php:
$.post('ajax.php', {
    action: 'FEEDBACK-PLEASE?????',
    command: 'show status'
}, function(msg) {
    console.log(msg); // shows data arrived
    // following does not show the msg at all
    $('#terminal_output').html(msg);
    alert('HELLO!!!!!! HELLO!! where is my feedback!! why you no alert???');
}, 'json');

EDIT: XHR body has data

A: you are not returning json from your post request remove the json property
$.post('ajax.php', {
    action: 'FEEDBACK-PLEASE?????',
    command: 'show status'
}, function(msg) {
    console.log(msg); // shows data arrived
    // following does not show the msg at all
    $('#terminal_output').html(msg);
});


text:
Q: Google Sheets: indexOf() doesn't accept string object I'm trying to filter CSV data by comparing it to an existing google sheet. This is the code:
var ss = SpreadsheetApp.getActive();
// get booking ID
var idList=ss.getSheetByName("Umsatzliste").getRange("G:G").getValues();
var filteredCSV=[];
for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ){
    if (idList.indexOf(csvData[i][6].toString())!=-1) {
      filteredCSV.push(csvData[i]);
    }
}
csvData=filteredCSV;

The indexOf()-function never seems to work out. csvData is a 2d-array with all csv-values:
ss.toast("ID#1: "+idList[0]+" ID#2: "+csvData[2349][6]+" - "+(idList[0]==csvData[2349][6]).toString());

returns
ID#1: MC/000002674 ID#2: MC/000002674 - false

Alright, the typeof reveals they are both "objects", so i try convert the csvData to a string value:
ss.toast("ID#1: "+idList[0]+" ID#2: "+csvData[2349][6]+" - "+(idList[0]==csvData[2349][6].toString()).toString());

which returns:
ID#1: MC/000002674 ID#2: MC/000002674 - true

So a comparison works. Any idea why indexOf() doesn't work?

A: The data idList retrieved by getValues() is 2 dimensional array. indexOf() cannot search the string from 2 dimensional array. So how about the following modification?
From :
if (idList.indexOf(csvData[i][6].toString())!=-1) {

To :
if (Array.prototype.concat.apply([], idList).indexOf(csvData[i][6].toString())!=-1) {

Note :

*

*Using Array.prototype.concat.apply([], idList), 2 dimensional array is converted to 1 dimensional array.

References :

*

*getValues()

*indexOf()

*Array.prototype.concat.apply()
If I misunderstand your question, I'm sorry.


text:
Q: Using Webpack to bundle Nodejs code with node_modules I found many tutorials on how to get things running without node_modules, but I want to run Webpack and end up with one JavaScript file, that contains all of my dependencies.

A: You can use Webpack configuration file in order to create one bundle file
output: {
    library: 'someLibName',
    libraryTarget: 'umd',
    filename: 'app.bundle.js',
    auxiliaryComment: 'Test Comment'
  }

above will crate a bunndle in the path you have defined.


text:
Q: AngularJS Calling Service from Controller Error I am not sure why I am getting this error, could someone please explain this to me?

TypeError: Cannot read property 'getValueByName' of undefined
      at Object. (http://localhost:63342/Hardcore%20Gaming%20JS/scripts/MainApp.js:175:32)
      at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:4473:17)
      at extend.instance (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:9093:34)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8205:36)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)
      at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7512:30)
      at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:986:7)
      at invokeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8746:9)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8246:11)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)

I have created a service in order to store, update, and return the values of a parts list. I am trying to update the partsList after they click on the different radio buttons.
Also if you know how to make these selections persist through different view changes that would be awesome to know about as well.
Thanks!!
Here is my Service Code:
mainApp.service('MyService', function () {
    var partsList = [
        {name: "selected_computer_type", value: ''},
        {name: "selected_computer_size", value: ''},
        {name: "selected_computer_color", value: ''}
    ];

    //iterates through partslist, finds object that matches and sets the new value
    this.setValue = function (name, value) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name) partsList[i].value = value;
    };

    this.getValueByName = function (name) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name)
                return partsList[i].value;
        return "";
    };
});

Here is my Controller Code:
mainApp.controller('controller_Computer_Type', ['$scope', function ($scope, MyService) {
    //Computer Type Selected
    $scope.current = MyService.getValueByName("selected_computer_type");

    //Updates the partsList
    $scope.change = function () {
        var value = $scope.current.toString();
        MyService.setValue("selected_computer_type", value);
    };

    //List of options for computer type
    $scope.types = [
        //TODO: update url images to reflect personal gaming and business profiles
        {name: 'Personal', value: 'personal', url: 'images/intel 700/ABFS_1_201706141903610053.jpg'},
        {name: 'Gaming', value: 'gaming', url: 'images/amd 500/83-230-100-02.jpg'},
        {name: 'Business', value: 'business', url: 'images/intel 500/83-101-369-z01.jpg'}
    ];
}]);

Here is my View Code:

Type of Computer

            <input type="radio" name="radio_type" ng-model="$parent.current" ng-change="change()" value="{{option.value}}" hidden/>

Current RB - {{current}}

Current DD - {{selectedItem.name}}

Message - {{message}}

A: U miss this
mainApp.controller('controller_Computer_Type', ['$scope','MyService', function ($scope, MyService)


text:
Q: PHP e Mysql Divisão sem resto em PHP divisão de tarefas Galera é o seguinte preciso atribuir tarefas a um numero variável de participantes.
EX: Através de um select obtive 49 tarefas a ser executadas e tenho que distribuir para 4 funcionários. Ou seja a divisão seria assim 1º funcionário  teria 12 tarefas o 2º funcionário  teria 12 tarefas o  3º funcionário  teria 12 tarefas e o 4º funcionário  teria 13 tarefas que seria o restante.
Tanto a quantidade de  tarefas quantos os funcionários vem de um select podem variar e cada tarefa e funcionário tem um código único.
Funcionário 1 tarefa 1
Funcionário 1 tarefa 2
e assim ate completar 12 dai passaria para o outro com mais 12...
Estou usando PHP PDO Mysql e preciso  fazer um loop que faça esta distribuição da forma que expliquei mas não sei como fazer. se algum puder me ajudar ficarei muito agradecido.

A: Amigo,
Fiz aqui, mas não pude compilar. Acredito ser o suficiente para você enterder a lógica que apliquei... espero que te ajude!
<?php

  $qtdTarefas = 49;
  $qtdFuncionarios = 4;
  $aux = 0;

  while($qtdTarefas != 0){ //Enquanto existir tarefa...
    $funcionario[$aux] = recebeTarefa(); //Funcionario recebe a tarefa
    if(($qtdTarefas - 2) < 0){//Se essa for a penultima tarela da lista
      $qtdTarefas--;
      $funcionario[$aux] = recebeTarefa();//O mesmo funcionario recebe essa outra tarefa
      break;//Para o loop
    } else {
      $qtdTarefas--;
      $aux++;
      if ($aux > $qtdFuncionarios){ //Volta ao funcionario 0 quando chega no ultimo
        $aux = 0;
      }
    }
  }

 ?>

Abraços


text:
Q: Need help regarding regex to extract OTP from SMS? I am developing Android App to read OTP from SMS and give user option to directly copy the OTP in clipboard.
Now problem is SMS can be as follow:-

*

*Time: 02:30 PM Your OTP is 3242. (otp can be of any digits).

*12345 is your OTP. TIME: 04:45 AM.

*Your OTP for account 123456789 is 4565.

I need help to extract otp using Pattern and Matchers in java.
or any other simple solution to get otp. Third case can  be ignored.
It will also work if we can get 4 or 5 or 6 digit numbers from SMS using Pattern and Matchers.

A: You can use this
This will cover all the three cases you given in example.
^\d+(?=\sis)|(?<=is\s)\d+\.?$

*

*^\d+(?=\sis) - Matches any digit followed by space and is. (^ anchor to start of string). Covers condition of 2nd example.

*(?<=is\s)\d+\.?$ - Matches any digit preceded by is and space. ($ anchor to end of string). covers 1st and last example

Demo


text:
Q: How to modify some options for Matrix from existing type to create a new Matrix type in template programming? For example, assuming we have a matrix type T, can we create a new type that has only 1 cols like Matrix<..., ..., 1 ,...> and keep other options exactly the same in type T?

A: In this particular case, this should be the simplest form:
using Matrix = Eigen::Matrix<...>; // your type
using Vector = typename Matrix::ColXpr::PlainObject;

A: After some research I give following solution:
template<typename T1>
auto fun(const Eigen::MatrixBase<T1>& _X)
{
    using T = typename T1::PlainObject;
    using T2 = Eigen::Matrix<typename  T::Scalar,
        T::RowsAtCompileTime, T::ColsAtCompileTime,
        T::Options, T::MaxRowsAtCompileTime, T::MaxColsAtCompileTime>;

    if constexpr (std::is_same_v<T2, T>)
    {
        std::cout << "True" << std::endl;
    }
    return T();

}


text:
Q: How to wait until Eclipse IProject.create() and IProject.open() are completed before running Eclipse Java project I have an Eclipse plugin that automatically loads existing Eclipse Java project to workspace, opens it and finally runs the Java application. If the Java project already exists in the workspace, the plugin refreshes the project relative to the project on the file system.
When doing only refreshing the plugin works fine, but when the plugin first imports the project by calling IProject.create(), opens it and runs it, I get a error dialog saying that program  was not found.
The IProject.create() and open() are said to be long-running operations. Is there some way wait until the IProject.create() is finished then and then call IProject.open and after compliting the open methdod call the project.run() method?

A: IProject#create() and IProject#open() are both blocking methods, so you don't have to do anything special to "wait for them" -- when control returns to the call site, they're done creating and opening the project respectively.
Does the project contain Java source that needs to be compiled? If so you should probably also build the project after opening it and before attempting to run the Java program therein. Try using this:
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);


text:
Q: How can I draw EditText on canvas in View class I'm developing an android game and I need to load player nick to save score with nick but I don't know how to draw EditText on canvas.
Is that possible? And if not is there another way to get user input like String?


text:
Q: Gremlin traversal using both in and out edges I'm trying to traverse all the nodes of a graph starting from a given root node. While traversing I want to "fix up" the edge from the previous vertex to the current vertex, so that the edge goes from the previous vertex to the current one (It may be the other way around, but the end graph should be a tree with the root vertex at the root).
The problem seems to be that the edges being traversed aren't all strictly out or in edges.
I'm trying to create a breadth first traversal (should I not do breadth first?), but since there are both in and out edges the query I started with looks like this
g.v('rootVertex').as('x').both.gather.scatter.loop('x'){true}{true}

This seems to be creating an infinite loop due to the ".both" (I think).
Is there a way to do this in gremlin that doesn't create an infinite loop and allows me to fix / verify the edge from the previous node?
Also, could I get a simple illustrative example of the "gather.scatter" part of the query? I'm having trouble visualizing what it exactly is that that step is achieving.

A: Add a simplePath step to prevent the traversal from cycling between two nodes:
g.v('rootVertex').as('x').both().simplePath().loop('x'){true}{true}


text:
Q: App crashes when reading excel files I'm trying to open xls files. This is my code:
File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

And when my app tries to run this line:
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

the app crashes.
Where is the problem?
EDIT:
permission:
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


text:
Q: Get the last call fail cause with Android I am new to Android development and I'm trying some core telephony development. Can anyone tell me how I can get the last call fail cause (or cause code)? I have seen references to LAST_CALL_FAIL_CAUSE, but I don't know how to implement this?
Thanks


text:
Q: Stopping current operation and proceed to another (new) operation function windowResize() {
  someFunction();
  console.log("test3");
}

function someFunction(){
  console.log("test");
  longExecutingFunctionWithAsyncReq();
  console.log("test2");
}

function longExecutingFunctionWithAsyncReq() {
  // some codes here
}

whenever the window is resize(zoomed out/in), this function is called.
But if the user spams the zoom, someFunction() will not have the time to finish and will then cause the error.
I'm thinking of addressing this issue by stopping the current operation and then process the new operation. Also, I've tried reading about Deferred and Promise, but I can't grasp the simplicity of the topic and I'm not sure if it really solves my problem. Plus, I've also checked on callbacks and was very doubtful that this will not solve my problem either.
If my solution is not possible though, I thought of just queuing the operations, but the downside might be, the queue might overflow if not controlled. As for this solution, I've not looked any farther to this, except reading about it.

A: you could use a timeout and clear it before resetting it when the resize function is called:
var myTimeout;
function windowResize() {
   clearTimeout(myTimeout);
   myTimeout = setTimeout(someFunction, 500);
}

this way the function will be called when the user stops resizing and 500 miliseconds have passed.

A: if you just need to wait for operation to finish you can set up a flag.
var working = false;
function windowResize() {
  if (!working){
      working = true;
      someFunction();
      console.log("test3");
  }

}

function someFunction(){
  console.log("test");
  longExecutingFunctionWithAsyncReq();
  console.log("test2");
}

function longExecutingFunctionWithAsyncReq() {
  // some codes here
  // on finish set working to False
}

A: var isStillWorking = false;

function windowResize() {
  if(isStillWorking) {
    // Do nothing.
  } else {
    someFunction(function(){
      isStillWorking = false;
    });
    console.log("test3");
  }
}

function someFunction(callback){
  isStillWorking = true;
  console.log("test");
  longExecutingFunctionWithAsyncReq();
  console.log("test2");
}

function longExecutingFunctionWithAsyncReq() {
  // some codes here
}

To clarify more of Anton's answer I manage to implement the same thing using a flag [global] variable and a callback. I use a callback in order to flag=false since I also need to wait for the asynchronous requests inside the function to finish before resetting the flag.


text:
Q: Doctrine auto-truncate values on insert I'm working on a script that reads XML from a third party partner and places the data in a database table.  I have no control over the length or quality of the content.  I want to avoid adding logic to inspect the length of every field.
For example: I have a column in a mysql DB of type varchar(255), the value from the XML import is greater than 255 characters.  I want Doctrine to insert the first 255 character instead of throwing a Doctrine_Validator_Exception with message "1 validator failed on headline (length)"
Using Doctrine 1.2

A: I know you said you "want to avoid adding logic to inspect the length of every field", but you didn't specify whether that was for performance reasons, or because there were many, and you didn't want to write the code individually.  If it is the latter, I would use something like this on the Doctrine Record:
function set($fieldName, $value, $load = true) {
  switch($fieldName) {
  case 'id':
  case 'foo':
  case 'bar':
    // list all of the fields that you DON'T want to truncate in this section
    break;
  default:
    $value = substr($value, 0, 255);
  }
  parent::set($fieldName, $value, $load);
}

This function overrides the default set() method on the Record.  It is going to truncate all fields to 255 characters that don't match the ones listed in the first part (id, foo, bar).
If that isn't what you want, you can let MySQL do the truncation, it issues a warning if you write past the column length (1265 | Data truncated for column 'xxx' at row 1), but that is discarded by Doctrine as the query will complete.  To do that, you can change the column type from "string" to "blob" and make the second parameter null instead of the column length, then just set the proper limits in MySQL.


text:
Q: How to set variables with basenode (in nodes.pp)? I'm trying Puppet and it seems to be good.
My question is very easy but I can't answer.
I have a file "node.pp" :
node basenode {
         include "dns"
#        include "ntp"
}

node 'myserver.domain.com' inherits basenode {
        $type_server = "client"
        include "ntp"
}

I would like to declare my variable "$type_server" without to do declare "include ntp" on each server.
I would like "basenode" includes "ntp" and use the value of "$type_server" in the node of my server.
The variable is used in the manifests of NTP.
Thanks in advance.

A: Don't use variables -- as Shane said, variable scoping in Puppet is FUBAR, and trying to use it just causes pain, suffering, nausea, headaches, and probably heart disease.
Instead, use defined types.  It's what they're designed for.  So, instead of using classes and includes everywhere, use a defined type and pass it the data it needs:
define ntp_server($type_server) {
    # Do all the things you'd normally do, using $type_server as needed
}

node 'myserver.domain.com' {
    ntp_server { ntp:
        type_server => "client"
    }
}

A: The scoping in puppet is a bit.. unintuitive.  It's a linear evaluation behavior - since the inherit happens before the variable is defined, and the classes included in the inherited class are evaluated immediately, the variable is set after you need it.
Instead of inheriting, try just including the "base" at the bottom of every node, so that it's evaluated after the necessary variables are set.  It's not a very object oriented way to do things, but this scoping behavior doesn't leave a lot of options.
node 'myserver.domain.com' {
    $type_server = "client"
    include basenode
}

A: I know this is pretty old, but as I was having some troubles with it and found this thread, it might be useful for others.
Instead of using defined types or including a node within a node - which doesn't sound very nice imo - I would suggest using parameterized classes. By using that, the author could keep using his classes normally, and those classes would only have a slight modification to receive the variables (that they are already using) as parameters.
So, as example, instead of:
class foo {
  file { 'abc':
    path => "some/path"
    content => $content
  }
}

It could have:
class foo($content) {
  file { 'abc':
    path => "some/path"
    content => $content
  }
}

And use it like this:
node 'myserver.domain.com' {
    class { 'foo':
        $content => "something pretty smart"
    }
}


text:
Q: How to properly flip 2D character with new Unity4.3 2D framework? (Rotation of gameobjects during animation) i'm already checked official Unity 4.3 example project, and there they use
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;

This works pretty well, but. But i'm encountered an trouble, not sure this trouble with this Flip or with something else.
I'm use Animator to animate my characters, i have Attack animation, which in addition to the sprite animation also move character's Hand, which can carry the Weapon. Problem is when i flip the character to opposite direction Hand will move wrong (not as planned), which is wrong. (video below will be more descriptive)
I discovered that this problem occure only if i modify the Hand's rotation in animation, so if i works only with .position this works well, but i need the rotation!
What is best way to get this work?
Here the youtube video: http://youtu.be/qpMK2gRgDz8
At video i show animation without rotation uses, hand moves correct. But next i show it with rotation, as you can see when character turned right this works well, but when left, its completely wrong.

A: What you want to do cannot be done with scaling cause scaling does not change the rotation of the object and so the forward vector remains the same. You must create double sided objects and just rorate them 180 degrees or you can ue a shader that draws a polygon even when its normal vector is against the camera.


text:
Q: How add сomments in my app on Ionic? How better implement the possibility of comments (I meant that users would comment) in my application. Are there any plugins for this?
I did not try anything, because I don't know where to start. Here's an example: you have an application store, and on the page of each product users have the opportunity to comment (leave a review about the quality of the goods).

A: Ionic is based on AngularJS; which is a Javascript framework.
Comments for Javascript are always using the same statements.
// before your comment

or <!-- for your comments -->

A: You want a plugin which should handle user comments and reviews.
It is totally code based, It does not have/require a plugin as such.
As comments/feedbacks/chats requires database, you need to write your own logic.
I am afraid there is no such plugin that could handle such senarios.
You can find UI for that but you need to write login or use js help.
Let me know if you find such.

A: According to you described above, I don't think you need any plugins currently.
At client side, in order to allow users to provide comments, just create a UI for users to fill comments, and then create a http request (see @angular/http) which submits the gathered comments to somewhere (eg:your can create a server to do so)


text:
Q: Concatenate dataframes and remove duplicates based on multiple columns value I want to concatenate two dataframes that have the same columns and remove duplicates.
I then want to remove duplicates of the new dataframe based on multiple key columns.
For example I have these two dataframes
import pandas as pd

    data1 = {'first_column':  ['1', '2', '2', '2'],
            'second_column': ['1', '2', '2', '2'],
           'key_column1':['1', '2', '2', '6'],
          'key_column2':['1', '2', '2', '1'],
           'fourth_column':['1', '2', '2', '2'],
            }
    df1 = pd.DataFrame(data1)

    data2 = {'first_column':  ['1', '2', '2', '2'],
            'second_column': ['1', '2', '2', '2'],
           'key_column1':['1', '3', '2', '6'],
          'key_column2':['1', '5', '2', '2'],
           'fourth_column':['1', '2', '2', '2'],
            }

    df2 = pd.DataFrame(data2)

Expected output:

A: Use pandas.concat to concatenate a list of dataframes. Then, use pandas.DataFrame.drop_duplicates() to drop the duplicate records. The pandas.DataFrame.drop_duplicates() function has a parameter called subset that you can use to determine which columns to include in the duplicates search. Here's how to do it, using the example you gave:

import pandas as pd

data1 = {
    "first_column": ["1", "2", "2", "2"],
    "second_column": ["1", "2", "2", "2"],
    "key_column1": ["1", "2", "2", "6"],
    "key_column2": ["1", "2", "2", "1"],
    "fourth_column": ["1", "2", "2", "2"],
}
df1 = pd.DataFrame(data1)

data2 = {
    "first_column": ["1", "2", "2", "2"],
    "second_column": ["1", "2", "2", "2"],
    "key_column1": ["1", "3", "2", "6"],
    "key_column2": ["1", "5", "2", "2"],
    "fourth_column": ["1", "2", "2", "2"],
}

df2 = pd.DataFrame(data2)

df_combined = (
    pd.concat([df1, df2])
    .drop_duplicates(subset=["key_column1", "key_column2"], keep="first")
    .reset_index(drop=True)
)
df_combined

The above code outputs the following:

If you want to wrapt it all inside of a function here's how you might consider doing it:
from __future__ import annotations
from typing import List
import pandas as pd

def concat_no_dups(*dfs: pd.DataFrame, key_columns: List[str] | str | None = None) -> pd.DataFrame:
    """
    Concatenate dataframes together and drop duplicates based on equality of
    selected columns.

    Parameters
    ----------
    dfs : pd.DataFrame
        A sequence of dataframes.
    key_columns : List[str] | str | None, optional
        The columns to use as keys to drop duplicates.
        If no list, or column provided, it uses all the columns
        from the concatenated dataframe, to search for duplicates

    Returns
    -------
    df_combined : DataFrame
        The concatenated dataframe with duplicate rows removed.

    Raises
    ------
    KeyError
        If one or more keys from `key_columns` do not exist in the dataframe,
        obtained after combining all `dfs` together.

    Examples
    --------
    >>> import pandas as pd
    >>> data1 = pd.DataFrame(
        [['a', 12], ['a', 15], ['b', 19], ['c', 18]],
        columns=['key', 'value']
    )
    >>> data2 = pd.DataFrame(
        [['a', 16], ['a', 10], ['b', 13], ['e', 19]],
        columns=['key', 'value']
    )
    >>> concat_no_dups(data1, data2, key_columns='key')
      key  value
    0   a     12
    1   b     19
    2   c     18
    3   e     19
    >>> concat_no_dups(data1, data2, key_columns=['key', 'value'])
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    >>> concat_no_dups(data1, data2)
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    >>> concat_no_dups(data1, data2, data1)
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    """
    df_combined = pd.concat([df for df in dfs])
    if key_columns is None:
        key_columns = list(df_combined.columns)
    elif not hasattr(key_columns, '__iter__') or isinstance(key_columns, str):
        key_columns = [key_columns]
    missing_keys = pd.Index(key_columns).difference(df_combined.columns)
    if not missing_keys.empty:
        raise KeyError(
            f"The following key columns weren't found: {list(missing_keys)}. "
            f"Available columns: {list(df_combined.columns.astype(str))}."
        )
    return df_combined.drop_duplicates(subset=key_columns).reset_index(drop=True)

A: You need first to concat"
df = pd.concat([df1, df2])

And then to remove duplicates by not leaving any of them (keep=False):
df.drop_duplicates(keep=False, inplace=True)
df

  first_column second_column key_column1 key_column2 fourth_column
3            2             2           6           1             2
1            2             2           3           5             2
3            2             2           6           2             2

if you need to reset the index, do:
df.reset_index(drop=True, inplace=True)
df

  first_column second_column key_column1 key_column2 fourth_column
0            2             2           6           1             2
1            2             2           3           5             2
2            2             2           6           2             2


text:
Q: Why is my x-value infinite if my position_hint is "x" instead of "left? In the following kv-code I assign x the value 0.1 and pos_hint["x"] x.
ball:
        id: bl_w
        x: 0.1
        pos_hint: {"x":self.x, "y":0.4}
        size_hint: .05, .05
        source: "ball.jpg"

print(widget.pos_hint) returns {'x': inf, 'y': 0.4} but if I change my kv code to pos_hint: {"left":self.x, "y":0.4}, print(widget.pos_hint) returns {'x': 0.1, 'y': 0.4}. Unfortunately, the value is then no longer relative to the screen size, which is why I do not want to use "left" for "pos_hint".
Thanks a lot in advance!

A: Your pos_hint triggers recursive update events, when it's used to position the ball then the ball's self.x changes, which triggers the pos_hint to update again, which causes self.x to change again, and so on.


text:
Q: Tensorflow: what does index denote in CUDA_1D_KERNEL_LOOP(index, nthreads) op user I have seen in several standard ops of tensorflow layers ( such as https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/maxpooling_op_gpu.cu.cc ), the code CUDA_1D_KERNEL_LOOP(index, nthreads) as part of the Forward and Backward passes...
I think the "index" here is related somehow to the bottom feature map coordinates but am not so sure of its exact meaning... Anyone who could help?

A: CUDA_1D_KERNEL_LOOP(i, n) is a preprocessor macro defined in tensorflow/core/util/cuda_kernel_helper.h. It provides a generic control flow statement that is used in many Cuda kernels within the Tensorflow codebase.
The statement is typically used for iterating through elements of an array within a kernel. The argument i is the name of the control variable and the argument n is the stopping condition for the control statement. Cuda kernels are launched in parallel threads. Each thread typically operates on a subset of array elements. The macro provides some convenience for accessing the desired array elements.
In the example that you link to, CUDA_1D_KERNEL_LOOP(index, nthreads) is interpreted as:
for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads; index += blockDim.x * gridDim.x)

Hence index is declared and initialized within CUDA_1D_KERNEL_LOOP before entering the subsequent code block. The precise meaning of index depends on how it is used within the code block.

A: One thing that puzzled me when I first read this macro is, "Why is it a loop, isn't this inside the kernel which has already been parallelized?"  The answer is, the loop handles the case when you have more "threads" than your GPU actually supports.
For example, suppose you are doing a parallelized vector addition, and you have decided that for your GPU, you will be using 512 threads per block, scheduling a maximum of 4096 blocks (these are the default parameters in Caffe2). This means that you can only schedule a maximum of 2097152 threads. Suppose your vector actually has 4M elements; now you can't actually allocate a thread per element. So each thread must be responsible for summing more than one element in the vector: that is what this loop is for!
Here is a smaller example which precisely describes how work ends up being scheduled. Suppose that blockDim.x == 2, gridDim.x == 2, and nthreads == 7. Then if we identify a GPU thread as (blockIdx.x, threadIdx.x), we allocate them to do the following work on the vector: [(0,0), (0,1), (1,0), (1,1), (0,0), (0,1), (1,0)]. In particular, we can see that according to the grid size, there are only four GPU threads available; so for blockIdx.x == 0 threadIdx.x == 0, index will handle processing the vector elements at BOTH 0 and 4.


text:
Q: Insert markup without loss of jQuery Mobile styling Hi I'm trying to make a collapsable list with dynamic data. I'm having a problem when I'm trying to insert some markup inside a div. More specifically all the html doesn't get styled by jQuery Mobile.
Here is a simplified version of how I'm trying to do it:
THE HTML

THE JAVASCRIPT
$(document).ready(function() {
    append();
});

function append() {
    var str =   '' +
                '
' +
                    '
' +
                        '
Måndag
' +
                        '<form>' +
                            '<fieldset data-role="controlgroup">' +
                                '<input type="checkbox" name="checkbox-monday-Coachtid" id="checkbox-monday-Coachtid">' +
                                'Coachtid' +
                                '<button data-theme="b">Spara</button>' +
                            '</fieldset>' +
                        '</form>' +
                    '
' +
                '
' +
                '';
    $("#testdiv").html(str).testdiv;
}

When I try to put str in like this with Javascript I end up with something like this:

But when just paste str as if it were written as is in the html file it looks like this:

My Question, is there any way to insert html inside a div and make it get rendered by jQuery Mobile and get that styling?
Thanks

A: $('#testdiv').trigger('create')


text:
Q: Chrome Extension - Canceling $interval on navigation I have a AngularJS app implemented in a Chrome Extension. It's using Content Scripts to inject itself into the user's pages as they navigate. In it there's an $interval that calls back to our servers every N seconds as a polling mechanism to check for new data to return to the client.
myInterval = $interval(function() {
    // calls back to server
}, 30000);

$scope.$on("$destroy", function() {
    if (angular.isDefined(myInterval)) {
        $interval.cancel(myInterval);
        myInterval = undefined;
    }
};

I noticed the traffic on our servers was increasing so I investigated and found that the query triggered by this interval is slamming our servers at a way higher rate than our users could possibly be triggering under expected conditions. For example, at a rate of 200+ requests per minute from the same user.
It seems the interval is staying alive even after navigating to a new page, closing the tab, etc. I've come to understand that listening for $destroy and canceling the interval takes care of routing changes within the app, but how do I make sure the interval is cancelled when a user undergoes normal browsing activity (since a new interval is about to be created when the next page is loaded)?

A: To listen for what you refer to ad "normal browsing activities", you can register a listener for window's onbeforeunload event.
$window.onbeforeunload = function (evt) {
    $interval.cancel(myInterval);
};


text:
Q: Rubymine for remote SDK. Gems downloading and suddenly stop I'm having this issue since yesterday and I am not sure what could be the problem. I have a Rails application that I want to run against a remote SDK installed on my VirtualBox (Ubuntu); yesterday I was able to set it up on another VM I have and when I went to Settings in Rubymine and added the SSH credentials, it took some time but finally a lot of gems were downloaded and I was able to run the project directly from Rubymine environment, trying to prepare everything for debug.
I had to change my VirtualBox and now when I connect to it via SSH it starts "Collecting files..." for a while and then "Downloading..." the gems... it looks like it restarts for a couple of times and then at some point, after a while and without any further notice, it stops.
If it helps, my host is Windows 7, my guest is Ubuntu 14.04; my RVM is 1.9.3-p392.
Any ideas? I'm surprised because this worked like a charm yesterday and today is not. Thank you in advance for any help.

A: What version is your Rubymine? I had issue back with version 6.x with remote rubies freezing the system. Also are you using a Vagrant box? I have seen some of the Vagrant boxes have issues as well. I would log in to the Ubuntu Guest via command line/SSH and see if you still have issues downloading gems.


text:
Q: Proving that the union of two vector sub spaces of the same space are not a sub space. I hope that I translated it correctly, correct me if I'm wrong :)
Let $V_1$ and $V_2$ be sub spaces of $L$.
Prove that $V_1\cup V_2$ is a vector sub space if and only if $V_1 \subseteq V_2$ or $V_2\subseteq V_1$
I was thinking of assuming it is correct and taking $2$ vectors from each subspace such that:
$$
t_1 \notin V_2 , t_2 \notin V_1 \\
t_1,t_2 \in V_1 \cup V_2
$$
Then :
$$t_1 + t_2 ∈ V1$$
This is where I am unsure how to explain my moves...
The teacher said it is incorrect, do you guys have any hints then, perhaps on how to refine a better mathematical 'language of reasoning' too?
I am new at this whole math world :)
Many thanks.

A: You are on the right track. Try to be slightly more strict in writing what you are doing as it will help you think and explain your thoughts.
What you want to prove is that if neither $V_1\subseteq V_2$ nor $V_2\subseteq V_1$ holds, then $V_1\cup V_2$ is not a vector space. For this, you have correctly chosen $t_1\in V_1\setminus V_2$ and $t_2\in V_2\setminus V_1$. Then you have chosen to calculate $t_1+t_2$.
The mistake you made here is writing $t_1+t_2\in V_1$, which is not something you have proven. Try to think about what you can prove about $t_1+t_2$. Hint: $t_1$ and $t_2$ are both elements of $V_1\cup V_2$. If $V_1\cup V_2$ is a vector space, what does that tell you about $t_1+t_2$?


text:
Q: jQuery - How to remove event handler only while an animation or function is running? I am attempting to create an image gallery. At the bottom I have a strip of thumbnails these thumbnails slide left and right when you click an arrow but if you click the arrow multiple times it ques the function.
I would like to remove the click handler while the function is run, then replace it again.
On a side note, my thumbnail scroller uses margin-left to animate, is it possible to use scrollTo or similar, to move an element a specific amount, horizontally, so if the thumbnails change size, it would still work?

A: There are many ways to do this. The easiest way is not to remove the click handler, but simply do nothing in the callback if it's animating already, eg:
$('.thumb').click(function() {
    if ($('#thumb-strip:animated').size() != 0)
        return;

    /* else animate #thumb-strip */
});

If you want to remove the click handler, and add it before, just do this:
var animateHandler = function() {
    var params = {}; // animate params
    $('.thumb').unbind('click', animateHandler); // unbind the click handler
    $('#thumb-strip').animate(params, function() {
        $('.thumb').click(animateHandler); // re-bind the click handler when animation is done
    });
};
$('.thumb').click(animateHandler);

Needless to say, the first way is simpler.
However what I usually do is not prevent the click event from happening, because the user won't expect that, but I also want to get rid of the queuing of animations. So what you can do is allow the user to click a thumb, and make it instantly animate to the new place with stop:
$('.thumb').click(function() {
    var params = {}; // animate params
    $('#thumb-strip').stop().animate(params);
});

This is the simplest and most intuitive solution.
And to answer your second question, you can use $(this).position() to get the thumb's relative position to the parent, and then animate based on that.


text:
Q: Update table in SQL I need to update two tables, I just try following two cases.
case 1: Update the two tables in one single query as,
UPDATE tableName1,tableName2
SET    tableName1.column1 = 12,
       tableName2.column1 = 12
WHERE  tableName1.column2 = 13
AND    tableName2.column2 = 13;

case 2: Update by two separate queries as,
UPDATE tableName1
SET    column1 = 12
WHERE  column2 = 13;

UPDATE tableName2
SET    column1 = 12
WHERE  column2 = 13;

Here case 1 take more time to execute the query as compared to case 2 why?
And which is the better method to do this operation?

A: You are using a Cartesian join of the two tables drastically increasing the number of rows being evaluated on a table of any decent size. Specify a join condition on indexed fields to resolve this.
These are also not equivalent queries in their functionality.

A: The first UPDATE is pointlessly complex.
The pair of independent UPDATE operations is able to make full use of indexes on Column2 in each table (if they're present), and will generally be much swifter.

A: In the first way, the database engine should do a join in order to find the particular records  to be updated. in the second way, its just two different updates on two different table, the time, resources to do the 2 table join is saved. hence the second way is more preferred.

A: If you are using a Stored Procedure you can use separate queries and yet need to pass the values in to the procedure as parameters. It is better to use the second method if there is no special case such as both the tables need to be updated at the same time etc.


text:
Q: C# Check url exist? How can I check whether a page exists at a given URL?
I have this code:
private void check(string path)
    {

        try
        {
            Uri uri = new Uri(path);
            WebRequest request = WebRequest.Create(uri);
            request.Timeout = 3000;
            WebResponse response;
            response = request.GetResponse();

        }
        catch(Exception loi) { MessageBox.Show(loi.Message); }

    }

But that gives an error message about the proxy. :(

A: First,  you need to understand that your question is at least twofold,
you must first check if the server is responsive, using ping for example - that's the first check, while doing this, consider timeout, for which timeout you will consider a page as not existing?
second, try retrieving the page using many methods which are available on google, again, you need to consider the timeout, if the server taking long to replay, the page might still "be there" but the server is just under tons of pressure.

A: If the proxy needs to authenticate you with your Windows credentials (e.g. you are in a corporate network) use:
WebRequest request=WebRequest.Create(url);
request.UseDefaultCredentials=true;
request.Proxy.Credentials=request.Credentials;

A: try
{
    Uri uri = new Uri(path);
    HttpWebRequest request = HttpWebRequest.Create(uri);
    request.Timeout = 3000;
    HttpWebResponse response;
    response = request.GetResponse();
    if (response.StatusCode.Equals(200))
    {
        // great - something is there
    }
}
catch (Exception loi)
{
    MessageBox.Show(loi.Message);
}

You can check the content-type and length, see MSDN HTTPWebResponse.

A: At a guess, without knowing the specific error message or path, you could try casting the WebRequest to a HttpWebRequest and then setting the WebProxy.
See MSDN: HttpWebRequest - Proxy Property


text:
Q: weird response from server with ajax EDIT:
Apparently they add this to free hosting pages to prevent abuse. But I got rid of it by adding "exit;" on the end.
ENDofEDIT
I made a function called ajax, so I wouldn't have to write the code everywhere I need it and it works great.
But now as response I always get the data I expected as the response plus this:

I check the data with if (xmlhttp.readyState == 4 && xmlhttp.status == 200){alert(xmlhttp.responseText);}
I'm sure the code is ok because it is the same code I used before. Here it is:
function ajax(adress, thenDo)
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            thenDo(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET",adress,true);
    xmlhttp.send();
}

Does anyone know how to get rid of this?
And I just checked it is on bottom on every page of mine on that server. (I'm using free hosting on hourb hosting)

A: This is almost certainly being added by your hosting provider, and its usage is one of the things that helps keep your free hosting free.
On the plus side, they would only be adding this for certain content-types, so you may want to check that your data is being returned as text/xml. If it is, then I would recommend contacting them directly, and asking if the configuration can be altered to exclude XML files.


text:
Q: Elasticsearch notifications Is it possible what Elasticsearch will notify if an object was added and it corresponds to some criteria?
For example if it has category_id=4 and it has in title or in description word "iphone" Elasticsearch should notify.
version: 5.1.1

A: You can use ElastAlert by Yelp to send alerts. This is a free application, and is easy to set up.
Once installed, create a Blacklist rule; it "... will check a certain field against a blacklist, and match if it is in the blacklist."
Your Blacklist rule might look like this:
es_host: localhost
es_port: 9200

name: category_id_is_4-Blacklist

type: blacklist

index: logstash-*

compare_key: category_id

blacklist:
- "4"

realert:
  hours: 4

filter:
- query_string:
    query: "title:*iphone* OR description:*iphone*"

alert:
- "jira"
- "slack"

slack_webhook_url: https://hooks.slack.com/services/XYZ/XYZ/XYZ

jira_server: https://XYZ.atlassian.net
jira_project: XYZ
jira_issuetype: Task
jira_account_file: /home/user/elastalert/rules/jira_acct.txt

You would then receive a notification to Slack and Jira. You can also set up ElastAlert for other alerts, you are not limited to Slack and Jira.

A: You can use the Watcher of the x-pack. I would set it up with a query that filters "unacknowledged documents" with the rest of the query, (category:4 "iPhone" etc) and the action would update that document to be "acknowledged" after the notification is handled and no longer relevant to the query.
https://www.elastic.co/guide/en/x-pack/current/how-watcher-works.html


text: Q: How to automatically add to the address book the addresses from emails I've received in Outlook Express 6? I have quite a few saved emails in Outlook Express. Is there some way to automatically get the email addresses of their senders and add them to the address book? I can do some programming if it's necessary.


text:
Q: Different Behavior Depending on the Data Let's make it a simple example. Suppose I have a collection of Number objects, which can then be even or odd.
Suppose I want to traverse this collection and process each element. The process depends on the type of element: even or odd.
Example: Print each element, such that:

*

*if Number is even, I have "This is an even number."

*if Number is odd, I have "This is an odd number."
However, I may decide later that I want for only the even numbers to print "An even number."
So, as we see, this could be solved with Inheritance and Polymorphism, through the use of virtual functions:
class Number {/*...*/};              // base class
class Even : public Number {/*...*/} // derived class
class Odd  : public Number {/*...*/} // derived class

However, how can I provide the flexibility in the process to execute different behavior later on, as shown in the example above? Also, is there an alternative way to inheritance and polymorphism? Because I did not wanted to create inheritance tree only because of a specific computation/process.
The original problem is to execute different mathematical model depending on the type of an object, and the mathematical model is not unique for a given type of object (as the way I can print the even number is not unique).

Edit: It is funny that this post was closed with the argument that it is difficult to tell what is being asked. The authors of the several answers below seem to not agree with this, since all of them could understand it and reply what I was looking for.

A: Well, you could use a Strategy pattern:  have two classes EvenStrategy and OddStrategy, put the behavior in them, and add then to the Even and Odd classes at construction orm when you insert them in the collection.

A: You could separate your Strategy hierarchy from the actual numbers. This way there is no need for an artificial class hierarchy, and you are free to change associations between number (value) types and actions even runtime. The association can be defined

*

*if you stick to the Number class hierarchy, then between Number subclass (Odd, Even) and strategy class (OddNumberStrategy, EvenNumberStrategy), or

*by a mapping between concrete values and strategy instances (of course this is suitable only if you have relatively few concrete values), or

*by a selector function.

As an alternative approach, you can redefine your Strategies as handlers, each of which can decide whether a given value is suitable for them to handle, and process them if so. Such handlers could even be chained or stored in a collection (and then iterated over for every value), such that some values can be processed by multiple "overlapping" handlers, if this suits you.

A: There are several ways to solve this, but in general they all use composition. Let's take your example. Say we have an array of integers:
int foo[] = {0,1,2,3,4,5,6,7,8,9};

Now, we want to print all the odd numbers from that:
void printIfOdd(int number) {
    if(number % 2 == 1)
        std::cout << number << std::endl;
}

std::for_each(foo, foo+10, printIfOdd);

We could do the same for even numbers. If you want to print both, you can compose the functions (which in this case is not in the mathematical sense of function composition):
template<class T>
class apply_all_functor {
public:
    apply_all_functor(T f1, T f2) : f1(f1), f2(f2) {}

    void operator()(int number) {
        f1(number);
        f2(number);
    }
private:
    T f1, f2;
};

template<class T>
apply_all_functor<T> apply_all(T f1, T f2) {
    return apply_all_functor<T>(f1, f2);
}

std::for_each(foo, foo+10, apply_all(printIfOdd, printIfEven);

The idea of composition can of course also be extended to objects, which gives rise to patterns like the Strategy-Patter and the Decorator-Pattern. You can see all full example of the code here.


text:
Q: Angular http calls for local server getting redirect to https I am running python flask application on my local.
Developing angular UI on local environment, One of the call is getting redirect from http to https. Rest of the calls are working fine.
Any suggestions?


text:
Q: AMQP Library not loading for apache2, ubuntu 14.04 I am trying to install Rabbit MQ and the php library AMQP on Ubuntu 14.04, but am receiving an error upon apache start (in apache error log)
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/amqp.so' - /usr/lib/php5/20121212/amqp.so: undefined symbol: amqp_error_string2 in Unknown on line 0

And AMQP does not start.
I followed this: https://github.com/pdezwart/php-amqp/issues/87
And...
locate librabbitmq.so

returns:
/usr/lib/librabbitmq.so.0
/usr/lib/librabbitmq.so.0.0.0

ls -al librabb* returns:
/usr/lib/librabbitmq.so.0 -> librabbitmq.so.0.0.0  (root / root)
librabbitmq.so.0.0.0 (root / root)

In /user/local/lib there is also:
librabbitmq.so -> /usr/lib/librabbitmq.so.0 (root / root)

Permissions are root/root and 755 on all.
Any help, most appreciated.
Thanks

A: Installing amqp via pecl didn't worked for me so i had to compile the RabbitMQ C AMQP client library and pecl amqp myself.
RabbitMQ C AMQP Client library can be found at https://github.com/alanxz/rabbitmq-c/
and Pecl amqp from http://pecl.php.net/package/amqp .
Here is a list of commands that should do the trick on ubuntu 14.04:
#create a directory for sources
mkdir ~/kit
cd ~/kit

#download and install the rabbitmq c amqp lib
wget https://github.com/alanxz/rabbitmq-c/releases/download/v0.5.1/rabbitmq-c-0.5.1.tar.gz
tar -zxvf rabbitmq-c-0.5.1.tar.gz
cd rabbitmq-c-0.5.1/
./configure
make
sudo make install

cd ..

#download and compile the amqp
wget http://pecl.php.net/get/amqp-1.4.0.tgz
tar -zxvf amqp-1.4.0.tgz
cd amqp-1.4.0/
phpize && ./configure --with-amqp && make && sudo make install

#Add amqp extension to php mods-availabile directory
echo "extension=amqp.so" > /etc/php5/mods-available/amqp.ini

#Enabled it in cli
cd /etc/php5/cli/conf.d/
ln -s ../../mods-available/amqp.ini 20-amqp.ini
php -m | grep amqp

#Enabled it in cli
cd /etc/php5/apache2/conf.d/
ln -s ../../mods-available/amqp.ini 20-amqp.ini

#restart Apache and than check phpinfo on web
service apache2 restart


text:
Q: Get Max value comparing multiple columns and return specific values I have a Dataframe like:
Sequence    Duration1   Value1  Duration2   Value2  Duration3   Value3
1001        145         10      125         53      458         33
1002        475         20      175         54      652         45
1003        685         57      687         87      254         88
1004        125         54      175         96      786         96
1005        475         21      467         32      526         32
1006        325         68      301         54      529         41
1007        125         97      325         85      872         78
1008        129         15      429         41      981         82
1009        547         47      577         52      543         83
1010        666         65      722         63      257         87

I want to find the maximum value of Duration in (Duration1,Duration2,Duration3) and return the corresponding Value & Sequence.
My Desired Output:
Sequence,Duration3,Value3
1008,    981,      82

A: With wide data it can be easier to first reshape with wide_to_long. This creates 2 columns ['Duration', 'Value'], and the MultiIndex tells us which number it was. There is no reliance on any specific column ordering.
import pandas as pd

df = pd.wide_to_long(df, i='Sequence', j='num', stubnames=['Duration', 'Value'])
df.loc[[df.Duration.idxmax()]]

              Duration  Value
Sequence num
1008     3         981     82

A: Without using numpy wizardry:

*

*First, there are some really great solutions to this problem, by others.

*Data will be that provided in the question, as df
# find the max value in the Duration columns
max_value = max(df.filter(like='Dur', axis=1).max().tolist())

# get a Boolean match of the dataframe for max_value
df_max = df[df == mv]

# get the row index
max_index = df_max.dropna(how='all').index[0]

# get the column name
max_col = df_max.dropna(axis=1, how='all').columns[0]

# get column index
max_col_index = df.columns.get_loc(max_col)

# final
df.iloc[max_index, [0, max_col_index, max_col_index + 1]]

Output:
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

Update

*

*Last night, actually 4 a.m., I dismissed a better solution, because I was overly tired.

*

*I used max_value = max(df.filter(like='Dur', axis=1).max().tolist()), to return the maximum value within the Duration columns

*Instead of max_col_name = df.filter(like='Dur', axis=1).max().idxmax(), to return the column name where the maximum value occurs

*I did that because my addled brain told me I was returning the max value of the column names, instead of the maximum value in the column.  For example:

test = ['Duration5', 'Duration2', 'Duration3']
print(max(test))
>>> 'Duration5'

*

*This is why being overtired, is a poor problem solving condition

*With sleep, and coffee, a more efficient solution

*

*Similar to others, in the use of idmax
New & Improved Solution:
# column name with max duration value
max_col_name = df.filter(like='Dur', axis=1).max().idxmax()

# index of max_col_name
max_col_idx =df.columns.get_loc(max_col_name)

# row index of max value in max_col_name
max_row_idx = df[max_col_name].idxmax()

# output with .loc
df.iloc[max_row_idx, [0, max_col_idx, max_col_idx + 1 ]]

Output:
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

Methods used:

*

*pandas.DataFrame.max

*pandas.DataFrame.filter

*pandas.DataFrame.idxmax

*pandas.Index.get_loc

*pandas.DataFrame.iloc

A: You can obtain the index of the maximum value of a column using:
>>> idx = df['Duration3'].idxmax()
>>> idx
7

And the relevant columns only using:
>>> df_cols = df[['Sequence', 'Duration3', 'Value3']]
>>> df_cols.loc[idx]
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

So, simply wrap all that up into one nice function:
def get_max(df, i):
    idx = df[f'Duration{i}'].idxmax()
    df_cols = df[['Sequence', f'Duration{i}', f'Value{i}']]
    return df_cols.loc[idx]

And loop over 1..3:
>>> max_rows = [get_max(i) for i in range(1, 4)]
>>> print('\n\n'.join(map(str, max_rows)))
Sequence     1003
Duration1     685
Value1         57
Name: 2, dtype: int64

Sequence     1010
Duration2     722
Value2         63
Name: 9, dtype: int64

Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

If you want to reduce these 3 down to a single maximum row, you can do the following:
>>> pairs = enumerate(max_rows, 1)
>>> by_duration = lambda x: x[1][f'Duration{x[0]}']
>>> i, max_row = max(pairs, key=by_duration)
>>> max_row
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

A: If I understand the question correctly, given the followind dataframe:
df = pd.DataFrame(data={'Seq': [1, 2, 3], 'Dur1': [2, 7, 3],'Val1': ['x', 'y', 'z'],'Dur2': [3, 5, 1], 'Val2': ['a', 'b', 'c']})
    Seq  Dur1 Val1  Dur2 Val2
0    1     2    x     3    a
1    2     7    y     5    b
2    3     3    z     1    c

These 5 lines of code solve your problem:
dur_col = [col_name for col_name in df.columns if col_name.startswith('Dur')] # ['Dur1', 'Dur2']
max_dur_name = df.loc[:, dur_col].max().idxmax()
val_name = "Val" + str([int(s) for s in max_dur_name if s.isdigit()][0])

filter_col = ['Seq', max_dur_name, val_name]

df_res = df[filter_col].sort_values(max_dur_name, ascending=False).head(1)

And you get:
   Seq  Dur1 Val1
1    2     7    y

Code explanation:
I automatically get the columns that start with 'Dur', and I find the column name with a longer duration:
dur_col = [col_name for col_name in df.columns if col_name.startswith('Dur')] # ['Dur1', 'Dur2']
max_dur_name = df.loc[:, dur_col].max().idxmax()
val_name = "Val" + str([int(s) for s in max_dur_name if s.isdigit()][0])

Choose the columns I'm interested in:
filter_col = ['Seq', max_dur_name, val_name]

Filter the columns that interest me, I order for max_dur_name and I get the search result:
df_res = df[filter_col].sort_values(max_dur_name, ascending=False).head(1)

# output:
   Seq  Dur1 Val1
1    2     7    y

A: Here is another way ,
m=df.set_index('Sequence') #set Sequence as index
n=m.filter(like='Duration') #gets all columns with the name Duration
s=n.idxmax()[n.eq(n.values.max()).any()]
#output Duration3    1008
d = dict(zip(m.columns[::2],m.columns[1::2])) #create a mapper dict
#{'Duration1': 'Value1', 'Duration2': 'Value2', 'Duration3': 'Value3'}
final=m.loc[s.values,s.index.union(s.index.map(d))].reset_index()

   Sequence  Duration3  Value3
0      1008        981      82

A: A bit similar to @Massifox's answer, but I think is different enough to be worthy to be added.
mvc = df[[name for name in df.columns if 'Duration' in name]].max().idxmax()
mvidx = df[mvc].idxmax()
valuecol = 'Value' + mvc[-1]
df.loc[mvidx, ['Sequence', mvc, valuecol]]

*

*First I get the column name mvc where the maximum value is located (mvc is 'Durantion3' following your example).

*Then I get the row index mvidx of the maximum value (mvidx is 7).

*Then I build the correct Value column (valuecol is 'Value3').

*Finally with loc I select the desired output, which is:
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

A: Try the following, quite short code, based mainly on Numpy:
vv = df.iloc[:, 1::2].values
iRow, iCol = np.unravel_index(vv.argmax(), vv.shape)
iCol = iCol * 2 + 1
result = df.iloc[iRow, [0, iCol, iCol + 1]]

The result is a Series:
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

If you want to "rehape" it (first index values, then actual values),
you can get something like this executing:
pd.DataFrame([result.values], columns=result.index)

A: if len(df[df[dur1]>=df[dur2].max()])==0:
    if len(df[df[dur2]>=df[dur3].max()])==0:
        print(df[df[dur3].idmax()][[seq,dur3,val3]])
    else:
        print(df[df[dur2].idmax()][[seq,dur2,val2]])
else:
   if len(df[df[dur1]>=df[dur3].max()])==0:
       print(df[df[dur3].idmax()][[seq,dur3,val3]])
   else:
       print(df[df[dur1].idmax()][[seq,dur1,val1]])


text:
Q: JavaScript - proxy object to behave like primitive I'm trying to build a system that "caches" calls to a library before that library has loaded.
This is similar to what the Google Analytics "setup" code is doing with the _gaq variable - it's initialized as an array that "caches" calls to the real analytics endpoints until the ga.js library has loaded. When it does, it reads _gaq and replays the calls.
We decided to do this because our legacy code contains a lot of calls to a particular library which is loaded synchronously in <head>. This greatly increases the time to first contentful paint, as a lot of JS is evaluated and executed.
However, there are too many places in the code that would need to be changed (wrapped in a 'DOMContentLoaded' listener), so we decided to try using  workaround.
We decided to try using Proxy to catch calls to our library's methods, and replay them once it's ready:
// Original code:
var ourLib = new OurLib({ ... });

// Throughout the site, calls such as:
var res1 = ourLib.doThis();
var res2 = ourLib.getThat(3);

Here's a sort-of "simplified" version of what our new code is doing:
// New code:
var ourLib = new Proxy({
    calls: [],
}, {
    get(target, prop) {
        if (prop in target) {
            return Reflect.get(...arguments);
        }

        const callref = { prop, args: [], placeholder };
        target.calls.push(callref);

        return function(...args) {
            const placeholder = MakeResultPlaceholder(...);

            callref.args = args;
            callref.placeholder = placeholder;

            return placeholder;
        };
    },
});

// Throughout the site, calls continue as before, except now they're 'stored' in `calls`
var res1 = ourLib.doThis();
var res2 = ourLib.getThat(3);

// Much later, the original lib is loaded, and
var ourRealLib = new OurLib({ ... });
__playbackCalls(ourLib.calls, ourRealLib);

// Replace the proxy with the real thing
ourLib = ourRealLib;

After the run above, the calls property will be something like this:
[
    {
        prop: 'doThis',
        args: [],
        reference: ResultPlaceholder
    },
    {
        prop: 'getThat',
        args: [3],
        reference: ResultPlaceholder
    }
]

The __playbackCalls function iterates through the calls array and apply each method from ourRealLib with the args stored in each object.
calls.forEach(({ prop, args, reference }) => {
    reference._value = ourRealLib[prop].apply(ourRealLib, args);
});

The problem comes when the result of the proxy's calls needs to be used. Right now, as you can see, the calls return a placeholder object (which is in itself another proxy). These placeholders hold a _value property that becomes populated during "playback".
So here's the question:

*

*Let's say ourLib.getThat() is meant to return a number.

*During the first "run", because of the whole proxy thing, res1 will point to a placeholder object: Proxy { _value: undefined }

*The real lib is loaded, "playback" finishes, ourRealLib.getThat(3) returns 23, so res1 will be Proxy { _value: 23 }

*Can I do anything so that we can use res1 as a number? Something like:

console.log(res1 * 2); // 46


text:
Q: Understanding the coverage summary for dotCover in TeamCity I'm running dotCover coverage in Teamcity. After the build it constructs the coverage report in which you can drill down to individual class coverage.
I have a class containing 1 method that produces the following summary.

Class, %
  100% (1/1)
Method, %
  86.7% (13/15)
Statements, %
  91.7% (55/60)

Class and statement results seem straight forward but I can't see how to interpret the method result.
What have I got 15 of (of which 13 are covered)?
Update
Here is the gist of the class
    public static class MyClass
    {
        public static List<B> Bye(X x, B b)
        {
            List<B> bList = new List<B>();

            if (x is A)
            {
                // Do something
            }
            else if (x is B)
            {
                // Do something else
            }

            if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

             if (b.Something)
            {
               x.Where.ToList().Foreach(x => x.Work());
            }

            return bList;
        }
    }

A: I would say it was 13 of 15 methods covered (or at least one statement executed in each method marked as covered/visited). If you can't see all the methods then remember that get/set of properties are also methods; they may also include the default constructor in that figure but I would have though it unlikely.
For most coverage tools I've used, I use statement coverage as my main value and method coverage(visited) next.


text:
Q: I am trying to do an if statement with the input to be 21 and the result be Time printed out So first of all I want to know is there something that goes if Hello = 18 print Hello.
My code looks like this I want it to print out time which is already a working variable. I want if Hello = 21 but it doesn't do =. I also want to know why I can't just do print Time.
Hello = (input("What is 10 + 9 "))
if Hello > 20:
print Time`

A: import datetime

hello = input("What is 10+9?")

if hello > 20:
   print(datetime.datetime.now)

A: You want to use the == operator , that is the one for checking equality.
Example -
Hello = int(raw_input("What is 10 + 9 "))
if hello == 21: print Time

Also, since you are using Python 2.x , you should use raw_input() and then convert it to int (As i did above).
input() in Python 2.x evaluates whatever is inputted, which may be dangerous.


text:
Q: Failover to secondary origin if primary origin responds with expired content? I'm using a S3 bucket as my primary origin. It contains cached HTML with an Expires header.
I want Cloudfront to notice when the Expires date is past and try my secondary origin instead of forwarding the expired response to the viewer.
Is this possible?


text:
Q: Sending socket to a Wi-Fi controller in Python Is it possible to send socket to a Wi-Fi module? I have a Wi-Fi led controller and I would like to make it possible to control it without connecting manually to the controller.

Code:
def send(text):
ip = "10.10.123.3"
port = 48899

byte_array = convert_to_bytes(text)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ip, port))
s.send(byte_array)
s.close()

The code is working correctly if I'm connecting to it.