text:
Q: No more disk space on ec2 I am using a D class EC2 which is supposed to be a storage optimized EC2. I have about 20 GB of files that I need to write to disk. I am getting an out of disk space  error once the total size of files reaches 15 GB. The instance is supposed to have way more than this. Why am I getting this error? How can I write more than 15GB of data to a D class EC2?

A: From Amazon EC2 Instance Types - Amazon Web Services:

D2 instances feature up to 48 TB of HDD-based local storage, deliver high disk throughput, and offer the lowest price per disk throughput performance on Amazon EC2.

Please note that this is local storage, which is very fast but the contents of these disks is lost if the instance is stopped. Therefore, it is recommended for temporary storage only.
Linux
I launched a d2.xlarge Linux instance.
I then followed instructions from How to use "Instance Store Volumes" storage in Amazon EC2?:
$ sudo fdisk -l

Disk /dev/xvda: 8 GiB, 8589934592 bytes, 16777216 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 70E4A118-98BD-4BF4-8DF9-6926A964902A

Device       Start      End  Sectors Size Type
/dev/xvda1    4096 16777182 16773087   8G Linux filesystem
/dev/xvda128  2048     4095     2048   1M BIOS boot

Partition table entries are not in disk order.

Disk /dev/xvdb: 1.8 TiB, 2000387309568 bytes, 3907006464 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/xvdc: 1.8 TiB, 2000387309568 bytes, 3907006464 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/xvdd: 1.8 TiB, 2000387309568 bytes, 3907006464 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

This showed 3 disks, each of 1.8TiB.
I then formatted and mounted them:
sudo mkfs.ext4 /dev/xvdb
sudo mkfs.ext4 /dev/xvdc
sudo mkfs.ext4 /dev/xvdd
sudo mkdir /mnt/disk1
sudo mkdir /mnt/disk2
sudo mkdir /mnt/disk3
sudo mount -t ext4 /dev/xvdb /mnt/disk1
sudo mount -t ext4 /dev/xvdc /mnt/disk2
sudo mount -t ext4 /dev/xvdd /mnt/disk3

I then viewed the mounted disks:
$ df -h

Filesystem      Size  Used Avail Use% Mounted on
devtmpfs         15G     0   15G   0% /dev
tmpfs            15G     0   15G   0% /dev/shm
tmpfs            15G  436K   15G   1% /run
tmpfs            15G     0   15G   0% /sys/fs/cgroup
/dev/xvda1      8.0G  1.3G  6.8G  16% /
tmpfs           3.0G     0  3.0G   0% /run/user/1000
/dev/xvdb       1.8T   77M  1.7T   1% /mnt/disk1
/dev/xvdc       1.8T   77M  1.7T   1% /mnt/disk2
/dev/xvdd       1.8T   77M  1.7T   1% /mnt/disk3

I was then able to use the disks. (Tip: Change permissions on the mount folders so you don't need to sudo all the time.)
Windows
I also booted up a d2.xlarge Windows instance. I then had to:

*

*Run Disk Management

*Bring each of the 3 disks online

*Initialized the disks

*Created a new Simple Volume for each disk

*They appeared as D:, E: and G:

A: Please check if there are multiple user profiles, in case if there are you may not have permissions to see them and this will not allow you to see the space occupied by them.


text:
Q: How can I increase the i in a for? I want to increase in 6 the value of i to read a file that have a question with 4 answers and a character of the correct answer, for example:
A
Which sport uses the term LOVE ?
Tennis
Golf
Football
Swimming
B
What is the German word for WATER ?
Wodar
Wasser
Werkip
Waski

My code:
fd = open(dFile)
lineas=fd.readlines()
fd.close()

for i in range(len(lineas)):
    print "CA:"+lineas[i]+"Q:"+lineas[i+1]+"A1:"+lineas[i+2]+"A2:"+lineas[i+3]+"A3:"+lineas[i+4]+"A4:"+lineas[i+5];
    i=i+6

A: Try using the "step size" argument to range or xrange:
fd = open(dFile)
lineas = fd.readlines()
fd.close()

for i in xrange(0, len(lineas), 6):
    print "CA:"+lineas[i]+"Q:"+lineas[i+1]+"A1:"+lineas[i+2]+"A2:"+lineas[i+3]+"A3:"+lineas[i+4]+"A4:"+lineas[i+5];

A: range has an optional step argument.
for i in range(0, 10, 3):
    print i  # Prints 0, 3, 6, 9

For your case, use a step size of 6.
for i in range(0, len(lineas), 6):

A: The following code snippets illustrate a way of treating each group of six lines from the input file as a tuple, which removes some of the clumsy lineas[i], lineas[i+1] etc indexing (at the cost of a clumsy-looking zip statement).  The first snippet of code is just to create a test file containing numbered lines.
with open('eh','w') as fo:
    for i in range(19):
        fo.write('{}\n'.format(i))
...
with open('eh') as fi:
    for (ca,q,a1,a2,a3,a4) in zip(*[iter(fi.readlines())]*6):
        print "CA:"+ca+"Q:"+q+"A1:"+a1+"A2:"+a2+"A3:"+a3+"A4:"+a4

This produces output like
CA:0
Q:1
A1:2
A2:3
A3:4
A4:5

CA:6
Q:7
A1:8
(etc)

Note, I would ordinarily write something like
print 'CA: {} Q: {} A1: {} A2: {} A3: {} A4: {}'.format(ca,q,a1,a2,a3,a4)

instead of
print "CA:"+ca+"Q:"+q+"A1:"+a1+"A2:"+a2+"A3:"+a3+"A4:"+a4

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to debug c# code called from R by rClr? I'm trying to debug C# methods that are called from R by means of rClr. In the VS-project I have set the the start action property to start Rscript.exe with the R-script as commandline parameter.  (Similar to what you would do e.g. to debug c# functions called from Excel using ExcelDNA.) The R-script runs as expected, but execution doesn't stop at the breakpoints. So I'm not able to do any debugging from Visual Studio.
What am I doing wrong?
Here is a minimal example:
C#-code in VS-project RLib1 - Calculates.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RLib1
{
    public class Calculate {
        public static double Sum(double x1, double x2) {
            return x1 + x2;
        }
    }
}

Properties in RLib1.csproj
Start external program: c:\R\R-3.3.2\bin\Rscript.exe
Command line arguments: c:\VSProjects\RLib1\TestRLib1.R
R-script in TestRLib1.R
library(rClr)
clrLoadAssembly('C:/VSProjects/RLib1/RLib1/bin/Debug/RLib1.dll')
clrGetTypesInAssembly("RLib1")
clrCallStatic("RLib1.Calculate","Sum",2,5)

A: You may want to use the "Attach to process" feature of visual studio as it is a bit more transparent in terms of debugging behavior; see https://github.com/jmp75/rClr/issues/32 for details.


text:
Q: Are two graphs isomorphic if: every spanning tree of one graph is isomorphic to some spanning tree of the other, and vice versa? Let $G_1,G_2$ denote two simple graphs, and $T_1,T_2$ denote their respective set of all spanning trees. Are $G_1,G_2$ isomorphic if every $t \in T_i$ is isomorphic to some $t' \in T_j$ for both $i,j \in\{1,2\}$? How do you prove or disprove this?

A: Both statements are wrong.

*

*Every spanning tree of graph $C_3$ is $P_3$  (a simple path of order 3). Exactly the same spanning tree has $P_3$.

*Consider a graph $G$ with vertices $V(G)=\{1,2,3,4\}$ and edges $E(G)=\{12,23,13,34\}$. This graph has spanning trees of two types: $T_1=G-12$, $T_2=G-13$.


text:
Q: xml parsing and unicode (again) xml header:
<?xml version="1.0" encoding="UTF-8"?><points>

xml data snippet:
<point>
<id>1781</id><lon>43.245766666667</lon><lat>56.636883333333</lat>
<type>vert</type><last_update>2016-11-18 22:55:11</last_update>
<active>1</active><verified>1</verified><international>0</international><name>Vеrshilovo</name><name_ru>Вершилово</name_ru><city/><belongs>АОН</belongs><inde

code:
tree = ET.parse(XMLFIL)
root = tree.getroot()
allpoints=root.findall('point')
for point in allpoints:
 id=point.find('id').text
 name=point.find('name').text.encode('utf8')
 print name

This will reward me with "AttributeError: 'NoneType' object has no attribute 'encode' " If I leave out the 'encode' I get the infamous ''ascii' codec can't encode character u'\u0435' in position 1: ordinal not in range(128)'
NB the error is with the 'e' of 'Vershilovo' : it looks ok like that but a hexdump of the xml data gives
00000000  56 e5 72 73 68 69 6c 6f  76 6f 0a                 |V.rshilovo.|

I found several related questions but none brought me a solution. The root cause may well be incorrect encoding of my xml data but I have no control over it. I can quite live with having to reset illegal values to some default like "???" or such.

A: It looks like some of the items don't have a text attribute.  You could use a try-except block or use a default value if text is None, eg:
name = (point.find('name').text or '').encode('utf8')

Another example, using an if statement:
name = point.find('name').text
if name:
    name = name.encode('utf8')


text:
Q: SFML 2.1 get frame time What is the equivalent of window.GetFrameTime in SFML 2.1?
I think it's from SFML 1.6 or SFML 2.0.
How can I use it in SFMl 2.1 on c++?

A: GetFrameTime() was removed from SFML at the beginning of 2012. The reasoning for it can be found here:  http://en.sfml-dev.org/forums/index.php?topic=6831.0
Users have to create an sf::Clock object now and keep time themselves. This has more advantages than disadvantages including:

*

*Correct time reporting (GetFrameTime() reported the time spent during the last frame)

*More control over between which points in your code the time is to be measured

*More control over the precision required

The new way of measuring the update time is 100% accurate (also thanks to the new sf::Clock::Restart function)
Code:
sf::Clock clock;
...
Update(clock.Restart());


text:
Q: Google Cloud Shell, Upgrade Docker from 1.9.1, it's impossible? I followed this guide: https://docs.docker.com/engine/installation/linux/debian/
but nothing, after all steps my docker version is this:
Client:
 Version:      1.12.3
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   6b644ec
 Built:        Wed Oct 26 21:39:14 2016
 OS/Arch:      linux/amd64
Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.21)

It is always to version 1.9.1.
How to do?
I need docker-compose working with docker-compose.yml file VERSION 2.
So I need docker-engine at least 1.10.x.
How to do?

A: I managed to temporarily upgrade via:
$ sudo apt update
$ sudo apt upgrade
$ sudo service docker restart

Updated 2017-01
Cloud Shell upgraded their software to make docker-compose work again.


