text:
Q: Software for unit aware calculations? When doing engineering calculations it is great convenience to do have software that keeps track of units.
Example when calculate something trivial as stress:
$\sigma = \frac FA$
And be able to write:
$\frac {1kN}{1m*1mm}$ and get the answer in MPa
This is by nature a poll thread that i know is frowned upon on StackOverflow, is it going to be closed?

A: Google Calculator does this nicely for units it knows about:

And you can't beat the price.

A: One of the top search results for "units software" is the appropriately named GNU Units, which lets you say
You have: ten furlongs per fortnight
You want: kilometers per hour

and tells you "0.0059871429".

A: There is SpeQ Mathematics for Windows environments. It is probably more of what your looking for.
http://www.speqmath.com/index.php?id=1

A: insect has both web- and terminal-based versions. It does support parsing, handling and conversion of physical units, for example:
>>> 4kN / (0.8m * 2mm) -> MPa

   = 2.5MPa

>>> 2min + 30s

   = 2.5min

>>> 40000km / speedOfLight -> ms

   = 133.426ms

>>> 6Mbit/s * 1.5h -> GB

   = 4.05GB

>>> 2J·s + 3W

  Unification error:

    Cannot unify unit W (base units: kg·m²·s⁻³)
            with unit J·s (base units: kg·m²·s⁻¹)

A: I'll add F# to the list.

Floating point and signed integer values in F# can have associated
  units of measure, which are typically used to indicate length, volume,
  mass, and so on. By using quantities with units, you enable the
  compiler to verify that arithmetic relationships have the correct
  units, which helps prevent programming errors.

A: MathCad handles units in a nice way but it is too expensive for home use.

A: You might be interested in Frink.
It has an interpreter that you can download as a desktop app. It also has a web interface, which lets you type
in  >> 1 kN / (1 m * 1 mm)
out >> MPa

to get
result >> 1 MPa

There is a list of sample calculations covering a wide variety of physical applications.

A: I'll throw my hat in the ring too. Maxima [1] has an add-on package ezunits which carries out various dimensional operations. Quantities can be symbolic (e.g. x meters per year) as well as numerical. The notation is, I hope, convenient: single left quote to indicate units, double left quote to indicate conversions. For the given example:
load (ezunits);
F : 1 ` kN;
A : 1 ` m * 1 ` mm;
sigma : F/A `` MPa;
  => 1 ` MPa

There's more to be said, but I'll let it be enough for now. Disclaimer: I wrote the ezunits package.
[1] http://maxima.sourceforge.net

A: The Squants library provides units of measure for Scala, including a natural-language DSL:
val load1: Power = Kilowatts(12)        // returns Power(12, Kilowatts) or 12 kW
val load2: Power = Megawatts(0.023)     // Power: 0.023 MW
val sum = load1 + load2                 // Power: 35 kW - unit on left side is preserved
sum should be(Kilowatts(35))
sum should be(Megawatts(0.035))         // comparisons automatically convert scale

val load1 = 100 kW                  // Simple expressions don't need dots
val load2 = 100 megaWatts
val time = 3.hours + 45.minutes     // Compound expressions may need dots

(Example taken from the README.)

A: I would suggest finding a package for doing this in your programming language of choice, since you're going to be using that to check/automate your engineering calculations anyways.
For R
The units library is one option. It looks something like this:
> library('units')
> m <- ud_units$m; mm <- ud_units$mm; kN <- ud_units$kN; MPa <- ud_units$MPa
> sigma <- 1*kN/(1*m * 1*mm)
> units(sigma)= MPa
> sigma
1 MPa

If you try an operation that mixes dimensions, it throws an error:
> 1*m + sigma
Error: cannot convert MPa into m

However, if you try an operation that mixes units of the same dimensions, it just puts the result in one of those units:
> 1*m + 1*mm
1.001 m

I haven't used the units library enough to vouch for its stability, but R libraries are typically very stable and well tested.
For Python:
There are a few options available (one of the curses of a language that's popular among CS folks), but I think the magnitude module is the cleanest looking. It works like this:
>>> from magnitude import mg
>>> x= mg(1,'m')
>>> y= mg(1,'mm')
>>> F= mg(1,'kN')
>>> sigma= F/(x*y)
>>> print(sigma.ounit('MPa'))
1.0000 MPa

This module still has a semi-serious bug which causes it to give very misleading output if you try to assign an invalid unit to an existing variable. It also has the downside that you can't freely switch between the objects created my mg() and the usual numeric types. e.g., instead of numpy.pi*mg(5,'m')**2 you'd have to wrap pi in mg() with no units as in mg(numpy.pi)*mg(5,'m')**2.

A: Frink Programming Language
Frink is a practical calculating tool and programming language designed to make physical calculations simple, to help ensure that answers come out right, and to make a tool that's really useful in the real world. It tracks units of measure (feet, meters, kilograms, watts, etc.) through all calculations, allowing you to mix units of measure transparently, and helps you easily verify that your answers make sense. It also contains a large data file of physical quantities, freeing you from having to look them up, and freeing you to make effortless calculations without getting bogged down in the mechanics.
Homepage
Samples

A: There is also SpeedCrunch. Is FOSS (free and opensource software) and Cross-platform (Windows + MAC + Linux).
You can calculate 25 meters + 8 foot in angstrom and it will return the result in Ansgtroms. It's also possible to define functions.

A: As free (but not open source) alternative to Mathcad with very similar user interface there is a windows software under https://smath.info .
There is a cloud version and free software download.
I use it for chemical engineering calculations at a vocational school.


text:
Q: Change citation conjunction from "and" to "och" using apalike and natbib in OVERLEAF I am using overleaf, the bibliography style 'apalike' and the usepackage 'natbib'. In the output, the citations use the conjunction "and" between two authors. However, I'm writing in Swedish so I want the conjunction to be "och".
I have seen the other posts regarding this subject, like Change citation conjunction from "and" to "i", which seems to discuss the same issue. However, I'm not sure how to incorporate the suggested changes in the overleaf editor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If Blank Cell Shift Cells Up I want to enter data on column D based on column A without the blank cells.
  A B C D F
1 X     X
2       Y
3 Y     Z
4 Z
5

I need a formula for the formula bar since column A changes dynamically. So manually sorting the data using excel settings for rows et cetera won't help.

A: For Excel 365 only:
In D1 enter:
=FILTER(A:A,LEN(A:A))

(if you do not have Excel 365, ignore this answer)


text:
Q: Using Bootstrap Datepicker with Highcharts I am trying to implement the solution here: Highstock + Bootstrap datepicker but I end up with an Undefined error in my console.
jsFiddle: http://jsfiddle.net/rlsaj/r6es2jyc/.
  setTimeout(function () {
        $('input.highcharts-range-selector', $(chart.container).parent())
            .datepicker({
            format: "dd/mm/yyyy",
            todayBtn: "linked",
            orientation: "auto left",
            autoclose: true,
            todayHighlight: true
        });
    }, 0);

My goal is to implement the Angular Bootstrap datepicker (http://angular-ui.github.io/bootstrap/) but I think I can solve that if the above fiddle can be fixed.

A: 1.) bootstrap requires a more recent jQuery version.
2.) bootstrap does not contain a native datepicker.  I imagine you want to use this, so you'll need to source it in:
<script src="http://rawgit.com/eternicode/bootstrap-datepicker/release/js/bootstrap-datepicker.js"></script>

3.) setDefaults is a method of jquery-ui's datepicker not the bootstrap implementation I link above.
Updated fiddle.


text:
Q: Print a div as PDF in lightning I am trying to print a PDF on a Lightning page using the jsPDF library.
A first problem is that when wanting to execute the following code, it tells me that the 'save' function is not defined.

var pdf = new jsPDF('p','pt','a4');
  pdf.text(20, 20, 'Hello world.');
  pdf.output('save', 'filename.pdf');

I added the FileSaver library using the saveAs method, but it did not solve the problem either.
The same thing happens to me when I want to use other functions of the jsPDF library, such as addHTML.
Has anyone successfully tested printing part of a lightning document in PDF?

A: I have been doing some PoC and I can use jsPDF to download a PDF with some text (I can't add HTML until now)
You can download and deploy it from my git hub


text:
Q: Android Button Response Problem hi all
since i am using a button and on the click of that button it connects to a Web Service.
But the problem is that when i press the button it does not showed me that it has been clicked and goes to connect to the internet and web service. after connecting it shows me the response that it has been clicked. in short the response of button is very slow. if that buton has some INternet connectvity in its Listener.
i know it has something to do with UI thread. but please friends guide me through this.
Thanks a bunch,

A: You have to use Handler for this background operation already ask on OS follow this link
progress dialog not showing in android?

A: You should write a class say MyWebService and extend it from AsyncTask. Perform the connect operation in its overridden doInBackground() method and update any UI changes in its onPostExecute() method.

A: Create a new Thread in the onClickListener that does the heavy work in the background. That way the UI thread will be able to update the state of the button:
button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        new Thread(new Runnable() {

        @Override
        public void run() {
            // Code that connects to web service goes here...
        }
    }).start();
});

A: Put the following code in your class:
 // Need handler for callbacks to UI Threads
    // For background operations
    final Handler mHandler = new Handler();

    // Create Runnable for posting results
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            // Do your task which needs to get done after webservice call is complete.
        }
    };

And for calling the webservice use the following code in button event:
new Thread() {
            public void run() {
                // Place the webservice call here.

                mHandler.post(mUpdateResults);
            }
            }.start();

Actually what are you looking for is multithreading, all the webservice calls and network activities should go in separate thread.
After the thread start() call you can do what ever you want and would be done instantly without any delay (in your case showing that button pressed).


text:
Q: Can I use an Azure Dev Ops build definition both for a Release Management pipeline and a pull request but with the latter not triggering the pipeline In short; we want to use a build definition to both generate artifacts for  Release Management and checking Pull Requests, but not allow the latter to trigger a new release.
We have CI build definition on our Git Repo feeding artifacts into a Release Management Pipeline. Like many teams we also have Pull Requests set up to protect our git master. We'd like to reuse our CI build to validate Pull Requests before they are merged in but doing so automatically triggers our release pipeline (bypassing the merge to master).
We've been working round this so far by duplicating builds but that feels clunky. Looking through the documentation there isn't an obvious way to filter a Release Trigger, or skip the publishing step in the build. I feel there must be away of preventing the trigger without duplicating the build but I can't see it!

A: There is no out of box feature to achieve this for now, there is already a similar feature request submitted on VSTS User Voice and you can vote it: Trigger release definition only for specific branches.
The alternative way to achieve to this would updating your release definition to configure it to be triggered by "Manual", and then add a PowerShell script task in your build definition to check the source refs of current build and then trigger the release via VSTS Rest API.

A: I'm not sure if this is too old a question for this answer to be valid, but if you're now using Azure DevOps (formerly VSTS) you can accomplish this by using the Control Options: Custom Conditions for the task of the CI build that publishes the artifacts.

A: The ability to trigger releases based on the build's refspec isn't a capability at present.

A: Azure Dev Ops now has a way of achieving this behaviour. You can modify the Continuous Deployment trigger for a Release definition. The two applicable options are:

