Q: MergeMap from Array of Observables TLDR: Working example is in the last codeblock of this question. Check out @bryan60 answer for a working example using concat rather than mergeMap.

I'm trying to run a number of remote requests sequentially, but only the first observable is executed.
The number of request vary, so I can't do a dodgy solution where I nest observables within each other.
I'm using the following code:
const observables = [
  observable1,
  observable2,
  ...
];

from(observables).pipe(
  mergeMap(ob=> {
    return ob.pipe(map(res => res));
  }, undefined, 1)
).subscribe(res => {
  console.log('Huzzah!');
})

In the past (rxjs 5.5) Ive used the following:
let o = Observable.from(observables).mergeMap((ob) => {
  return ob;
}, null, 1);

o.subscribe(res => {
  console.log('Huzzah!');
})

I'm not sure what I'm doing wrong, can anybody shed some light?
An additional request would be to only print 'Huzzah!' once on completion of all requests rather than for each individual Observable.
EDIT:
Removing undefined from my original code will make it work, however there was another issue causing only the first observable to be executed.
I'm using Angular's HttpClient for remote requests. My observable code looked like this:
const observables = [];

// Only the first observable would be executed
observables.push(this.http.get(urla));
observables.push(this.http.get(urlb));
observables.push(this.http.get(urlc));

Adding .pipe(take(1)) to each observable results in each observable being executed:
const observables = [];