text:
Q: Jupyter Notebook : How to select previous cell with Javascript I try to select a previous cell in my notebook with Javascript only.
I managed to find the code to select the current and the next cell.
The script to select the next cell is :
Jupyter.notebook.select_next().get_selected_cell()

(it works)
So i tried with this to get the previous cell :
Jupyter.notebook.select_previous().get_selected_cell()

But it's not working,
does someone know the right code to do that ?
(Sorry if my english is a bit bad...)

A: have you tried this:
Jupyter.notebook.select_prev().get_selected_cell()

In Chrome the JavaScript Console has a autocomplete feature that helps exploring functions and properties of objects.


text:
Q: Cohomological dimension of a group, fibration and local coefficients Hello,
I want to show that the cohomological dimension (say over Z or R) of some group $K$ is 1. $K$ occurs in an exact sequence $1 \to K \to \pi_1(X) \to \pi_1(C) \to 1$, where $\pi_1(X)$ has cohomological dimension 3 (in the same coefficients) and $C$ is a curve of genus greater than 2.
So I want a kind of additivity but this is not true in general. If I look at the associated fibration $BK \to B\pi_1(X) \to C$ and use Leray-Serre spectral sequence, I have some information on the cohomology of $BK$ and in fact can solve the problem if I assume that the action of the fundamental group of $B$ on the cohomology of the fiber is trivial. But I'm not familiar with cohomology with local coefficients and don't manage to show the general case.
Someone can help me ? (or solve this problem more directly ?) (or this is false in general ?)
mister_jones

A: It is false. The spectral sequence shows that cohomological dimension of group extensions is subadditive. It is not additive in general as every group is resolved by free groups, eg, $F_\infty\to F_3\to \mathbb Z^3$.
For your hypotheses, let $G=A*B$ be the free product of a three dimensional group $A$, say, $\mathbb Z^3$, and a surface group $B$. The dimension of the free product is the maximum of the dimensions of the factors, so 3. There is a natural map $G\to B$ that is the identity on $B$ and trivial on $A$. The kernel is 3-dimensional because it contains $A$, which is 3-dimensional.


text:
Q: Bash script successfully executes locally but not in Azure Devops pipeline I have a bash script that executes successfully in my local environment:
#!/bin/bash
#build changelog

version="Version: "
current_date=`date`
cat <(printf " \n") <(echo $version $env:BUILD_BUILDNUMBER $current_date) <(tail -n+6 pr-changelog.md) ./CHANGELOG.md > output
mv output ./CHANGELOG.md

However using the the Bash build package in my Azure Devops pipeline, whilst the script succeeds, does not throw any errors and the pipeline completes, the changes in the script do not take place.
The script copies lines from one file to the CHANGELOG.md and a couple of other small things. Locally the text is copied, but after running the pipeline, the CHANGELOG.md file has not changed in my branch.
Can I expect this to work and if not, what further steps should I take?
TIA

A:
Bash script successfully executes locally but not in Azure Devops pipeline

When we execute the build on the Azure pipeline, it will checkout the source from the repo to the build agent and the next operation is also done on the agent. It will not directly affect the repo, this way will protect the security of the source in our repo.
That is the reason why the changes in the script do not take place in your branch.
To resolve this issue, we need to submit this change to the repo by the git command: git add git commit and git push:
git config --global user.email "xxx@xyz.com"
git config --global user.name "Admin"

cd "$(System.DefaultWorkingDirectory)"

version="Version: "
current_date=`date`
cat <(printf " \n") <(echo $version $env:BUILD_BUILDNUMBER $current_date) <(tail -n+6 pr-changelog.md) ./CHANGELOG.md > output
mv output ./CHANGELOG.md

git add CHANGELOG.md

git commit -m "copies lines to CHANGELOG.md"

git push https://<PAT>@dev.azure.com/YourOrganization/YourProject/_git/YourProject HEAD:master

I test it with Azure pipeline, it works fine.


text:
Q: Amazon Redshift - Get week wise sales count by category I have daily sales data as below. I am trying to group by sales week wise.
I tried using group by that gives total count for the period, how could I modify the query to obtain an output as shown below:
Expected output:
Last N days,Count,Category

Last 7 days,225,Category_1
Last 14 days,136,Category_2
Last 7 days,172,Category_1
Last 14 days,321,Category_2

Input data:
Date,*Sales*,Category

01-06-2018,10,Category_1
01-06-2018,19,Category_1
03-06-2018,3,Category_1
04-06-2018,13,Category_1
05-06-2018,10,Category_1
06-06-2018,14,Category_1
07-06-2018,20,Category_1
08-06-2018,49,Category_1
09-06-2018,5,Category_1
10-06-2018,4,Category_1
11-06-2018,20,Category_1
12-06-2018,49,Category_1
13-06-2018,5,Category_1
14-06-2018,4,Category_1
01-06-2018,10,Category_1
01-06-2018,34,Category_2
03-06-2018,22,Category_2
04-06-2018,13,Category_2
05-06-2018,1,Category_2
06-06-2018,9,Category_2
07-06-2018,60,Category_2
08-06-2018,9,Category_2
09-06-2018,35,Category_2
10-06-2018,41,Category_2
11-06-2018,2,Category_2
12-06-2018,9,Category_2
13-06-2018,35,Category_2
14-06-2018,41,Category_2

Query tried:
select count(*),Category from sales
group by Category;

I am using Amazon redshift DB.
Could anyone help,thanks..
Update as of 06/19:
select Category,
sum(case when date >= dateadd(day, -7, CURRENT_DATE) then count(sales) else 0 end) as count_07,
sum(case when date >= dateadd(day, -14, CURRENT_DATE) then count(sales) else 0 end) as count_14
from sales
group by Category

A: I would put the values in separate columns.  Something like this:
select category,
       sum(case when date >= dateadd(day, -7, CURRENT_DATE) then sales else 0 end) as count_07,
       sum(case when date >= dateadd(day, -14, CURRENT_DATE) then sales else 0 end) as count_14
from sales s
group by category;

A: Looks like you are one DATEADD away from the solution.
For seven days, it should be as follows:
Select Count(*),Category From sales Where Date >= Dateadd(day,-7, CURRENT_DATE)

Group By Category;
Change -7 to -14 to get last 14 days.


text:
Q: QMake OBJECTS issue after clean I have a precompiled object file, say myObjectFile.o.  Inside my .pro file I have a block of code like this:
mac {
    ...
    OBJECTS += myObjectFile.o
}

This works great for linking in the object file with the rest of the project, but there is a fatal issue.  If I do a clean this object file gets deleted.  And since it's precompiled, when I try to build again I get a linking error until I copy the file back into my projects directory (I actually have a system call in my .pro file to copy the file so I just run qmake again).
This problem is annoying and causes some issues with our continuous integration server.  Basically, I'm looking for a way I can link precompiled object files into my code.

A: You do this by adding the object files in LIBS rather than OBJECTS:
mac {
    ...
    LIBS += myObjectFile.o
}

The contents of LIBS are passed to the linker as-is, which makes it possible to include object files in it.


text:
Q: How to line my input boxes horizontaly like in the image I want to do is make list of contact number form registration just like in the picture.
http://s38.photobucket.com/user/eloginko/media/number_zps5e6e5445.png.html
My problem is the form is making a newline after a new form. I want to make a copy just like in the picture. Can anyone help me, I'm using bootstrap 3.
current output: http://jsfiddle.net/5kcsn/79/
Contact Numbers *

Please provide at least one contact number information.

                             Home

                            +<input class="form-control" value="63" size="6" type="text" maxlength="6" id="inptboxCountryCodehomeContactNumber" width="40" style="width:30px" name="homeContactNumberCountryCode">
                            -<input  class="form-control" value="" type="text" size="5" maxlength="6" id="inptboxAreaCodehomeContactNumber" width="50" style="width:40px" name="homeContactNumberAreaCode">
                            -<input  class="form-control" value="" type="text" size="null" maxlength="30" id="inptboxhomeContactNumber" name="homeContactNumber" width="80" style="width: 80px">

Country Code - Area code - Tel. Number
 Ex. +63-02-1234567

                             Office

                            +<input class="form-control" value="63" size="6" type="text" maxlength="6" id="inptboxCountryCodeofficeContactNumber" width="40" style="width:30px" name="officeContactNumberCountryCode">
                            -<input  class="form-control" value="" type="text" size="5" maxlength="6" id="inptboxAreaCodeofficeContactNumber" width="50" style="width:40px" name="officeContactNumberAreaCode">
                            -<input  class="form-control" value="" type="text" size="null" maxlength="30" id="inptboxofficeContactNumber" name="officeContactNumber" width="80" style="width: 80px">

Country Code - Area code - Tel. Number
 Ex. +63-02-1234567

                             Mobile

                            +<input class="form-control" value="63" size="6" type="text" maxlength="6" id="inptboxCountryCodemobileContactNumber" width="40" style="width:30px" name="mobileContactNumberCountryCode">
                            -<input  class="form-control" value="" type="text" size="5" maxlength="6" id="inptboxAreaCodemobileContactNumber" width="50" style="width:40px" name="mobileContactNumberAreaCode">
                            -<input  class="form-control" value="" type="text" size="null" maxlength="30" id="inptboxmobileContactNumber" name="mobileContactNumber" width="80" style="width: 80px">

Country code - Network Code - Mobile Number
 Ex. +63-987-6543210

A: Do you think something like this http://jsfiddle.net/5kcsn/80/ ?
Just add the following to your css:
.form-control {
    display: inline-block;
}

This displays the input like inline-block so do not wrap the new line. But if you would like to stay another inputs not changed, just add some other class next to form-control and set the property to this new class.

A: .col-sm-3 input {display: inline;}

http://jsfiddle.net/5kcsn/85/


text:
Q: How to most efficiently extract content from this html string with javascript? (Highest Peformance = Lowest Milliseconds) I have the following HTML string in variable "myhtml":
<title>hackaday</title>
Welcome to the world.
You want a little treat...tomatoes berries walnutsDont You? Get Your Treat You will enjoy it. Eat It. Love it.

What I want to extract from this html string is "tomatoes berries walnuts". Note that every time I refresh the HTML page, there may be different words that show up instead of "tomatoes berries walnuts" like "chocolate chips soda".
What is the absolute fastest way to extract the string I am looking for? My current solution is to use a split on the "..." to get everything after, then use another split on the word "Dont" since nothing on that page/html changes except for those specific three words.
Is there a smarter/faster solution?

A: In theory, using a sliding window would be the fastest possible solution as it would take one pass and is O(n). However, also in theory all O(n) are equivalent and as a result using 3 passes is just as fast.
Use large segments in your index to ensure accuracy.