*

*Disable the (handily titled) Pull Request trigger

*Add a branch filter i.e. include only master

Note another answer suggested making the artifact upload conditional, however we still needed the artifact for other reasons.

A: In Azure DevOps I wasn't able to fully stop the releases from triggering but I was able to sort circuit them getting the branch that triggered the release and then using a custom condition on my release tasks, skip them if the triggering branch was merge
PowerShell task
Below is the PowerShell I'm currently using in the very first task
# Use the triggering artifact alias and constructing the name of the variable that will ultimately get us the source branch that triggered the release
$SrcBranchName = "RELEASE_ARTIFACTS_$(('$(RELEASE.TRIGGERINGARTIFACT.ALIAS)' -replace '(^\s+|\s+$)','' -replace '\s+','_').ToUpper())_SOURCEBRANCHNAME"

# Get the environment variable that holds the name of the source branch
$SrcBranchName = Get-Item  env:$SrcBranchName | Select-Object -ExpandProperty Value
Write-Host "SrcBranchName: $SrcBranchName"

if ($SrcBranchName -eq "merge") {
    Write-Host "Release caused by a PR - no further steps will run."
}

# Set an environment variable with the source branch name for use in a Custom Conditions Control
Write-Host "##vso[task.setvariable variable=TriggeringArtifactSourceBranchName;]$SrcBranchName"

Custom Condition
Then for my custom conditions in each task, I use the following which skips the task if the TriggeringArtifactSourceBranchName is set to merge.
and(succeeded(), ne(variables['TriggeringArtifactSourceBranchName'], 'merge'))


text:
Q: How to use multiple checkbox and a submit button to retrieve firebase realtime database data I want to retrieve specific data from firebase. Example, specific actor from database if the submitted checkbox id is matched with genre of an actor

A: You can use orderByChild
List<string> actors = new ArrayList<>();

   foreach(String actor: actors){

   ref.orderByChild(actor).addListenerforSingleValueEvent
   //continue the listener
   }

This how you add an actor to List
if(checkBox.Check()){
   actors.Add(actorName);
}else{
    actors.Remove(actorName);
}

A: First check which all checkboxes are checked, for that on the button click check all the checkboxes ie., checkbox.isChecked();
If checked add the name of the actor to the query.


text:
Q: How to read request body dynamic attributes in express? I am very new to express and have a small question. Actually I am a SAP developer, but learning express.
I have few form input text elements in JADE which are dynamically generated. The form elements which are generated dynamically are called optiondes1, optiondes2, optiondes3 and so on. Now, when I post the request, I can see in req.body all those input text values.
How to extract or read the dynamic text elements value from the request body (req.body). I am using body parser. Similarly, I also want to read the dynamic files elements named file1, file2, and so on from the req.files. Please advice.
for (var i = 0; i < numofoptions; i++){

    var optcount = i + 1;
    optdes = ('req.body.' + 'optiondes' + optcount);
    // This prints req.body.optiondes1 as string, but I need the value of req.body.optiondes1
    console.log(optdes);

    optfile = 'file' + optcount;
    origFileName = ('req.files.' + optfile + '.originalFilename');
    console.log(origFileName);
};

A: Try:
optdes = req.body['optiondes' + optcount]

For more examples, search for things like: Converting string to variable name. (JavaScript)


text:
Q: How do I parse a root JSON Array with restassured? I see that I can do the following with restassured.  Given JSON:
{"locationId"=456,"name"="Home"}

I can get an object representing that json like this:
Location location = given().headers(headers).when().expect().statusCode(200).get(getUrl(urlQualifier)).as(Location.class);

How do I parse this JSON is I receive a root array of my Location objects in JSON.  So, given this JSON:
[{"locationId"=1,name="Home"},{"locationId"=2,name="Work"}]

I want to parse out a List object.  The following of course is a compile error, but it demonstrates what I am trying to do:
List<Location> list = given().headers(headers).when().expect().statusCode(200).get(getUrl(urlQualifier)).as((List<Location>).class);

A: Try deserializing it to a Java array:
Location[] list = given().headers(headers).when().expect().statusCode(200).get(getUrl(urlQualifier)).as(Location[].class);


text:
Q: how to solve nonhomogeneous recurrence relation?? How to solve non homogeneous recurrence relation for a given one like in the photo
$a_n = a_{n-1} + 2a_{n-2} + 2^n$
and
$a_0 = 1; a_1 = 1$ ; n >= 2
If someone could help me with a kind of formula or something similar , cause I am
 new are really stucked here

A: $$a_n = a_{n-1} + 2a_{n-2} + 2^n \tag{1}$$
$$a_{n-1} = a_{n-2} + 2a_{n-3} + 2^{n-1} \tag{2}$$
$$a_{n-2} = a_{n-3} + 2a_{n-4} + 2^{n-2} \tag{3}$$
$$a_{n-3} = a_{n-4} + 2a_{n-5} + 2^{n-3} \tag{4}$$
$$...$$
$$a_4 = a_3 + 2a_2+2^4$$
$$a_3 = a_2 + 2a_1+2^3$$
$$a_2 = a_1 + 2a_0+2^2$$
Substituting in $(1)$ with (2):
$$a_n = a_{n-2}+2a_{n-2}+2a_{n-3}+2^n+2^{n-1}$$
$$a_n = (1+2)a_{n-2}+2a_{n-3}+2^n+2^{n-1} \tag{5}$$
Substituting in $(5)$ with (3):
$$a_n = 3a_{n-3}+2a_{n-3} + 3·2a_{n-4} +2^n+2^{n-1} + 3·2^{n-2}$$
$$a_n = (1+2+2)a_{n-3} + (1+2)2a_{n-4} +2^n+2^{n-1} + (1+2)·2^{n-2} \tag{6}$$
Substituting in $(6)$ with (4):
$$a_n = 5a_{n-4} + 6a_{n-4} + 5·2a_{n-5}+ 2^n+2^{n-1} + 3·2^{n-2} + 5·2^{n-3}$$
$$a_n = (1+2+2 + (1+2)2)a_{n-4} + (1+2+2)2a_{n-5}+ 2^n+2^{n-1} + (1+2)·2^{n-2} + (1+2+2)·2^{n-3} \tag{7}$$
Let's write $(7)$ this way:
$$a_n = S_1a_{n-4} + S_2a_{n-5}+ 2^n+2^{n-1} + S_3·2^{n-2} + S_4·2^{n-3}$$
Where the coefficients $S_1, S_2, S_3, S_4$ are sumatories of series I have sketched above.
I leave to you the job of finding out those series. Hint: what happens at each serie each time I make a substitution? How many substitutions I need?


text:
Q: Challenging Joint Probability Question This is quite a challenging question I've been having trouble with lately and seems to be an atypical example of a joint distribution question - While I can derive the marginal density of $X$ simply from the uniform distribution, I am at a loss for how the marginal density for $Y$ and the joint density may be derived. Any suggestions would be enormously appreciated!
John wakes 6 AM each morning and then lies in bed for up to 3 hours. After getting up he takes one hour to get ready for work. After that, John likes to play computer games until he goes to work. However he never leaves after 11 AM. For the 3 hours he lies in bed, John is equally likely to get up at any time within that timeframe (uniformly distributed). Also, from the from the time he begins playing computer games and 11 AM, John is equally likely to go to work at any time during that timeframe.
Suppose $X$ is the time John lies in bed, and $Y$ the number of hours from waking to the moment he left home. Find the following:
a. Determine the marginal density of $X$.
b. Determine the marginal density of $Y$ .
c. Determine the $f(y, x)$.
d. Determine the $f(y|x)$.
Update 1:
The marginal density for $y$ I obtained, using the uniform distribution: $f(y)=1/(4-x)$, however I am a little confused as why it is in terms of $x$. Could this be the joint distribution?
(sorry still havent figured out how to use LaTeX on this site!)

A: Notice that the quantity you computed, $1/(4-x)$ is not the marginal for $Y$ but the density of $Y$ given the value of $X$, that is, it is $f(y|x)$ (one has to be really careful about the $x$ and $y$ intervals for which this density is valid).
From the above you can henceforth compute $f(x,y)=f(y|x)f(x)$ and the marginals by integration.
The marginals are
$$f(x)=\frac{1}{3}, \text{ for } 0\le x \le 3,$$
and
$$f(y) =
\begin{cases}
0, & \text{if } 0\le y \le 1\\
\frac{1}{3}\log{\frac{4}{5-y}}, & \text{if } 1\le y\le 4\\
\frac{1}{3}\log{4} & \text{if } 4\le y \le 5.
\end{cases} $$
See if you can arrive at them through integration. I strongly suggest you make a bidimensional plot of the regions for which $f(x,y)$ is nonzero.


text:
Q: JPopupMenu in JFrame using AWTUtilities.setWindowOpaque(window, false) using synth L&F not appearing This one has me quite puzzled.  Basically I am developing a multi window application using transparent shaped windows using a custom Synth L&F.  Parts of the application invoke JFrame/JDialog components from the parent frame.  Within these components I have pop up menus and comboboxes, the problem is that some people using the applications experience the pop up menus not appearing when invoked.  There are no exceptions and the code executes fine including for popup menus 'show' method.
I have tried to nail this down to OS specifics without much joy, apart from there doesn't seem to be an issue on mac OSX.  Some windows users such as myself experience no problems, others do....
Also I have tracked down the offending line of code which sets the window opacity:
AWTUtilities.setWindowOpaque(window, false)

If I remove this LOC then the popup windows appear fine.  In addition replacing this LOC with :
window.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f));

produces the same issue.  Another thing is that if I use the default L&F the popups render ok.
Just to confirm the issue is the same for both JFrame and JDialog components, and was just wondering if anybody else has either come across this issue or could point me in the direction of the possible cause.
Cheers
Test source to reproduce:
import com.sun.awt.AWTUtilities;

import javax.swing.*;
import javax.swing.plaf.synth.SynthLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestFrame extends JFrame{

    public TestFrame(){
        super.setTitle("Test Frame");

        JButton btnDialog = new JButton("Open Dialog");
        btnDialog.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                TestDialog dialog = new TestDialog(TestFrame.this, true);
                dialog.setVisible(true);
            }
        });

        super.add(btnDialog, BorderLayout.CENTER);
        super.pack();
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        super.setVisible(true);
    }

    public static void main(String[] args){
        initLookAndFeel();
        new TestFrame();
    }

    public static void initLookAndFeel() {
        SynthLookAndFeel lookAndFeel = new SynthLookAndFeel();
        try {
            lookAndFeel.load(TestFrame.class.getResourceAsStream("/testskin.xml"), TestFrame.class);
            UIManager.setLookAndFeel(lookAndFeel);
        }
        catch (Exception e) {
           e.printStackTrace();
        }
    }

    public static class TestDialog extends JDialog{

        public TestDialog(Frame owner, boolean modal) {
            super(owner, modal);

            JComboBox petList = new JComboBox(new String[] { "Bird", "Cat", "Dog", "Rabbit", "Pig" });
            super.add(petList, BorderLayout.CENTER);

            super.setUndecorated(true);
            AWTUtilities.setWindowOpaque(this, false);
            super.pack();
        }
    }
}