// All observables will now be executed
observables.push(this.http.get(urla).pipe(take(1));
observables.push(this.http.get(urlb).pipe(take(1));
observables.push(this.http.get(urlc).pipe(take(1));

The code I ended up using, which executes all observables in sequential order and only triggers Huzzah! once is:
const observables = [];

observables.push(this.http.get(urla).pipe(take(1));
observables.push(this.http.get(urlb).pipe(take(1));
observables.push(this.http.get(urlc).pipe(take(1));

from(observables).pipe(
  mergeMap(ob=> {
    return ob.pipe(map(res => res));
  }, 1),
  reduce((all: any, res: any) => all.concat(res), [])
).subscribe(res => {
  console.log('Huzzah!');
})

Thanks to @bryan60 for helping me wit this issue.

A: if these are http requests that complete, I think your bug is caused by a change to the mergeMap signature that removed the result selector. it's hard to be sure without knowing exactly which version you're on as it was there, then removed, then added again, and they're removing it once more for good in v7.
if you want to run them sequentially... this is all you need...
// concat runs input observables sequentially
concat(...observables).subscribe(res => console.log(res))

if you want to wait till they're all done to emit, do this:
concat(...observables).pipe(
  // this will gather all responses and emit them all when they're done
  reduce((all, res) => all.concat([res]), [])
  // if you don't care about the responses, just use last()
).subscribe(allRes => console.log(allRes))

In my personal utility rxjs lib, I always include a concatJoin operator that combines concat and reduce like this.
the only trick is that concat requires observables to complete till it moves on to the next one, but the same is true for mergeMap with concurrent subscriptions set to 1.. so that should be fine. things like http requests are fine, as they complete naturally after one emission.. websockets or subjects or event emitters will behave a bit differently and have to be manually completed, either with operators like first or take or at the source.

A: If you are not concerned about the sequence of execution and just want 'Huzzah!'  to be printed once all the observable has been executed forkJoin can also be used.Try this.
forkJoin(...observables).subscribe(res => console.log('Huzzah');


Q: Issues with document syncing between iOS and host computer I had an app in my iphone which i recorded a meeting, (TSA) it said it was ready to sync to document folder. so I syncd and they all disappeared.
Where is the document folder located?
When itunes deletes from iphone is there any way to find those and restore?
Why did itunes delete apps that were installed?

A: Did you sync with a computer that you don't usually use? If you lost the app, you lost it's Documents directory, and your recording is gone.
Here's what is supposed to happen;
You're supposed to open iTunes and browse to your device. In the list of apps with the iOS Home Screen style view, there is a section at the bottom to select an Application, and manage it's Documents storage folder.
You do not need to sync in order to view up-to-date information in this screen. You are immediately able to save the data out of the app into a location on your computer.
Unfortunately, if you've sync'ed your phone and lost the app you've also lost the data from within it. There is little likelihood for data recovery on a Flash Disk device.


Q: Localization works in iOS 7 but not in iOS 8 I have localized versions of a file hello.txt in folders en.lproj and fr.lproj.
When I run the following code on iOS 7 simulator with language set to French, the French version is loaded. But with iOS 8 in French, I only get English... Why?
println (NSLocale.preferredLanguages().first!)
println (NSBundle.mainBundle().preferredLocalizations.first!)
let path = NSBundle.mainBundle().pathForResource ("hello", ofType: "txt")
let text = NSString (contentsOfURL: NSURL (fileURLWithPath: path!)!, encoding: NSUTF8StringEncoding, error: nil)
println (text!)

A: Known issues in Xcode 6.1:

Localization and Keyboard settings (including 3rd party keyboards) are
  not correctly honored by Safari, Maps, and developer apps in the iOS
  8.1 Simulator. [NSLocale currentLocale] returns en_US and only the English and Emoji keyboards are available. (18418630, 18512161)

Problem exists since Xcode 6 GM


Q: Adding a column to a Dataframe containing the Symbol of the parent node I am using bulk data (List of CPC Valid symbols) from the CPC website. I've read the csv into a pandas df, and the first 30 rows (of over 260K) are:
    SYMBOL  level   not-allocatable additional-only
1   A   2   True    False
2   A01 4   True    False
3   A01B    5   True    False
4   A01B 1/00   7   False   False
5   A01B 1/02   8   False   False
6   A01B 1/022  9   False   False
7   A01B 1/024  9   False   False
8   A01B 1/026  9   False   False
9   A01B 1/028  9   False   False
10  A01B 1/04   9   False   False
11  A01B 1/06   8   False   False
12  A01B 1/065  9   False   False
13  A01B 1/08   9   False   False
14  A01B 1/10   9   False   False
15  A01B 1/12   9   False   False
16  A01B 1/14   9   False   False
17  A01B 1/16   8   False   False
18  A01B 1/165  9   False   False
19  A01B 1/18   9   False   False
20  A01B 1/20   8   False   False
21  A01B 1/22   8   False   False
22  A01B 1/222  9   False   False
23  A01B 1/225  10  False   False
24  A01B 1/227  9   False   False
25  A01B 1/24   8   False   False
26  A01B 1/243  9   False   False
27  A01B 1/246  9   False   False
28  A01B 3/00   7   False   False
29  A01B 3/02   8   False   False

The level value creates a hierarchy. So node A01B 1/00 is level 7 and a child of A01B. A01B 1/02 is level 8 and the child of A01B 1/00 & A01b 3/00 is a child of A01B.
What I would like is a way to create a new column called PARENT that contains the SYMBOL of the node's direct parent. For example, I edited the csv in Excel to show the desired result of the first few rows:

Note: there are no level 1, 3, or 6 symbols. There are multiple level 2 symbols. There is no parent for level 2 symbols, the parent of level 4 symbols can be assigned the first level 2 symbol above it, and the parent of level 7 symbols likewise can be assigned the first level 5 symbol above it.

EDIT: I need to better explain how to determine a node's parent. The level value and the row position are all that is needed to determine a parent.
I would like to use pandas to do the work, but I am not sure how to get started. Any takers? Thank you

A: In this answer I assume that your direct parent is always in a row above your own as it is what your expected output and your diagramm suggests.
With this hypothesis, we can, for each row, take the closest row with a level below the row :
import pandas as pd

data={"Symbol":["A", "A01", "A01B", "A01B 1/00", "A01B 1/02", "A01B 1/022", "B"], "level":[2,4,5,7,8,9,2]}

df=pd.DataFrame(data=data)
df['Parent'] = ''

for index, row in df.iterrows():
    # We look at the potential parents
    potential_parents = df.loc[df.index.isin([x for x in range(index)]) & (df['level'] < row['level']), 'Symbol']
    # And we take the last one as our parent
    if len(potential_parents) == 0:
        df.loc[index, 'Parent'] = ''
    else:
        df.loc[index, 'Parent'] = potential_parents.iloc[-1]

Output :
       Symbol  level     Parent
0           A      2
1         A01      4          A
2        A01B      5        A01
3   A01B 1/00      7       A01B
4   A01B 1/02      8  A01B 1/00
5  A01B 1/022      9  A01B 1/02
6           B      2

A: Here's another method.  GetParent() returns a function that keeps track of the most recent symbol for each level and returns the parent of the current level.  Using it in pandas.apply() creates a column with the parent symbols.
def GetParent():
    #            0  1  2  3  4  5  6  7  8  9  10
    hierarchy = [0, 0, 0, 0, 2, 4, 0, 5, 7, 8, 9]
    parent = [' ']*11

    def func(row):
        #print(row)
        symbol,level = row[['SYMBOL', 'level']]

        parent_level = hierarchy[level]
        parent_symbol = parent[parent_level]

        parent[level] = symbol

        return pd.Series([parent_symbol], index=['parent'])

    return func

# create a column with the parents
parents = df.apply(GetParent(), axis=1)
df = pd.concat([df, parents], axis=1)

df

Output:
    SYMBOL  level   na      ao      parent
0   A           2   True    False
1   A01         4   True    False   A
2   A01B        5   True    False   A01
3   A01B 1/00   7   False   False   A01B
4   A01B 1/02   8   False   False   A01B 1/00
5   A01B 1/022  9   False   False   A01B 1/02
6   A01B 1/024  9   False   False   A01B 1/02
7   A01B 1/026  9   False   False   A01B 1/02
8   A01B 1/028  9   False   False   A01B 1/02
9   A01B 1/04   9   False   False   A01B 1/02
10  A01B 1/06   8   False   False   A01B 1/00
11  A01B 1/065  9   False   False   A01B 1/06
12  A01B 1/08   9   False   False   A01B 1/06
...


Q: Why do the LED light bulbs flicker but CFL light bulbs don't? We've tried 60 watt LED light bulbs on a ceiling fixture and a lamp in the house. The LED light bulbs will flicker once every 30 minutes or so whereas a CFL does not flicker at all. Neither of the problem fixtures are dimmers. It's an older house built in the late 1940's. We have ceiling fixtures elsewhere in the house with LEDs with no problem.
Hoping we just got a bad batch of LEDs
Is there a reason why the LEDs would flicker when the CFL bulbs do not? Are they more prone to electrical wiring issues?

A: There is a good article here:
https://www.ccohs.ca/oshanswers/ergonomics/lighting_flicker.html
Fluorescent lights actually do flicker but the frequency will typically be high and the light dims a lot less at it’s minimum point than LEDs.
LEDs tend to be instant on / instant off and run from DC.  LED circuits can be designed to reduce flicker by adding capacitance and using a full bridge rectifier or inverter to convert AC to DC, but cheap Christmas light strings may not use a full bridge rectifier, which would cause flicker at around 50/60 Hz.  Additionally, if the circuit does not include enough capacitance the intensity of the flicker will increase.

A: My best guess is you've got a bad connection or other resistance in the wiring (maybe oxidation on switch contact etc) the comment to change bulb position(s) or feedback on trying this would help rule out the bulb itself.

A: Is this the stair light?
Also, question should clarify whether these are flickering when the power is ON, or OFF.
Assuming OFF, it's because of stray power on the circuit, usually from electrostatic coupling from other cables (though degraded insulation is also a possibility).
I've even seen a CFL flicker on a (UK, 230V) dual switched circuit (stair light) though CFL are much less prone to it.
In this circuit there's an upstairs switch, and a downstairs switch, both SPCO (changeover) switches, and a 2-core cable (+earth) between them. In this arrangement, the lamp is ON when both switches connect to the same core, and OFF when one switch connects to the other core.
This leaves power connected to the "off" core via the capacitance between the cores for the whole length of the cable, and you can see half the supply voltage via several hundred pF, capable of sourcing tens of microamps. (Why only half? There's a similar capacitance to that Earth line).
That's enough to slowly charge up the capacitor in a LED bulb (and rarely in a CFL) until it turns on momentarily, drains the cap, off again, and repeat.
Other circuits may exhibit this to an extent, but it's particularly bad in stair lights for the above reason.
If this is what you're seeing, it's worth having the wiring checked for degraded insulation, but otherwise it's a curiosity rather than a problem. Any incandescent bulb, however low power, on that circuit, will drain the stray power before it becomes a problem.

A:
The LED light bulbs will flicker once every 30 minutes or so whereas a CFL does not flicker at all.

HVAC, water heater, etc flipping on or off and injecting noise into the power lines.  Your LED bulbs are extremely sensitive to it because they have cheap power supplies.

Is there a reason why the LEDs would flicker when the CFL bulbs do not? Are they more prone to electrical wiring issues?

Yes absolutely.  It is due to the way cheap LED bulb power supplies work.  A typical LED bulb is made of ~3v diodes arranged in series hooked up to a rectifier and a current limiting element (either a capacitor/resistor as in this diagram or more commonly in the USA a linear regulator on the DC side):

In this design the LEDs are stacked up to be close to the rectified mains voltage so that losses are low in the resistor/regulator.  This works great as long as the mains voltage is perfectly stable.  However, if any load on the line switches, the voltage will fluctuate.  Since the diodes summed forward voltage is very nearly the rectified line voltage, even small fluctuations are enough to drop below the forward voltage and turn off the lights resulting in flickering.  If the capacitor were very large, or some kind of regulation were present in the circuit, this would not happen, but that would be much more expensive so you don't see it in cheap products.  Similarly, they could put fewer diodes in series resulting in more headroom between the forward voltage and the rectified line voltage (and more dissipated across the resistor/regulator), but this is a nonisolated design - everything is attached to mains voltage, so by regulation it cannot have any exposed metal heatsinking.  Without heatsinking, dissipated power must be kept to an absolute minimum as there is little ability to get heat out.

A: LEDs are a goldrush right now, and as such there are a lot of "bottom of barrel" manufacturers in the game.  People who buy mail-order or who buy cheap are particularly vulnerable to encountering this crud.  Even a UL listing is no guarantee; UL certifies safety, not quality.  Everything at CostCo and huge swaths of what I see at box stores are on my "never buy" list.
However, there are also bona-fide electrical system faults that can cause this.  Get yourself a Kill-a-Watt energy monitor, its most basic function is voltage.  Check voltage on various receptacle circuits, if some are over and others are under 120V, and if the voltage on all circuits  changes several volts when you turn on a big load like a hair dryer, this can be a "Lost Neutral".  That is a power outage at the pole, which the power company will fix for free, but it's devilishly difficult to detect.  If that is the case, then a motor startup surge is causing a wild voltage swing, driving the LED circuit to say 30 volts (whilst the other leg is 210V),  which is causing the LEDs to misbehave.
A lost neutral is not certain or even likely.  But it's such a dangerous problem, and such an easy and free fix, that it's worth checking for it.


Q: how to loop + 7 days and display the data based on that loop I have a problem with my code, I want to show Tadarus, Kajian, Edukasi and Umum. example I have variable $startdate = '2019-09-20'.
If $startdate + 7day, I want to echo Tadarus
If $startdate + 14day, I want to echo Kajian
If $startdate + 21day, I want to echo Edukasi
If $startdate + 28day, I want to echo Umum
and then if last echo is Umum, I want to show data from Tadarus again. This is my code:
date_default_timezone_set("Asia/Jakarta");
$getdate = date("Y-m-d");
if (strtotime("+7 day", $getdate)) {
   echo "Tadarus";
}elseif(strtotime("+14 day", $getdate)){
   echo "Kajian";
}elseif(strtotime("+21 day", $getdate)){
   echo "Edukasi";
}elseif(strtotime("+28 day", $getdate)){
 echo "Umum";
}

A: Why don't you do something like that:
function echoBasedOnDay($date) {
    if ($date === date('Y-m-d', strtotime("+7 days"))) {
        echo "Tadarus";
    } elseif($date === date('Y-m-d', strtotime("+14 days"))){
        echo "Kajian";
    } elseif($date === date('Y-m-d', strtotime("+7 days"))){
        echo "Edukasi";
    } elseif($date === date('Y-m-d', strtotime("+7 days"))){
        echo "Umum";
    }
}

echoBasedOnDay(date('2019-09-27')); // You can pass any date you want in here as the function's parameter


Q: Mathematical operations are not shown correctly in the Stack Exchange Android app In the Stack Exchange Android app, mathematical operations are not shown correctly. They are shown in some coded words. To read the questions or answers with use of such operations, I have to open the question in the browser.
Is this problem only with me or do the app need an update? Here is a snapshot of someone's question in the app -

And here it is how it is shown in the browser -


Q: How to setup path to jupyter lab of activated environment I need to configure several pieces of software to access various executables that might change with conda environments.
I know that this is broad so lets stick to jupyter lab, I want to add an item to Windows' context menu. I have all of keys in my registy setup except for Default of command and this entry needs to path to jupyter lab.
As I understand all anaconda's executables will be found in

Users\my.name\AppData\Local\Continuum\anaconda3

This is the part where I'm lost directory above contains "Scripts" and "env" after examining each it looks to me like "Scripts" contains executables for base(root) environment and env contains files specific to each environment.
Is there another directory that I missed, that contains files/links to currently activated environment?
Maybe my approach is to0 direct so is there a programmatic way to  figure out where is the executable I'm looking for?
I should point out that I'm working on Win 10 machine.


Q: User with dba privs can't login to APEX, but can from SQL*Plus I'm using Oracle 11gR2 XE. A user with dba privileges can't log in to the APEX interface, but can from the command line with sqlplus.
I just created user:
CREATE ROLE administrators;
GRANT dba TO administrators;
CREATE USER superuser IDENTIFIED BY "root";
GRANT administrators TO superuser;

If I run cmd, type sqlplus and log in with "superuser", I get access.
But the web interface (APEX) denies access with an "invalid credentials" error message.
What do I need to do to be able to log in on the APEX interface?

A: The APEX administrator accounts are not linked to a database schema. Reciprocally, creating a database schema won't create an APEX account.
You'll have to create the administrator account via the web interface.

*

*Connect to the administration page:

*

*If your setup uses the embedded PL/SQL gateway, go to:
http://hostname:port/apex/apex_admin

*If your setup uses Apache and mod_plsql, go to:
http://hostname:port/pls/apex/apex_admin

Then On the Login page:

*

*In Username, enter admin.

*In Password, enter the Oracle Application Express administrator account password you specified when you installed Oracle Application Express.

*There are three levels of administration, decide which type you want to create:

*

*Developers create and edit applications.

*Workspace administrators are developers who also perform administrator tasks specific to their workspace such as managing user accounts, monitoring workspace activity, and viewing log files. See "Workspace and Application Administration".

*Oracle Application Express administrators are superusers that manage the entire hosted instance using the Oracle Application Express Administration Services application.

I suppose you want to create an APEX administrator account. They are workspace administrator of the special workspace "Administration" that you can create following the standard APEX account creation.


Q: What is wrong with this email headers? It always go to gmail and yahoo spam box Delivered-To: xxxx@gmail.com

Received: by 10.229.249.207 with SMTP id ml15cs152516qcb;
        Tue, 9 Aug 2011 05:22:45 -0700 (PDT)

Received: by 10.151.142.17 with SMTP id u17mr6831320ybn.198.1312892565452;
        Tue, 09 Aug 2011 05:22:45 -0700 (PDT)

Return-Path: <xxxxx@xxxxxxxxx>

Received: from mail.mydomain.com.br (mail.mydomain.com.br [xx.xx.xxx.xx])
        by mx.google.com with ESMTP id g4si5211294ybi.22.2011.08.09.05.22.44;
        Tue, 09 Aug 2011 05:22:44 -0700 (PDT)

Received-SPF: pass (google.com: domain of xxxxx@xxxxxxxxx designates xx.xx.xxx.xx as permitted sender) client-ip=x.xx.xxx.xx;

Authentication-Results: mx.google.com; spf=pass (google.com: domain of xxxxx@xxxxxxxxx designates x.xx.xxx.xx as permitted sender) smtp.mail=xxxxx@xxxxxxxxx; dkim=pass header.i=@mydomain.com.br

Received: from mydomain.com.br (xxxxxxxxxxxxxxx.xxxxxxxxxxxxxxx [x.xx.xxx.xx])
    by mail.mydomain.com.br (Postfix) with ESMTPA id 02C12B543AE
    for <xxxx@gmail.com>; Tue,  9 Aug 2011 09:22:42 -0300 (BRT)

DomainKey-Signature: a=rsa-sha1; s=mail; d=mydomain.com.br; c=simple; q=dns;
    b=K7lPw72zqmctULDiEdOjdgQWpmClkICAjdKo07hkSicyQU7nRjFAQXR9hf270t0aq
    wD5XjP35FRY3a52kNsVo1OAI22ttiKEDUC/N9e0/57cnoTXFVvzumYBSylgKyk3mPbu
    H0cEJtAVlutfgCES8x1Gdjigd/ek11WQabWWjnk=

DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=mydomain.com.br;
    s=mailk; t=1312892562;
    bh=1lADbHhk2GRaz/mXB4uRhcq7+ei8fg20sFxDsiIDW4A=;
    h=Date:To:From:Reply-to:Subject:Message-ID:MIME-Version:
     Content-Type;
    b=NN2JnPJJZfWnAjYU8x1dC5Cwz3WbkwPAx1yU0w9Xbz55Aa2KpbpIYnTiRmbKg7L0O
     7aP0EgAoqCMRwni6S6HqLw3MjR2I3B3qVmkMkyKMHjZ6N2sivovrTq/R0P9A4X+8G9
     GLim31Yo/ZTLl3cEyOrWCvokAVJYMSm/uS8aTpaY=

Date: Tue, 9 Aug 2011 09:22:42 -0300

To: xxxxx@xxxxxxxxx

From: xxxxx <xxxxx@xxxxxxxxx>

Reply-to: xxxxx <xxxxx@xxxxxxxxx>

Subject: =?iso-8859-1?Q?Reuni=E3o_de_professores_na_escola?=

Message-ID: <b8b16385ed9c0141365ee6257a39d284@xxxxx>

X-Priority: 3

X-Mailer: PHPMailer 5.2 (http://code.google.com/a/apache-extras.org/p/phpmailer/)

MIME-Version: 1.0

Content-Type: multipart/alternative;
    boundary="b1_b8b16385ed9c0141365ee6257a39d284"

--b1_b8b16385ed9c0141365ee6257a39d284
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit

Teremos reunião na escola a noite, favor comparecer. obrigado.

--b1_b8b16385ed9c0141365ee6257a39d284
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit

Teremos reunião na escola a noite, favor comparecer. obrigado.

--b1_b8b16385ed9c0141365ee6257a39d284--

Mail always to Gmail and Yahoo always go to spam.
The server is dedicated and it's not blacklisted.
Perhaps it could be some postfix config?

A: It's almost certainly the fact that the body of the e-mail is very short, and the subject is gobbledygook to a English based spam filter.
Subject: =?iso-8859-1?Q?Reuni=E3o_de_professores_na_escola?=


Q: Firebase-auth Error with Facebook Firebase auth with Facebook just stopped working on all our Polymer websites. One of them where updated 19th of march and has been working until yesterday/this afternoon (2017-03-27).
I get the following error message in chrome:
firebase-auth.js:32

"{"error":{"errors":[{"domain":"global","reason":"invalid","message":"A system error has occurred"}],"code":400,"message":"A system error has occurred"}}

A: Firebase Authentication is having problems right now. Look at the Firebase Status Dashboard here:
https://status.firebase.google.com/

A: Graph API v2.2 has reached the end of its 2-year lifetime on 27 March, 2017, so this might be connected. You should check your library and possible updates. See this chart of deprecation dates, which lists v2.2 as available until March 25, 2017.


Q: How to replace forward slashes with backslashes in a string in Emacs Lisp? I would like to replace forward slaches to backslashes in emacs lisp.
If I use this :
(replace-regexp-in-string "\/" "\\" path))

I get an error.
(error "Invalid use of `\\' in replacement text")

So how to represent the backslash in the second regexp?

A: Does it need to be double-escaped?
i.e.
(replace-regexp-in-string "\/" "\\\\" path)

A: Try using the regexp-quote function, like so:
(replace-regexp-in-string "/" (regexp-quote "\\") "this/is//a/test")
regexp-quote's documentation reads

(regexp-quote string)
  Return a regexp string which matches exactly string and nothing else.

A: What you are seeing in "C:\\foo\\bar" is the textual representation of the string "C:\foo\bar", with escaped backslashes for further processing.
For example, if you make a string of length 1 with the backslash character:
(make-string 1 ?\\)

you get the following response (e.g. in the minibuffer, when you evaluate the above with C-x C-e):
"\\"

Another way to get what you want is to switch the "literal" flag on:
(replace-regexp-in-string "/" "\\" path t t)

By the way, you don't need to escape the slash.

A: Don't use emacs but I guess it supports some form of specifying unicode via \x
e.g. maybe this works
(replace-regexp-in-string "\x005c" "\x005f" path))

or
(replace-regexp-in-string "\u005c" "\u005f" path))


Q: Передача параметра из qml в qt не так давно изучаю qml, возник вопрос, как можно передать по клику на кнопку в qml слое, параметр в c++.
Сам коннект обмена данными между c++ и qml осуществляю так:
main.cpp
QQmlApplicationEngine engine;
Class class;
QQmlContext *context = engine.rootContext();
context->setContextProperty("class", &class);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

class.h
signals:
void sendToQml(int k);
public slots:
void receiveFromQml();
private:
int k;

class.cpp
void Class::receiveFromQml()
{
    k++;
    emit sentToQml(k);
}

На слое qml принимаю параметр через Connections
main.qml
Connections{
    target: class
    onSendToQml: receiveIntToCpp.text = k;
}

Параметр выводится в текстовое поле, все ок, но не могу понять, как сделать обратную операцию, по клику на кнопку отправить переменную из qml в c++.
Может быть есть какие-нибудь примеры, или советы.
Спасибо за внимание!

A: context->setContextProperty("class", &class);

Вот этой строкой ты сделал объект class "видимым" в QML под именем "class".
Теперь, в QML-коде можно вызвать слот напрямую по имени объекта
class.receiveFromQml()


Q: Notation for the indefinite integral Can,
$$\int_{}^{l}f(t)dt$$
Where $l$ is a function of $x$, be considered as another representation of an indefinite integral?
Let us have the integral function, $y(l)=\int_{a(x) }^{l}f(t)dt$, where $l$ is the argument that takes functions of $x$, to be continuous and differentiable in an interval $I$.
$$y'(l) =l'.f(l)-a'(x).f(a(x))$$
The antiderivative of its derivative is, say, $$g(l)=y(l)+C$$
If the lower limit were specified as $a(x)$, the second part of the Fundamental Theorem of Calculus would give us, $$y(l)=g(l)−g(a(x))$$
$g$ being the antiderivative of $f$. Here in my representation, we know not what $a(x)$ is. Might as well write $y(l)=g(l)−C=g(l)+K$, where $C$ can be any constant.
We know that, an indefinite integral is expressed as a function of $x$ plus a constant. Here, $y(l)=\int_{}^{l}f(t)dt$,  seems like an appropriate representation of the indefinite integral. I find this approach comforting because it helps me accept the integral notation used in the definition of the indefinite integral. Could I be right about this?

A: When an integral has bounds, it means that we are integrating over a region. In Calc 3 with multiple integrals we have regions that are purely functions. So when you have just one bound like your notation suggests it doesn't make too much sense with the integral notation itself. Consider the following $\ln x=\int_{1}^{x}\frac{1}{t}\,\mathrm{d}t$. As a representation for $\ln x$, we can express functions like this, however notice we have both bounds. Of course, I am guilty of making up notation for convenience like $\ln^2 x$ instead of $(\ln x)^2$ it is purely up to the worker. However, it is customary to see one bound, the lower bound that describes the region such as $\displaystyle\oint\limits_{\mathbb{R}}\frac{1}{1+x^2}\,\mathrm{d}x$, then again, that is a definite integral. So what this amounts to is essentially no, due to the second fundamental theorem of calculus $\int_{a}^{b}f'(x)dx=f(b)-f(a)$. 2 bounds or a subscript that describes the region that will be integrated over. Hope this helps.  (PS also we don't need to know what a(x) other than that it is a function of x)


Q: Shows only one added record, cant view more in CMS admin panel I'm doing PHP course where need to build a CMS system.
Problem: In Admin panel shows only one row of added post information: example.
If i add more posts it must show more rows like this.
Help me i can't find mistake?
Source code:
view_all_posts.php
<?php

    $query = "SELECT * FROM posts";
    $select_posts = mysqli_query($connection, $query);

    /* check there are records in recordset */
    if( mysqli_num_rows( $select_posts ) > 0 ) {

        while ($row = mysqli_fetch_assoc($select_posts)) {
            $post_id = $row['post_id'];
            $post_author = $row['post_author'];
            $post_title = $row['post_title'];
            $post_category_id = $row['post_category_id'];
            $post_status = $row['post_status'];
            $post_image = $row['post_image'];
            $post_tags = $row['post_tags'];
            $post_comment_count = $row['post_comment_count'];
            $post_date = $row['post_date'];
        }

        echo "
";
        echo "$post_id	";
        echo "$post_author	";
        echo "$post_title	";

        $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} ";
        $select_categories_id = mysqli_query($connection, $query);

        while ($row = mysqli_fetch_assoc($select_categories_id)) {
            $cat_id = $row['cat_id'];
            $cat_title = $row['cat_title'];

            echo "{$cat_title}	";

        }

        echo "$post_status	";
        echo "	";
        echo "$post_tags	";
        echo "$post_comment_count	";
        echo "$post_date	";
        echo "Edit	";
        echo "Delete	";
        echo "
";

    }

    ?>

add_post.php
<?php

if(isset($_POST['create_post'])){

    $post_title = $_POST['title'];
    $post_author = $_POST['author'];
    $post_category_id = $_POST['post_category'];
    $post_status = $_POST['post_status'];

    $post_image = $_FILES['image']['name'];
    $post_image_temp = $_FILES['image']['tmp_name'];

    $post_tags = $_POST['post_tags'];
    $post_content = $_POST['post_content'];
    $post_date = date('y-m-d');

    move_uploaded_file($post_image_temp, "../images/$post_image" );

    $query = "INSERT INTO posts (post_category_id, post_title, post_author, post_date,
 post_image, post_content, post_tags, post_status) ";

    $query .= "VALUES({$post_category_id}, '{$post_title}', '{$post_author}', now(),
    '{$post_image}', '{$post_content}', '{$post_tags}', '{$post_status}' ) ";

    $create_post_query = mysqli_query($connection, $query);

    confirmQuery($create_post_query);

}

?>

<form action="" method="post" enctype="multipart/form-data">

        Post Title
            <input type="text" class="form-control" name="title">

        <select name="post_category" id="">

            <?php

            $query = "SELECT * FROM categories";
            $select_categories = mysqli_query($connection, $query);

            confirmQuery($select_categories);

            while($row = mysqli_fetch_assoc($select_categories )) {
                $cat_id = $row['cat_id'];
                $cat_title = $row['cat_title'];

                echo "<option value='$cat_id'>{$cat_title}</option>";

            }

            ?>

        </select>

        Post Author
            <input type="text" class="form-control" name="author">

        Post Status
            <input type="text" class="form-control" name="post_status">

        Post Image
            <input type="file" name="image">

        Post Tags
            <input type="text" class="form-control" name="post_tags">

        Post Content
            <textarea class="form-control" name="post_content" id="" cols="30" rows="10"></textarea>

        <input class="btn btn-primary" type="submit" name="create_post" value="Publish Post">

</form>

A: It seems that its just a minor mistake that you have to move your SELECT query of categories within the while loop of $select_posts.
Since, in given code, only last record will be passed to next while loop to fetch categories and eventually printed to browser.
So, correct code should look like this.

    {
    while ($row = mysqli_fetch_assoc($select_posts)) {
         $post_id = $row['post_id'];
         $post_author = $row['post_author'];
         $post_title = $row['post_title'];
         $post_category_id = $row['post_category_id'];
         $post_status = $row['post_status'];
         $post_image = $row['post_image'];
         $post_tags = $row['post_tags'];
         $post_comment_count = $row['post_comment_count'];
         $post_date = $row['post_date'];

         echo "";
         echo "$post_id";
         echo "$post_author";
         echo "$post_title";
         $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} ";
         $select_categories_id = mysqli_query($connection, $query);
         while ($row = mysqli_fetch_assoc($select_categories_id)) {
            $cat_id = $row['cat_id'];
            $cat_title = $row['cat_title'];
            echo "{$cat_title}";
         }
         echo "$post_status";
         echo "";
         echo "$post_tags";
         echo "$post_comment_count";
         echo "$post_date";
         echo "Edit";
         echo "Delete";
         echo "";
    }
}

A: Use it like this:
Print data inside while loop
<?php

    $query = "SELECT * FROM posts";
    $select_posts = mysqli_query($connection, $query);

    /* check there are records in recordset */
    if( mysqli_num_rows( $select_posts ) > 0 ) {

        while ($row = mysqli_fetch_array($select_posts)) {
            $post_id = $row['post_id'];
            $post_author = $row['post_author'];
            $post_title = $row['post_title'];
            $post_category_id = $row['post_category_id'];
            $post_status = $row['post_status'];
            $post_image = $row['post_image'];
            $post_tags = $row['post_tags'];
            $post_comment_count = $row['post_comment_count'];
            $post_date = $row['post_date'];

            echo "
";
        echo "$post_id	";
        echo "$post_author	";
        echo "$post_title	";

        $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} ";
        $select_categories_id = mysqli_query($connection, $query);

        while ($row = mysqli_fetch_array($select_categories_id)) {
            $cat_id = $row['cat_id'];
            $cat_title = $row['cat_title'];

            echo "{$cat_title}	";

        }  // End of Category Loop

        echo "$post_status	";
        echo "	";
        echo "$post_tags	";
        echo "$post_comment_count	";
        echo "$post_date	";
        echo "Edit	";
        echo "Delete	";
        echo "
";
      }   // End of Posts Loop

    }  // End of IF

    ?>


Q: *.stackoverflow.com with answers, suggestions, examples, and no questions I think it would be great to have a *.stackoverflow.com with answers only and no questions.
Ok, not really answers, but suggestions.
For example "I found a great way to do this, or I made this workaround for that bug, etc"
Wouldn't it be cool?
Stackoverflow is great when you are faced with a problem and need a solution, but what I propose, will not solve problems immediately but will feed your imagination with things you may never had wondered.

A: It's called "StackOverflow Jeopardy!".  Just post your suggestion by identifying the problem your suggestion solves, asking that question, and then supplying your suggestion as an answer.
It's also common etiquette to make the question — or at least your answer — community wiki to avoid the appearance of begging rep.

A: Turning a Q&A engine into an A engine...
I don't think this has future

A: What is with this compulsive desire to warp SO into every different thing imaginable?  StackOverflow is a question and answer site; this goes against the very point of it.  Can't we just appreciate SO for what it is and does well?
If you really want a site like this, Jeff would tell you to get off your butt and do it.

A: Boy there seems to have been a lot of talk lately about changing the StackExchange sites into things they're not. This suggestion, the "ability to purchase rep for bounty" question, etc.
I'm against most of it. Don't get me wrong, some of the individual ideas are neat -- including this one -- but the right answer isn't the official StackExchange-based LOJ sites. For this specific suggestion, the right answer is -- as others have mentioned -- a blog, or a license of StackExchange and build it yourself. (Heck, they might even make you a member of the ever-growing LOJ!)
These communities (S[OFU]) are all based on Q&A -- take the Q out, and you have essentially a wiki-based blog/forum. While that concept is fairly cool, it isn't what these sites are for, and ultimately (I think) would dilute the quality of these sites.

A: Many SO users already have blogs.  Visit the profile pages of users whose answers you find particularly helpful/insightful and see if they have one listed.

A: I think Mayor Adam West best explains the value questions give to answers:

An answer without a question is a statement.


Q: Handling json error messages in blob http calls We have http calls like:
this.http.get(`${environment.baseUrl}/api/v.1/reports/...`,
{ responseType: ResponseContentType.Blob })

which returns blob pdfs which we further on save through FileSaver.
Problem is if server returns 4XX response with some application/json and message in body. In that case, we cannot find a way how to access it as responseType has to be set prior to request and cannot be altered later.
Is there any elegant solution for it?

A: I did a few tests and this is what i did so far. It works, all as expected. But i will not accept it as answer yet but leave for some time for a community to review. If someone sees problems with this approach, please point them out in comments.
ErrorMessage is of simple format:
{ message:string }
Service:
getPDF() {
    return this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob })
      .map((res) => {
        return {
          blob: new Blob([res.blob()], { type: 'application/pdf' }), filename: this.parseFilename(res)
        }
      })
      .catch((res) => {
        let fileAsTextObservable = new Observable<string>(observer => {
          const reader = new FileReader();
          reader.onload = (e) => {
            let responseText = (<any>e.target).result;

            observer.next(responseText);
            observer.complete();
          }
          const errMsg = reader.readAsText(res.blob(), 'utf-8');
        });

        return fileAsTextObservable
          .switchMap(errMsgJsonAsText => {
            return Observable.throw(JSON.parse(errMsgJsonAsText));
          })
      });
  }