var htmlString = "<title>hackaday</title>Welcome to the world.
You want a little treat...tomatoes berries walnutsDont You? Get Your Treat You will enjoy it. Eat It. Love it.
";
var start = "
You want a little treat...";
var end = "Dont You? <a href=\"http://getyourtreat.com";
var startIndex = htmlString.indexOf(start);//pass one
var endIndex = htmlString.indexOf(end);//pass two
var result = htmlString.substring(startIndex+start.length,endIndex);//pass three
console.log(result);

A: You can use a regex instead:

var str = '<title>hackaday</title>Welcome to the world.
You want a little treat...tomatoes berries walnutsDont You? Get Your Treat You will enjoy it. Eat It. Love it.
';
var pattern = /\.{3}([\w\s]+)Dont/;
console.log(str.match(pattern)[1]);

With my update to match \w\s instead of (.*) my solution is faster (than the substring index method) in Firefox, Chrome and Safari
https://jsperf.com/substring-index-vs-regex


text:
Q: How to create API calls in REACT and FLUX I'm new to react and flux and I am having a hard time trying to figure out how to load data from a server. I am able to load the same data from a local file with no issues.
So first up I have this controller view (controller-view.js) that passes down initial state to a view (view.js)
controller-view.js
var viewBill = React.createClass({
getInitialState: function(){
    return {
        bill: BillStore.getAllBill()
    };
},
render: function(){
    return (

            <SubscriptionDetails subscription={this.state.bill.statement} />

    );
}
 });
 module.exports = viewBill;

view.js
var subscriptionsList = React.createClass({
propTypes: {
    subscription: React.PropTypes.array.isRequired
},
render: function(){

   return (

Statement

            From: {this.props.subscription.period.from} - To {this.props.subscription.period.to}

            Due: {this.props.subscription.due}

            Issued:{this.props.subscription.generated}

    );
}
 });
 module.exports = subscriptionsList;

I have an actions file that loads the INITAL data for my app. So this is data that is not called by as user action, but called from getInitialState in the controller view
InitialActions.js
var InitialiseActions = {
initApp: function(){
    Dispatcher.dispatch({
        actionType: ActionTypes.INITIALISE,
        initialData: {
            bill: BillApi.getBillLocal() // I switch to getBillServer for date from server
        }
    });
}
};
module.exports = InitialiseActions;

And then my data API looks like this
api.js
var BillApi = {
getBillLocal: function() {
    return billed;
},
getBillServer: function() {
    return $.getJSON('https://theurl.com/stuff.json').then(function(data) {

        return data;
    });
}
};
module.exports = BillApi;

And this is the store
store.js
var _bill = [];
var BillStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function() {
    this.emit(CHANGE_EVENT);
},
getAllBill: function() {
    return _bill;
}
});

Dispatcher.register(function(action){
switch(action.actionType){
    case ActionTypes.INITIALISE:
        _bill = action.initialData.bill;
        BillStore.emitChange();
        break;
    default:
        // do nothing
}
});

module.exports = BillStore;

So as I mentioned earlier, when I load data locally using BillApi.getBillLocal() in actions everything works fine. But when I change to BillApi.getBillServer() I get the followind errors in the console...
Warning: Failed propType: Required prop `subscription` was not specified in     `subscriptionsList`. Check the render method of `viewBill`.
Uncaught TypeError: Cannot read property 'period' of undefined

I also added a console.log(data) to BillApi.getBillServer() and I can see that the data is returned from the server. But it is displayed AFTER I get the warnings in the console which I believe may be the issue. Can anyone offer some advice or help me to fix it? Sorry for such a long post.
UPDATE
I made some changes to the api.js file (check here for change and DOM errors plnkr.co/edit/HoXszori3HUAwUOHzPLG ) as it was suggested that the issue is due to how I handle the promise. But it still seems to be the same issue as you can see in the DOM errors.

A: This is an async issue. Using $.getJSON().then() is not enough. Since it returns a promise object, you have to handle the promise at invocation by doing something like api.getBill().then(function(data) { /*do stuff with data*/ });
I made a CodePen example with the following code:
function searchSpotify(query) {
  return $.getJSON('http://ws.spotify.com/search/1/track.json?q=' + query)
  .then(function(data) {
    return data.tracks;
  });
}

searchSpotify('donald trump')
.then(function(tracks) {
  tracks.forEach(function(track) {
    console.log(track.name);
  });
});

A: It looks like from your code that the intended flow is something like:

*

*some component fires initialize action,

*initialize action calls API

*which waits for results from server (I think here is where things break down: your component render starts before results from server are back),

*then passes the result to the store,

*which emits change and

*triggers a re-render.

In a typical flux setup, I would advise to structure this somewhat different:

*

*some component calls API (but does not fire action to dispatcher yet)

*API does getJSON and waits for server results

*only after results are received, API triggers the INITIALIZE action with received data

*store responds to action, and updates itself with results

*then emits change

*which triggers re-render

I am not so familiar with jquery, promises and chaining, but I think this would roughly translate into the following changes in your code:

*

*controller-view needs a change listener to the store: add a componentDidMount() function that adds an event listener to flux store changes.

*in controller-view, the event listener triggers a setState() function, which fetches the most recent _bill from the store.

*move the dispatcher.dispatch() from your actions.js to your api.js (replacing return data);

That way, your component initially should render some 'loading' message, and update as soon as data from server is in.

A: An alternative method would be to check if the prop of subscription exists before you play with the data.
Try modifying your code to look a bit like this:
render: function(){

  var subscriptionPeriod = '';
  var subscriptionDue = ['',''];
  var subscriptionGenerated = '';

  if(this.props.subscription !== undefined){
       subscriptionPeriod = this.props.subscription.period;
       subscriptionDue = [this.props.subscription.due.to,this.props.subscription.due.from];
       subscriptionGenerated = this.props.subscription.generated;
  }

  return (

Statement

        From: {subscriptionPeriod[0]} - To {subscriptionPeriod[1]}

        Due: {subscriptionDue}

        Issued:{subscriptionGenerated}

);
}

In the render function before the return try adding the following:
    if(this.props.subscription != undefined){
    // do something here
    }
Due your data changing the state of the top level component it will retrigger the render once it has the data with the subscription prop being defined.

A: If I understand correctly you could try with something like this
// InitialActions.js

var InitialiseActions = {
initApp: function(){
    BillApi.getBill(function(result){
      // result from getJson is available here
      Dispatcher.dispatch({
          actionType: ActionTypes.INITIALISE,
          initialData: {
              bill: result
          }
      });
    });
}
};
module.exports = InitialiseActions;

//api.js

var BillApi = {
    getBillLocal: function() {
        console.log(biller);
        return biller;
    },
    getBill: function(callback) {
      $.getJSON('https://theurl.com/stuff.json', callback);
    }
};

$.getJSON does not return the value from the http request. It makes it available to the callback.
The logic behind this is explained in detail here: How to return the response from an asynchronous call?

A: I'll separate my Actions, Stores and Views (React components).
First of all, I'd implement my Action like this:
import keyMirror from 'keymirror';

import ApiService from '../../lib/api';
import Dispatcher from '../dispatcher/dispatcher';
import config from '../env/config';

export let ActionTypes = keyMirror({
  GetAllBillPending: null,
  GetAllBillSuccess: null,
  GetAllBillError: null
}, 'Bill:');

export default {
  fetchBills () {
    Dispatcher.dispatch(ActionTypes.GetAllBillPending);

    YOUR_API_CALL
      .then(response => {
        //fetchs your API/service call to fetch all Bills
        Dispatcher.dispatch(ActionTypes.GetAllBillSuccess, response);
      })
      .catch(err => {
        //catches error if you want to
        Dispatcher.dispatch(ActionTypes.GetAllBillError, err);
      });
  }
};

The next is my Store, so I can keep track of all changes that suddenly may occur during my api call:
class BillStore extends YourCustomStore {
  constructor() {
    super();

    this.bindActions(
      ActionTypes.GetAllBillPending, this.onGetAllBillPending,
      ActionTypes.GetAllBillSuccess, this.onGetAllBillSuccess,
      ActionTypes.GetAllBillError  , this.onGetAllBillError
    );
  }

  getInitialState () {
    return {
      bills : []
      status: Status.Pending
    };
  }

  onGetAllBillPending () {
    this.setState({
      bills : []
      status: Status.Pending
    });
  }

  onGetAllBillSuccess (payload) {
    this.setState({
      bills : payload
      status: Status.Ok
    });
  }

  onGetAllBillError (error) {
    this.setState({
      bills : [],
      status: Status.Errors
    });
  }
}

export default new BillStore();

Finally, your component:
import React from 'react';

import BillStore from '../stores/bill';
import BillActions from '../actions/bill';

export default React.createClass({

  statics: {
    storeListeners: {
      'onBillStoreChange': BillStore
     },
  },

  getInitialState () {
    return BillStore.getInitialState();
  },

  onBillStoreChange () {
    const state = BillStore.getState();

    this.setState({
      bills  : state.bills,
      pending: state.status === Status.Pending
    });
  },

  componentDidMount () {
    BillActions.fetchBills();
  },

  render () {
    if (this.state.pending) {
      return (

          {/* your loader, or pending structure */}

      );
    }

    return (

        {/* your Bills */}

    );
  }

});

A: Assuming you are actually getting the data from your API, but are getting it too late and errors are thrown first, try this:
In your controller-view.js, add the following:
componentWillMount: function () {
    BillStore.addChangeListener(this._handleChangedBills);
},

componentWillUnmount: function () {
    BillStore.removeChangeListener(this._handleChangedBills);
},

_handleChangedBills = () => {
    this.setState({bill: BillStore.getAllBill()});
}

And in your getInitialState function, give an empty object with the structure that your code expects (specifically, have a 'statement' object inside it). Something like this:
getInitialState: function(){
return {
    bill: { statement:  [] }
};
},

What is happening is that when you are getting your initial state, it isn't fetching from the store properly, and so will return an undefined object. When you then ask for this.state.bill.statement, bill is initialized but undefined, and so it cannot find anything called statement, hence why you need to add it in. After the component has had a bit more time (this is an async problem like the other posters said), it should fetch properly from the store. This is why we wait for the store to emit the change for us, and then we grab the data from the store.