and the testskin.xml:
<synth>

    <style id="backingStyle">
        <opaque value="true"/>
        <font name="Dialog" size="14"/>
    </style>
    <bind style="backingStyle" type="region" key=".*"/>

    <style id="ComboBox List Renderer">
        <opaque value="true"/>
        <state value="ENABLED">
            <color type="TEXT_FOREGROUND" value="#000000"/>
        </state>
        <state value="DISABLED">
            <color type="TEXT_FOREGROUND" value="#999999"/>
        </state>
        <state value="SELECTED">
            <color type="TEXT_FOREGROUND" value="#CC6600"/>
            <color type="TEXT_BACKGROUND" value="#FFEEDD"/>
        </state>
    </style>
    <bind style="ComboBox List Renderer" type="name" key="ComboBox.listRenderer" />

    <style id="Combo Box">
        <property key="ComboBox.showPopupOnNavigation" type="boolean" value="true"/>
        <state>
            <color value="#D8D987" type="BACKGROUND"/>
        </state>
    </style>
    <bind style="Combo Box" type="region" key="ComboBox" />

</synth>

As mentioned removing:
AWTUtilities.setWindowOpaque(window, false)

makes the combobox pop up menu render ok, in addition adding a default background to all styles (under style="backingStyle") e.g.:
<state>
   <color value="#D8D987" type="BACKGROUND"/>
</state>

will at least make the pop menu appear, however it is still not renderd properly.  I have tried this on three seperate windows xp virtual machines, all experience the same issues.  In addition do not think I mentiod this but it was built on JDK 7, and run on equivalent JRE in all cases.  I myself on windows 7 ultimate 64 bit experience no problems, another user using windows 7 premium 64 bit does experience the same issues.

Some progress, The paint method for the pop up menu components fails to invoke if:
AWTUtilities.setWindowOpaque(window, false)

is set.  Manually calling repaint, updateUI, revalidate after calling the 'show' method will make the pop up menu render ok.  For combox elements setting a custom UI and overiding the 'createPopup' method, with a class extending javax.swing.plaf.basic.BasicComboPopup that invokes repaint/updateUI/revalidate on show e.g. :
 public class ComboPopup extends BasicComboPopup {

    public ComboPopup( JComboBox combo ) {
        super(combo);
    }

    @Override
    public void show(Component invoker, int x, int y) {
        super.show(invoker, x, y);
        this.updateUI();
    }
}

will make the combox menu render ok.  However I am yet to find a workaround for submneu (JMenu) items for a popup since the popup is created within a private method.  This seems like a bug, but if I am doing something wrong could someone let me know :)
Cheers
Jonathan

A: I answered a similar question here. Hoping it's helpful to others who find this thread, I'll put my workaround here too.
Basically your problem is presenting whenever you need a HeavyWeightPopup -- a popup that doesn't fit within the target window. The workaround is to invoke a repaint after any popup displays. Simply invoke the following code when you launch your application.
PopupFactory.setSharedInstance(new PopupFactory()
{
    @Override
    public Popup getPopup(Component owner, final Component contents, int x, int y) throws IllegalArgumentException
    {
        Popup popup = super.getPopup(owner, contents, x, y);
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                contents.repaint();
            }
        });
        return popup;
    }
});


text:
Q: Detect application close based on app user's name been trying to create script to detect user's application crash. (Assume the computer is used by multiple users)
so far only managed to come out below code to query the application (based on user name) only but not app close or crash
gwmi -query "select * from win32_process where name='calc.exe'" | %{if($_.GetOwner().User -eq 'myUser'){
    #do something when app crash
}}

A: You can use the Register-WmiEvent cmdlet to register an event with the Win32_ProcessStopTrace event class.
The Win32_ProcessStopTrace doesn't have a GetOwner() method, but you can use your current code to gather the Process ID's of the processes you're interested in, and use those in your event query:
$UserName = 'myUser'
$ProcessName = 'calc.exe'
$PIDFilters = Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='$ProcessName'" |Where-Object {
    $_.GetOwner().User -eq $UserName
} |Select-Object -ExpandProperty ProcessId |ForEach-Object {
    "ProcessId={0}" -f $_
}

$WmiFilter = $PIDFilters -join " OR "

Now, you have a $WmiFilter that looks something like this:
ProcessId=2468 OR ProcessId=11576 OR ProcessId=5426

You can use that in a WMI query:
$WmiQuery = "SELECT * FROM Win32_ProcessStopTrace WHERE ($WmiFilter)"

And finally register the event with Register-WmiEvent:
Register-WmiEvent -Query $WmiQuery -SourceIdentifier CalcStopEvent -Action {
    $TraceEvent = $Event.SourceEventArgs.NewEvent
    if($TraceEvent.ExitStatus -ne 0){
        # The process didn't exit with success/noerror
        # Send many emails!
        # Sound the klaxon!
        # Call the fire brigade!
        # or, whatever you feel like ...
    }
}


text:
Q: Given axioms, how do we know it defines a geometry? It is known that besides using coordinates and algebra, there are axiomisation of geometry such as Tarski, Hilbert and Euclid.

*

*However looking at the axioms of Tarski for example:

Betweeness $B(\cdot,\cdot,\cdot)$ satisfy e.g.:
\begin{align}
Bxyz &\to x=y\\
(Bxuz \land Byvz) &\to \exists a(Buay \land Bvax)
\end{align}
Congruence $\equiv$ satisfy e.g.:
\begin{align}
xy\equiv zz &\to x=y\\
& \equiv \text{is reflexive and transitive}
\end{align}

*Now look at the axioms of a group:
\begin{align}
&\text{There exist $e \in G$ such that for all $x \in G$: }xe=ex=x\\
&\text{There exist $x^{-1} \in G$ such that for all $x\in G$: }xx^{-1}=x^{-1}x=e\\
&\text{For all $x,y\in G$: $xy \in G$}\\
&\text{For all $x,y\in G$: $(xy)z=x(yz)$}
\end{align}
If these are the two sets of axiomatic systems given and no other context is given, then in some way, they prescribe how primitive mathematical objects should behave under some logical rules. The reason we knew that $(1)$ is related to geometry is because we build $(1)$ motivated by the need to describe about triangles and planes.
Is there a way to tell whether an axiomatic system defines a geometry just by looking at it and start deriving and exploring the theorems it resulted from  without context. Is there some kind of axioms or schema that all notions of geometry must obey?

A: It depends on your definition of a geometry. And usually, such a definition would be "A geometry is something that satisfies the following axioms." Of course, when we talk about non-Euclidean geometries, we know what we mean, namely, things that satisfy all axioms for a Euclidean geometry except for the parallel axiom. But would something satisfying all axioms except some other axiom still be a geometry? It depends on what you mean with "geometry". Probably not, if you want your definition to be interesting to the mathematical community.
But more to the point, you might be interested in the fact that when we prove things based on the Hilbert axioms except the parallel axiom we are proving things about absolute geometries, i.e., things that are true in both Euclidean and non-Euclidean geometries. And it is remarkable that you lose very few theorems from Euclidean geometry. In this sense, I guess that absolute geometry is the notion that you are looking for.
EDIT: It is relevant whether you are only interested in planar geometry or not. Things might be more complicated in higher dimensions, but I think that there are Hilbert's axioms for 3D absolute geometry as well.
EDIT: I am assuming here that you are interested in "classical" geometry, and not in more complicated things like differential geometry, even though parts of what I have said are still relevant (think of hyperbolic manifolds)

A: No.  The term "geometry" is informal and it is entirely subjective what qualifies as a "geometry" or not.  (I'm sure someone somewhere has given some precise definition of what a "geometry" is, but such definitions are usually not intended as a definitive answer to your question (rather they are technical definitions being used in a certain restricted context) and certainly are not broadly accepted as such.)


text:
Q: Page scrolls up using JQuery fadeIn - fadeOut Hi I use the following code to create a slideshow with multiple DIV elements:
var $ = jQuery.noConflict();
function fadeContent() {
  $(".slideshow .asset-abstract:first").fadeIn(500).delay(2000).fadeOut(500, function() {
    $(this).appendTo($(this).parent());
    fadeContent();
  });
}
fadeContent();

The slideshow works properly but there's a problem. When the delay(2000) trigger a fadeIn-fadeOut, the page scrolls up!
What can I do to prevent this?

A: I think when the element fades out it does not take a real estate on the page. The element beneath it will take its place and you feel like the page scrolled. You can have a wrapper to the element you are trying to fadeIn/fadeOut and provide an appropriate height to this wrapper element. But this is not a good UX because when the element will fadeOut there will be empty section on the page.

A: Its because the fadeOut method ends op settings display:none; on the element.
If you force display block in css this will not happen:
Css:
.slideshow .asset-abstract:first-child {
    display:block;
}


text:
Q: Make POST request with no "Basic" in Auth Header I am new to .NET and is trying to call third-party API but the API requires to send Auth Header without the word "Basic". It is a base-64 encoded string. But when I call the API, http client throws an exception as invalid value.
I am using .NET v6.
Below is the code
        var endpoint = new Uri("api-url");
        var newPostJson = JsonConvert.SerializeObject(request);
        var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
// getting the issue at the below line.
        client.DefaultRequestHeaders.Add("Authorization", signature);

        var response = await client.PostAsync(endpoint, payload);
        var responseString = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseString);

I tried to use TryAddWithoutValidation instead of Add but get no response.


text:
Q: Open set in such a set w.r.t weak topology Let $(\mathcal X,\mathcal F)$ be a measurable space and $\mathcal P$ the set of probability measures  on this space. With weak convergence (i.e., $P_n\to P$ weakly if and only if $\mathbb E_{P_n}(f)\to\mathbb E_P(f)$ for every bounded continuous functions $f:\mathcal X\to\mathbb R$), a basis of the corresponding weak topology induced by this weak convergence is a collection of the following sets:
$$U(P,\alpha)=\left\{Q:\left|\int f_idP-\int f_idQ\right|<\alpha,i=1,\ldots,n\right\}$$
for some $P\in\mathcal P$, $f_i$ bounded continuous functions, $n$ is finite, and $\alpha>0$. Then there exists a finite measurable partition $A_1,\ldots,A_m$ of $\mathcal X$ and $\beta>0$ such that
\begin{align}
\tilde{U}(P,\beta)=\{Q:|P(A_j)-Q(A_j)|<\beta\}\subset{U}(P,\alpha).
\end{align}
My questions are:

*

*is $\tilde{U}(P,\epsilon)$ also open?

*if not, is there an open set, say $U'(P, \alpha')$, that is contained in $\tilde{U}(P,\beta)$? or under what conditions there exists such a $U'(P, \alpha')$? (might have different bounded continuous functions)
Can you help me with these question? or please see my thinking below.