Q: How to change convert different csv files into standard format? I have 2-3 .csv files with fields like Date, Amount, Transaction Description etc and all the csv files contains these fields but in shuffled order. I want a output file to with a standard order (like if I input the sample .csv file, then I can get the things in order in output file).
I tried to do it for one file by taking substrings from the .csv file (at that time I didn't know that other files have shuffled order fields).
I am kind of new, tell me if I am asking question in a good format!
Can I put a link for the sample input and output .csv file for the reference?
--> https://drive.google.com/drive/folders/1-NZi5OTMTbOWXAfCTsc-ahNYm1N5DG2g (just because it would be very hard to explain that how file looks like)
What I have done?
I have just tried to extract data from the fields using the BufferReader using split but it can only work for one type of file, I cant have a standard format using this!
Sorry for posting such a long code but what I have done is selected field from the file and copied them into output file corresponding to the standard fields in the output file.
Suggest me if there is any other method with which I can proceed.
File file = new File("C:\\Users\\R\\Desktop\\CSVDemo.csv");
        try {
            // create FileWriter object with file as parameter
            FileWriter outputfile = new FileWriter(file);

            CSVWriter writer = new CSVWriter(outputfile, ',',
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);

            // create a List which contains String array
            String[] header = { "Date", "Transaction Description", "Debit","Credit","Currency","CardName","Transaction","Location" };
            writer.writeNext(header);

            String splitBy = ",";
            BufferedReader br = new BufferedReader(new FileReader("G:\\US\\HDFC-Input-Case1.csv"));
            String line;
            String transaction = "",name  = "";
            while ((line = br.readLine()) != null) {
                // use comma as separator
                String[] cols = line.split(splitBy);

                if(cols.length == 2 && cols[1].equals("Domestic Transactions")) {
                    transaction  = "Domestic";
                    continue;
                }
                else if(cols.length == 2 && cols[1].equals("International Transactions")) {
                    transaction  = "International";
                    continue;
                }
                else if(cols.length == 2) {
                    name = cols[1];
                    continue;
                }
                else if(cols.length<1){
                    continue;
                }
                else if(cols.length>2) {
                    if(cols[0].contains("Date")){
                        continue;
                    }
                    String[] data1 = new String[header.length];
                        data1[0] = cols[0];
                        String curr ;
                        if(cols[1].substring(cols[1].length()-3).equals("USD") || cols[1].substring(cols[1].length()-3).equals("EUR")) {
                            data1[4] = cols[1].substring(cols[1].length()-3);
                            curr = cols[1].substring(0,cols[1].length()-4);
                            data1[1] = curr;
                        }
                        else {
                            data1[4] = "INR";
                            data1[1] = cols[1];
                        }

                        if(cols[2].contains("cr")){
                            data1[3] = cols[2].substring(0,cols[2].length()-2);
                            data1[2] = "0";
                        }
                        else {
                            data1[2] = cols[2];
                            data1[3] = "0";
                        }

                        data1[5] = name;
                        data1[6] = transaction;
                        writer.writeNext(data1);
                }
                System.out.println();
            }

            // closing writer connection
            writer.close();
        }

A: You can read the header of your input csv files first and find the indexes of required field in this given csv file.
Once you have required indexes for every header, read those fields using indexes in the standard order you want for your output csv file.
sample codes:
`CSVReader reader = new CSVReader(new FileReader(fileName ));
String[] header = reader.readNext();
List<String> list= Arrays.asList(header);
int indexOfFieldTransaction=list.indexOf("transaction");`

Now make a List and insert the field in order you want to write in output file.you will get -1 if the field you are trying to get index of is not present in the input file.


Q: Magnification produced by combination of lenses In combination of thin lenses in contact, why is the total magnification(m) equal to the product of magnification of individual lenses(m1,m2,m3...)
That is, why m=m1m2m3...

A: Let lens $L_1$ have object place at $u$ and form an image at $x_1$. Now, let another lens $L_2$ have object placed at $x_1$ and form an image at $x_2$ and so on. The last lens will have object distance as $x_{n-1}$ and form an image $v$.
Observe that the magnification of each lens $L_i$is given by:
$$m_1=-\frac {x_1}u, m_n=-\frac v{x_{n-1}}$$
$$m_i=-\frac {x_i}{x_{i-1}}$$
The final magnification of the combination of the lenses is $m=-\frac vu$. Observe what happens when we multiply the magnification of all lenses.
$$m_1\times m_2\times m_3\cdots \times m_n=-\frac {x_1}{u}\times-\frac {x_2}{x_1}\times-\frac {x_3}{x_2}\cdots \times-\frac {v}{x_{n-1}}=-\frac vu$$


Q: Printing items selected from Knapsack Unbounded algorithm? I know how standard knapsack works, and i can afford to print the items selected in the 2D matrix, but from what i figured, unbounded knapsack is a 1D array. How do you print items selected by unbounded knapsack algorithm?

A: Unbounded Knapsack can be solved using 2D matrix, which will make printing the included items easy. The items included in the knapsack can be backtracked from the matrix in the same way as in 0/1 Knapsack.
After the dp[][] matrix is populated, this will print the included items:
// dp[val.length+1][sackWeight+1] is the matrix for caching.
// val[] is the array that stores the values of the objects
// and wt[] is the array that stores the weight of the corresponding objects.
int x = val.length, y = sackWeight;
    while (x > 0 && y > 0) {
        if (dp[x][y] == dp[x - 1][y])
            x--;
        else if (dp[x - 1][y] >= dp[x][y - wt[x - 1]] + val[x - 1])
            x--;
        else {
            System.out.println("including wt " + wt[x - 1] + " with value " + val[x - 1]);
            y -= wt[x - 1];
        }
    }

A: Assuming dp[][] is a matrix that is populated correctly.
We can backtrack to find selected weights

def print_selected_items(dp, weights, capacity):
    idxes_list = []
    print("Selected weights are: ", end='')
    n = len(weights)
    i = n - 1
    while i >= 0 and capacity >= 0:
        if i > 0 and dp[i][capacity] != dp[i - 1][capacity]:
            # include this item
            idxes_list.append(i)
            capacity -= weights[i]
        elif i == 0 and capacity >= weights[i]:
            # include this item
            idxes_list.append(i)
            capacity -= weights[i]
        else:
            i -= 1
    weights = [weights[idx] for idx in idxes_list]
    print(weights)
    return weights

For details on how to generate this DP array from bottom up DP.
def solve_knapsack_unbounded_bottomup(profits, weights, capacity):
    """
    :param profits:
    :param weights:
    :param capacity:
    :return:
    """
    n = len(profits)
    # base checks
    if capacity <= 0 or n == 0 or len(weights) != n:
        return 0
    dp = [[-1 for _ in range(capacity + 1)] for _ in range(n)]
    # populate the capacity=0 columns
    for i in range(n):
        dp[i][0] = 0
    # process all sub-arrays for all capacities
    for i in range(n):
        for c in range(1, capacity + 1):
            profit1, profit2 = 0, 0
            if weights[i] <= c:
                profit1 = profits[i] + dp[i][c - weights[i]]
            if i > 0:
                profit2 = dp[i - 1][c]
            dp[i][c] = max(profit1, profit2)
    # maximum profit will be in the bottom-right corner.
    print_selected_items(dp, weights, capacity)
    return dp[n - 1][capacity]


Q: printing float, preserving precision I am writing a program that prints floating point literals to be used inside another program.
How many digits do I need to print in order to preserve the precision of the original float?
Since a float has 24 * (log(2) / log(10)) = 7.2247199 decimal digits of precision, my initial thought was that printing 8 digits should be enough. But if I'm unlucky, those 0.2247199 get distributed to the left and to the right of the 7 significant digits, so I should probably print 9 decimal digits.
Is my analysis correct? Is 9 decimal digits enough for all cases? Like printf("%.9g", x);?
Is there a standard function that converts a float to a string with the minimum number of decimal digits required for that value, in the cases where 7 or 8 are enough, so I don't print unnecessary digits?
Note: I cannot use hexadecimal floating point literals, because standard C++ does not support them.

A:
24 * (log(2) / log(10)) = 7.2247199

That's pretty representative for the problem.  It makes no sense whatsoever to express the number of significant digits with an accuracy of 0.0000001 digits.  You are converting numbers to text for the benefit of a human, not a machine.  A human couldn't care less, and would much prefer, if you wrote

24 * (log(2) / log(10)) = 7

Trying to display 8 significant digits just generates random noise digits.  With non-zero odds that 7 is already too much because floating point error accumulates in calculations.  Above all, print numbers using a reasonable unit of measure.  People are interested in millimeters, grams, pounds, inches, etcetera.  No architect will care about the size of a window expressed more accurately than 1 mm.  No window manufacturing plant will promise a window sized as accurate as that.
Last but not least, you cannot ignore the accuracy of the numbers you feed into your program.  Measuring the speed of an unladen European swallow down to 7 digits is not possible.  It is roughly 11 meters per second, 2 digits at best.  So performing calculations on that speed and printing a result that has more significant digits produces nonsensical results that promise accuracy that isn't there.

A: If you have a C library that is conforming to C99 (and if your float types have a base that is a power of 2 :) the printf format character %a can print floating point values without lack of precision in hexadecimal form, and utilities as scanf and strod will be able to read them.

A: If the program is meant to be read by a computer, I would do the simple trick of using char* aliasing.

*

*alias float* to char*

*copy into an unsigned (or whatever unsigned type is sufficiently large) via char* aliasing

*print the unsigned value

Decoding is just reversing the process (and on most platform a direct reinterpret_cast can be used).

A: In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires

The original binary value will be preserved by converting to decimal and back again using:[10]

    5 decimal digits for binary16
    9 decimal digits for binary32
    17 decimal digits for binary64
    36 decimal digits for binary128

For other binary formats the required number of decimal digits is

    1 + ceiling(p*log10(2))

where p is the number of significant bits in the binary format, e.g. 24 bits for binary32.

In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold().
Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions.

A: The floating-point-to-decimal conversion used in Java is guaranteed to be produce the least number of decimal digits beyond the decimal point needed to distinguish the number from its neighbors (more or less).
You can copy the algorithm from here: http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html
Pay attention to the FloatingDecimal(float) constructor and the toJavaFormatString() method.

A: If you read these papers (see below), you'll find that there are some algorithm that print the minimum number of decimal digits such that the number can be re-interpreted unchanged (i.e. by scanf).
Since there might be several such numbers, the algorithm also pick the nearest decimal fraction to the original binary fraction (I named float value).
A pity that there's no such standard library in C.

*

*http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf

*http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf

A: You can use sprintf. I am not sure whether this answers your question exactly though, but anyways, here is the sample code
#include <stdio.h>
int main( void )
{
float d_n = 123.45;
char s_cp[13] = { '\0' };
char s_cnp[4] = { '\0' };
/*
* with sprintf you need to make sure there's enough space
* declared in the array
*/
sprintf( s_cp, "%.2f", d_n );
printf( "%s\n", s_cp );
/*
* snprinft allows to control how much is read into array.
* it might have portable issues if you are not using C99
*/
snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n );
printf( "%s\n", s_cnp );
getchar();
return 0;
}
/* output :
* 123.45
* 123
*/