text:
Q: Critical exponent in mean field theory In the book I'm recently reading about quantum statistics, the author takes the following example to show how to obtain critical exponent:
Considering magnetic system in a simple case where both magnetic polarization and external magnetic field are uniform over space, then the free energy is:
$$\psi(m,h) = -m h + \frac{1}{2} r_0 m^2 + \mu_0 m^4$$
where $r_0 = a_0t$ and $ \mu_0 > 0$. $a_0$ is a constant coefficient and $t = (T - T_c)/T_c$, ${T_{c}}$ is the Curie temperature.
So the energy is
$$E[m,h]=\int d^{d}x \psi(m,h) \, .$$
Therefore the partition function is
$$Z=\int(Dm)e^{-\frac{E[m,h]}{k_{B}T}}$$
where $k_{B}$ is Boltzmann constant
In a rough approximation, $Z$ can be replaced by the term contributing most, hence we have
$$\frac{\partial \psi(m,h)}{\partial m}|_{m_{0}}=0$$
and
$$\frac{\partial^{2} \psi(m,h)}{\partial^{2} m}|_{m_{0}}>0 \, .$$
After skipping some process, we find the specific heat:
$$
C =
\begin{cases}
0 \quad \text{for} \quad t < 0 \\
\frac{3 a_0^2 T}{8\mu_0 T_c^2} \quad \text{for} \quad t>0
\end{cases}
$$
Then the author says to reflect the discontinuity of $C$ at temperature $T_{c}$, $\alpha$ must be zero with $C\sim (T_c - T)^{-\alpha}$.
So here is my question:
why $\alpha=0$? To me, it seems more sensible to set $\alpha=-1$ because $C$ is propotional to $T$.


text:
Q: Creating Raster to Point data using ArcMap ModelBuilder Iterate raster tool Creating Raster to Point data using ArcGIS ModelBuilder Iterate raster

*

*Raster material is in folder (ffaa)

*Using Iterate rasters in model builder

*Select folder 1 (ffaa) in step 2

*Raster to point function input and input raster, output point feature setting

*Set field to blank

Status
ArcToolbox's raster to point function creates 1 raster to point data.
However, it fails in ModelBuilder.
As a result of confirmation, there is no field selection in the raster to point of ModelBuilder.
I tried entering a value in the field name, but it failed.
Error message

ERROR 010151: No features found in raster. Possible empty feature
class. Failed to execute (Raster to Point).
ERROR 999999: Error executing function. Failed to execute (Raster to
Point).

desired goal
When I want to use the raster to point function in the ModelBuilder, I want to select the field I want in the field selection.
So I directly used Value, "", ==, %%, %Value%, !Value!, $Value$, all, && etc in the field field, but it didn't work.

A: I think that you should check the configuration of the Raster To Point tool in your model.
It looks like you have set Output point features to:
D:WexportW%name%.shp

instead of:
D:\WexportW%name%.shp

A: I got the answer through various attempts.
The file I have is raster.
Do not put this in a folder, just save it in GDB format and run it.
I don't know why this is happening.


text:
Q: Getting the names of documents in Firestore Collection to show up as options in Select Input I'm trying to make an app that will allow users to register for a tournament, where the tournament options are pulled from a firestore collection and their name displayed in a dropdown select.
Currently I can see how many tournaments are available in the drop-down, but they just say undefined instead of the name.
If it helps for this form I only care about the name of the tournament, I don't need all the other attributes that are being mapped.
Image Showing Drop Down When Two Items Are In The Database Collection
Image Showing How The Firestore DB is set up

  componentDidMount() {
    let tournaments = this.db
      .collection("tournaments")
      .get()
      .then(querySnapshot => {
        tournaments = querySnapshot.docs.map(doc => doc.data());
        this.setState({ tournaments });
        this.tournamentChoices();
      });
  }

  tournamentChoices() {
    var select = document.getElementById("select");
    for (var i = 0; i < this.state.tournaments.length; i++) {
      var option = document.createElement("OPTION"),
        txt = document.createTextNode(this.state.tournaments[i].name);
      option.appendChild(txt);
      option.setAttribute("value", this.state.tournaments[i].name);
      select.insertBefore(option, select.lastChild);
    }
  }

  <FormGroup>
    <Input type="select" id="select" onChange={this.handleTournament}>
        <option value="default">Select Tournament</option>
    </Input>
</FormGroup>

A: I fixed it. The problem was with how I was storing tournaments when adding to the db from my app. I had it set up incorrectly so tournaments were being nested inside a tournament of the same name without any other attributes.
Thanks for the help.
this.db.collection('tournaments').doc(this.state.name).set(
            tournament //originally this was {tournament} so was passing in an object not the values
        );
    };


text:
Q: Adding event callback for YouTube JS Player API when related video clicked YouTube's iFrame embed JS player API  allows you to add callbacks to certain events. I want to add a callback for when a related video at the end of a video is selected.
To be more specific, when viewing a video in an embed, at the end it displays related videos within the embed. I want to run some code when one of those is selected. How can this be accomplished? I see that there is an onStateChange but none of the states are related to related videos. Do I need to add an onStateChange for YT.PlayerState.PLAYING and then compare the playing video to the original video to see if they're different somehow?