Let me first prove the existence of such $\tilde{U}(P,\beta)\subset U(P,\alpha).$
Since $f_i$ is bounded continuous, then there exists a simple function $\tilde f_i$ such that $\|f_i-\tilde f_i\|_{\infty} <\frac{\alpha}{3}$. Then if $|\int \tilde{f}_idP - \int \tilde{f}_idQ|<\frac{\alpha}{3}$, we have
\begin{align}
&\left|\int f_idP-\int f_idQ\right|\\
=~&\left|\int f_idP-\int \tilde f_idP+\int \tilde f_idP-\int \tilde f_idQ+\int \tilde f_idQ-\int f_idQ\right|\\
<~&\alpha.
\end{align}
We can then define a finite partition according to these simple functions, as $f_i$'s are bounded. By choosing a small enough $\beta$, $|P(A_j)-Q(A_j)|<\beta$ for all $i$ implies $|\int \tilde f_idP-\int \tilde f_idQ|<\frac{\alpha}{3}$.

I have no idea about question 1, so I go to question 2, thinking to construct some bounded continuous functions to build a new open set.
a). for each measurable set $A_i$, find two continuous functions $\bar{f_i}$ and $\underline{f_i}$, such that
$$\bar{f_i}(x)\geq I_{A_i}(x)\geq \underline{f_i}(x),~\text{for every $x\in\mathcal X$},$$
$$\int \bar{f_i} dP- \int \underline{f_i}dP<\frac{\beta}{2},$$
where $I_{A_i}(\cdot)$ is the indicator function.
b). For any probability measure $Q$, we have $$\int\underline{f_i}dQ\leq Q(A_i)\leq\int\bar{f_i}dQ.$$ Thus, if $|\int\bar{f_i}dP - \int\underline{f_i}dQ|<\beta$ and $|\int\underline{f_i}dP - \int\bar{f_i}dQ|<\beta$, we must have $|P(A_i)-Q(A_i)|<\beta$. We also have
\begin{align}
&\left|\int\underline{f_i}dP - \int\bar{f_i}dQ\right|\\
=~&\left|\int\underline{f_i}dP-\int\bar{f_i}dP+\int\bar{f_i}dP-\int\bar{f_i}dQ \right|\\
\leq~&\left|\int\underline{f_i}dP-\int\bar{f_i}dP\right|+\left|\int\bar{f_i}dP-\int\bar{f_i}dQ \right|
\end{align}
Similarly, we have $$\left|\int\bar{f_i}dP - \int\underline{f_i}dQ\right|\leq\left|\int\bar{f_i}dP-\int\underline{f_i}dP\right|+\left|\int\underline{f_i}dP-\underline{f_i}dQ \right|$$
As such, adding the following constraints $$\left|\int\underline{f_i}dP-\underline{f_i}dQ \right|<\frac{\beta}{2}, \left|\int\bar{f_i}dP-\bar{f_i}dQ \right|<\frac{\beta}{2}$$
will construct a new open set that is contained in $\tilde{U}(P,\beta)$.
It seems that a) is not always true. When $\mathcal X=\mathbb R$, consider $P= \frac{1}{2}I_{[0,1]} + \frac{1}{2}I_{\{3\}}$. For a measurable set $A=[2,3)$, no such $\bar{f_i}$ and $\underline{f_i}$ exist for each $\beta>0$. I think it possible to place some constraints on the partition $A_1,A_2,\ldots, A_m$ for the simple functions $\tilde f_i$, but I got no formal proof/reference to it. Can you advise me how to make this work? Thanks!!~

A: This is not true, let $X=[-1,1]$ and consider $P = \delta_0$. Let $f_1,...,f_n$ be continuous on $X$. Note that $U_{\{f_1,..,f_n\}}(P,\epsilon)=\bigcap_i U_{f_i}(P,\epsilon)$.
You can do a continuity argument to find non-singular measures $Q=\frac1h \chi_{[-h,h]}$ so that for any fixed $f$ you have $Q\in U_f(P,\epsilon)$. So any weak-open set around $f$ contains non-singular measures. On the other hand let $A=\{0\}$, then
$$\tilde U_A (P,\epsilon) = \{Q\mid |1-Q(\{0\})|<\epsilon\}$$
contains only measures that are singular (provided $\epsilon<1$), thus this cannot be an open neighbourhood of $P$.
If you restrict your $A_i$ to be open the statement should be true (if your measure space has the Borel sigma algebra), if necessary add in $X$ to be locally compact and probability measures to be regular.


text:
Q: snowflake substring with pattern A column in sf table has values like
test/SalesID
test2/SalesIDaccount
mytempSalesID
1234SalesIDnum
...

I want to substring this column to show only
SalesID
SalesIDaccount
SalesID
SalesIDnum

so remove everything before SalesID and keep whatever left. How to approach it?

A: Use regexp_substr
select regexp_substr(col, '.*(SalesID.*)', 1, 1, 'e', 1) as "RESULT";

A: You can use split_part().  To get the last component:
select split_part(col, '/', -1)

To get the second component:
select split_part(col, '/', 2)

It is not clear if you want the last, second, or if it doesn't matter.


text:
Q: Is it possible to have Excel Interop's AutoFit disregard Hidden Rows? On the spreadsheet I'm creating, I hide certain rows:
if (_hide)
{
    var hiddenRange = _xlSheet.Range[_xlSheet.Cells[_curDescriptionTopRow, ITEMDESC_COL], _xlSheet.Cells[_lastRowAdded, TOTALS_COL]];
    hiddenRange.EntireRow.Hidden = true;
}

I subsequently (after all the rows have been added, both the visible and the hidden, AutoFit / right-size the columns) right-width them:
_xlSheet.Columns.AutoFit();

However, this autofitting (oddly, I think) takes into account hidden column vals, too. I want it to disregard the hidden vals. Is this possible?


text:
Q: How to use string interpolation and verbatim string together to create a JSON string literal? I'm trying to create a string literal representing an array of JSON objects so I thought of using string interpolation feature as shown in the code below:
    public static void MyMethod(string abc, int pqr)
    {
        string p = $"[{{\"Key\":\"{abc}\",\"Value\": {pqr}  }}]";
    }

Now I thought of using verbatim string so that I don't have to escape double quotes using backslashes. So I came to know through this answer that verbatim string and string interpolation can be used together. So I changed my code as below:
public static void MyMethod(string abc, int pqr)
{
    string p = $@"[{{"Key":"{abc}","Value": {pqr} }}]";
}

But it fails to compile. Can anyone help me if there is anything wrong in my usage or it will not be possible to escape double quotes in such a case using string verbatim feature of C#?

A: I agree with everyone else that building it from strings is a bad idea.
I also understand that you don't want to include an extra dependency.
Here's a bit of code I wrote previously to convert a Dictionary to a JSON string. It's pretty basic, only accepts string types, and doesn't escape quote marks in any of the names/values, but that can be done fairly easily.
If you're trying to serialize a large JSON string from basic types, this is the way I'd recommend to do it. It'll help you stay sane.
private static string DictToJson(Dictionary<string, string> Dict)
{
    var json = new StringBuilder();

    foreach (var Key in Dict.Keys)
    {
        if (json.Length != 0)
            json = json.Append(",\n");

        json.AppendFormat("\"{0}\" : \"{1}\"", Key, Dict[Key]);
    }
    return "{" + json.ToString() + "}";
}

A: The best way is to use JSON serializers as they have in-built handling related to escape characters and other things. See here.
However, if we want to go through this path only to create the JSON string manually, then it can be solved as follows by changing the inner double quotes to single quotes :
public static string MyMethod(string abc, int pqr)
{
   string p = $@"[{{'Key':'{ abc}','Value': {pqr} }}]";
   return p;
}

A: you can create dictionary and serialize it to json using Json.NET does this.
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");

string json = JsonConvert.SerializeObject(values);
// {
//   "key1": "value1",
//   "key2": "value2"
// }

you can see here more detail : http://www.newtonsoft.com/json/help/html/SerializingCollections.htm


text:
Q: Most efficient Many-Many object mapping (in JSON) I need to represent a many-many object mapping between two different groups of objects using JSON. For example's sake, lets say my first set of objects is "students" and the second is "courses". Each student can have many courses, but each course can also have many students. Is there a standard way of representing such a schema, such that lookups are as efficient as possible?
I know that I could, for example, do
"ELEC1000": ["Bob", "Jessica", "Jeff"],
"MECH1000": ["Aaron", "Bob", "Ben", "Sally"]

This would lead to very fast results when trying to find what students are enrolled in ELEC1000, but would make searching for classes Bob is enrolled in inefficient. I suspect I need to use a hashmap of some sort, but am not entirely sure how to implement this.
Thanks in advance!

A: If you want efficient lookup both ways, you need to have to duplicate the data (in the form of what a database would call an index).
For example, in addition to the map you already have (course => list of students), also build the opposite map (student => list of courses).
Of course, you need to maintain both maps when there are updates.


text:
Q: How to make a queue system with game rooms using node.js and socket.io? I'm trying to implement this idea but I don't know what's the best way to do it.
There should be a button to queue up for a game, and there should be game rooms with 3 players in each.

A: Since your question is rather vague, I will give you a general workflow.

*

*An Express/HTTP server starts with a listening websocket.

*User loads page. Page loaded and attempt to make a websocket connection with the server.

*Websocket established. Shows "Join Queue" button on the game.

*Server updates client with available rooms in real time. Game can choose to show each room or just hide them in the background so that when player clicks on "Join Queue", he will be connected to the first available room.

*User clicks on "Join Queue" and joins a room.

Sample Code for joining a room after connection established.
// io is exposed as a global variable in the client once you import the library.
// Join an existing room on connection established
io.on('connection', function(socket){
    socket.join('some room');
});
// Establish a websocket connection
var socket = io();


text:
Q: grouping over multiple columns in DynamicJasper I have a problem of creating 1 group that "spand" over multiple colums in DynamicJasper. Example would be something like this:
i get data from base, which i can not change:
id1      id2       id3         id4     id5

1       Vega    Steve      8,000.23    yes

1       Vega    Steve      3,465.33    yes

2       Minson  Mark     123,987.23    no

2       Minson  Mark       3,465.33    yes

5       Lucky   Luck   3,123,465.33    no

after grouping over first 3 columns report would look like this:
id1      id2       id3         id4     id5

1       Vega    Steve      8,000.23    yes

                           3,465.33    yes

2       Minson  Mark     123,987.23    no

                           3,465.33    yes

5       Lucky   Luck   3,123,465.33    no

Is this possible to achieve in DynamicJasper?

A: Yes its possible.
You can generate a group by a report.
GroupBuilder gb  = new GroupBuilder();
DJGroup g = gb.setCriteriaColumn((PropertyColumn) columnname)
.setGroupLayout(GroupLayout.VALUE_IN_HEADER)
.build();
.firstReport.addGroup(g);

you can add multiple groups.
Create the same code for the next column.
And please add it in the order of there grouping level.
Like first add company, then department and then designation.


text:
Q: Google Bigtable under usage "performance" I have seen the warnings of not using Google Big Table for small data sets.
Does this mean that a workload of 100 QPS could run slower (total time; not per query) than a workload of 8000 QPS?
I understand that 100 QPS is going to be incredibly inefficient on BigTable; but could it be as drastic as 100 inserts takes 15 seconds to complete; where-as a 8000 inserts could run in 1 second?
Just looking for a "in theory; from time to time; yes" vs "probably relatively unlikely" type answer to be a rough guide for how I structure my performance test cycles.
Thanks