A: With something like
def f(a):
    b=0
    while a != int(a): a*=2; b+=1
    return a, b

(which is Python) you should be able to get mantissa and exponent in a loss-free way.
In C, this would probably be
struct float_decomp {
    float mantissa;
    int exponent;
}

struct float_decomp decomp(float x)
{
    struct float_decomp ret = { .mantissa = x, .exponent = 0};
    while x != floor(x) {
        ret.mantissa *= 2;
        ret.exponent += 1;
    }
    return ret;
}

But be aware that still not all values can be represented in that way, it is just a quick shot which should give the idea, but probably needs improvement.


Q: How to redirect .htaccess My old website has 3 url's that lead to same place.
http://hemodialysis-krk.com/
http://www.hemodialysis-krk.com/
http://hemodialysis-krk.com/index.php?l=HR

I plan delete old website and put new one with totally different url's. Including index.html.
So what would be solution for that situation?
Should I 301 redirect some off them to index.html? Will first two automaticly link to new index.html file in public_html without redirecting?
Thanks.

A: Use this to redirect all traffic to new site using .htaccess of old sites.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} .*hemodialysis-krk.com
    RewriteRule (.*) http://www.newsite.com/ [R=301,L]
</IfModule>

Or create more rules, if you can map sections of pages from old to new site. If you use:
RewriteRule (.*) http://www.newsite.com/$1 [R=301,QSA,L]