A: That seems like a reasonable solution to me.
The only point worth mentioning (which you've noted) is that you will be not able to tell if the change in the video is due to the user clicking on a related video, but if you're not interacting with the player dynamically, comparing the previous VideoID should suffice.
Just a heads up, if you're interested in a jQuery plugin that simplifies some of the callback/event handling work check out: https://github.com/nirvanatikku/jQuery-TubePlayer-Plugin

A: I ended up doing it basically the way I described. Here's the code I used:
started = false;

var onYouTubeIframeAPIReady = function(id) {
  var player = new YT.Player('player', {
    videoId: id,
    events: {
      'onStateChange': function (event) {
        if (event.data == 1) { // The video started playing
          started = true;
        }
        if (started && event.data == -1) {
          // Video had already started playing before and is now in
          // "unstarted" state so it must be a new video.
          var video_url = event.target.i.videoUrl;
          var video_id = video_url.replace('http://www.youtube.com/watch?v=', '').replace('&feature=player_embedded', '');
          window.location = '#/view/' + video_id;
        }
      }
    }
  });
}

So basically, when a video starts playing, you set a "started" variable to true. Then, if/when the video enters the "unstarted" state, if "started" is true, then you know that it's a new video that just started playing. In that case, grab its video ID from the event.target object and do whatever you want with it.
My full commit is here if anyone wants to see the context and you can see it in action on http://toogl.es.


text:
Q: Reading Metadata of CustomField with Custom GlobalValueSet returning null for valueSet I'm using metadataAPi (apex-mdapi)
My current use case is to read the metadata of a custom picklist field, and be returned with the complete list of picklist values available. Regardless of whether the field uses a GlobalValueSet or not. All of the examples on MetadataService are using the deprecated picklistValues code, whereas today we would need to use valueSet.
Currently, I need to return a list of picklistValues (they're a global value set) related to a custom field. The service has been instantiated and everything has been deployed using the github loader.
The code I believe should work is
 MetadataService.CustomField customField = (MetadataService.CustomField) service.readMetadata(
'CustomField', new String[] {'Opportunity.Area_of_Work2_Taxonomy__c' }
).getRecords()[0];

List<MetadataService.CustomValue > pickVals = new List<MetadataService.CustomValue >();
for (MetadataService.CustomValue  pk : customField.valueSet.valueSetDefinition.value ) {
   //pickVals.add(pk);
  System.debug('CS: Individual PK ' + pk );
 }

However, when outputting this information. A null item is returned for customField.valueSet.valueSetDefinition and customField.valueSet.valueSettings
System debug of customField.valueSet
ValueSet:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false),
controllingField=null,
controllingField_type_info=(controllingField, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
field_order_type_info=(controllingField, restricted, valueSetDefinition, valueSetName, valueSettings),
restricted=true,
restricted_type_info=(restricted, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
valueSetDefinition=null, //HERE
valueSetDefinition_type_info=(valueSetDefinition, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
valueSetName=Pitch_category,
valueSetName_type_info=(valueSetName, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false),
valueSettings=null, //HERE
valueSettings_type_info=(valueSettings, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false)]

My assumption is that, according to the Metadata documentation one of those fields should be populated. Is that correct?
Could anyone give me some assistance in either solving or gaining a better understanding of why?
Thank you kindly

A: For anyone with a similar problem in the future. I solved this problem by using the valueSetName=Pitch_category, attribute into a second call as a GlobalValueSet
globalPickListApi = (MetadataService.GlobalValueSet) service.readMetadata('GlobalValueSet', new String[] { picklistFieldMdApi.valueSet.valueSetName }).getRecords()[0];


text:
Q: Unlimited energy storage using relativistic flywheel? Theoretically, is it possible to store huge amount of energy using a flywheel that spins at speeds that approach light speed? Can the amount of energy be higher than the mass equivalence of the wheel?

A: Theoretically, it would be possible to accelerate any mass, even spin a flywheel, to near light speed. As mass increases with speed, relativistic mass could be many times the rest mass. In practice, however, with any material available today, a flywheel would tear itself to pieces long before reaching relativistic speeds.


text:
Q: shorthand std::array literal parameter I've been trying to write some shorter code that still uses std::array but I'm not sure how to get the deduction to work in my favor.
Is there a way to write this that is equally as short(readable) as the vector version?
#include <array>
#include <iostream>
#include <vector>

template <std::size_t SIZE>
void afunc(const std::array<std::string_view, SIZE> &v)
{
    for(int i=0; i<10; i++)
    {
        std::cout << v[rand()%SIZE];
    }
}

void vfunc(const std::vector<std::string_view> &v)
{
    for(int i=0; i<10; i++)
    {
        std::cout << v[rand()%v.size()];
    }
}

using namespace std::string_view_literals;

int main()
{
  std::array<std::string_view, 2> works = {"1","2"};
  afunc(works);// verbose
  //afunc({ "1","2" }); // 1st  fail
  //afunc({ "1"sv,"2"sv }); // 2nd fail
  //afunc(std::array{ "3","4" });// 3rd fail
  afunc(std::array{ "3"sv,"4"sv, "test"sv,"other"sv });// works but verbose

  vfunc({"5","6", "7"});// vectors are easy to code with

  return 0;
}

A: std::array and std::vector have the same size() and operator[] members, so you could roll your 2 functions into 1 function:
template <typename Container>
void func(const Container &c)
{
    for(int i = 0; i < 10; ++i)
    {
        std::cout << c[rand() % c.size()];
    }
}

std::array<std::string_view, 2> a{"1","2"};
func(a);

std::vector<std::string_view> v{"1","2"};
func(v);

func<std::array<std::string_view, 2>>({"1","2"});

func<std::vector<std::string_view>>({"1","2"});

Demo
But, as you can see, that can be too verbose for your taste.  But, you can support braced lists as a parameter without having to specify the template argument explicitly, by defining an extra function that accepts std::initializer_list as a parameter, and then the compiler can deduce that parameter for you.
But, std::initializer_list doesn't have operator[], so you would have to change your main function logic to use random-access iterators instead, if you intend to share common code between the functions, eg:
template <typename Iter>
void func(Iter begin, Iter end, std::random_access_iterator_tag)
{
    size_t size = end - begin;
    for(int i = 0; i < 10; ++i)
    {
        std::cout << *(begin + (std::rand() % size));
    }
}

template <typename Iter>
void func(Iter begin, Iter end)
{
    func(begin, end,
      typename std::iterator_traits<Iter>::iterator_category());
}

template <typename Container>
void func(const Container &c)
{
    func(std::begin(c), std::end(c));
}

template <typename T>
void func(const std::initializer_list<T> &l)
{
    func(l.begin(), l.end());
}

std::array<std::string_view, 2> a{"1","2"};
func(a);

std::vector<std::string_view> v{"1","2"};
func(v);

func({"1"sv, "2"sv});

Demo

A: You can't infer a compile-time size from an initializer list parameter, so you need to pass the size explicitly:
template <std::size_t Size>
void afunc(const std::array<std::string_view, Size> &v)
{ ... }

int main()
{
    afunc<2>({ "1", "2" }); // ok
}

Your vfunc for std::vector doesn't need to deduce a compile-time size, which is why this limitation only applies to template argument deduction for std::array in afunc.

A: Found out how to get C style arrays to work as an option. When I had tried this before my reference was not const thus would not compile with a temporary. Not as good as arrays for the lack of iterators but still straightforward
template<size_t N>
 void carr_try(std::string_view const(&a)[N])
 {
    for(int i=0; i<10; i++)
    {
        std::cout << a[rand()%N];
    }
 }

// for illustrative purposes of how to NOT write this routine
 template<size_t N>
 void nonconst(std::string_view (&a)[N])
 {
    for(int i=0; i<10; i++)
    {
        std::cout << a[rand()%N];
    }
 }

int main()
{
    carr_try({ "1", "2" }); // ok
//nonconst({"1","2"});// not ok
std::string_view temp[]={"3","4"};
nonconst(temp);// is fine but long
}


text:
Q: How to pass exceptions to the first instance? How can I pass any occuring exception to the first instance which is responsible for all function calls (in this example function3())?
Is there a simple solution?
Edit:
The problem is that function3() is in module1 and function2() and function1() in module2. function1() calls a Tkinter-based function which throws the exception: Exception in Tkinter callback (...) IndexError which is not being handled in the except-block
def function1():
   #Call another function which throws an exception

def function2():
   function1()

def function3():
   try:
      function2()
   except:
      #Do xyz for any occuring exception during the execution

A: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
def function1():
   raise Exception("Exc found!")

def function2():
   function1()

def function3():
   try:
      function2()
   except:
      import traceback
      traceback.print_exc()

Method traceback.print_exc() will catch the exception thrown at function1 and print the traceback for it, but won't stop the software.
If you want just the message, you can do this:
def function1():
   raise Exception("Exc found!")

def function2():
   function1()

def function3():
   try:
      function2()
   except ValueError:
      print("Found a ValueError")
   except Exception as e:
      print(f"Exception found: {e}")

In this second case, if the exception thrown is a ValueError, it will print "Found a ValueError". If it's any exception that is instance of Exception class and not a ValueError, it will print "Exception found: [a message here]".
Note that there are some exceptions that aren't child of Exception class, but all exceptions are child of BaseException class.
Another note is that isn't a good practice to catch "All exceptions" with the same way. Treat them specifically, as this avoid bugs by catching wrong exceptions.
For more info, you can read the documentation about exceptions (FROM PYTHON DOCS):
https://docs.python.org/3/tutorial/errors.html


text:
Q: after flutter upgrade to 3.0, manifest.lock is deleted after "flutter pub get" I am super newbie on flutter and programming also on this side stack overflow too.
Few days ago, Like everybody know, Flutter had a big update.
After That, after Flutter Clean -> Flutter pub get,
Then, my 'manifest.lock' is auto deleted ("flutter project/ios/pods/manifest.lock")
So i have to remake that file every time I want to build on Xcode.
ㄴ> I'm using the method from this article. (thank you always)
Could not build application for the simulator for flutter
Anyway, I wan't to fix the origin of this problem.
Is there anyone who can help me out from this?!


text:
Q: Use of Encrypted Fields in List views and Reports Am I able to use Encrypted Fields in filter criteria in list views, reports and communities? Is there documentation anywhere I can find? I want to verify before rolling out encryption?

A: There are various limits on listview / reports when using deterministic encryption
In particular, you can not do:

*

*Filter on Contains or Starts With or any relative operator (>, < >=, <=)

*Use the column sort on any encrypted field in a listview (as Order BY is not supported). This does not affect reports, only ListViews

I strongly suggest doing this in a sandbox and testing first.

A: Yes, if you encrypt a field with deterministic encryption you can filter on that field in list views and reports (and even SOQL if you need).
The documentation for deterministic encryption is here.


text:
Q: Does clojure need dependency injection to make code more testable? I remember reading an article about how Ruby doesn't really need DI or DI frameworks because the classes are open.  As a result, you can simply rewrite a dependency's constructor so that it returns a fake object.
I'm very new to Clojure and functional programming.  I'm wondering if Clojure needs dependency injection or it can forgo it for similar/other reasons.  Here's a concrete example to work with (feel free how to point out how my design is non-idiomatic of Clojure):

Imagine you're developing a web crawler/spider.  It needs to traverse a webpage you've downloaded.  This is an action with side-effects.  The webpage could change on every query, your internet connection could cut out, etc.  It finds all the links on the webpage, visits each one, and then traverses it in the same way.

Now, you want to write a test that mocks out the http client so it returns a hard coded string response instead.  How do you call the program's -main in a test and prevent it from using the real http client?

A:
Imagine you're developing a web crawler/spider. It needs to traverse a
  webpage you've downloaded. This is an action with side-effects. The
  webpage could change on every query, your internet connection could
  cut out, etc. It finds all the links on the webpage, visits each one,
  and then traverses it in the same way.

I don't see a need for dependency injection here. Here's how I think I'd tackle this problem whilst maintaining testability: separate out the implementation into a minimum of two functions. One function fetches and returns the webpage, and the other parses the response. In your main function, you'd have something like (-> "http://google.com" fetch parse).
Then, to test parse, you can simply bypass the fetch method and feed fake webpage data directly into the parse method.
(deftest test
     (is (= {:something "blah"} (parse "<title>Fake webpage etc..</title>"))))

So long as you're careful about breaking down problems into clear functions, I don't think you need anything sophisticated like DI to test.
I'm new to Clojure, so I'm not familiar with the macros and techniques mentioned by others in here, but the above methodology has served me fine thus far.

A: The with-redefs macro in clojure.core is very useful for stubbing out functions.
Here's a short REPL session to demonstrate this:
user=> (defn crawl [url]
  #_=>   ;; would now make http connection and download content
  #_=>   "data from the cloud")
#'user/crawl
user=> (defn -main [& args]
  #_=>   (crawl "http://www.google.com"))
#'user/-main
user=> (-main)
"data from the cloud"
user=> (with-redefs [crawl (fn [url] "fake data")]
  #_=>   (-main))
"fake data"

Since a Clojure program is composed (mostly) of functions, not objects, dynamic rebinding of functions replaces a good deal of what a DI framework would do for testing purposes.

A: In Clojure you usually achieve the equivalent of dependency injection with alternative methods:

*

*Dynamic binding - e.g. useful for redirecting standard output in test functions by doing (binding [*out* some-writer-object] ...)

*Higher order functions - can be used to provide a form of dependency injection by passing other functions as parameters

*Configuration with data - it's fairly idiomatic in Clojure to pass around maps which contain configuration parameters (or even functions to configure custom behaviour).

All of these are integral to the language itself. So you definitely don't need anything like a "DI framework". IMHO, needing a framework for DI is really just compensating for a lack of sufficient features in the language itself.


text:
Q: Migration not handled properly in Room I have one db table class where I did change related to indices. Previously indices was like :
@Entity(indices = {@Index(value = {"jobNumber", "jobId"},
        unique = true)})

But I changed it to
@Entity(indices = {
        @Index(value = "jobNumber", unique = true), @Index(value = "jobId", unique = true)
})

But when I tried migration it's giving me issue like :
caused by: java.lang.IllegalStateException: Migration didn't properly handle Job

I need to go with second format only. I tried to add migration but seems not working. Here is my code :
 public static final Migration MIGRATION_4_5 = new Migration(4, 5) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        migrateJobTableForIndices(database);
    }
};

private static void migrateJobTableForIndices(SupportSQLiteDatabase database) {
    //create new table
    database.execSQL(
            "CREATE TABLE Job_new (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, jobId INTEGER NOT NULL, " +
                    "jobNumber TEXT)");

    database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_Job_new_jobNumber_jobId ON Job_new (jobNumber, jobId)");
    // Copy the data
    database.execSQL(
            "INSERT INTO Job_new (id, jobId, jobNumber) " +
                    "SELECT id, jobId, jobNumber " +
                    "FROM Job");
    // Remove the old table
    database.execSQL("DROP TABLE Job");
    // Change the table name to the correct one
    database.execSQL("ALTER TABLE Job_new RENAME TO Job");
}

Is there any way to add migration for updated indices format. Any reference is really appreciated

A: As Room generates index names. You could export the scheme to see what is happening. By adding the following to your build.gradle:
android {
    ...
    javaCompileOptions {
        annotationProcessorOptions {
            arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
        }
    }

    ...
}

Now for the migration.
Beforehand you have to turn the foreign_keys off:
database.execSQL("PRAGMA foreign_keys=OFF;")

You have to drop the existing index. For example:
database.execSQL("DROP INDEX IF EXISTS `index_Job_jobNumber_jobId`")

Then I would suggest renaming the old table.
ALTER TABLE Job RENAME TO Job_old

Create the new table Job.
Then create the index, which you will find in the exported schema location. In this example, it is in your $projectDir/schemas. From the files there you could see and copy how Room creates the indexes and add the creation of these indexes after the table creation.
Migrate the data.
Drop the old table.
Turn the foreign_keys on:
database.execSQL("PRAGMA foreign_keys=ON;")


text:
Q: Principal components analysis I was working on an exercise that asks me to get a k-dimensional approximation of a data vector using PCA (containing 4096 dimensions - the faces data set). I did this in R, but the last section asks for a "short mathematical expression for how you construct the approximation where you need to account appropriately for the mean and standard deviation terms". I am familiar how to derive the PC's of the covariance matrix using eigen decomposition but I don't get the "accounting for the mean and sd" part.
Can someone help?

A: In PCA, our goal is to find linear combinations of the data such that the variance is maximized subject to certain conditions. If our original data is not all on the same scale, and especially if the scale difference is large, then the result can be somewhat meaningless. We can rectify this by standardizing our data first and then running the procedure - this is equivalent to using our original correlation matrix as the covariance matrix in the PCA. This can be shown as follows:
$$
Cov\left(\frac{X_1-\mu_1}{\sigma_1}, \frac{X_2-\mu_2}{\sigma_2}\right) = \frac{Cov(X_1,X_2)}{\sigma_1\sigma_2} = Corr(X_1, X_2)
$$
As we can see, the correlation matrix is equivalent to the covariance matrix of the standardized variables. Note that, as a result, your conclusions should be about the standardized variables and not your original variables.


text:
Q: How to store tags in the url without a "?" I'm wondering how I can store tags in a url without the ? and without keys.
eg. Google Product forums does this: http://productforums.google.com/forum/#!topic/analytics/8qtK861a0iU
Each topic wouldn't have it's own directory and so a server side script determines which topic to show visitors.
Does anybody know how it is possible to do this with PHP?
Thanks

A: Google use a range of software to do this. one of which, can be done using .htaccess used on Apache servers (not IIS)
This is called modrewrite. A URL below can show an example of such tasks:
http://roshanbh.com.np/2008/03/url-rewriting-examples-htaccess.html
Do start learning this, upload a file called .htaccess to your Apache driven webserver.


text:
Q: Setting a variable once for each time rspec is run I am writing a Ruby gem that accesses the features of a web based API. I need to set up an object which will be initialized and log into the API just once for each time the tests are run. before(:all) is still excessive because it will run once for every describe block, and what I want is something that universally sets up once for all of the test files.
UPDATE
Just as a follow up, to make the object I was using available in the tests, I had to add a setting to the rspec config like this
config.add_setting :client
config.before(:suite) do
  RSpec.configuration.client = TDAmeritradeApi::Client.new
  RSpec.configuration.client.login
end

And then in the describe blocks I do this:
let(:client) { RSpec.configuration.client }

A: I believe you are looking for before(:suite) and you can use it in the config section of your spec_helper.rb.
RSpec.configure do |config|
  config.before(:suite) do
    # API login
  end
end

A: You can use before(:suite) to run a block of code before any example groups are run. This should be declared in RSpec.configure
Source: http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks


text:
Q: Chart.js Formatting dual axis and labels jsfiddle here.
First time using Chart.js and I cannot find an example with the whole code to review. I have the following data for 3 months to chart:
Project hours billed, Project hours not billed (stacked bar, for each month)
Billed Amount, To Be Billed amount (stacked bar for each month)

I want to stack the hours and also the billing totals, and want two Y axis, one for hours, the other for dollars.
I have got as far as this code, but it does not stack the hours or the invoiced amounts for each month. Also, I cannot seem to format either axis and the values in the labels to time and currency.
Is there an example you can point me to showing this. Thanks!
var barChartData = {
    labels: ["January", "February", "March"],
    datasets: [{
            type: 'bar',
            label: 'Billed Hours',
            backgroundColor: "rgba(220,220,220,0.5)",
            yAxisID: "y-axis-1",
            data: [33.56, 68.45, 79.35]
        }, {
            type: 'bar',
            label: 'Non Billed Hours',
            backgroundColor: "rgba(222,220,220,0.5)",
            yAxisID: "y-axis-1",
            data: [3.50, 8.58, 7.53]
        }, {
            type: 'bar',
            label: 'Income',
            backgroundColor: "rgba(151,187,205,0.5)",
            yAxisID: "y-axis-2",
            data: [3800.00, 7565.65, 8500.96]
        }, {
            type: 'bar',
            label: 'Income',
            backgroundColor: "rgba(155,187,205,0.5)",
            yAxisID: "y-axis-2",
            data: [320.00, 780.65, 850.96]
        }]

};
var ctx = document.getElementById("projectHours").getContext("2d");
window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        hoverMode: 'label',
        hoverAnimationDuration: 400,
        stacked: true,
        title: {
            display: true,
            text: "Billed / Billable Project Summary"
        },
        scales: {
            yAxes: [{
                type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
                display: true,
                position: "left",
                id: "y-axis-1",
            }, {
                type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
                display: true,
                position: "right",
                id: "y-axis-2",
                gridLines: {
                    drawOnChartArea: false
                },
            }],
        },
        animation: {
            onComplete: function () {
                var ctx = this.chart.ctx;
                ctx.textAlign = "center";
                Chart.helpers.each(this.data.datasets.forEach(function (dataset) {
                    Chart.helpers.each(dataset.metaData.forEach(function (bar, index) {
                        ctx.fillText(dataset.data[index], bar._model.x, bar._model.y - 10);
                    }),this)
                }),this);
            }
        }
    }
});

A: You can extend the bar chart to do this

Preview

Script
Chart.defaults.groupableBar = Chart.helpers.clone(Chart.defaults.bar);

var helpers = Chart.helpers;
Chart.controllers.groupableBar = Chart.controllers.bar.extend({
    calculateBarX: function (index, datasetIndex) {
        // position the bars based on the stack index
        var stackIndex = this.getMeta().stackIndex;
        return Chart.controllers.bar.prototype.calculateBarX.apply(this, [index, stackIndex]);
    },

    // hide preceding datasets in groups other than the one we are in
    hideOtherStacks: function (datasetIndex) {
        var meta = this.getMeta();
        var stackIndex = meta.stackIndex;

        this.hiddens = [];
        for (var i = 0; i < datasetIndex; i++) {
            var dsMeta = this.chart.getDatasetMeta(i);
            if (dsMeta.stackIndex !== stackIndex) {
                this.hiddens.push(dsMeta.hidden);
                dsMeta.hidden = true;
            }
        }
    },

    // reverse hideOtherStacks
    unhideOtherStacks: function (datasetIndex) {
        var meta = this.getMeta();
        var stackIndex = meta.stackIndex;

        for (var i = 0; i < datasetIndex; i++) {
            var dsMeta = this.chart.getDatasetMeta(i);
            if (dsMeta.stackIndex !== stackIndex) {
                dsMeta.hidden = this.hiddens.unshift();
            }
        }
    },

    // we hide preceding datasets in groups other than the one we are in
    // we then rely on the normal stacked logic to do its magic
    calculateBarY: function (index, datasetIndex) {
        this.hideOtherStacks(datasetIndex);
        var barY = Chart.controllers.bar.prototype.calculateBarY.apply(this, [index, datasetIndex]);
        this.unhideOtherStacks(datasetIndex);
        return barY;
    },

    // similar to calculateBarY
    calculateBarBase: function (datasetIndex, index) {
        this.hideOtherStacks(datasetIndex);
        var barBase = Chart.controllers.bar.prototype.calculateBarBase.apply(this, [datasetIndex, index]);
        this.unhideOtherStacks(datasetIndex);
        return barBase;
    },

    getBarCount: function () {
        var stacks = [];

        // put the stack index in the dataset meta
        Chart.helpers.each(this.chart.data.datasets, function (dataset, datasetIndex) {
            var meta = this.chart.getDatasetMeta(datasetIndex);
            if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) {
                var stackIndex = stacks.indexOf(dataset.stack);
                if (stackIndex === -1) {
                    stackIndex = stacks.length;
                    stacks.push(dataset.stack);
                }
                meta.stackIndex = stackIndex;
            }
        }, this);

        this.getMeta().stacks = stacks;
        return stacks.length;
    },
});