A: There's a flat start up cost to running any Cloud Bigtable operations.  That start up cost generally is generally less than 1 second.  I would expect 100 operations should take less than 8000 operations.  When I see extreme slowness, I usually suspect network latency or some other unique condition.

A: We're having issues with running small workloads on our Developer Big Table instance (2.5 TB) One instance instead of 3.
We have a key set up on user id and around 100 rows on the key user id.  Total records in the database are a few million.  We querying big table and seeing 1.4 seconds of latency from fetching the rows associated with a single key of user id.  Total number of records returned is less than 100 and we're seeing way over a second of latency.  It seems to me that giant workloads are the only way to use this data store.  We're looking at other NoSQL alternatives like Redis.


text: Q: Как организовать приватное и публичное API? Только начал углубляться в веб разработку. Не могу понять одной вещи. Допустим, на сайте есть приватные API, которые могут использоваться только самим сервером, и публичные, которые используют клиенты. Как это правильно организовать?


text:
Q: Make variable string ignore escape sequences I'm currently facing an issue with a method parsing a string to another method. The problem is that I want to prevent it from using possible escape sequences.
The string I want to parse is not constant so (as far as I know) using the R declaration to make it a raw literal is not applicable here since I have to use variables.
Furthermore, in some cases there is user input included into the string (unconverted), so simply escaping those sequences by replacing a "\" character with "\\" is not an option either, the input can include those sequences too.
To be more precise on the issue:
A string formatted like f.e. " "\x10\x4 \x6(" " is getting auto compiled and converted into a non-human readable format as soon as it gets parsed to the next function. I want to prevent that conversion without In order to get the exact same string in the next function which needs to work with it.
Hope someone can help me since I'm new to c++ programming. Thanks in advance :D
#include "pch.h"
#include <iostream>

int main()
{
    stringTester stringtester;
    std::string test = stringtester.exampleString();
    stringtester.stringOutput(test);
}

std::string stringTester::exampleString()
{
    std::string exampleInput = "\x10\x5\x1a\aTestInput\\n \x6(";
    return exampleInput;
}

void stringTester::stringOutput(std::string test)
{
    std::cout << test << std::endl;
}

The actual output her (copied from console) is " TestInput\n ( ", whereas the wanted output would be the original string "\x10\x5\x1a\aTestInput\n \x6("
Edit: It seems like on SO it can't show the unknown characters. There are xtra characters in front and after the "TestInput\n ("

A: When you write a string literal in your source code the compiler replaces escape sequences with the character that they represent. That's why the quoted string in your example gets turned into nonsense. The way to fix that is to either replace each backslash with two backslashes or to make it a raw string literal.
When your program reads text input it doesn't do any of those adjustments. So if the code does
std::string input;
std::cin >> input;

and the user types the characters \x10\x5\x1a\aTestInput\\n \x6( into the console, input will end up with the characters \x10\x5\x1a\aTestInput\\n \x6(.
Once you've got the string, whether as a string literal or as text from the console, you can do whatever you want with it.

A: You have two possibilities for a backslash to remain a backslash in your C/C++ strings (and Java, JavaScript, PHP...)

*

*Double all the Backslashes

Just as you said, you want to double all backslashes. This is fine. If the input was:
\\\\

Then your C/C++ string is going to be:
"\\\\\\\\"

(a mouthful, I know...)

*Use the Hex/Octal Character

The other way, if you don't like the double backslash too much (if it scares you, somehow), is to use the character sequence in octal or hex (or Unicode in newer versions):
\    becomes   "\134"   or   "\x5C"

As you may notice, though, this means 4 characters per backslash. So most people will generally just double the backslash (one 2 characters). Plus the double backslash is well understood. The code point may not be as well known by programmers coming behind you.
As a side note, if your user can enter any character, then they can also enter the double quote (") character. It is important that you also escape those. You can similarly use the backslash and the double quote character or its code point:
\"   or   \042   or   \x22


text:
Q: How to responsively embed Vimeo Videos into a Slick Slider? I have a slick.js slider with several videos and photos in them. I want all of them to have the same responsive height. With the images that's easy since I can just give them height: 60vh;. I now struggle to responsively embed the videos that are hosted on vimeo, since the container div of the video needs to have a specified width to begin with. But since the videos can change and have different aspect ratios I don't know the width.
I tried several ways including manually calculating the width of the container div by multiplying the height and the aspect ratio of the video (that I can obtain automatically by using the Vimeo API, but this is not part of the problem). But then the video will not resize when the browser window is changing height.
I have this jsfiddle setup:
https://jsfiddle.net/shy_seagull/3evy2tkp/23/
Is there a better way to do this than manually calculating the width of every video and changing the width of the container div with javascript?


text:
Q: Can we find if 0 occurs odd number of times in an array using bit manipulation I know that, XORing all elements of an integer array which contains all of its elements except 1 element occuring even number of times gives the number that occurs odd number of times.
Example
{ 1, 1, 2, 2, 3 }
1 ^ 1 ^ 2 ^ 2 ^ 3 = 3;
^ is XOR
What if the number occuring odd number of times is 0?
{ 1, 1, 2, 2, 0 }
1 ^ 1 ^ 2 ^ 2 ^ 0 = 0    // Both give
1 ^ 1 ^ 2 ^ 2 = 0        // same answer

How to confirm that 0 is occuring odd number of times
PS : Prefer the answer code to be in C/C++

A: Let's call N, the number of elements in your array:

*

*If (N is even) AND (XORing all elements ==0) -> All the elements occur even number of times

*if (N is odd) AND (XORing all elements ==0) -> You single element is zero.

This is how to check if an integer is even or odd in C / C++


text:
Q: Email personalization when sending to Salesforce report or campaign How can we personalize the emails when sending to Salesforce Report or Campaign?
How do we use personalization strings with data from Salesforce as Reports and Campaigns?
or should we directly use AMPscript ?
Thank you

A: Only fields that you have already configured and mapped in your Field Mapping will be available.
Your other three options are:

*

*Using a Lookup or LookupRows on the synchronized DE

*Or a RetrieveSalesforceObject

*Or importing the campaign or report into a sendable data extension.

Examples:
LookupRows('ZipCode','City',HomeCity)

%%[ var @rs

Set @rs= RetrieveSalesforceObjects('Lead', 'Id, FirstName,LastName', 'region', '=', 'west','AnnualRevenue', '>', '1000000')

]%%


text:
Q: JQuery does not set variable after $.get Hello gurus in the house. It sounds like a duplicate but I am having a tough time with it since 48hrs past. The question is based on a jQuery. I have a file that i would like to pass into a variable then later use the variable in other places of my code. The file only contains 'I love you'.
<script>

var kk;
$.get('k.txt', function(data) {
kk = data;
}, 'text');
alert(kk);   //undefined
</script>

The result of the alert is undefined and it does not work in opera browser. I can alert it like this.
<script>

var kk;
$.get('k.txt', function(data) {
alert(kk);   //alert is fine
}, 'text');
</script>

I don't mind if you can show me any other working process apart from this. Please I need this so badly and I have being dealing with this since yesterday. Thank you sirs for understanding.


text:
Q: java.lang.NoClassDefFoundError: android.support.v7.recyclerview.R$styleable java.lang.RuntimeException: Unable to resume activity {com.example.recyclerview/com.example.recyclerview.screen.HomeFragment}: **android.view.InflateException: Binary XML file line #7: Error inflating class android.support.v7.widget.RecyclerView**

     Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class android.support.v7.widget.RecyclerView
            at android.view.LayoutInflater.createView(LayoutInflater.java:623)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:699)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:400)
            at com.example.recyclerview.screen.HomeFragment.onCreateView(HomeFragment.java:67)

     **Caused by: java.lang.NoClassDefFoundError: android.support.v7.recyclerview.R$styleable**
            at android.support.v7.widget.RecyclerView.<init>(RecyclerView.java:440)
            at android.support.v7.widget.RecyclerView.<init>(RecyclerView.java:409)
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at android.view.LayoutInflater.createView(LayoutInflater.java:597)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:699)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:400)
            at com.example.recyclerview.screen.HomeFragment.onCreateView(HomeFragment.java:67)
            at

I have added android-support-v7-recyclerview and android-support-v7-appcompat to my project but still getting this error. I'm using IDE as Intellij Idea.


text:
Q: Python Pandas Add empty column in the middle of a dataframe I am trying to add an empty column after the 3ed column on my data frame that contains 5 columns. Example:
Fname,Lname,city,state,zip

mike,smith,new york,ny,11101

This is what I have and below I am going to show what I want it to look like.
Fname,Lname,new column,city,state,zip

mike,smith,,new york,ny,11101

I dont want to populate that column with data all I want to do is add the extra column in the header and that data will have the blank column aka ',,'.
Ive seen examples where a new column is added to the end of a data frame but not at a specific placement.

A: Use reindex or column filtering
df = pd.DataFrame(np.arange(50).reshape(10,-1), columns=[*'ABCDE'])

df['z']= np.nan

df[['A','z','B','C','D','E']]

OR
df.reindex(['A','z','B','C','D','E'], axis=1)

Output:
    A   z   B   C   D   E
0   0 NaN   1   2   3   4
1   5 NaN   6   7   8   9
2  10 NaN  11  12  13  14
3  15 NaN  16  17  18  19
4  20 NaN  21  22  23  24
5  25 NaN  26  27  28  29
6  30 NaN  31  32  33  34
7  35 NaN  36  37  38  39
8  40 NaN  41  42  43  44
9  45 NaN  46  47  48  49

A: you should use
df.insert(loc, column, value)

with loc being the index and column the column name and value it's value
for an empty column
df.insert(loc=2, column='new col', value=['' for i in range(df.shape[0])])

A: You can simply go for df.insert()
import pandas as pd
data = {'Fname': ['mike'],
        'Lname': ['smith'],
        'city': ['new york'],
        'state': ['ny'],
        'zip': [11101]}
df = pd.DataFrame(data)
df.insert(1, "Address", '', True)
print(df)

Output:
  Fname Address  Lname      city state    zip
0  mike          smith  new york    ny  11101


text:
Q: saving string matches to list of lists I have a string while looks like this
Name: Thompson shipping co.
17VXCS947
Name: Orange juice no pulp, Price: 7, Weight: 2, Aisle:9, Shelf_life: 30,
67 Name: Orange juice pulp, Price: 7, Weight:2, Aisle:9, Shelf_life:30,
Photo is available,
Photo is available,
56GHIO098
Name: Cranberry Juice, Price: 3, Weight: 1, Aisle:9, Shelf_life:45,
Name: Lemonade, Price:1, Weight:1, Aisle:9, Shelf_life:10,