original path and get query will be used in redirection too. This is always handy working on unique url to reach better position in search engines results.
EDIT:
If you need to redirect only urls, which don't exists anymore, then use (not tested):
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.*) / [R=301,L]
</IfModule>


Q: What does “likelihood” mean in the image? It is about insurance fraud. The image 2 shows the result of analysis with likelihood of claim referral, which is the target variable, from the previous analysis, image 1, on historical referral data. How should I interpret the likelihood in the image?
The description from the article is as follows:

*

*The link to the document: http://support.sas.com/resources/papers/proceedings14/1837-2014.pdf

*Analysis of Historical Referrals
This first analysis allows insurance companies to apply analytics for more consistent claim referrals to the SIU. For
this analysis, the target variable is a history of claim referrals to the special investigative unit. This target can be
adjusted to just use the referrals of those claim adjusters that are considered the most experienced or most
effective. The independent variables considered in the analysis are the details of the claims. The result of the
analysis is, based on the historical claim referrals, the likelihood that a new claim should be referred to the
investigative unit.
The chart below shows the partial results of a decision tree based on an analysis of a database of automobile
insurance bodily injury coverage closed claims. The dataset included an indicator if the claim was referred to an
investigative unit, and also included the details of the claim (injury details, accident severity, claimant
characteristics, location, and payment information).