and then
    ...
    type: 'groupableBar',
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // we have to set this manually (or we could calculate it from our input data)
                    max: 160,
                },
                stacked: true,
            }]
        }
    }
});

Note that we don't have any logic to set the y axis limits, we just hard code it. If you leave it unspecified, you'll end up with the limits you get if all the bars were stacked in one group.

Fiddle - http://jsfiddle.net/4rjge8sk/


text:
Q: Unclosed XML tag My GPX tracks¹ start with
<?xml version="1.0"?>
<gpx xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="http://www.delorme.com" xmlns="http://www.topografix.com/GPX/1/1">
  <trk>

and end with </trk> with no </gpx> anywhere.
I am pretty sure there are no practical drawbacks to this, but what might be the benefit of "fixing" it in thousands of files?
¹Several years of hiking and biking.

A: The benefit would be that any program reading these files that failed to do so before due to their ill-formity, would now do so.
It is impossible for us to predict what software you might use in the future, or what level of compatibility with ill-formed files said software might have, so that is literally (and obviously) as detailed as we can be.
But, does it matter? It's one line of Bash to fix these files. If you're concerned about your future with these files, simply append </gpx> to each one then move on to real problems.

A: The benefit to making your "XML" be well-formed is that then anyone wishing to process your data will be able to use standards-based XML tools to do so.  Without your textual data being well-formed XML, it's a non-standard format, its resemblance to XML notwithstanding.
There are many editors, parsing libraries, schema validation processors, transformation languages, etc, which become available if you fix your "XML".
See also How to parse invalid (bad / not well-formed) XML?


text:
Q: What are the differences between the perceptron and linear regression hypothesis set? While studying machine learning I have known 2 learning models: linear regression and perceptron.
I know the difference between the Learning algorithm they use, but the hypothesis set look the same to me.
Are there any difference?


text:
Q: How can I edit my home index page and other pages source file in WordPress using html? I am having difficulty adding an HTML element to my menus on my WordPress website because I am not finding the SourceCode of my website to edit it. I am using WordPress with Sinatra Theme. Is it possible to edit my WordPress website source code and if not how can I add an element of HTML to my Navbar and add a CSS style to it.

A: You cannot add html to build in wordpress menu. First there is PHP, second you need to create separate menu in HTML and CSS and use it instead (if you really want). Also if you even find a way how to implement it make sure you create child element because every time when you update WP all changes will be gone.
The second option: You need to create entire header including menu. Switch off build in WP menu totaly and put new instead.


text:
Q: Implicit conversion of integers to floats in c I'm having trouble understading why this code's output is 2147483648:
#include <stdio.h>
int main (void){
    float f = 2147483638;
    printf("%f",f);
}

I tried to find explanation using IEEE 754 standard for float representation but using my calculations I get that output should be 2147483520, not 2147483648.
Thanks for help!

A: That is the way that float works on your system.
Note that the C standard is intentionally flexible as to the type and sizes of the floating point types. A float does not have to be an IEEE754 32 bit floating point type.