There are no new line characters and everything is one big string.
My end goal is to save them to an excel sheet. I am trying to either save these to list of lists of dictionary which looks like
[['Name:  Thompson shipping co.'],['Name: Orange juice no pulp', 'Price: 7', 'Weight: 2', 'Aisle:9', 'Shelf_life: 30'],['Name: Orange juice pulp', 'Price: 7', 'Weight:2', 'Aisle:9', 'Shelf_life:30',['.....']]

or a dictionary.
My current solution is to use regex to find Name, Price, Weight, Aisle, Shelf_life with
re.findall('(?<=,)[^,]*Name:[^,]*(?=,)'),re.findall('(?<=,)[^,]*Price:[^,]*(?=,)'),re.findall('(?<=,)[^,]*Weight:[^,]*(?=,)')....

How do I save them to a list of lists or a dict? Thinking out loud, I can count the iterations and save every 5th one to new list but the first Name occurrence is a corner case.
What's the neater way to do this?

A: Would you please try the following:
import re

str = '''
Name: Thompson shipping co.
17VXCS947
Name: Orange juice no pulp, Price: 7, Weight: 2, Aisle:9, Shelf_life: 30,
67 Name: Orange juice pulp, Price: 7, Weight:2, Aisle:9, Shelf_life:30,
Photo is available,
Photo is available,
56GHIO098
Name: Cranberry Juice, Price: 3, Weight: 1, Aisle:9, Shelf_life:45,
Name: Lemonade, Price:1, Weight:1, Aisle:9, Shelf_life:10,
'''.replace('\n', ' ')

print([re.findall(r'\b\w+:\s*[^,]+', x) for x in re.findall(r'\bName:\s*.+?(?=\s*\bName|$)', str)])

Output:
[['Name: Thompson shipping co. 17VXCS947'], ['Name: Orange juice no pulp', 'Price: 7', 'Weight: 2', 'Aisle:9', 'Shelf_life: 30'], ['Name: Orange juice pulp', 'Price: 7', 'Weight:2', 'Aisle:9', 'Shelf_life:30'], ['Name: Cranberry Juice', 'Price: 3', 'Weight: 1', 'Aisle:9', 'Shelf_life:45'], ['Name: Lemonade', 'Price:1', 'Weight:1', 'Aisle:9', 'Shelf_life:10']]

*

*The second findall() function creates a list of strings which starts with
Name:.

*The first findall() function creates a list of name: value pairs
out of the list items created above.

As seen, the string 17VXCS947 is appended to the first list element.
If you want to remove it, we'll need another logic to exclude it.


text:
Q: I want to combine certain line items of data into one tab I run an audit at work which can return several million line items of data.  So excel gives me many tabs of 65,536 line items on each tab. I have the vba code which will combine all data onto one tab but again this won't work because of the row limits for each tab.  Therefore I only want certain line items being pulled out.
I only want to include the line items where the Field Name is Position is Using Time.  I am new to VBA and assume that I should specify that within the Loop?
So (within the code listed below) I need to include For every time the Field Name equals Position is Using Time I want that entire line item to be dropped into the new Audit Trail tab. I have included an example of the line item I am looking for within each tab, and also a copy of the code I use for combining smaller audit trails.
Any help is very much appreciated!  Thank you.
Example of line item I need to pull from the data

Sub CopyFromWorksheets()
    Dim wrk As Workbook 'Workbook object
    Dim sht As Worksheet 'Object for handling worksheets in loop
    Dim trg As Worksheet 'Audit Trail Worksheet
    Dim rng As Range 'Range object
    Dim colCount As Integer 'Column count in tables in the worksheets

    Set wrk = ActiveWorkbook 'Working in active workbook

     'Add new worksheet as the last worksheet
    Set trg = wrk.Worksheets.Add(After:=wrk.Worksheets(wrk.Worksheets.Count))
     'Rename the new worksheet
    trg.Name = "Audit Trail"

     'Get column headers from the first worksheet
     'Column count first
    Set sht = wrk.Worksheets(1)
    colCount = sht.Cells(1, 255).End(xlToLeft).Column

     'Retrieve Headers
    With trg.Cells(1, 1).Resize(1, colCount)
        .Value = sht.Cells(1, 1).Resize(1, colCount).Value
         'Set font as bold
        .Font.Bold = True
    End With

     'Start loop
    For Each sht In wrk.Worksheets

         'If worksheet in loop is the last one, stop execution (it is Master worksheet)
        If sht.Index = wrk.Worksheets.Count Then
            Exit For
        End If
         'Data range in worksheet - starts from 1st row as headers are only in first tab.
        Set rng = sht.Range(sht.Cells(1, 1), sht.Cells(65536, 1).End(xlUp).Resize(, colCount))

         'Put data into the Master worksheet
        trg.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
    Next sht

     'Fit the columns in Master worksheet
    trg.Columns.AutoFit

End Sub

A: The 64K row limit went away with Excel 2007. It's over a million rows since that version. With Power Pivot (XL 2010 and later), you can load a LOT more rows than that into the data model. Looping through all that data with VBA will be painfully slow. Using modern tools like Power Query, you can combine the data from all sheets and set filters. That will run a LOT faster.


text:
Q: Data is not inserting into database, no error showed I have this code into my php script that i test:
mysql_query("INSERT INTO te_sales(uid,s_credit,s_price,s_date) VALUES ('$user_info[id]','$cPack[t_credit]','$cPack[t_price]',time())");

but when purchase something, data about buyer are not inserted into te_sales table  into database. What is wrong with that?
This is entire code:
if(isset($_POST['te_package'])){
// Lets get the data....
 $sP = intval($_POST['te_package']);
// Lets check in DB either it is there or not.
$chk = mysql_query("SELECT * FROM te_pack WHERE id='$sP' LIMIT 1");
 if(mysql_num_rows($chk)== 1){ // Founded go ahead
// Fetch the sP pack
$cPack = mysql_fetch_array($chk);
// Check user balance...
if($user_info['purchase_balance'] >= $cPack['t_price']){ // Proceed as user
have enough balance to make purchase.
// Lets Cut out the user balance... And give the TE Credits
mysql_query("UPDATE members SET purchase_balance = purchase_balance -
'$cPack[t_price]' , te_credit = te_credit + '$cPack[t_credit]'
WHERE id='$user_info[id]'");
// Insert the logs of sales...
//mysql_query("INSERT INTO te_sales(uid,s_credit,s_price,s_date) VALUES
('$user_info[id]','$cPack[t_credit]','$cPack[t_price]',time())");
 $result = mysql_real_escape_string("
INSERT INTO te_sales(uid,s_credit,s_price,s_date)
VALUES ('$user_info[id]','$cPack[t_credit]','$cPack[t_price]',time())
");

if (!$result) {
die('Invalid request : ' . mysql_error());
}

A: Have you look if there was an error?
<?php
$result_data = mysql_query('
    INSERT INTO te_sales(uid,s_credit,s_price,s_date)
    VALUES (
        "'.mysql_real_escape_string($user_info['id']).'",
        "'.mysql_real_escape_string($cPack['t_credit']).'",
        "'.mysql_real_escape_string($cPack['t_price']).'",
        now()
    )
');

if (!$result_data) {
  die('Invalid query request: ' . mysql_error());
}
?>

A: You insert syntax is wrong, try like this
$result_data = mysql_query("
  INSERT INTO te_sales(uid,s_credit,s_price,s_date) VALUES ('".$user_info['id']."','".$cPack['t_credit']."','".$cPack['t_price']."',time()     )
");

if (!$result_data) {
  die('Invalid query request: ' . mysql_error());
}


text:
Q: Accessing Math functions from rootpy I'm currently trying to access Math functions such as DeltaR from rootpy, but I'm not sure how this is done.  I've seen nothing in the documentation or in any examples.  The C++ equivalent would be something like:
double dR = ROOT::Math::VectorUtil::DeltaR((jets)[i],(partons)[i]);
But I'm unable to find a rootpy or even pyroot equivalent that'll work.  If I try in pyroot with
import ROOT as r
r.Math.VectorUtil.DeltaR(jets[i],partons[i])

I get the error:
AttributeError: type object 'ROOT::Math' has no attribute 'VectorUtil'
When it quite clearly should, unless I don't understand correctly what it means by 'Attribute'.  Anyway, I don't want to ask pyroot questions here :) I just put this down to a quirk in the way that pyroot handles such things, which is why I thought I'd give rootpy a try.  I'm not sure if this is possible however.
Cheers,
Joseph

A: The functions from ROOT::Math::VectorUtil are in libGenVector which is loaded automatically in neither CINT nor PyROOT. Manually loading it (like you probably do in your root_logon.C) makes the functions available, e.g.
import ROOT as r
r.gSystem.Load('libGenVector')

# ...

r.Math.VectorUtil.DeltaR(jets[i],partons[i])

A: If jets and partons are TLorentzVectors then you should be able to do:
from ROOT import *
dR = jet.DeltaR(parton)


text:
Q: Passing a pointer to an object with an initializer list, into another objects ctor I am writing an example of the object adapter design pattern. Here is my adaptee class
class Adaptee
{
public:
    Adaptee(Coord x1, Coord y1, Coord x2, Coord y2)
    {
        x1_ = x1;
        y1_ = y1;
        x2_ = x2;
        y2_ = y2;
        std::cout << "LegacyRectangle:  create.  (" << x1_ << "," << y1_ << ") => ("
            << x2_ << "," << y2_ << ")" << std::endl;
    }

    void oldDraw()
    {
        std::cout << "LegacyRectangle:  oldDraw.  (" << x1_ << "," << y1_ <<
            ") => (" << x2_ << "," << y2_ << ")" << std::endl;
    }
private:
    Coord x1_;
    Coord y1_;
    Coord x2_;
    Coord y2_;
};

In my adapter class I pass a pointer of Adaptee to the constructor, and I declare an Adaptee pointer field in my private data area. The problem is I am confused about how to include Adaptee's initialiser list in Adapters ctor. Here is my attempt
class Adapter : public Target
{
public:
    Adapter(Adaptee* adaptee) : _adaptee(adaptee)
    {
        std::cout << "RectangleAdapter: create.  (" << _adaptee->x1_ << "," << y <<
            "), width = " << w << ", height = " << h << std::endl;
    }

    virtual void draw()
    {
        std::cout << "RectangleAdapter: draw." << std::endl;
        oldDraw();
    }

private:
    Adaptee* _adaptee;
};


text:
Q: Incorrect placement of token in 2D grid I'm making a treasure hunt game on a changeable 8 x 8, 10 x 10 or 12 x 12 grid as part of an assignment for school and I need some help. Whenever I make the move on  the grid it doesn't always move to the desired position. Can someone help me or explain to me why it doesn't work?
The code below is what I have so far.
def makeMove():
   global board, numberOfMoves, tokenBoard, playerScore, tokenBoard
   playerCoords = getPlayerPosition()
   currentRow = playerCoords[0] #sets var to playerCoords[0]
   currentCol = playerCoords[1] #sets var to playerCoords[1]

   directionUD = input("Up/Down?") #sets var to the input of "Up/down?"
   movement_col = int(input("How many places?"))
   if directionUD == "u": #checks if var equals "u"
      newCol = currentCol - movement_col
      print (newCol)
   elif directionUD =="d": #checks if var equals "d"
      newCol = currentCol + movement_col

   directionLR = input("Left/Right?") #sets var to the input of "Up/down?"
   movement_row = int(input("How many places?"))
   if directionLR == "l": #checks if var equals "l"
     newRow = currentRow - movement_row
     print(newRow)
  elif directionLR == "r": #checks if var equals "r"
     newRow = currentRow + movement_row
     print(newRow)

  calculatePoints(newCol, newRow) #calls the calculatePoints function

  if newCol > gridSize or newRow > gridSize:
    print("That move will place you outside of the grid. Please try again.")

   board[newCol][newRow] = "X" #sets the new position to "X"
   board[currentRow][currentCol] = "-"
   numberOfMoves = numberOfMoves + 1 #adds 1 to the numberOfMoves
   displayBoard() #calls the displayBoard function

A: Okay, I feel like an idiot. It took reproducing your work from scratch before I noticed the problem - I'm confusing columns with rows. I think this might be your issue as well.
In your game, you should determine your player's horizontal movement ('Left/Right?') by changing the current column and the player's vertical movement ('Up/Down?') by changing the current row.
This is because when you determine a value for newRow that differs from currentRow, you're moving across rows rather than along them. Similar logic applies for columns.
Here's my code below for reference:
def create_board(size):
    return [['_' for _ in range(size)] for _ in range(size)]

def print_board(board):
    for row in board:
        print(row)

def get_board_dimensions(board):
    # PRE: board has at least one row and column
    return len(board), len(board[0])

def make_move(board, player_position):
    def query_user_for_movement():
        while True:
            try:
                return int(input('How many places? '))
            except ValueError:
                continue

    def query_user_for_direction(query, *valid_directions):
        while True:
            direction = input(query)
            if direction in valid_directions:
                return direction

    vertical_direction = query_user_for_direction('Up/Down? ', 'u', 'd')
    vertical_displacement = query_user_for_movement()
    horizontal_direction = query_user_for_direction('Left/Right? ', 'l', 'r')
    horizontal_displacement = query_user_for_movement()

    curr_row, curr_column = player_position
    new_row = curr_row + vertical_displacement * (1 if vertical_direction == 'd' else -1)
    new_column = curr_column + horizontal_displacement * (1 if horizontal_direction == 'r' else -1)

    width, height = get_board_dimensions(board)

    if not (0 <= new_row < height):
        raise ValueError('Cannot move to row {} on board with height {}'.format(new_row, height))
    elif not (0 <= new_column < width):
        raise ValueError('Cannot move to column {} on board with width {}'.format(new_column, width))

    board[curr_row][curr_column] = '_'
    board[new_row][new_column] = 'X'

    return board

if __name__ == '__main__':
    # Set up an 8 x 8 board with the player at a specific location
    board_size = 8
    player_position = (1, 2)
    board = create_board(board_size)
    board[player_position[0]][player_position[1]] = 'X'
    print('Initialised board with size {} and player at ({}, {})'.format(board_size, *player_position))
    print_board(board)

    # Allow the player to make their move.
    print('Player, make your move:\n')
    board = make_move(board, player_position)

    # Show the new board state
    print('Board after making move')
    print_board(board)

Starting a game
Initialised board with size 8 and player at (1, 2)
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', 'X', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
Player, make your move:

Moving one tile down
Up/Down? d
How many places? 1
Left/Right? r
How many places? 0
Board after making move
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', 'X', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']

Moving one tile right
Up/Down? d
How many places? 0
Left/Right? r
How many places? 1
Board after making move
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', 'X', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']

Moving one tile up
Up/Down? u
How many places? 1
Left/Right? l
How many places? 0
Board after making move
['_', '_', 'X', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']

Moving one tile left
Up/Down? d
How many places? 0
Left/Right? l
How many places? 1
Board after making move
['_', '_', '_', '_', '_', '_', '_', '_']
['_', 'X', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']

Moving diagonally down and right
Up/Down? d
How many places? 1
Left/Right? r
How many places? 1
Board after making move
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', 'X', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_', '_']

Making an illegal move
Up/Down? u
How many places? 3
Left/Right? r
How many places? 0
Traceback (most recent call last):
  File "C:/Users/<<me>>/.PyCharmCE2016.3/config/scratches/scratch_2.py", line 62, in <module>
    board = make_move(board, player_position)
  File "C:/Users/<<me>>/.PyCharmCE2016.3/config/scratches/scratch_2.py", line 41, in make_move
    raise ValueError('Cannot move to row {} on board with height {}'.format(new_row, height))
ValueError: Cannot move to row -2 on board with height 8


text:
Q: Split string in java giving some issues public class llearning1 {

    public static void main(String[] args) {

        String text = "is";
        String x = "what is good";
        String y[] = x.split(" ");

        for (String temp: y) {

            if (temp == text) {
                System.out.println("found");
            } else {
                System.out.println("nothing");
            }
        }
    }
}

output:
expected : code should display "found"
but it is displaying "nothing"

A: Compare the String with equals() method not with == operator
== operator is used to compares the reference of the object.
change if (temp == text) to if (temp.equals(text))

A: String is Object and object equality checks with .equals() method.
so try:
if(temp.equals(text))

== operator is used for object reference comparison means two reference is pointing to the same object or not or primitive(int, double, ...) value comparison.


text:
Q: Django context processor not setting request var in template I have the following view:
@login_required
def manage(request):
    ''' Display the list of posts that belong to the user '''
    posts = Post.objects.filter(user=request.user).order_by('created_at')
    return render_to_response('posts/manage.html', {'posts':posts}, context_instance=RequestContext(request))

The request variable is empty in my template.
My settings:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    'social_auth.context_processors.social_auth_by_name_backends',
)

I want to access the logged in user through request.user.
What could be wrong? Thanks.
Note that I am using social auth for user login.

A: Add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS

A: With those context processors, you don't have access to request at all - but you do have access to user directly.


text:
Q: Cannot read records after inserting to google calendar Cannot read records after inserting to google calendar.
Some time letter, records are read.
Why?
If take Context from Activity, then everything works fine. If Context from AndroidTestCase or take on their Application, it does not work.
Note: Calendar with id=calendarId is empty.
public static void test(final Context context, final int calendarId) {
    // insert
    java.util.Calendar calendar = java.util.Calendar.getInstance();

    ContentValues contentValues = new ContentValues();

    contentValues.put("calendar_id", calendarId);
    contentValues.put("dtstart", calendar.getTime().getTime());
    contentValues.put("dtend", calendar.getTime().getTime() + 1L*60*60*1000);
    contentValues.put("title", "test_title");

    Uri uri = Uri.parse("content://com.android.calendar/events");
    context.getContentResolver.insert(uri, contentValues);

    // read
    Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
    ContentUris.appendId(builder, Long.MIN_VALUE);
    ContentUris.appendId(builder, Long.MAX_VALUE);

    Cursor cursor = context.getContentResolver.query(
        builder.build(),
        new String[]  { "event_id", "title" },
        "Calendars._id=" + calendarId,
        null,
        null);
    try {
        if (!cursor.moveToNext()) {
            // fail
            throw new IllegalStateException();
        }
    } finally {
        cursor.close();
    }
}

A: My mistake. In code:
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
ContentUris.appendId(builder, Long.MIN_VALUE);
ContentUris.appendId(builder, Long.MAX_VALUE);

Can not set start date Long.MIN_VALUE value.


text:
Q: Getting absolute URL from href I'm trying to automate downloading files from a website, but links are relative. How do I get full path to the file?
$a = Invoke-WebRequest -Uri 'http://www.website.com/folder/default.aspx' -UseBasicParsing

$a.Links[$i].href - can be a relative path, so how can I expand it to a full path?

A: Using Uri class and its new(baseUri, relativeURLString) constructor:
function Get-AbsoluteURL($pageUrl, $url) {
    [Uri]::new([Uri]$pageUrl, $url).AbsoluteUri
}

Example:
Get-AbsoluteURL 'https://stackoverflow.com/questions/38899802/getting-blabla' `
                '../aa.jpg'

https://stackoverflow.com/questions/aa.jpg


text:
Q: Is it possible to mount an MFM drive without an ISA slot? As the title indicates, is there a way to connect a vintage MFM 5.25 form factor hard drive to a modern system that lacks an ISA slot (hence no MFM controller) ?
I know its a long shot, but ideally I would like some hodgepodge of adapter(s) that will let me mount one of these drives under Windows 7 for some benchmarking.  For that matter, I wonder if Windows 7 would even address such a device without some degree of 3rd party hackery/emulation?

A: You might be able to connect a controller using a USB to ISA board, such as http://www.arstech.com/item-USB-2-0-to-ISA-card-usb2isa.html
I believe Linux 2.6 does have drivers for MFM controllers, whereas I find it highly unlikely that Windows 7 would support MFM controllers... Good luck though!


text:
Q: Start a MVP WinForms application with Ninject I am trying to startup an simple Model View Presenter WinForms application and use the constructor injection to inject IMainView, IEventPublisher and IRepository to the main presenter.
However, I am having some problems to find out how to exactly do this. My problem is that for some reason presenter seems to create two instances of the view or view is created and not shown.
Program.cs
  var kernel = new StandardKernel();
  kernel.Load(Assembly.GetExecutingAssembly());
  //var view = kernel.Get<View.MainForm>();
  var presenter = kernel.Get<Presenter>();

  //Application.Run(view);
  Application.Run();

If view is initialized on the program.cs, then also presenter creates its own view? And with the active approach above, the view is created but not shown.
Presenter.cs
public Presenter(IMainForm view,
  IRepository repository,
  IEventPublisher eventPublisher)
{
  _view = view;
  _repository = repository;
  _reactiveEventPublisher = eventPublisher;
}

MainForm.cs
public Form(IEventPublisher eventPublisher)
{
  _reactiveEventPublisher = eventPublisher;
}

NinjectBindings.cs
  public class NinjectBindings : NinjectModule
  {
    public override void Load()
    {
      Bind<IRepository>().To<Repository>();

      Bind<IMainForm>().To<View.MainForm>();

      Bind<IEventPublisher>().To<ReactiveEventAggregator>().InSingletonScope();

      Bind<Presenter>().ToSelf();

    }
  }

Question is, what is the proper way to start WinForms application in case the view is injected to the presenter?
Using Ninject 3.3.4 as IoC container.

A:
If view is initialized on the program.cs, then also presenter creates
  its own view?

This is because of the object scoping. If you request an IMainForm in Program.cs, and then request a Presenter, then Ninject will inject a new instance of View.MainForm for the Presenter and thus you have two instances of the view. To use the same instance you need to scope the binding in singleton scope.
Bind<IMainForm>().To<View.MainForm>().InSingletonScope();

When requesting an instance of the view, ensure you do so via your binding, i.e. var view = kernel.Get<View.IMainForm>(); otherwise Ninject will try to self-bind and will be dodging your singleton scope.


text:
Q: jQuery find next anchor element inside td I have HTML that looks like this:

    Hello

    Bye

    Foo

    Bar

...

The divs have a listener for tab keydown, so whenever a tab is pressed it should go to the next link. (or perhaps it's enough to go to the next td element?)
For instance I click on Hello anchor, then Bye anchor should get focused. If I click on Bye anchor then Foo anchor should get focused.

A: You can get the index of the clicked link and call .focus() on the next element in the array:
var $links = $('table a');
$links.on('click', function() {
    $links.eq($links.index(this)+1).focus();
});

https://jsfiddle.net/qcbozbyn/1/

A: How about working with jquery Next() and prev() methods
$("table tr td a").click(function(){
   var me = $(this) ;
    var nextElm = me.closest("td").next();
    if(nextElm.length>0){
        nextElm.find("a").css("color","green");
    }
    else{
        var prevElm = me.closest("td").prev();
        if(prevElm.length>0){
            prevElm.find("a").css("color","red");
        }
    }
});

JSfiddle link: https://jsfiddle.net/7fw2oeLm/


text:
Q: mongoDB index structure I have put Index on mongoDB.
when I ensureIndex using php it put 1 as NumberLong(1) .
I want to know:

*

*will this Indexing work or not.
If not

*how to remove this NumberLong(1)
Code:
"0": {
    "v" : 1,
    "key" : {
        "telNum" : NumberLong(1),
        "requestID" : NumberLong(1)
    },
    "ns" : "database.collections",
    "background" : true,
    "name" : "tel_req"
  }

A: Yes, the index will still work.
This is due to a change in the way that the PHP driver works ( https://jira.mongodb.org/browse/PHP-955 ).
I will come out immediately and say that it is not advised to remove it. That NumberLong object supports throwing in 64bit integers by default so it is extremely useful to have the defaults in the new PHP driver on by default and to treat NumberLong as the new generic number object.
However, to go into this a bit more and explain to you what's happening, there is this runtime configuration option called native_long: http://www.php.net/manual/en/mongo.configuration.php#ini.mongo.native-long which essentially allows MongoDB to store 64bit numbers by storing them into NumberLong objects. In PHP it would automatically convert to int data type and back again, making this transparent to the end user.
If you have this turned off MongoDB can only store 32bit integers.
This option used to be off by default but now it is on, that is why you are seeing this behaviour.
You can turn it off in the PHP configuration to remove the NumberLongs


text:
Q: cannot select option from multiple select after removing old options I am using chosen.jquery to convert my select to multiple select. When I remove the current options from my select field and load the new ones, I am not able to select the newly added options.
I debugged and noticed that at following line from Chosen.Jquery.js the selected option is unselected.
  if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
      this.form_field_jq.trigger("change", {
        'selected': this.form_field.options[item.options_index].value
      });
    }

I execute following code after I remove the options from the list.
$('#partnerCasteId').trigger("liszt:updated");

I just noticed that liszt:updated option is not present in the Chosen.jquery.
Do I need to get a different version?
Please help


text:
Q: Socket programing Hello I'm doing a work on creating a connection between a client and a server, the point of the work is sending a GET request using only the sockets, we are using XAMPP as the servers, we have two txt files on htdocs and I want to request one or the other, but I'm having 404 not found.
How do I fix this?
from socket import*

#IP, Porto do servidor
HOST = '127.0.0.1'
PORT = 80

#Criar o socket TCP
clientSocket = socket(AF_INET, SOCK_STREAM)

#Estabelecer ligação ao servidor
clientSocket.connect((HOST,PORT))

#Escolha entre Fernando Pessoa ou Luis de Camões
print('Qual o seu Poeta Favorito: ')
voto = input('1-Luis de Camoes ou 2-Fernando Pessoa' )

#Pedido de Get
pedidoHTTP = None
if(voto == '1'):
    pedidoHTTP =  f"GET /localhost/trabalho/1.txt HTTP/1.1\r\nHost: {HOST}:{PORT}\r\n\r\n".encode()
elif(voto == '2'):
    pedidoHTTP = f"GET /localhost/trabalho/2.txt HTTP/1.1\r\nHost: {HOST}:{PORT}\r\n\r\n".encode()
else:
    print('Pressione 1 ou 2 para ser valido')
    clientSocket.close()

clientSocket.sendall(pedidoHTTP)

#Ler a resposta do servidor
Rececao = clientSocket.recv(8000).decode()


text:
Q: Unexpected behavior from python's relativedelta I'm getting a confusing result when using Python's timestamps and

my_timestamp

Timestamp('2015-06-01 00:00:00')

my_timestamp + relativedelta(month = +4)

Timestamp('2015-04-01 00:00:00')
Naturally I expected the output to Timestamp('2015-10-01 00:00:00')
What is the correct way to add "months" to dates?

[EDIT]: I've since solved this by using the following (in case anyone in Pandas has the same problem):

print my_timestamp
  print my_timestamp + DateOffset(months=4)

2015-06-01 00:00:00
2015-10-01 00:00:00

A: The issue is that you are using the wrong keyword argument.  You want months instead of month.
Per the documentation, month denotes absolute information (not relative) and simply replaces the given information, as you are noting.  Using months denotes relative information, and performs the calculation as you'd expect:
Timestamp('2015-06-01 00:00:00') + relativedelta(months=4)

2015-10-01 00:00:00


text:
Q: can't get to run chemfig module properly I did structure formulas with latex before, but now I wanted to reaction mecanisms with electron movement arrows and everything.
I used some example code to try and get to know the principles, but it doesn't work. Some commands don't work apparently and the arrows go anywhere but not where I want them to go.
This is my file:
\documentclass[a4paper,10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{chemfig}
\usepackage{chemmacros}

\begin{document}

\chemsetup[chemformula]{format=\sffamily}
\renewcommand*\printatom[1]{\ensuremath{\mathsf{#1}}}
\setatomsep{2em}
\setdoublesep{.6ex}
\setbondstyle{semithick}

\section{A}

\setatomsep{7mm}
\setchemrel{}{}{5mm}
\chemfig{R-@{dnl}\lewis{26,O}-H}
\chemsign{+}
\chemfig{R-@{atoc}C([6]-OH)=[@{db}]O}
\chemrel[\chemfig{@{atoh}\chemabove{H}{\scriptstyle\oplus}}]{<>}
\chemmove[->,shorten <=2pt]{
\draw[shorten >=2pt](dnl)..controls +(90:1cm)and+(north:1cm)..(atoc);
\draw[shorten >=6pt](db)..controls +(north:5mm)and+(100:1cm)..(atoh);}

\bigskip

\end{document}

the commands "\chemrel", "\chemsign" and "\setchemrel" are errored. Did I miss something?

A: Yes, you did miss something: \setchemrel etc are deprecated since chemfig features complete schemes (since v1.0 2011/06/15). They have been removed with v1.2 2015/10/08. Just use the \schemestart ... \arrow ... \schemestop:
\documentclass[a4paper,10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{chemfig}
\usepackage{chemmacros}

\renewcommand*\printatom[1]{\ensuremath{\mathsf{#1}}}
\setatomsep{2em}
\setdoublesep{.6ex}
\setbondstyle{semithick}

\begin{document}

\section{A}

\schemestart
  \chemfig{R-@{dnl}\lewis{26,O}-H}
  \+
  \chemfig{R-@{atoc}C([6]-OH)=[@{db}]O}
  \arrow(.10--){<=>[\chemfig{@{atoh}\chemabove{H}{\scriptstyle\fplus}}]}
  \chemfig{R-C([6]-OH)(-[2]\chemabove{O}{\scriptstyle\fplus}(-[4]R)-[0]H)-O-H}
\schemestop

\chemmove[->,shorten <=2pt]{
  \draw[shorten >=2pt](dnl)..controls +(90:1cm)and+(north:1cm)..(atoc);
  \draw[shorten >=6pt](db)..controls +(north:5mm)and+(100:1cm)..(atoh);
}

\end{document}


text:
Q: Data Reader error using Entity Framework I'm in the process of building a WCF Service Application which connects to an SQL Database using Entity SQL (Entity Framework). At the moment I keep getting this error with several methods:
The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.
This is an example of one of the methods and would appreciate some advice on how to approach this:
public string[] Tables()
    {
        string Sql = @"SELECT * FROM information_schema.tables";

        using (var Context = new XEntities())
        {
            Context.Database.Connection.Open();

            IEnumerable<string> Query = Context.Database.SqlQuery<string>(Sql);
            string[] results = Query.ToArray();

            Context.Database.Connection.Close();

            return results;

        }

The method is supposed to query the database for a list of tables and send them back in an array. This will then be inputted into a ListBox by the Windows Phone App.
Thank You for your time.

A: Modify your query to select the column you want to populate Query with:
string Sql = @"SELECT TABLE_NAME FROM information_schema.tables";


text:
Q: If my friend has GTA 5 for 360 and I have one can I invite them to my game online? My friend and I want to play GTA 5 together online, but I have an Xbox one and she has an Xbox 360. Can I join or invite them to my game so we can play together?

A: Due to differences in hardware and gaming architecture it's not possible to cross platform game on GTA V.

A: Because the Xbox One has more hardware, different hardware, and more up to date hardware than the Xbox 360, you cannot play games together.


text:
Q: Error of "Object Required" for copy an array value I have the error message of

Object Required

at the line of hostname(X, 1).Copy
I have used msgbox to test this line and the hostname for this array can be found, but just this line of code has error message. The hostname for this array value is W01GOPTIMAPP1A.
The related code is
wSlastRow = .Range("B" & .Rows.Count).End(xlUp).Row
    hostname = WintelSheet.Range("B1:B" & wSlastRow).Value2
    '// Now Loop through each row
    For X = 2 To wSlastRow

    If Not IsError(.Range("AI" & X).Value) Then
        If IsDate(.Range("AI" & X)) Then

        '//Calculate the last day of the month for dates in Column W (dtStart) and first day of the next current month (dtFinal)
        dtStart = DateSerial(Year(.Range("AI" & X)), Month(.Range("AI" & X)) + 1, 1)
        dtFinal = DateSerial(Year(Now), Month(Now) + 1, 1)
        With AparSheet
        .AutoFilterMode = False
        With .Range("J:L")
        .Columns(3).AutoFilter field:=1, Criteria1:=">=" & dtStart, _
        Operator:=xlAnd, Criteria2:="<" & dtFinal
            With .Resize(.Rows.Count - 1, 1).Offset(1, 0)
            NumberOfPasteRows = .Rows(.Rows.Count).End(xlUp).Row
            If CBool(Application.Subtotal(103, .Columns(1))) Then
                .EntireRow.Copy Destination:=GeneratedSheet.Rows(wSLastPasteRow & ":" & (wSLastPasteRow + NumberOfPasteRows - 1))
                hostname(X, 1).Copy
                GeneratedSheet.Range("B" & wSLastPasteRow).Resize(NumberOfPasteRows - 1).PasteSpecial xlPasteValues
                wSLastPasteRow = wSLastPasteRow + NumberOfPasteRows - 1

            End If
            End With
        End With
        End With
        End If
    End If
    Next X

A: The posted code is incomplete but based on behavior "hostname" is declared as Variant, or it is a Variant if it's not declared
When you perform this operation hostname = WintelSheet.Range("B1:B" & wSlastRow).Value2 you assign the values from a Range object to a Variant (array)
The Range object has a method called ".Copy", the Variant doesn't
Edit:
To be able to copy from hostname declare it as a Range object:
Dim hostname As Range
Set hostname = WintelSheet.Range("B1:B" & wSlastRow)

hostname(x, 1).Copy

or simply use the range itself:
WintelSheet.Range("B" & wSlastRow).Copy