Image 1.
It can be determined from this analysis which factors were associated with increased claim referrals. These characteristics included the severity of the injury, the location of the accident, and whether the claimant was
represented by an attorney. While the decision tree results are shown here, three separate predictive models were developed: Decision Tree, Neural Network, and Logistic Regression. Ultimately, the predicted referral was determined by an Ensemble model which used the combined effect of the three models to produce a more accurate prediction.
The distribution of the predicted likelihood of referral for the claims in the bodily injury dataset is shown below.

Image 2
Based on this distribution, a cutoff score could be chosen such that claims above a certain point would automatically be referred to the investigative unit. These claims could be sent directly to the SIU, allowing experienced claim adjusters to spend their time on those claims the model classifies as being borderline in regards to fraud likelihood.


Q: Scipy maximizing linear programming doesn't work I have the following:
ball = scipy.optimize.linprog(array([0,0,1]), A, b)

where
A =
array([[-1.0,  0.0,  1.0],
   [ 1.0,  0.0,  1.0],
   [ 0.0, -1.0,  1.0],
   [ 0.0,  1.0,  1.0]], dtype=float128)

b = array([ 0.0,  1.0,  0.0,  1.0], dtype=float128)

We can maximize this by hand to get the answer x = [0.5, 0.5, 0.5]. Yet scipy gives me
  status: 0
   slack: array([ 0.,  1.,  0.,  1.])
 success: True
     fun: -0.0
       x: array([ 0.,  0.,  0.])
 message: 'Optimization terminated successfully.'
     nit: 0

Which is simply the wrong answer! Is my code wrong, or did I find a bug?
EDIT:
To verify that the solution given by scipy is not optimal, do
np.all(np.dot(A, np.array([0.5,0.5,0.5])) <= b)

to see that my solution satisfies the constraints. Then note that
np.dot(np.array([0,0,1]), np.array([0.5,0.5,0.5])) > np.dot(np.array([0,0,1]), np.array([0,0,0]))

to see it is at least a better solution. In fact, it is the optimal solution.
EDIT 2:
scipy.__version__ = 0.16.0

A: According to the docs, linprog finds the minimum, while your proposed solution is the maximum.


Q: How to kill an android app from another app? i wanna know how to kill an android app from another, i'm developing a tasker, and i wanna to be able to kill an app selected by the user when an event occurs, i readed about Process.killProcess() but only allows me to kill apps in the same package, and that's not the idea! So, in my case, my kill section will request root rights, calling su before accept a kill request, but i don't know how to kill an app using a script! Anyones knows some script to do that??
EDIT:
The solution is in this thread:
ANDROID: How to gain root access in an Android application?
Please close.


Q: How to "succinctly" detect changed values in the PostgreSQL's upsert (on conflict) where clause while supporting null changes? We maintain a large data warehouse implemented in PostgreSQL and python. One very common pattern we do is to make upserts, and log when things were updated. We have some unique key my_key and values, say, my_uuid, my_text, my_int, my_date. If any any of those values change for a given my_key we would like to update the row. That's fine, and we have a pattern which works well:
insert into my_table (
    my_key,
    my_uuid,
    my_text,
    my_int,
    my_date
)
select
    some_key,
    some_uuid,
    some_text,
    some_int,
    some_date
from some_table
on conflict (my_key) do update set
    some_uuid = excluded.some_uuid,
    some_text = excluded.some_text,
    some_int = excluded.some_int,
    some_date = excluded.some_date,
    update_timestamp = now()
where
    coalesce(my_table.some_uuid, uuid_nil()) <> coalesce(excluded.some_uuid, uuid_nil())
    or coalesce(my_table.some_text, '') <> coalesce(excluded.some_text, '')
    or coalesce(my_table.some_int, -1) <> coalesce(excluded.some_int, -1)
    or coalesce(my_table.some_date, '3000-01-01'::date) <> coalesce(excluded.some_date, '3000-01-01'::date)

The last on conflict ... where clause is important, because it makes sure that the update_timestamp is only updated when there are changes. It also makes sure we don't update rows unnecessarily, improving performance.
Anyway, we often have an issue with the coalesce() logic. The reason it exists in this pattern is to support the value going to and from null. Let's take the following example:
coalesce(my_table.some_text, '') <> coalesce(excluded.some_text, '')

This works fine, and produces the following results for a comprehensive list of test cases:
select coalesce('a', '') <> coalesce('a', '')  --> false
union all
select coalesce(null, '') <> coalesce(null, '')  --> false
union all
select coalesce('a', '') <> coalesce('b', '')  --> true
union all
select coalesce(null, '') <> coalesce('b', '')  --> true
union all
select coalesce('a', '') <> coalesce(null, '')  --> true

That is, it is only true when the value actually changed. However, what happens if a value genuinely is empty string ''? Then it won't update.
This means we need to be creative about choosing the dummy value '' such that it isn't a value which would naturally occur. We could just invent a keyword which is unlikely to occur in production. But I'd rather find another pattern which doesn't have this drawback.
What options exist to do this susinclty giving the same change "truth table" I showed above? We could always use case when ..., but it becomes extremely verbose. We need something which is easy to write and easy to read. A row can often include 5-15 value columns
Are there any alternatives which could do an upsert without the drawback of the pattern we are using today?

The following can be used as a testbed to find a suitable pattern:
select
    v1, v2, expected,
    COALESCE(v1, '') <> COALESCE(v2, '') as current_version,
    COALESCE(v1 <> v2, true) as candidate_version
from (
    select 'a' as v1, 'a' as v2, false as expected
    union all
    select null as v1, null as v2, false as expected
    union all
    select '' as v1, null as v2, true as expected
    union all
    select null as v1, '' as v2, true as expected
    union all
    select 'a' as v1, null as v2, true as expected
    union all
    select null as v1, 'b' as v2, true as expected
    union all
    select 'a' as v1, 'b' as v2, true as expected
) q

Returning:
v1     v2     expected current_version candidate_version
a      a      false    false           false
null   null   false    false           true
''     null   true     false           true
null   ''     true     false           true
a      null   true     true            true
null   b      true     true            true
a      b      true     true            true

A: You can use is distinct from as gsiems mentioned which is the null safe "not equals" operator. null is distinct from null is false, and 42 is distinct from null is true.
Your testbed:
select
    v1, v2, expected,
    v1 is distinct from v2 as is_different
from (
  values
    ('a', 'a', false),
    (null, null, false),
    ('', null, true),
    (null, '', true),
    ('a', null, true),
    (null, 'b', true),
    ('a', 'b', true)
) q (v1, v2, expected)

returns
v1 | v2 | expected | is_different
---+----+----------+-------------
a  | a  | false    | false
   |    | false    | false
   |    | true     | true
   |    | true     | true
a  |    | true     | true
   | b  | true     | true
a  | b  | true     | true

You can make this even shorter by comparing a complete record which also removes the need for the OR
where
   (my_table.some_uuid, my_table.some_text, my_table.some_int, my_table.some_date)
       is distinct from
   (excluded.some_uuid, excluded.some_text, excluded.some_int, excluded.some_date)