text:
Q: Why does my text fields gets cleared when I pressed a button that will reveal obscure text in Flutter? I'm trying to make a a sign-in page as side project, it contains two fields of text, Email address & Password, on the password field it has a button that will reveals the obscure text on click and re-obscure the password text on second click and so on.
Now the main problem is: Instead of revealing the password text on click, both text field gets cleared instead.
This is the code:
  bool _visiblePassword = false;

  @override
  void initState() {
    _visiblePassword = false;
  }

  final _emailController = TextEditingController();
  final _passController = TextEditingController();

  body: Padding(
        padding: EdgeInsets.all(28),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            TextFormField(
              controller: _emailController,
              style: TextStyle(color: Color.fromARGB(255, 214, 213, 213)),
              decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                filled: true,
                hintStyle: TextStyle(color: Color.fromARGB(255, 197, 197, 197)),
                hintText: "Enter your email",
                fillColor: setupMainTheme,
              ),
            ),

            SizedBox(height: 18),

            TextFormField(
              controller: _passController,
              obscuringCharacter: '*',
              obscureText: !_visiblePassword,
              style: TextStyle(color: Color.fromARGB(255, 214, 213, 213)),
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  icon: Icon(
                    _visiblePassword ? Icons.visibility : Icons.visibility_off,
                    color: Theme.of(context).primaryColorDark,
                  ),
                  onPressed: () {
                    setState(() {
                      _visiblePassword = !_visiblePassword;
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                filled: true,
                hintStyle: TextStyle(color: Color.fromARGB(255, 197, 197, 197)),
                hintText: "Enter your password",
                fillColor: setupMainTheme,
              ),
            ),

A: If you have _emailController and _passController defined inside the build method, then move them outside it. This is so they don't get reinitialized when setState is called.


text:
Q: OpenReadAsync call on storagefile hangs I am reading a file, present in the Universal windows Application scope, from an external project added as .dll to the first one. The code seems to stuck or hang at GetFileAsync.
Also when I run the same stub from the Application instead of the .dll project, it works.
I need to know if there is a different way of reading a file present in Application folder from a .dll project, to be used in same project,.
Code for reading the file :
private static async Task<Stream> getStreamAsync()
{
    try
    {
        StorageFolder storageFolder = Package.Current.InstalledLocation;
        StorageFile file = await storageFolder.GetFileAsync("file.json");
        Stream stream = null;
        if (file != null)
        {
            var randomAccessStream = await file.OpenReadAsync().AsTask().ConfigureAwait(false);
            stream = randomAccessStream.AsStreamForRead();
        }

        return stream;
    }
    catch (Exception ex)
    { }
}

private Stream fetchStream()
{
    var stream = getStreamAsync().Result;
    return stream;
}

private func()
{
    Stream StreamFetched = fetchStream();
}

A: You're deadlocking your UI thread with itself:
fetchStream calls getStreamAsync().
getStreamAsync() awaits on storageFolder.GetFileAsync, scheduling the continuation to the current synchronization context (the UI thread's message queue).
The UI thread immediately returns from getStreamAsync() and continues executing fetchStream().
Executing .Result blocks the UI thread waiting for the continuation to complete.
... BUT
The continuation will never complete because the continuation is scheduled to run later on the UI thread and the UI thread is blocked.
Try something like:
StorageFile file = await storageFolder.GetFileAsync("file.json").ConfigureAwait(false);

That will cause the continuation to be scheduled against the default synchronization context instead of the current one. This is (presumably) why you also have a ConfigureAwait(false) further down on OpenReadAsync()


text:
Q: Footer Page Links I would like to have something like this at the bottom of my chrome extension:
https://gyazo.com/89f5f73f1f4fc24a764c058dbfee24de
Mine currently looks like this:
https://gyazo.com/f71a60149cc0301f965e7f0736815505
This is my html code:
https://gyazo.com/2fb446ed0b7fd61bde06d201f175495d
What should I do to get mine looking like the first one.

A: I think that you would want to use CSS to solve this issue. The code of which should be found on this website. It should have all the information on how to split the footer in half. You would also want to take the background color out of the CSS as well.

A: You need CSS for this. Add the class footer to the td

td.footer{
 background-color: none;
}

td.footer a {
 color: aqua;
}


text:
Q: RegEx, colon separated list I am trying to match a list of colon separated emails. For the sake of keeping things simple, I am going to leave the email expression out of the mix and match it with any number of characters with no spaces in between them.
The following will be matched...
somevalues  ;somevalues;       somevalues;

or
somevalues; somevalues             ;somevalues

The ending ; shouldn't be necessary.
The following would not be matched.
somevalues ;   some values    somevalues;

or
some values; somevalues some values

I have gotten this so far, but it doesn't work. Since I allow spaces between the colons, the expression doesn't know if the space is in the word, or between the colon.
([a-zA-Z]*\s*\;?\s*)*

The following is matched (which shouldn't e)
somevalue ; somevalues  some values;

How do I make the expression only allow spaces if there is a ; to the left or right of it?

A: Why not just split on semi colon and then regex out the email addresses?

A: This following PCRE Expression should work.
\w+\s*(?:(?:;(?:\s*\w+\s*)?)+)?
However if putting the email address validation regular expression on this will require
replacing \w+ with (?:<your email validation regex>)
Probabbly This is exactly what you want, tested on http://regexr.com?2rnce
EDIT: However depending on the language you might? need to escape ; as \;

A: The problem comes from the ? in \;?
[a-zA-Z]*(\s*;\s*[a-zA-Z]*)*

should work.

A: Try
([a-zA-Z]+\s*;\s*)*([a-zA-Z]+\s*\)?

Note that I changed * to + on the e-mail pattern since I assume you don't want strings like ; to match.

A: to solve this with regex, you must prepend + append the delimiter to your input lines, otherwise you cannot easily detect the first and last item
#!/bin/bash

input=a:aa:aaa:aaaa
needle=aa
if [[ ":$input:" =~ ":$needle:" ]]
then
  echo found
else
  echo not found
fi
# -> found

.. this takes 45 nanoseconds
bash globbing is faster with 35 nanoseconds
input=a:aa:aaa:aaaa
needle=aa
if [[ ":$input:" == *":$needle:"* ]]
then
  echo found
else
  echo not found
fi
# -> found

stupid solution: split by delimiter and match whole lines. this one is really slow, with 5100 nanoseconds
echo a:aa:aaa:aaaa | tr ':' $'\n' | grep "^aa$"
# -> aa


text:
Q: Retrofit how to pass location iside the GET I want to show Nearby restaurants using my current location. I am using Retrofit, but I don't know how to pass my current latitude and longitude inside GET. I'm using ZOMATO API to get information about restaurants.
My geocode URL
If I get my location in MainActivity then how to pass it inside GET.
Please help me it's my first time working with Retrofit and API.
My interface class - ZomatoApi.java
package com.example.zomatoapi;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;

public interface ZomatoApi {

String baseUrl = "https://developers.zomato.com/api/v2.1/";

@Headers("user-key: 1d63821dbb228ee5d09e8c8f7cfe10c3")
@GET("geocode?lat=18.521428&lon=73.8544541")
   Call<CurrentCity> getRestaurant();

}

MainActivity
package com.example.zomatoapi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

private FusedLocationProviderClient mFusedLocationClient;

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

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ZomatoApi.baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ZomatoApi zomatoApi = retrofit.create(ZomatoApi.class);

    final ListView listView = findViewById(R.id.restaurantList);

    final ArrayList<String> restaurantNames = new ArrayList<>();

    Call<CurrentCity> listCall = zomatoApi.getRestaurant();

    listCall.enqueue(new Callback<CurrentCity>() {
        @Override
        public void onResponse(Call<CurrentCity> call, Response<CurrentCity> response) {

            CurrentCity currentCity = response.body();

            List<NearbyRestaurant> nearbyRestaurants = currentCity.getNearbyRestaurants();

            for (NearbyRestaurant nearbyRestaurant : nearbyRestaurants) {
                Restaurant restaurant = nearbyRestaurant.getRestaurant();

                Log.i("heyy", restaurant.getName());

                restaurantNames.add(restaurant.getName());
            }

            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, restaurantNames);
            listView.setAdapter(arrayAdapter);
        }

        @Override
        public void onFailure(Call<CurrentCity> call, Throwable t) {

        }
    });

}

}

A: Try this out :
 @POST("nearestrestaurants?key=your_api_key")
// Call<MySnappedPoints> getNearestrestaurants();
Call<MySnappedPoints> getNearestRoad(@Query("points") String points);

To get this points :
 String test = Double.toString(mGoogleMap.getCameraPosition().target.latitude) + "," +
Double.toString(mGoogleMap.getCameraPosition().target.longitude);
Call<MySnappedPoints> call = retrofitClientMap.getNearestRoad(test);

A: As per given documentation by Zomato, it accepts lat/lng as query params.
Try something like below
@Headers("user-key: xxxxxxxxxxxxxxx")
    @GET("/geocode?")
        Call<CurrentCity> getRestaurant(@Query("lat") double lat, @Query("lng") double lng);


text:
Q: Spark SQL - orderBy decreases the number of partitions to value range, resulting in spill and ultimately no space on disk I have a pretty straightforward pyspark SQL application (spark 2.4.4, EMR 5.29) that reads a dataframe of the schema topic, year, count:
df.show()

+--------+----+------+
|   topic|year| count|
+--------+----+------+
|covid-19|2017|606498|
|covid-19|2016|454678|
|covid-19|2011| 10517|
|covid-19|2008|  6193|
|covid-19|2015|510391|
|covid-19|2013| 29551|

I then need to sort by year and collect counts to a list so that they be in ascending order, by year:
df.orderBy('year').groupBy('topic').agg(collect_list('count').alias('counts'))

The issue is, since I order by year, the number of partitions used for this stage is the number of years in my dataset. I thus get a crazy bottleneck stage where 15 out of 300 executors are utilised, leading to obvious memory spills and disk spills, eventually failing the stage due to no space left on device for the overpopulated partitions.
Even more interesting is that I found a way to circumvent this which intuitively appears to be much less efficient, but actually does work, since no bottlenecks are created:
df.groupBy('topic').pivot('year', values=range(START, FINISH)).agg(first('count')) \
    .select('topic', array([col(c) for c in range(START, FINISH)]).alias('counts'))

This leads to my desired output, which is an array of counts sorted by year.
Anyone with an explanation or idea why this happens, or how best to prevent this?
I found this answer which and this jira where it is basically suggested to 'add noise' to the sort by key to avoid these skew related issues.
I think it is worth mentioning that the pivot method is a better resolution than adding noise, and to my knowledge whenever sorting by a column that has a small range of values. would appreciate any info on this and alternate implementations.

A: Range Partitioning is used for Sorting, ordering, under water by Spark.
From the docs it is clear that the calculation for determining the number of partitions that will contain ranges of data for sorting subsequently via mapPartitions,
is based on sampling from the existing partitions prior to computing some heuristically optimal number of partitions for these computed ranges.
These ranges which are partitions may decrease the number of partitions as a range must be contained with a single partition - for the order by / sort to work. Via mapPartitions type approach.
This:
df.repartitionByRange(100, 'some_col1', 'some_colN')...

can help or of you order by more columns I suspect. But here it appears not to be the case based on your DF.
The question has nothing to do with pyspark, BTW.
Interesting point, but explainable: reduced partitions needing to hold more data via collect_list based on year, there are obviously more topics than years.


text:
Q: How to know I tap "taking photo button" with UIImagePicker There are three delegate method with UIImagePickerDelegate.
(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info;

This method tell you the piture you take.
 But when I tap the "taking photo button", how I know the event?

A: You should
1) subclass UIImagePickerController
2) set showCameraControls = NO
3) create your own controls on this ViewController's view