A: Have tried using IS DISTINCT FROM?
SELECT ...
    FROM ...
    WHERE my_table.some_uuid IS DISTINCT FROM excluded.some_uuid
        OR (my_table.some_text IS DISTINCT FROM excluded.some_text
        ...


Q: Reading an XML from a JavaFX application I would like to import an XML file via a pop-up window in my JavaFX application. After the importing, I would like to read it. For example I want to store, for every <testbus> the <index> and the <tb_name> in a List or something similar, where the <index> is the index of the List and the <tb_name> is the elementof the List. I also would like that for every <testbus> I can access the bitfields and their name. So I was thinking about List of List. I have found a java Library called JAXB that can parse XML files, but I do not know how to achieve what I want.
This is the XML file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testbuses>
    <testbus>
        <index>00</index>
        <tb_name>buffermngr00</tb_name>
            <bitfield0>
                <bitf_name>aaa_00</bitf_name>
            </bitfield0>
            <bitfield1>
                <bitf_name>aaa_01</bitf_name>
            </bitfield1>
            <bitfield2>
                <bitf_name>aaa_02</bitf_name>
            </bitfield2>
            <bitfield3>
                <bitf_name>aaa_03</bitf_name>
            </bitfield3>
            <bitfield4>
                <bitf_name>aaa_03</bitf_name>
            </bitfield4>
            <bitfield5>
                <bitf_name>aaa_04</bitf_name>
            </bitfield5>
            <bitfield6>
                <bitf_name>aaa_04</bitf_name>
            </bitfield6>
            <bitfield7>
                <bitf_name>aaa_05</bitf_name>
            </bitfield7>
    </testbus>
    <testbus>
        <index>01</index>
        <tb_name>buffermngr01</tb_name>
            <bitfield0>
                <bitf_name>bbb_00</bitf_name>
            </bitfield0>
            <bitfield1>
                <bitf_name>bbb_00</bitf_name>
            </bitfield1>
            <bitfield2>
                <bitf_name>bbb_00</bitf_name>
            </bitfield2>
            <bitfield3>
                <bitf_name>bbb_00</bitf_name>
            </bitfield3>
            <bitfield4>
                <bitf_name>bbb_01</bitf_name>
            </bitfield4>
            <bitfield5>
                <bitf_name>bbb_01</bitf_name>
            </bitfield5>
            <bitfield6>
                <bitf_name>bbb_02</bitf_name>
            </bitfield6>
            <bitfield7>
                <bitf_name>bbb_03</bitf_name>
            </bitfield7>
    </testbus>
</testbuses>

Anyway the structure of this XML is not strict, so if you have a suggestion for a better structure in order to make the reading easily, I will be happy to hear your solution.

A: For your xml provided in the XML.
First create a java POJO class with fields as:
String index;
String tb_name;
List<String> bitf_names;

Use the class below for that:
import java.util.List;

class TestBus {
        private String index;
        private String tb_name;
        private List<String> bitf_names;

        public String getIndex() {
            return index;
        }

        public void setIndex(String index) {
            this.index = index;
        }

        public String getTb_name() {
            return tb_name;
        }

        public void setTb_name(String tb_name) {
            this.tb_name = tb_name;
        }

        public List<String> getBitf_names() {
            return bitf_names;
        }

        public void setBitf_names(List<String> bitf_name) {
            this.bitf_names = bitf_name;
        }

        @Override
        public String toString() {
            return "TestBus [index=" + index + ", tb_name=" + tb_name + ", bitf_name=" + bitf_names + "]";
        }
    }

After that, use the code below to create a list of TestBus classes:
i.e List<TestBus> testBusList = new ArrayList<>();
Use this class for the complete code and logic:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {
    public static List<TestBus> testBuses = new ArrayList<>();

    public static void main(String argv[]) {

        try {
            File fXmlFile = new File("D:\\ECLIPSE-WORKSPACE\\demo-xml-project\\src\\main\\resources\\testbus.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList testBusNodeList = doc.getElementsByTagName("testbus");

            for (int parameter = 0; parameter < testBusNodeList.getLength(); parameter++) {
                TestBus testBus = new TestBus();
                Node node = testBusNodeList.item(parameter);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;
                    String index = eElement.getElementsByTagName("index").item(0).getTextContent();
                    String tb_name = eElement.getElementsByTagName("tb_name").item(0).getTextContent();
                    NodeList bitf_name = eElement.getElementsByTagName("bitf_name");
                    List<String> bitf_namesList = new ArrayList<>();
                    IntStream.range(0, bitf_name.getLength()).forEach(bName -> {
                        bitf_namesList.add(bitf_name.item(bName).getTextContent());
                    });
                    testBus.setIndex(index);
                    testBus.setTb_name(tb_name);
                    testBus.setBitf_names(bitf_namesList);

                    testBuses.add(testBus);
                }
            }
        } catch (Exception e) {
            System.out.println("!!!!!!!!  Exception while reading xml file :" + e.getMessage());
        }

        testBuses.forEach(bus -> System.out.println(bus));  // in single line
        System.out.println("###################################################");

        // using getters
        testBuses.forEach(bus -> {
            System.out.println("index = " + bus.getIndex());
            System.out.println("tb_name = " + bus.getTb_name());
            System.out.println("bitf_names = " + bus.getBitf_names());
            System.out.println("#####################################################");
        });
    }
}


Q: MySQL substatements with more than one column Given a fake example where there are contacts and for each contact there can be one or zero Sms records; I can do this
SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id.

But I it needs to show a row even if there is no SMS number for that contact.
I know of two ways to accomplish this. One is with a UNION of two selects
(SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id) UNION (SELECT id, name, null provider, null number FROM Contact WHERE (SELECT 1 FROM Sms WHERE contactId = Contact.id) IS NULL).

and another is two substatements
SELECT id, name, (SELECT provider FROM Sms WHERE contactId = Contact.id) provider, (SELECT number FROM Sms WHERE contactId = Contact.id) number FROM Contact

The UNION method requires going through the database twice and the substatements method requires two lookups on the same table.
I run into this often and I prefer to have all the code in MySQL and not to work with the software code to accomplish this. Working with MySQL usually turns out to be more efficient as well as simpler. Many of the real situations I work with involve large databases.
Is there a way to get two fields from a related table with one query?

A:
But I it needs to show a row even if
  there is no SMS number for that
  contact.

Then use a LEFT OUTER JOIN, which returns a row from the left table even if there is no corresponding row in the right table.
It's a good idea to learn to always use JOIN syntax instead of the pseudo-inner-join when you just list tables with commas.
SELECT
  Contact.id,
  Contact.name,
  Sms.provider,
  Sms.number
FROM
  Contact
LEFT OUTER JOIN
  Sms
ON
  Sms.contactId = Contact.id


Q: Javascript: prevent internal element "scrolling" in an element I have a script that has a div with a width larger than its' parent, with the parent being set to overflow: hidden;. I have javascript that is setting the left positioning of the big div to create "pages". You can click a link to move between pages.
All of that works great, but the problem is if you tab from one "page" element to another, it completely messes up all the left positioning to move between the pages.
You can recreate this bug in the fiddle I set up by setting your focus to one of the input boxes on page ONE and tabbing until it takes you to page two.
I've set up a demo here.
The code that is important is as follows:
HTML:

Page One

            [... Page 1 Content here...]

Page Two

            [... Page  Content here...]

CSS:
.form {
    width: 400px;
    position: relative;
    overflow: hidden;
    border: 1px solid #000;
    float: left;
}

    .pagesContainer {
        position: relative; /*Width set to 10,000 px in js
    }

    .form .page {
        width: 400px;
        float: left;
    }

JS:
slidePage: function(page, direction, currentPage) {
    if (direction == 'next') {
        var animationDirection = '-=';
        if (page.index() >= this.numPages) {
            return false;
        }
    }
    else if (direction == 'previous') {
        var animationDirection = '+=';
        if (page.index() < 0) {
            return false;
        }
    }

    //Get page height
    var height = page.height();
    this.heightElement.animate({
        height: height
    }, 600);

    //Clear active page
    this.page.removeClass('active');
    this.page.eq(page.index()).addClass('active');

    //Locate the exact page to skip to
    var slideWidth = page.outerWidth(true) * this.difference(this.currentPage.index(), page.index());

    this.container.animate({
        left: animationDirection + slideWidth
    }, 600);

    this.currentPage = page;
}

The primary problem is that whatever happens when you tab from say, an input box on page one to something on page 2, it takes you there, but css still considers you to be at left: 0px;. I've been looking all over for a solution but so far all google has revealed to me is how to stop scrollbar scrolling.
Any help or suggestions would be appreciated, thanks!
P.S. The html was set up like this so that if javascript is disabled it will still show up all on one page and still function properly.

A: I updated your fiddle with a fix for the first tab with the form: http://jsfiddle.net/E7u9X/1/
. Basically, what you can do is to focus on the first "tabbable" element in a tab after the last one gets blurred, like so:
$('.form input').last().blur(function(){
    $('.form input').first().focus();
});

(This is just an example, the first active element could be any other element)

A: Elements with overflow: hidden still have scrolling, just no scroll bars. This can be useful at times and annoying at others. This is why your position left is at zero, but your view of the element has changed. Set scrollLeft to zero when you change "pages", should do the trick.


Q: Query: table name specified more than once i'm trying to fix a vue filter. I have to change a query, but i can't find it in the laravel directory.
SELECT
    count(*) AS aggregate
FROM (
    SELECT
        ST_asGeoJSON(elements.geom) AS geometry
    FROM
        "elements"
    LEFT JOIN subsidies ON elements.subsidy_id = subsidies.id
    LEFT JOIN owners ON elements.owner_id = owners.id
    LEFT JOIN locations ON elements.location_id = locations.id
    LEFT JOIN element_type ON elements.element_type_id = element_type.id
    LEFT JOIN shapes ON elements.shape_id = shapes.id
    LEFT JOIN objectives ON elements.objective_id = objectives.id
    LEFT JOIN diameters ON elements.diameter_id = diameters.id
    LEFT JOIN maintenances ON maintenances.element_id = elements.id
    LEFT JOIN maintenances ON elements.id = maintenances.element_id
WHERE
    elements.organisation_id = 14
    and(elements.deleted_at) IS NULL
GROUP BY
    elements.id,
    maintenances.element_id,
    subsidies.id,
    owners.id,
    locations.id,
    element_type.id,
    shapes.id,
    objectives.id,
    diameters.id,
    maintenances.id
HAVING
    COUNT(element_id) < 1) count_row_table

above is the query that is executed when then checkbox is checked:

SQLSTATE[42712]: Duplicate alias: 7 ERROR: table name "maintenances" specified more that once (SQL: select count(*) as...

['parent_table' => 'elements', 'join_table' => 'element_type', 'filter_column' => 'element_type_id', 'filter_value' => 'element_type_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'shapes', 'filter_column' => 'shape_id', 'filter_value' => 'shape_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'objectives', 'filter_column' => 'objective_id', 'filter_value' => 'objective_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'diameters', 'filter_column' => 'diameter_id', 'filter_value' => 'diameter', 'order_by' => 'diameters.id'],
['parent_table' => 'element_flora', 'join_table' => 'flora', 'filter_column' => 'flora_id', 'filter_value' => 'flora_' . \Config::get('app.locale'), 'additional_wheres' => ['element_flora.deleted_at is null']],
['parent_table' => 'element_fauna', 'join_table' => 'fauna', 'filter_column' => 'fauna_id', 'filter_value' => 'fauna_' . \Config::get('app.locale'), 'additional_wheres' => ['element_fauna.approval_pending is not TRUE', 'element_fauna.deleted_at is null']],
['parent_table' => 'elements', 'join_table' => 'owners', 'filter_column' => 'owner_id', 'filter_value' => 'owner'],
['parent_table' => 'maintenances', 'join_table' => 'elements', 'filter_column' => 'id', 'filter_value' => 'id', 'havingRaw' => 'COUNT(maintenances.element_id) < 1', 'join_type' => 'left', 'filter_null' => true],
['parent_table' => 'elements', 'join_table' => 'projects', 'filter_column' => 'project_id', 'filter_value' => 'project', 'order_by' => 'projects.id'],


Q: Asking whether it will take a long time to complete something If I want to ask someone whether it will take a long time to complete something, can I ask

Will it take long?

Does this sentence look awkward or is it the correct way to ask?

A: Sure.  There are lots of ways you could ask, and that's one of them:

*

*Will it take long?

*Will it take a long time?

*Will it take a long time to finish?

*When do you think it'll be done?

*When do you think it might be done?

*Could you tell me when you think it might be done?

*Do you have any idea how long it might take?

As usual, you can insert meaningless hedge words like might to soften the question, and you can make it more polite by using less direct language such as could you instead of will.  What level of politeness or directness is appropriate is, of course, something you'll have to determine by context.
And context can change everything.  For example, if you're dropping off a document to get copies printed up, you might ask when you can come back to pick them up.  The following question isn't literally about when the printing will finish or how long it will take, but it would nonetheless be a perfectly natural way of asking:

*

*When should I come back?

But speaking devoid of context, your way is fine.


Q: Xamarin IOS file picker : unable to get selected file from icloud drive I've installed filepicker control from Nuget and added tried adding reference from MonoTouch10 folder and later from github to my xamarin.ios project.
FileData file = await CrossFilePicker.Current.PickFile();

if (file != null) { }

this is the code i added to my browse button, after selecting a file from iCloud drive, control never comes to "if condition".
and again when i click on browse button for second time, app crashes saying "only one operation can be active at a time".

A: Modifying the source code of the FilePickerImplementation plugin for the iOS platform worked, in this way:
using Foundation;
using MobileCoreServices;
using Plugin.FilePicker.Abstractions;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UIKit;
using System.Diagnostics;

namespace Plugin.FilePicker
{
    /// <summary>
    /// Implementation for FilePicker
    /// </summary>
    public class FilePickerImplementation : NSObject, IUIDocumentMenuDelegate, IFilePicker
    {
        private int _requestId;
        private TaskCompletionSource<FileData> _completionSource;

        /// <summary>
        /// Event which is invoked when a file was picked
        /// </summary>
        public EventHandler<FilePickerEventArgs> Handler
        {
            get;
            set;
        }

        private void OnFilePicked(FilePickerEventArgs e)
        {
            Handler?.Invoke(null, e);
        }

        public void DidPickDocumentPicker(UIDocumentMenuViewController documentMenu, UIDocumentPickerViewController documentPicker)
        {
            documentPicker.DidPickDocument += DocumentPicker_DidPickDocument;
            documentPicker.WasCancelled += DocumentPicker_WasCancelled;
            documentPicker.DidPickDocumentAtUrls += DocumentPicker_DidPickDocumentAtUrls;
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(documentPicker, true, null);
        }

        private void DocumentPicker_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e)
        {
            var control = (UIDocumentPickerViewController)sender;
            foreach (var url in e.Urls)
                DocumentPicker_DidPickDocument(control, new UIDocumentPickedEventArgs(url));

            control.Dispose();
        }

        private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
        {
            var securityEnabled = e.Url.StartAccessingSecurityScopedResource();
            var doc = new UIDocument(e.Url);
            var data = NSData.FromUrl(e.Url);
            var dataBytes = new byte[data.Length];

            System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

            string filename = doc.LocalizedName;
            string pathname = doc.FileUrl?.ToString();

            // iCloud drive can return null for LocalizedName.
            if (filename == null)
            {
                // Retrieve actual filename by taking the last entry after / in FileURL.
                // e.g. /path/to/file.ext -> file.ext

                // filesplit is either:
                // 0 (pathname is null, or last / is at position 0)
                // -1 (no / in pathname)
                // positive int (last occurence of / in string)
                var filesplit = pathname?.LastIndexOf('/') ?? 0;

                filename = pathname?.Substring(filesplit + 1);
            }

            OnFilePicked(new FilePickerEventArgs(dataBytes, filename, pathname));
        }

        /// <summary>
        /// Handles when the file picker was cancelled. Either in the
        /// popup menu or later on.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DocumentPicker_WasCancelled(object sender, EventArgs e)
        {
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                tcs.SetResult(null);
            }
        }

        /// <summary>
        /// Lets the user pick a file with the systems default file picker
        /// For iOS iCloud drive needs to be configured
        /// </summary>
        /// <returns></returns>
        public async Task<FileData> PickFile()
        {
            var media = await TakeMediaAsync();

            return media;
        }

        private Task<FileData> TakeMediaAsync()
        {
            var id = GetRequestId();

            var ntcs = new TaskCompletionSource<FileData>(id);

            if (Interlocked.CompareExchange(ref _completionSource, ntcs, null) != null)
                throw new InvalidOperationException("Only one operation can be active at a time");

            var allowedUtis = new string[] {
                UTType.UTF8PlainText,
                UTType.PlainText,
                UTType.RTF,
                UTType.PNG,
                UTType.Text,
                UTType.PDF,
                UTType.Image,
                UTType.UTF16PlainText,
                UTType.FileURL
            };

            var importMenu =
                new UIDocumentMenuViewController(allowedUtis, UIDocumentPickerMode.Import)
                {
                    Delegate = this,
                    ModalPresentationStyle = UIModalPresentationStyle.Popover
                };

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(importMenu, true, null);

            var presPopover = importMenu.PopoverPresentationController;

            if (presPopover != null)
            {
                presPopover.SourceView = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
                presPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
            }

            Handler = null;

            Handler = (s, e) => {
                var tcs = Interlocked.Exchange(ref _completionSource, null);

                tcs?.SetResult(new FileData(e.FilePath, e.FileName, () => { var url = new Foundation.NSUrl(e.FilePath); return new FileStream(url.Path, FileMode.Open, FileAccess.Read); }));
            };

            return _completionSource.Task;
        }

        public void WasCancelled(UIDocumentMenuViewController documentMenu)
        {
            var tcs = Interlocked.Exchange(ref _completionSource, null);

            tcs?.SetResult(null);
        }

        private int GetRequestId()
        {
            var id = _requestId;

            if (_requestId == int.MaxValue)
                _requestId = 0;
            else
                _requestId++;

            return id;
        }

        public async Task<bool> SaveFile(FileData fileToSave)
        {
            try
            {
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var fileName = Path.Combine(documents, fileToSave.FileName);

                File.WriteAllBytes(fileName, fileToSave.DataArray);

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public void OpenFile(NSUrl fileUrl)
        {
            var docControl = UIDocumentInteractionController.FromUrl(fileUrl);

            var window = UIApplication.SharedApplication.KeyWindow;
            var subViews = window.Subviews;
            var lastView = subViews.Last();
            var frame = lastView.Frame;

            docControl.PresentOpenInMenu(frame, lastView, true);
        }

        public void OpenFile(string fileToOpen)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fileName = Path.Combine(documents, fileToOpen);

            if (NSFileManager.DefaultManager.FileExists(fileName))
            {
                var url = new NSUrl(fileName, true);
                OpenFile(url);
            }
        }

        public async void OpenFile(FileData fileToOpen)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fileName = Path.Combine(documents, fileToOpen.FileName);

            if (NSFileManager.DefaultManager.FileExists(fileName))
            {
                var url = new NSUrl(fileName, true);

                OpenFile(url);
            }
            else
            {
                await SaveFile(fileToOpen);
                OpenFile(fileToOpen);
            }
        }
    }
}

A: To answer my own question, i customized in plugin, like

*

*Used DocumentPicker_DidPickDocumentAtUrls event instead of DocumentPicker_DidPickDocument.

*while returning selected file used
 new FileData(e.FilePath, e.FileName, () =>
        {
            var url = new Foundation.NSUrl(e.FilePath);
            return new FileStream(url.Path, FileMode.Open, FileAccess.Read);
        })

This solved my issue. Thanks.

A: There are several forks of the FilePicker Xamarin plugin. I recommend the following project, since it's the most actively maintained one:
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows (note: I'm one of the contributors to the project).
With this version of the plugin file picking should work. The example code from sandeep's answer was already incorporated into the latest version of the plugin. Be sure to read the README.md's Troubleshooting page in case you're getting problems.


Q: Cumulative distribution function of Y How do you get the cumulative distribution function of $Y$ in terms of $X$?
Let's say that $E[X] = μ, Var[X] = σ^2,$ and $Y =a + bX$.
What would be the process to get the cumulative distribution function?

A:
Let's say that $E[X] = μ, Var[X] = σ^2,$ and $Y =a + bX$.
Wouldn't $E[Y]$ = $a + Bμ$ and $Var[Y] = B^2 σ^2$?

It actually would be that.

What would be the process to get the cumulative distribution function?

You start with the cummulative distribution function for $X$.
If $F_{\small X}(x)$ is the CDF for $X$, and $b>0$, then $F_{\small Y}(y)$, the cdf for $Y$, is:$$F_{\small Y}(y) ~=~ F_{\small X}\left(\dfrac{y-a}b\right)$$
Since $\mathsf P(Y\leqslant y) ~{= \mathsf P(a+bX\leqslant y)\\=\mathsf P\left(X\leqslant (y-a)/b\right)}$


Q: Creating a .jar in Android I have a Android project with some classes that I would like to compress to a JAR.
I create the JAR by right clicking my project - export - JAR - and the JAR gets created without any warnings.
I can access all classes from the JAR in my code but when I try to build the project get this exception :
java.lang.NoClassDefFoundError: name.of.class.in.package

Does anyone know what resources should be exported with the JAR? The options you get is
.class path
.prject
AndroidManifest.xml
proguard.cfg
project.properties

Right now I have included all of the above.

Making the JAR into a library project is not an option. And just to make it clear I don't have anything in the RES folder of my JAR project.

A: Just add your JAR to classpath or build your project with Maven and include dependencies

A: Open the project properties -> Java Build Path -> Order and Export and check item Android Dependencies are checked to be exported to the result APK.
And if .jar exist in Library tab under Android Dependencies item.
If you have .jar in the "libs" folder it should be included by default.

A: Try generating the jar in a different way. Basically jar is a zipped file of all class files with an extension of .jar.

*

*Select all your class files that needs to be included in a jar file.

*Right click and send to compressed (Zip File).

*you will have a zipped file which will contain all the class files.

*Rename this zipped file with having an extension .jar

Now include this jar file into your project whichever you want to use.
Or if you want to zip all the files by a different method then make sure all the files are zipped together without a folder. So when you unzip the files you should get all the files without contained in a folder.

A: It looks similar with this topic. Follow the very clear instructions written by Russ Bateman.


Q: Changing focus from one input to the next with a barcode scanner I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using:
    <form id="barcode1" name="barcode" method="Post" action="#">

          Barcode 1
          <input id="S1" class="bcode" type="text" name="S1" autofocus/>
          Barcode 2
          <input id="S2" class="bcode" type="text" name="S2" />
          Barcode 3
          <input id="S3" class="bcode" type="text" name="S3" />

<input type="submit" name="Submit" value="Submit">

    </form>

I have tried solutions from similar SO questions here and [here] (http://jsfiddle.net/davidThomas/ZmAEG/), but they don't seem to work.
Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it.
    $('form').on('keypress','input',function(e){
        var eClassName = this.className,
            index = $(this).index('.' + eClassName) + 1;
        if (e.which === 13){
            e.preventDefault();
            $('input.' + eClassName)
                .eq(index)
                .focus();
        }
    });

A: If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.
It seems like, by default, your scanner is trailing with an ENTER (carriage return).
Another option would be to also check for a LF (decimal 10) in your javascript code.

A: You need to return false in order to prevent the enter key from submitting the form.
The answer to this question will help you: Prevent form submission with enter key
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

No need to make any changes to your bar scanner.

A: Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.
$( "form" ).submit(function( event ) {
  if(/*all req. fields are filled -> submit the form*/)
     $(this).submit();
  event.preventDefault();
});


Q: Struts 2 token is not working with display tag pagination I have a Struts 2 application, I have created some reports with display tag  pagination, it works fine but when I apply CSRF token to that page, only first page displays properly and when I try to navigate other paginated pages application shows invalid.token error.
Can anyone please suggest how to apply CSRF token with display tag ?