A: Xcode 7.3, iOS 9.3
My way is a bit hacky, but essentially I drill down the view hierarchy to find CMKShutterButton, then attach a method to the the appropriate control event.
See my post and solution here: iOS, UIImagePickerController, is there a way to detect when user taps the take picture button without implementing custom controls? and https://stackoverflow.com/a/36489246/4018041.
Hope this helps!  Cheers.


text:
Q: How to set state of UIButton in function I have a for loop that loops through an array of object type Note that has the property fingering which is set to a button.
The for loop:
for (int i = 0; i < [Bb_major.scaleNotes count]; i++) {
        valve1.highlighted = NO;
        valve2.highlighted = NO;
        valve3.highlighted = NO;
        valve4.highlighted = NO;

        [Scale tutorial:valve1 :valve2 :valve3 :valve4 :Bb_major.scaleNotes[i]];
}

The tutorial method:
+(void)tutorial:(UIButton *)button1 :(UIButton *)button2 :(UIButton *)button3 :(UIButton *)button4 :(Note *)Note {

switch ([Note.fingering count]) {
    case 0:
        break;
    case 1:
        button1 = Note.fingering[0];

        button1.highlighted = YES;

        sleep(1.0);

        break;
    case 2:

        button1 = Note.fingering[0];
        button2 = Note.fingering[1];

        button1.highlighted = YES;
        button2.highlighted = YES;

        sleep(1.0);

        break;
    case 3:
        button1 = Note.fingering[0];
        button2 = Note.fingering[1];
        button3 = Note.fingering[2];

        button1.highlighted = YES;
        button2.highlighted = YES;
        button3.highlighted = YES;

        sleep(1.0);

        break;
    default:
        break;
}
}

I would like to have it so that when my for loop iterates through scaleNotes, each sequence of buttons is highlighted for a moment, then the next Notes buttons are highlighted. Is there a more efficient way to accomplish this task?


text:
Q: What is the optimal way to load form data into a string and then to localStorage? Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
    var sg = document.getElementById("selectedGateway");
    var sd = document.getElementById("selectedDestination");
    var dm = document.getElementById("departureMonth");
    var dd = document.getElementById("departureDay");
    var dy = document.getElementById("departureYear");
    var rm = document.getElementById("returnMonth");
    var rd = document.getElementById("returnDay");
    var ry = document.getElementById("returnYear");
    var ad = document.getElementById("adults");
    var ch = document.getElementById("option2");

    $("#searchRequestForm").submit(function() {
        var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
        localStorage.setItem("string", string);
    });
</script>

A: I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
    sg: $("#selectedGateway").val(),
    sd: $("#selectedDestination").val()

    // items here
};

localStorage.setItem("mykey", JSON.stringify(data));

To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);

See Also:

*

*https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

*http://api.jquery.com/jQuery.parseJSON/

A: I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
    "selectedGateway", "From: ",
    "selectedDestination", "\nTo :",
    "departureMonth", "\nDeparture: ",
    "departureDay", "/",
    "departureYear", "/",
    "returnMonth", " \nReturn: ",
    "returnDay", "/",
    "returnYear",  "/",
    "adults", " \nNumber of adults: ",
    "option2", " \nNumber of children: "];

var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
    submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);

A: You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
    return document.getElementById(id).value;
}


text:
Q: Only Authenticate from server (Facebook and Google access token) using Java Spring I only want to authenticate the user access token which I get from javascript.
I am using spring rest service.
I have seen this:
https://developers.google.com/identity/sign-in/web/server-side-flow
However I am trying to find the exact code piece for facebook and google.
Does anyone have any code snippet to share or direct any github. Including the dependencies also because those also creates some conflicts.

My personal solution offer is this. It is stable?
I will do simple hhtp get using these 2 urls
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=
https://graph.facebook.com/app?access_token
and compare the if the user id and email and name is matching.

If somebody finds this access token from their personal facebook login structure of different app (lets say 3rd party website has facebook login also) and uses the same token to enter my service (sending that token from that 3rd party service to my service api) can I do something to verify that this user access token is actually received from my own login system?
because with these 2 http gets there are no secret api key or anything.
Thanks

A: For example from this googleapis html
audience "1058748273114-6srsjvvag80n2kk6mc3v6fv2i3jdlm.apps.googleusercontent.com"
shows the exact app id information. This way I can validate that this id is matching my own personal apps id. This way I can verify for google at least
https://graph.facebook.com/v2.10/me?fields=id%2Cname&access_token=
is also good to check as well
With the previous link also I can check my api data and with this url I can check the person. 2 service call is needed.


text:
Q: Java compile error in linux: cannot find symbol "javax\mail\session" While compiling java file in linux. I get the error: cannot find symbol : "javax\mail\session". I am using mail.jar file. which is already included in classpath. But still I get this error. Please help.

A: Well for starters, on linux the file separator is a forward slash (only windows uses the back slash).
Where ever you're using "javax\mail\session", try "javax/mail/session" instead

A: is it javax/mail/session or javax/mail/Session. S is in caps. Are you using any Ide ?


text:
Q: Inheritence, pointers and Software Architecture #include <iostream>

class EquationOfMotion
{
    public:
        // other attributes
        virtual void findNextTimeStep() = 0;
};

class SystemModel
{
    public:
        EquationOfMotion* p_eom;
        // other atributes
        SystemModel(EquationOfMotion* new_p_eom)
        {
            p_eom = new_p_eom;
        }
};

class VehicleEquationOfMotion: public EquationOfMotion
{
    public:
        VehicleEquationOfMotion(...){/* initialise attribute*/}
        virtual void findNextTimeStep(){}
};

class Vehicle: public SystemModel
{
 // ???? Implementation ?????
}

Vehicle is a specialization of SystemModel where p_eom points to VehicleEquationOfMotion.
I would like to initialise, an instance of VehicleEquationOfMotion and point to it p_eom in Vehicle. I want it to be defined only within the scope of Vehicle, and at the same time, not to use heap.
Is it even possible to reside VehicleEquationOfMotion object inside Vehicle without using the heap? (If not, please suggest where the design has gone wrong).
Might be helpful: I thought about the implementation in this question but ran into trouble (see the question).

A: If I got your question correctly, then do it like this:
  class FooChild : public FooParent
  {
  public:
      FooChild (int pX):m_BarChild(pX), FooParent(&m_BarChild) // point p_barPar to instance of BarChild (i.e. m_BarChild)
      {
      }
  private:
      BarChild m_BarChild; // instance of BarChild resided in the stack(not the heap) and is local to FooChild
  }

A: If you want to have FooParent.p_barPar to be pointing to a BarChild that resides inside FooChild, you might need to add a default ctor to FooParent and a method as follows as well: set_p_barPar(BarChild* new_p_bar){p_barPar = new_p_bar;}. So you get:
class FooParent
{
    public:
        BarParent* p_barPar;
        FooParent (){}
        FooParent (BarChild* new_p_bar)
        {
            p_barPar = new_p_bar;
            std::cout << p_barPar->x << std::endl;
        }
    protected:
        set_p_barPar(BarChild* new_p_bar)
        {
            p_barPar = new_p_bar;
        }
}

Then you can implement FooChild:
class FooChild : public FooParent
{
     public:
          FooChild(int new_x, BarChild* new_p_bar):_bar_child(new_x)
          {
               set_p_barPar(&_bar_child);
          }

     private:     //? Depends on your plans
         BarChild _bar_child();
}

A: Use a class template.
class EquationOfMotion { ... };

template <typename EOM>
class SystemDynamics
{
    EOM EquationOfMotion;
    ...
};

class VehicleEquationOfMotion : public EquationOfMotion { ... };

class Vehicle : public SystemDynamics<VehicleEquationOfMotion> { ... };

A: May be this is what you want. But the design is not safe. You are passing the pointer to a uninitialized object.
class Vehicle: public SystemModel
{
public:
    Vehicle(): SystemModel(&_vem)
    {

    }

    VehicleEquationOfMotion _vem;
}

However, it is safer to do the following:
class SystemModel
{
    public:
        EquationOfMotion* p_eom;
        // other atributes
        SystemModel()
        {
        }
};

class Vehicle: public SystemModel
{
   public:
   Vehicle(): SystemModel(&_vem)
   {
      p_eom = &_vem;
   }
   VehicleEquationOfMotion _vem;
};


text:
Q: 2 screens on 2 gpus - Xorg config Can I run 2 screens connected to separat gpus? they are both Nvidia quadro 410. i have the nvidia driver installed, and tried to configure it over nvidia-settings. I didn't work right. one screen is working, but the other one isn't. But i can move my mouse cursor to the other screen and see it there.
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    Screen      1  "Screen1" RightOf "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "LG Electronics E2422"
    HorizSync       30.0 - 83.0
    VertRefresh     56.0 - 75.0
    Option         "DPMS"
EndSection

Section "Monitor"
    Identifier     "Monitor1"
    VendorName     "Unknown"
    ModelName      "AcerMFMAV"
    HorizSync       30.0 - 83.0
    VertRefresh     50.0 - 75.0
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "Quadro 410"
    BusID          "PCI:5:0:0"
EndSection

Section "Device"
    Identifier     "Device1"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "Quadro 410"
    BusID          "PCI:4:0:0"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "metamodes" "nvidia-auto-select +0+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Section "Screen"
    Identifier     "Screen1"
    Device         "Device1"
    Monitor        "Monitor1"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "metamodes" "nvidia-auto-select +0+0 {AllowGSYNC=Off}"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

this is my xorg.conf
is it even possible to do, what I'm trying to do ?