text:
Q: Split up a binary image using their white boundaries in MATLAB I'm trying to read the values in this image into variables using OCR in MATLAB. I'm having trouble doing so, so I tried to split up this image into smaller parts using the white boundary lines then trying to read it, but I dont know how to do this. Any help would be appreciated, thanks.

A: If the blocks are always delimited by a completely vertical line, you can find where they are by comparing the original image (here transformed from RGB to grayscale to be a single plane) to a matrix that is made of repeats of the first row of the original image only.  Since the lines are vertical the intensity of the pixels in the first line will be the same throughout.  This generates a binary mask that can be used in conjunction with a quick thresholding to reject those lines that are all black pixels in every row.  Then invert this mask and use regionprops to locate the bounding box of each region.  Then you can pull these out and do what you like.
If the lines dividing the blocks of text are not always vertical or constant intensity throughout then there's a bit more work that needs to be done to locate the dividing lines, but nothing that's impossible.  Some example data would be good to have in that case, though.
img = imread('http://puu.sh/cU3Nj/b020b60f0b.png');

imshow(img);

imgGray = rgb2gray(img);
imgMatch = imgGray == repmat(imgGray(1,:), size(imgGray, 1), 1);
whiteLines = imgMatch & (imgGray > 0);
boxes = regionprops(~whiteLines, 'BoundingBox');

for k = 1:6
    subplot(3,2,k)
    boxHere = round(boxes(k).BoundingBox);
    imshow(img(boxHere(2):(boxHere(2)+boxHere(4)-1), boxHere(1):(boxHere(1)+boxHere(3)-1), :));
end

A: You can sum along the columns of a binary image corresponding to that input image and find peaks from the sum values. This is precisely achieved in the code here -
img = imread('http://puu.sh/cU3Nj/b020b60f0b.png');
BW = im2bw(img,0.1); %// convert to a binary image with a low threshold

peak_sum_max = 30; %// max of sum of cols to act as threshold to decide as peak
peaks_min_width = 10; %// min distance between peaks i.e. min width of each part

idx = find( sum(BW,1)>=peak_sum_max );
split_idx = [1 idx( [true diff(idx)>peaks_min_width ] )];
split_imgs = arrayfun(@(x) img(:,split_idx(x):split_idx(x+1)),...
                                             1:numel(split_idx)-1,'Uni',0);

%// Display split images
for iter = 1:numel(split_imgs)
    figure,imshow(split_imgs{iter})
end

Please note that the final output split_imgs is a cell array with each cell holding image data for each split image.

If you would like to have the split images directly without the need for messing with cell arrays, after you have split_idx, you can do this -
%// Get and display split images
for iter = 1:numel(split_idx)-1
    split_img = img(:,split_idx(iter):split_idx(iter+1));
    figure,imshow(split_img)
end

A: There is now a built-in ocr function in the Computer Vision System Toolbox.


text:
Q: curl and ie strange behavior when opening a web site I need to download a web page using curl or php-curl. However, when I use curl on my personal computer it works well. When I use curl on a remote server, it returns an empty web page. Also, when I open this page in IE in my own PC it shows the right content, but when I open it on a remote windows server, it just returns empty or something different to what I expect to see. Can someone tell me what could be the reason behind this?
Regards,
Alex

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC5: Open URL from Controller I know how to route a link to a controller, and I know how to open a URL from the view. But I don't know how to combine the two.
I would generally, keep the opening a URL logic inside the view, but I want to set some variables before I redirect, so I am looking for something that can open a URL from the controller. I want to set some session variables before redirecting to the URL.
So this is what I want:
@Html.ActionLink("Click Me!", "HandleClick", "Controller", null, null)

And in m controller:
public ActionResult HandleClick()
{
    // Set Session variables
    // Open a URL
}

How can I do that? Also, is there any other better way to do this?
Note that the URL here is not a route, it is an external host like http://www.google.com

A: You can use ajax.actionlink and javascript
@Ajax.ActionLink("Click Me!", "HandleClick", "Controller", new AjaxOptions() { OnSuccess = "mySucess" });

    <script>
        function mySuccess() {
            window.open('http://www.google.com/');
        }
    </scrip

A: The marked answer did not worked for me. This is how I made it:
in View:
@Ajax.ActionLink("Click Me!", "HandleClick", new { url = "www.google.com" }, null, new { @target = "_blank" })

Notes:

*

*new {id = 1}: It is just to demonstrate how to pass parameter to HandleClick if you have any parameter. You can use NULL, if there is no parameter to pass to your action

*new { @target = "_blank" }: Only specify if you want to open the link in new tab

in Controler:
public ActionResult HandleClick(string url)
{
    //TODO do any server-side operation
    return Redirect(url);
}

This will open a new tab and then redirects the new tab to the specified url.
No need to use JavaScript.


text:
Q: Best practice for securing web API endpoint This is a question about a best practice for securing a Web API endpoint.
Say, I am working for a bank that lets users use a mobile app. I am a developer working on the mobile app for that bank. The app gets OAuth access token and access a web API hosted by the bank. The app has been released.
A regular user who has a valid account in the bank installs the mobile app. Through the mobile app, the user can view the balance, transfer money, etc.
This user has a dev skill and noticed that he can get the access token after he signs in to the bank with his user name and password.
Because this user has a valid account for the bank, the access token is valid to call the API endpoints. The user does trial and error in his Visual Studio to figure out what requests need to be sent to get a valid response from the API. He can refresh access token as many times as needed with the official mobile app manually and eventually finds a way to make valid calls against the API from his dev tool.
Question is, are there any mechanisms that can be utilized to prevent the user from calling the endpoint without going through the official mobile app? The web API can be marked with [RequiredScope] attribute, for example, but if he was able to sign in, should he have all the permissions to do what the normal users are allowed to do, such as transferring money?
I have done searches on this topic on the web as it seems to be a common topic, but have not found references yet.

A: When developing a UI client you should always assume that the user can grab tokens from a mobile app or secure cookies from a web app, then replay them against the API. Both of which are just HTTP headers. This is easy for any semi-technical user to do with an HTTP proxy tool.
SCOPES
APIs should validate the JWT access token received on every request. Then use scopes to prevent access to invalid operations. Eg if an access token without a money_write scope was used to attempt that operation it would fail with a 403 error.
CLAIMS
The main protection is usually always done when the API's logic verifies claims received in the JWT access token. This ensures that the user can never elevate their own privileges. Consider the following example:
sub: hd80423r2f
tenant-id: 123
role: user
subscription-level: silver

If an API receives this, then it would typically apply code to deny access to resources for other users, roles, tenants or subscription levels. In these cases I most commonly return a 404 resource not found for user response.
HIGH PRIVILEGE OPERATIONS
Operations such as money transfer would usually be accompanied by strong authentication with multiple factors, and short lived access tokens. It is common to also involve user consent, perhaps to a particular payment transaction.
Sometimes you need dynamic authorization behavior in APIs, eg only allow a money transfer if strong authentication was used. In these cases claims are used rather than fixed scopes, and this might result in the following extra claims in the JWT access token:
authentication_strength: high
payment_transaction_id: 123

The API's code could then deny access unless runtime claims such as these were also present.
SUMMARY
You cannot authorize based on use of a mobile app, since APIs cannot distinguish between HTTP requests from mobile apps or sent manually. The main thing to ensure is that if a user grabs a token using tools, they can only access the exact same data that they see in their UI user session.

A: My Answer Context

The web API can be marked with [RequiredScope] attribute, for example, but if he was able to sign in, should he have all the permissions to do what the normal users are allowed to do, such as transferring money?

I will not try to reply to this question because the accepted answer already does an excellent job at it.
My reply will be in the context of helping you to understand how your API may be empowered to have a very high degree of confidence in what is doing the request, therefore more in the context of your other question:

Question is, are there any mechanisms that can be utilized to prevent the user from calling the endpoint without going through the official mobile app?

The Difference Between WHO and WHAT is Accessing the API Server
First, let's distinguish the difference between who is in the request vs what is making the request to your API, and in a series of articles that I wrote around API and Mobile security, I explain it in the article Why Does Your Mobile App Need An Api Key?, where you can read:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?

The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

So think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.
When you grasp this idea and it's ingrained in your mindset, then you will look into API security with another perspective and be able to see attack surfaces that you never though they existed before.
Defending the API

Question is, are there any mechanisms that can be utilized to prevent the user from calling the endpoint without going through the official mobile app?

Now that you understand the difference between who vs what is accessing your API server you may want to employ some mechanisms that can help you with making that distinction for each request handled by your API.
For Web Requests
You can learn some useful techniques to help your API backend to try to respond only to requests coming from what you expect, your genuine web app, and to do so I invite you to read my answer to the question Secure api data from calls out of the app, especially the section dedicated to Defending the API Server.
You can also use the fingerprintjs library to help you to have a more high degree of confidence that what is doing the request is indeed a genuine browser:

FingerprintJS is a browser fingerprinting library that queries browser attributes and computes a hashed visitor identifier from them. Unlike cookies and local storage, a fingerprint stays the same in incognito/private mode and even when browser data is purged.

For Mobile Apps
To identify with a very high degree of confidence that what is doing the request is indeed your genuine and unmodified mobile app I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Hardening and Shielding the Mobile App, Securing the API Server and A Possible Better Solution, where you will find that the Mobile App Attestation may be the best fit to give you such guarantees.
Do You Want To Go The Extra Mile?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For APIS
OWASP API Security Top 10

The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

For Mobile Apps
OWASP Mobile Security Project - Top 10 risks

The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.

OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

For Web Apps
The Web Security Testing Guide:

The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.


text:
Q: Log object not showing string value I am working in opencart. I am using log object for debugging.
i am quering my db to give me email against an id i get perfect result in my SQL DB when i run it.
but in my code em getting nothing when i print my variable.
here is my code
 $email=$this->db->query("SELECT email FROM `" . DB_PREFIX . "shipping_pools`
 WHERE geo_zone_id = '".$zone_id."'");
 $this->log->write($email);

here is an error i get in my log file
"PHP Unknown:  Object of class stdClass could not be converted to string in /home/ifarpart/public_html/dev/system/library/log.php on line 14"

A: The $email returns an array. You should use $email->row['email'] in order to get email as a string.


text:
Q: How Keep JVM Alive Until All Threads Are Completed? I have a tool running, and is invoked through a BAT file in Command Prompt. In the tool, the Quartz scheduler periodically invokes a method, which performs the logic.
As per current implementation, all this is done through a single thread, thus even if the CTRL+C is performed on the BAT file, the tool is not shutdown until the process completes.
But, after looking at the process, we came up with the idea of performing part of the process in a separate thread. Here, the main thread would create a new thread, which would go on to perform some time consuming operations, while the parent thread dies. And another flow might be started by the Quartz even before the child thread has ended.
Thus, at a time, there can be only one parent thread, which the Quartz creates, but there can be any number of child threads operating.
In the above scenario, if CTRL+C is performed, then the Quartz scheduler only waits for the parent thread to complete before shutting down, and all other threads are left incomplete.
I would really appreciate it if someone can tell me how can keep the tool running until all threads have completed.
Thanks in advance.
PS: I have tried attaching the newly created child threads as shutdown hooks, but it doesn't seem to solve my problem. Maybe I am doing it wrong, but it hasn't helped me as of yet.

A: The child threads should not be daemon threads (Thread.setDaemon(false)), so they will keep the JVM alive.
In case they are not daemon threads, you could wait for all of them to terminate:
- wait for one thread using Thread.join()
- wait for n threads by passing them the same CountDownLatch(n) instance; each child thread will do countDown() on it when finished its work; parent thread should do await() on it

A: How did you used ShutdownHook? (I have used this functionality for the same purpose and it was working fine for me)
have a look on this Link(Useful Example of ShutdownHook)
Here is the pseudo code. (its just for the basic understanding.. your actual implementation will be lot more complex than this)
public class MyClass implements Runnable
{
    public static void main(String[] args)
        {
        public static boolean isRunning = false;
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                while(isRunning)
                    Thread.sleep(100);
            }
        });
        Thread t= new Thread (new MyClass());
    }

    public void run(){
        isRunning = true;
        //Do your all work
        isRunning = false;
    }
}

And I will recommend to add ShutdownHook compare to other ways (e.g, Thread.join() or creating user thread etc.) As this will give you a proper control.
Also, through Shutdownhook, you can notify your worker thread to stop further processing (if required).
Hope this will help you.


text:
Q: Android barcode button - I can't handle event I bought this Android phone + barcode scanner. I am using Phonegap (Cordova) and I want to build an app for Android in HTML + Javascript. Unfortunately I can't detect the "scan" button press (in the center of the phone).
It works if I focus input and I will press the "scan" button. The scanner puts the barcode into the input, but like I wrote, I can't handle this event (keydown, keyup, click, past .... not working).
I need to detect this event because I want to focus to the input if the barcode scan button is pressed.


text:
Q: MATLAB Unable to Store Symbolic Function with Multiple Variables I'm trying to take the definite integral from -1 to 1 of a function with respect to x. The function has variables a, b, c, d, and x, all of which I've defined as syms variables. I'm trying to keep a, b, c, d in my final integral because I'll later be differentiating with respect to each one for an optimization problem. Here's the current code that I have:
syms f(x);
syms a b c d;
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c((sqrt(45/8))*(x^2-(1/3)))+d((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;
integral = int(f, x, [-1 1]);
disp(integral);

Similar code worked when I tried it using only variables x and y for a smaller function. However, when I try this code, I get:

Error using sym/subsindex (line 825) Invalid indexing or function
  definition. Indexing must follow MATLAB indexing. Function arguments
  must be symbolic variables, and function body must be sym expression.
Error in sym/subsref (line 870)
              R_tilde = builtin('subsref',L_tilde,Idx);
Error in HW11 (line 4)
  f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)x)-c((sqrt(45/8))(x^2-(1/3)))+d((sqrt(175/8))((x^3)-(3/5)(x))))^2;

I'm pretty new to symbolic functions and syms variables in MATLAB, why is MATLAB rejecting this code? The similar code that I tried that worked was:
syms f(x);
syms y;
f(x) = (x^2) + y;
integral = int(f, x, [0 3]);
disp(integral);

A: As mentioned in the comment by Adam, you probably forgot to add a multiplication operator * after the the c and d, so when you write c(...) and d(...) MATLAB treats these as indexing of an array but you cannot index arrays with symbolic variables or expressions. You need to change it to c*(...) and d*(...).
Replace:
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c((sqrt(45/8))*(x^2-(1/3)))+d((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;

With:
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c*((sqrt(45/8))*(x^2-(1/3)))+d*((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;


text:
Q: Averaging time after converting to Seconds I have a list of times it takes to review reports
I am averaging time by this method:
Multiply the individual times by 86400 to convert to seconds (example, 00:11:36*86400=696)
Then, divide the total number of seconds by the number of reports
This is where it gets mucky for me.
Lets say the total number of reports are 523.
The total number of seconds is 28855.13333.I divide the number of seconds by reports and get 55.17233907. Then, I divide that by 60 seconds and get 0.919538984.
Is this telling me its 92 seconds?
In another situation,
63 reports
6628 total seconds
6628/63 = 105.2063492
105.2063492/60 = 1.753439153
Now, I believe the decimal part of this result is a fraction of the seconds, so I multiply
0.753439153 * 60 = 45.20634918
So is my result 1 minutes and 45 seconds?
Any help is appreciated

A: Since the result of seconds/reports is in seconds (per report) already, there is no need to divide by 60. From your description, you want seconds so...don't do that.
However if you did divide by 60, your result would be interpreted as minutes: .91 minutes is 54.6seconds.


text:
Q: Taylor's remainder in a compact My impression is that each function enough regular ($C^\infty$ ) in a compact is equivalent to a polynomial.  Is this true?
Is there a way to prove it?
The expression of the Taylor's remainder just goes to 0 with the increasing expansion of the series. Is there a way to show that the remainder is actually 0 and independent from $x$?.


text:
Q: Issue with Xcode CLI tools I know Xcode is installed because (1) I can launch it and (2) App Store offers to update it and successfully does so.
But every time I launch it, it asks me to install the command-line tools with a GUI pop-up, and makes no complaint of error when I OK that.
And brew keeps saying xcode-select --install but if I try it it complains
xcode-select: error: no developer tools were found, and no install could be requested (perhaps no UI is present), please install manually from 'developer.apple.com'.

It does NOT offer the GUI pop-up mentioned in the answer to Installing Xcode Command Line Tools
Solution?


text:
Q: Calculate maximum difference of rolling interval of n columns I have a dataset
df
                         Time   Spot Ubalance
0   2017-01-01T00:00:00+01:00  20.96      NaN
1   2017-01-01T01:00:00+01:00  20.90    29.40
2   2017-01-01T02:00:00+01:00  18.13    24.73
3   2017-01-01T03:00:00+01:00  16.03    24.73
4   2017-01-01T04:00:00+01:00  16.43    27.89
5   2017-01-01T05:00:00+01:00  13.75    28.26
6   2017-01-01T06:00:00+01:00  11.10    30.43
7   2017-01-01T07:00:00+01:00  15.47    32.85
8   2017-01-01T08:00:00+01:00  16.88    33.91
9   2017-01-01T09:00:00+01:00  21.81    28.58
10  2017-01-01T10:00:00+01:00  26.24    28.58

I want to generate a series/dataframe in which I calculate the maximum difference between the highest and lowest value of the last n rows within multiple columns, i.e., the maximum difference of these "last" 10 rows would be
33.91 (highest is here in "ubalance") - 11.10 (lowest is in "Spot") = 22.81
I've tried .rolling() but it apparently does not contain a difference attribute.
Expected outcome:
                         Time   Spot Ubalance  Diff
0   2017-01-01T00:00:00+01:00  20.96      NaN  NaN
1   2017-01-01T01:00:00+01:00  20.90    29.40  NaN
2   2017-01-01T02:00:00+01:00  18.13    24.73  NaN
3   2017-01-01T03:00:00+01:00  16.03    24.73  NaN
4   2017-01-01T04:00:00+01:00  16.43    27.89  NaN
5   2017-01-01T05:00:00+01:00  13.75    28.26  NaN
6   2017-01-01T06:00:00+01:00  11.10    30.43  NaN
7   2017-01-01T07:00:00+01:00  15.47    32.85  NaN
8   2017-01-01T08:00:00+01:00  16.88    33.91  NaN
9   2017-01-01T09:00:00+01:00  21.81    28.58  NaN
10  2017-01-01T10:00:00+01:00  26.24    28.58  22.81

A: Use Rolling.aggregate and then subtract:
df1 = df['Spot'].rolling(10).agg(['min','max'])
print (df1)
     min    max
0    NaN    NaN
1    NaN    NaN
2    NaN    NaN
3    NaN    NaN
4    NaN    NaN
5    NaN    NaN
6    NaN    NaN
7    NaN    NaN
8    NaN    NaN
9   11.1  21.81
10  11.1  26.24

df['dif'] = df1['max'].sub(df1['min'])
print (df)
                         Time   Spot  Ubalance    dif
0   2017-01-01T00:00:00+01:00  20.96       NaN    NaN
1   2017-01-01T01:00:00+01:00  20.90     29.40    NaN
2   2017-01-01T02:00:00+01:00  18.13     24.73    NaN
3   2017-01-01T03:00:00+01:00  16.03     24.73    NaN
4   2017-01-01T04:00:00+01:00  16.43     27.89    NaN
5   2017-01-01T05:00:00+01:00  13.75     28.26    NaN
6   2017-01-01T06:00:00+01:00  11.10     30.43    NaN
7   2017-01-01T07:00:00+01:00  15.47     32.85    NaN
8   2017-01-01T08:00:00+01:00  16.88     33.91    NaN
9   2017-01-01T09:00:00+01:00  21.81     28.58  10.71
10  2017-01-01T10:00:00+01:00  26.24     28.58  15.14

Or custom function with lambda:
df['diff'] = df['Spot'].rolling(10).agg(lambda x: x.max() - x.min())

EDIT:
For processing all columns from list use:
cols = ['Spot','Ubalance']
N = 10

df['dif'] = (df[cols].stack(dropna=False)
                     .rolling(len(cols) * N)
                     .agg(lambda x: x.max() - x.min())
                     .groupby(level=0)
                     .max())

print (df)
                         Time   Spot  Ubalance    dif
0   2017-01-01T00:00:00+01:00  20.96       NaN    NaN
1   2017-01-01T01:00:00+01:00  20.90     29.40    NaN
2   2017-01-01T02:00:00+01:00  18.13     24.73    NaN
3   2017-01-01T03:00:00+01:00  16.03     24.73    NaN
4   2017-01-01T04:00:00+01:00  16.43     27.89    NaN
5   2017-01-01T05:00:00+01:00  13.75     28.26    NaN
6   2017-01-01T06:00:00+01:00  11.10     30.43    NaN
7   2017-01-01T07:00:00+01:00  15.47     32.85    NaN
8   2017-01-01T08:00:00+01:00  16.88     33.91    NaN
9   2017-01-01T09:00:00+01:00  21.81     28.58    NaN
10  2017-01-01T10:00:00+01:00  26.24     28.58  22.81

A: you could a rolling window like this:
n = 10
df.rolling(3).apply(func=lambda x: x.max() - x.min())

you can specify in the lambda function the column you want to do the rolling window


text:
Q: changing the alpha image backround of a button swift I need to set the alpha of the image background  of a button when pressed , I've searched online on the code for that but I haven't found something , How can I do it ? Thank you

A: I am not sure, but you can try for change button image or their alpha as per your requirement.


text:
Q: Pysmell install error with Textmate? I'm trying to install PySmell with Textmate -
I'm using TextMate on Mac OS, and to complicate things a bit, I'm using Brew and several virtual environments.  In my case, I'm just trying to install Pysmell in my default version of Python.
I've followed the instructions for the install - and can import pysmell through a python shell - so that looks like it works.  I've also generated a tags file for my project
However, If I try to invoke alt/escape within TextMate, I get this text generated right after my cursor point:
usage: pysmell [-h] [-v] [-x [package [package ...]]] [-o OUTPUT] [-i INPUT]
               [-t] [-d]
               package [package ...]
pysmell: error: no such option: -c

I'm thinking I have something setup wrong - anyone have any idea?
Thanks in advance!

A: Doh!
I accidentally created my TM_PYTHON link to pysmell and not python.  Working fine now...


text:
Q: Is there any way to capture exact line number where exception happened in python Hi is there any way to get the exact line number where the exception happen? because i am using a wrapper method and in actual method there are many lines of code and i am getting a very generic exception and not sure where exactly it is happening . Eg code as below,
import sys
def test(**kwargs):
    print (kwargs)
    abc

def wraper_test(**kwargs):
    try:
        test(**kwargs)
    except Exception as e:
        exception_type, exception_object, exception_traceback = sys.exc_info()
        print(exception_object.tfline_no)

wraper_test(hello="test", value="lsdf")

Now in the exception line number what i am getting is for test(**kwargs) and not the exact location where the exception is generated in this case "abc" which is inside the test method.
Is there any way to capture the exact line number in exception when we are using wrapper method ?

A: Try this: the traceback library allows you to get a longer stack trace with more line numbers (this shows the real error is on line 5).
import sys, traceback

def test(**kwargs):
    print (kwargs)
    abc

def wrapper_test(**kwargs):
    try:
        test(**kwargs)
    except Exception as e:
        exception_type, exception_object, exception_traceback = sys.exc_info()
        traceback.print_tb(exception_traceback, limit=2, file=sys.stdout)

wrapper_test(hello="test", value="lsdf")


text:
Q: jsrender populate selectbox multiple with already selected options I want to populate select box through Jsrender.
The code populate the select box correctly, But i am not able to select few value by default. I created a  Jsrender helper function for this, but i think the other values are not accessible inside the loop, so that's why the function is not working.
Here is the link to jsfiddle
My html is

and my javascript is
$.views.helpers({

        selected: function(needle,haystack) {
            console.log(haystack);
            if(typeof haystack === "undefined" || haystack === null) {
                return;
            }
            var count=haystack.length;
            for(var i=0;i<count;i++){
                if(haystack[i]===needle){return 'selected="selected"'; }
            }
            return;
        }
    });
var cates = [
        {'term_id' : 1, 'name' : 'category 1'},
        {'term_id' : 2, 'name' : 'category 2'},
        {'term_id' : 3, 'name' : 'category 3'},
        {'term_id' : 4, 'name' : 'category 4'},
        {'term_id' : 5, 'name' : 'category 5'},

    ];
    var selected = [{'term_id' : 3}, {'term_id' : 4}];
    $( ".select_placeholder" ).html(
        $( "#selectbox" ).render({cats : cates,selected:selected})
   );

A: Try to combine data for view https://jsfiddle.net/fksj52c6/5/
var cates = [
        {'term_id' : 1, 'name' : 'category 1'},
        {'term_id' : 2, 'name' : 'category 2'},
        {'term_id' : 3, 'name' : 'category 3'},
        {'term_id' : 4, 'name' : 'category 4'},
        {'term_id' : 5, 'name' : 'category 5'},

    ];
    var selected = [{'term_id' : 3}, {'term_id' : 4}];

  for(var i = 0; i< selected.length; i++) {
        for(var j = 0; j < cates.length; j++)
                if(selected[i].term_id === cats[j].term_id) {
            cats[j].selected = true;
        }
    }
$( ".select_placeholder" ).html(
               $( "#selectbox" ).render({cats : cates})
             );

html


text:
Q: Mac OS X Mountain Lion - DNS resolving uses wrong order on VPN via dial-up connection I am using a MacBook with Mac OS X 10.8.2 and connect to my company's network via VPN. Everything works great when establishing the VPN connection via LAN or WLAN. However, when I use a dial-up connection (Huawei HSDPA USB Stick) host names are not correctly resolved in applications (e.g. Web-Browser). Command line tools like host name will correctly resolve the IP address, ping name will not resolve.
Using scutil --dns I dumped the DNS configuration when connecting via WLAN vs. dial-up. There is a notable difference in the lookup order:
connecting using WLAN:

resolver #1
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 6 (ppp0)
  reach    : Reachable,Transient Connection
  order    : 100000

resolver #2
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 6 (ppp0)
  reach    : Reachable,Transient Connection
  order    : 200000

resolver #3
  domain   : local
  options  : mdns
  timeout  : 5
  order    : 300000

resolver #4
  domain   : 254.169.in-addr.arpa
  options  : mdns
  timeout  : 5
  order    : 300200

resolver #5
  domain   : 8.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300400

resolver #6
  domain   : 9.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300600

resolver #7
  domain   : a.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300800

resolver #8
  domain   : b.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 301000

DNS configuration (for scoped queries)

resolver #1
  nameserver[0] : 192.168.1.1
  if_index : 4 (en0)
  flags    : Scoped
  reach    : Reachable,Directly Reachable Address

resolver #2
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 6 (ppp0)
  flags    : Scoped
  reach    : Reachable,Transient Connection

The ppp0 connection is the VPN connection. As you can see, two servers are connected and they answer correctly on the command line and in applications.
Connecting via UMTS:

resolver #1
  nameserver[0] : 139.7.30.126
  nameserver[1] : 139.7.30.125
  if_index : 6 (ppp0)
  reach    : Reachable,Transient Connection
  order    : 100000

resolver #2
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 7 (ppp1)
  reach    : Reachable,Transient Connection
  order    : 100000

resolver #3
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 7 (ppp1)
  reach    : Reachable,Transient Connection
  order    : 200000

resolver #4
  domain   : local
  options  : mdns
  timeout  : 5
  order    : 300000

resolver #5
  domain   : 254.169.in-addr.arpa
  options  : mdns
  timeout  : 5
  order    : 300200

resolver #6
  domain   : 8.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300400

resolver #7
  domain   : 9.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300600

resolver #8
  domain   : a.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 300800

resolver #9
  domain   : b.e.f.ip6.arpa
  options  : mdns
  timeout  : 5
  order    : 301000

DNS configuration (for scoped queries)

resolver #1
  nameserver[0] : 192.168.80.10
  nameserver[1] : 192.168.80.24
  if_index : 7 (ppp1)
  flags    : Scoped
  reach    : Reachable,Transient Connection

resolver #2
  nameserver[0] : 139.7.30.126
  nameserver[1] : 139.7.30.125
  if_index : 6 (ppp0)
  flags    : Scoped
  reach    : Reachable,Transient Connection

This time, ppp1 is the VPN connection and ppp0 is the UMTS connection. From the response times of the commands (using the non-existing hostname foo.bar.local) I infer that ping uses the first resolver chain, where as host uses the scoped query configuration. ping takes 5 seconds to return "Unkown host", hostgets back immediately. I assume ping runs into the 5 second timeout of the mdns resolver.
In order to fix my problem with the broken DNS lookups when dialing in via VPN over modem I need to change the order of the resolvers. So far I have not found a way of doing this.
Any ideas welcome.

A: This is still happening in 10.13.0
I have opened a bug report with Apple. It's not normal that "ping internalhostname" works but "host internalhostname" or "nslookup internalhostname" fails with split tunnel VPNs (Cisco IPSec based or IKEv2).
Also, as some have noticed, Cisco IPsec connections as well as IKEv2 connections can not be prioritized with "Set service order" unlike L2TP/IPsec which can.
Another point I'd like to bring up is that split tunnel Cisco IPSec or IKEv2 VPNs do not show any DNS servers or Search Domains in their Advanced settings even though this information does show up with "scutil --dns". L2TP/IPsec VPNs does show this information just fine.
Something has to give and Apple needs to provide some explanation/fix.

A: I had the same issue for long time, but now I had time to find a solution that works for me. I didn't change the order of the DNS server, but I'm using the DNS server behind the VPN permanently.

*

*Connect via dial-up.

*Connect the VPN connection and copy the DNS server IPs and the search domain from
VPN Connection → Advanced → DNS.

*Disconnect the VPN connection.

*Ping <name> or <hostname> of your VPN server and write down the IP.

*Disconnect the dial-up connection.

*Duplicate the dial-up connection (e.g. name it "3G for VPN").

*Enter the IPs and the search domain into the DNS tab of the dial-up connection. They will be stored and used permanently.

*Connect via the new dial-up connection.

*Now you have no access to the nameservers (because they are secured by the VPN) - you have to edit the server address of the VPN connection. Replace the host by the IP.

*Connect via VPN connection and you should be able to use it.
Note: In general hostnames does not change, but IPs can. So if it's not working someday, do the steps again…

A: I found a workaround: your VPN DNS will still be ignored, and only 3G-dongle DNS will be used, but just adding your VPN DNS to the list under 3G interface does the trick… The main problem is that 3G connectivity manager overwrites configuration everytime you click connect, and you need connectivity manager to enable Radio on the 3G dongle… so I mixed both solutions in one:

*

*Connect to your VPN and write down your DNS (I have 2 on the list). You can check it in Network Preferences → Advanced → DNS tab. Disconnect VPN. You need to connect to VPN because DNS is assigned dynamically upon connection…

*Connect to your 3G and do the same: write the DNS on paper. Then disconnect 3G.

*Go to Network Preferences → click on 3G interface → Advanced → DNS Tab, and under DNS table (that typically will be empty as you are not connected) click on '+'. Add all the DNS servers (those from 3G first and then add VPN later). Click OK and Apply.

*From now on, to connect to 3G, just plug your USB and wait until you have 3G coverage (you will need to open 3G connectivity manager), but do not use the supplied connectivity manager to connect. And if it automatically connects, go to preferences and uncheck that tick. You need that manager only to turn radio on in the USB Dongle, nothing else.
If you click on "connect" on your 3G manager, it will overwrite configuration on your 3G interface and you need to repeat step 3 again.

*Go to Network → Preferences and click on the 3G interface. Then click connect. It will connect to your 3G using the configured DNS servers (instead of dynamically received), that include both the "public" DNS and your VPN DNS.

*Connect to your VPN. It will work as expected.
Just be aware that:

*

*If your VPN DNS changes, you need to change it manually. This can easily be checked under Network → VPN interface w Advanced → DNS tab since your VPN DNS is still assigned dynamically to the interface (although ignored by OS X).

*If your 3G DNS changes (unlikely) you need to change it manually too. If something goes wrong and you cannot navigate you need to go through your 3G connectivity manager, click "Connect" and see what DNS are dynamically assigned… That will require you to go back to step 3 and reconfigure it.

A: I had the same problem on my Mac, and after fixing it I have figured out that it was caused by FortiClient (VPN client). Even when FortiClient was disconnected - it's DNS still appeared in the scutil.
The solution for me was:
scutil
> list ".*DNS"

This will show you a list of all DNS configs, that will look something like:
subKey [0] = State:/Network/Global/DNS

subKey [1] = State:/Network/MulticastDNS

subKey [2] = State:/Network/OpenVPN/DNS

subKey [3] = State:/Network/OpenVPN/OldDNS

subKey [4] = State:/Network/PrivateDNS

subKey [5] = State:/Network/Service/forticlientsslvpn/DNS

To check each of them run: (until you find the problematic one)
> get key_name
> d.show

…and to fix it run:
> get key_name
> d.remove ServerAddresses
> set key_name

This is how it looked on my machine:
> get State:/Network/Service/forticlientsslvpn/DNS
> d.show
<dictionary> {
  ServerAddresses : <array> {
    0 : 192.168.30.6
    1 : 192.168.30.15
  }
  SupplementalMatchDomains : <array> {
    0 :
  }
  SupplementalMatchOrders : <array> {
    0 : 100000
  }
}
> d.remove ServerAddresses
> d.show
<dictionary> {
  SupplementalMatchDomains : <array> {
    0 :
  }
  SupplementalMatchOrders : <array> {
    0 : 100000
  }
}
> set State:/Network/Service/forticlientsslvpn/DNS
> exit

A: Try changing the order of the DNS entries in the Network preference pane:

*

*Open System Preferences → Network.

*Select your network service in the list on the left.

*Unlock the preference pane using the lock in the bottom-left corner.

*Click Advanced… and choose the DNS tab.

*Change the order of the DNS servers by dragging them up/down.

A: what you said gave me a hint, so I've added the dns ip in the vpn connection to the dns list in the main connection (nothing fancy, just using the graphical interface for Network preferences.) I'm not sure if what you are dealing with is different, but it worked with me.

A: Does not work in Lion / Mountain Lion, due to a bug which causes the local DNS Server beeing always used instead of the DNS server of the remote network even when Split DNS is correnctly setup in the VPN router.
However, if you use a Cisco ASA IPSEC router, you can force the remote DNS Servers to be used whenever you establish a VPN connection:
If using Cisco ASDM, go to
Configuration > Network (Client) Access > Group Policies > (your vpn group for OSX/iPhones) > Advanced > Split Tunneling
There set:
DNS Names (uncheck "inherit" and define the internal dns domain names, e.g. myoffice.local)
Send All DNS Lookups Throug Tunnel: Set to YES (This is the important setting)
Save it and don't forget to store in the flash for future use.
If you use the IOS command line, set:
group-policy <your-tunnel-group-name> attributes
 split-dns value myoffice.local
 split-tunnel-all-dns enable`

A: You can fix this by adjusting the service order of the network connections. Move VPN to the top of the list and the resolver order will follow.
http://support.apple.com/kb/PH14006

Content of link found at https://web.archive.org/web/20170828193724/https://support.apple.com/kb/PH14006?locale=en_US   and duplicated here:

OS X Mavericks: Change the priority of your network connections
This article has been archived and is no longer updated by Apple.
If you connect to the Internet or a network in several different ways (using Wi-Fi or Ethernet, for example), you can change the order of the network port configurations your computer tries when connecting to the Internet or network.
If there are multiple active network port configurations when you try to connect, OS X tries the one at the top of the list first, then tries the other port configurations in descending order.

*

*Choose Apple menu > System Preferences, then click Network.

*Choose Set Service Order from the Action pop-up menu. [The gear icon beside + - ]

*Drag a service, such as Ethernet, to the top of the list.

*Click OK, then click Apply to make the new settings active.

If you connect to the Internet using a virtual private network (VPN), and you selected "Send all traffic over VPN connection" in the advanced options pane of VPN preferences, you don't need to move the VPN service to the top of the list.
Published Date: Oct 20, 2015


text:
Q: Load hundreds of fonts dynamically using JS with low manual work I have a folder /assets/fonts with several hundred fonts I want to use on a website dynamically. User will specify which one to use. Kinda like in a text editor.
Specifying font-face for each and every font manually makes no sense, because it would take me hours.
What procedure should I take to make all the fonts ready to be used?

A:

$("select").on("change",function(){
   $("h1").css("font-family",$(this).find("option:selected").val());
});
@import url("https://fonts.googleapis.com/css?family=Tangerine");
@import url("https://fonts.googleapis.com/css?family=Inconsolata");
@import url("https://fonts.googleapis.com/css?family=Roboto");

<select>
 <option >select font</option>
 <option value="Tangerine">Tangerine</option>
 <option value="Inconsolata">Inconsolata</option>
 <option value="Roboto">Roboto</option>
</select>

google Font

used local Font in css

  @font-face {
      font-family: 'MyWebFont';
      src: url('webfont.eot'); /* IE9 Compat Modes */
      src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
           url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
           url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
           url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
           url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
    }


text:
Q: Python: how to groupby over two columns? I have a dataframe df that has information of job and age of people in cities
df
    User   City     Job             Age
0    A      x    Unemployed         33
1    B      x     Student           18
2    C      x    Unemployed         27
3    D      y  Data Scientist       28
4    E      y    Unemployed         45
5    F      y     Student           18

For each city I would like to compute the unemployment rate and the median of the age.
For the unemployment rate I did the following
## Count the people in each city
cust = insDataRed.groupby(['City'])['User'].count() ## Number of people for each city
cust = pd.DataFrame(cust)
cust.columns=['nCust']
cust['City']=cust.index
cust=cust.reset_index(drop=True)

## Count the people unemployed in each city
unempl = df[df['Job'] == 'Unemployed']
unempl = unempl.groupby(['City'])['Job'].count()
unempl = pd.DataFrame(unempl)
unempl.columns=['unempl']
unempl['City']=unempl.index
unempl=unempl.reset_index(drop=True)

# 1. Fraction of Unemployment
unRate = pd.merge(unempl, cust, on = 'City')
unRate['rate'] =(unRate['unempl']/unRate['nCust'])*100

Is there a more elegant solution? How can I compute the median value of the age for each city?

A: If you want to do it only by the City:
df.groupby(by='City').median()
If you want to group by both City and Job:
df.groupby(by=['City', 'Job']).median()
Get unemployment rate per city:
import pandas as pd

df = pd.DataFrame({
    'User': ['A', 'B', 'C', 'D', 'E', 'F'], 'City': ['x', 'x', 'x', 'y', 'y', 'y'],
    'Job': ['Unemployed', 'Student', 'Unemployed', 'Data Scientist', 'Unemployed', 'Student'],
    'Age':[33, 18, 27, 28, 45, 18],
})

df['count'] = 1
unmpl = df.groupby(by=['City', 'Job'])['count'].sum().reset_index()

unmpl_by_city = unmpl[unmpl['Job'] == 'Unemployed'].reset_index(drop=True)
count_by_city = df.groupby(by=['City'])['count'].sum().reset_index(drop=True)

frac_by_city = (unmpl_by_city['count'] * 100.0 /
                count_by_city)

unmpl_by_city['frac'] = frac_by_city
unmpl_by_city


text:
Q: how to initialize an array? I have a 3dimensional array, how do I initialize it to a default value without having 3 loops.
dummy[4][4][1024]

, how do I initialize all the elements to 12?

A: Come on guys - let's do it the simple way that always works:

for(int i = 0; i &lt 4; i++)
{
  for(int j = 0; j &lt 4; j++)
  {
    for(int k = 0; k &lt 1024; k++)
    {
      dummy[i][j][k] = 12;
    }
  }
}

A: The default initialization to all zeros is just that:
unsigned dummy[4][4][1024] = { 0 };

If you want to initialize particular elements (and all others to zero) do this
unsigned dummy[4][4][1024] = { { { 5 }, { 0, 4 } } };

and if your compiler knows C99 use designated initializers
unsigned dummy[4][4][1024] = { [3] = { [2] = { [0] = 7 }, [1] = { [2] = 3, [1] = 4 } } };

and if you really insist to use all 12, just repeat the 12 16384 times :)

A: Since the 3-d array is a contiguous block of memory, you can view it as a 1-d array
int i, *dummy2 = &dummy[0][0][0];
for(i = 0; i < 4*4*1024; ++i)
    dummy2[i] = 12;


text:
Q: How do I get the value of a hidden field using jQuery? I have the following generic code to get hidden fields. If the hidden GUID is null, I show an error.
 $.validator.addMethod("isNotEmptyGuidtest", function (value, element, params) {
            debugger;
            var val = $.trim($(params[0]).val())

            if (val.length > 0) {

                if (val == "00000000-0000-0000-0000-000000000000") {
                    if ($(element).hasClass("notRequired") && $.trim(value).length == 0)
                        return true;
                    else
                        return false;
                }
                else {
                    return true;
                }
            }

        }, $.format("Incorrect {1}"));

However, var val = $.trim($(params[0]).val()) is not always giving me hidden field value. I don't know why. Please guide me to get the correct value of hidden fields.

A: Remove ignore:hidden from your validations(If you have) then it will work for the hidden fields also


text:
Q: Network Simulator in fedora - tools/ranvar.cc:219:70: error: how to solve this error I'm trying to build and install NS-allinone 2.34 on Fedora 23.  During the build process I'm getting the following error:

tools/ranvar.cc: In member function 'virtual double GammaRandomVariable::value()':
  tools/ranvar.cc:219:70: error: cannot call constructor 'GammaRandomVariable::GammaRandomVariable' directly
  tools/ranvar.cc:219:70: error: for a function-style cast, remove the redundant '::GammaRandomVariable'
  make: *** [tools/ranvar.o] Error 1
  Ns make failed!

What do I need to do to resolve this?
ns2

A:
Simple : Your compiler g++-5.* is way too new to compile the old ns-2.34 code.
# dnf install compat-gcc-34-c++
Solution 1) $ cd ns-allinone-2.34/ && export CC=gcc34 CXX=g++34 && ./install

Solution 2) $ cd ns-allinone-2.34/ && patch -p0 < ns234_gcc49.patch && ./install Link, the patch : https://drive.google.com/file/d/0B7S255p3kFXNZDNyV1BPZHhEY0U/view?usp=sharing
( Not sure this one (2) is tested with Fedora 23.)

ns2


text:
Q: iOS Swift cannot set AWSSNSSubscribeInput.protocol parameter I am using Swift for iOS app development in Xcode 6.1.1.
I am trying to programatically subscribe the app to a AWS SNS topic. As I know, you need to set:
let subscriptionRequest = AWSSNSSubscribeInput()
subscriptionRequest.protocol = "application"
subscriptionRequest.topicArn = kMyTopicArn
subscriptionRequest.endpoint = endPointARN

But the problem here is the IDE keeps telling me that

subscriptionRequest.protocol = "application"

is not acceptable and it won't even build.

Really have no idea how to solve this. Could anyone help here? THANKS!

A: This has something to do with the reserved words in Swift. To escape, just simple wrap the word in ``, e.g.
subscriptionRequest.`protocol` = "application"

See this for more: Reserved Words In Swift and How to Escape Them


text:
Q: Datafactory to sharepoint list I've setup a connection from our data factory in azure to a sharepoint site so I can pull some of the lists on the site into blob storage so I can then process into our warehouse. This all works fine and I can see the data I want. I don't however want to pull all the columns contained in the list I'm after. Looking at the connection I can specify a query, however anything I put in here has no affect on the data that comes back. Is there a way to specify the columns from a list in sharepoint through the copy activity into blob storage?

A: You need to user select query like below -
$select=Title,Number,OrderDate in the Query text field of the Azure Data Factory Source.
You could use Preview Data button to validate the results.  Please refer to the documentation for using Custom OData query options.
I have tried this and it works fine for me (see screenshot below)-

Thanks
Saurabh


text:
Q: Windows Runtime methods cannot be generic - Reasons, Workarounds, Alternatives? Here is an Interface, taken from my attempt to port MemBus, an Event Aggregator I maintain, to the Windows runtime world:
public interface ISubscriber
{
    IDisposable Subscribe<M>(Action<M> subscription);

    #if WINRT
    [Windows.Foundation.Metadata.DefaultOverload]
    #endif
    IDisposable Subscribe(object subscriber);

    IObservable<M> Observe<M>();
}

What I am getting is a Compiler error:

"error WME1031: 'MemBus.ISubscriber.Subscribe<M>(System.Action<M>)' is a generic method.  Windows Runtime methods cannot be generic."

I have only suspicions as to why this is the case, if anybody can clarify, please do.
My main question is: How are we supposed to deal with this when porting code to the Windows runtime?
A lot of higher Level functionality happens with generics. In fact, we use generic classes in the Windows Runtime (e.g. List<T>). How is a RT component supposed to expose generic types, and if not, is the only alternative available to go back to the ways of writing .NET 1.1 code, i.e. object in, object out and do casts?

A: The short story is that JavasScript does not know how to handle generics, so a WinRT component cannot use them.  See WinRT reason for disallowing custom generic types or interfaces for a longer discussion.

A: You need to choose a Class Library template from the Windows Store templates (not the Windows Runtime Component template).

This will allow you to use the full C# language in a Windows Store app, but won't allow other languages like C++ and JS to consume the assembly (as they don't support generics in the same way that C# does).


text: Q: Looking for name of short story - boy who saves the earth from alien invasion A short story from the 60s or 70s (I think) - a boy who meets invading aliens and saves the earth by telling them about the powers of his idol, a television superhero (he belongs to a fan club).  Passes the infallible lie-detection of the aliens because he really believes in the hero. They leave fearing certain defeat.  Earth is saved, but no one knows how close they came to being conquered by aliens.


text:
Q: How to used position fixed without overlapping the width of container Here is the codepen. As you can see using position: sticky; the div width is not overlapping. However when I tried using position: fixed the div width is overlapping. Can anyone help me with how to achieve it? My goal is I what my footer class to fixed at the bottom even I scroll.

* {
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    font-size: inherit;
}

.left {
    position: fixed;
    top: 0;
    width: 43px;
    left: 0;
    bottom: 0;
    /* border-right: 1px solid #e8edf3; */
    background-color: red;
    padding: 6px;
    overflow: hidden;
    transition: .18s ease-out width;
}

.main {
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    left: 42px;
    right: 0;
    bottom: 0;
    overflow: auto;
    transition: .22s ease left;
    background: green;
}

.tool {
    display: flex;
    padding: 3px 4px;
    /* box-sizing: border-box; */
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: sticky;
    top: 0;
    background-color: #ffffff;
    z-index: 13;
    justify-content: space-between;
}

.footer {
    padding: 3px 4px;
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 13;
    display: flex;
    justify-content: space-between;
}

Test toolbar design

Test toolbar design

Test footer design

Test footer design

A: Change the footer width to width: calc(100% - 43px);. Where 43px is the value of the left property of its relative parent (.main).
.footer {
    width: calc(100% - 43px);
}
.left.expand ~ .main .footer {
    width: calc(100% - 320px);
}


text:
Q: $anchorScroll not functioning properly On the click of a button i want the page to scroll a particular div bottom.
The 1st time i click, the page is going to the very top and the initial url  http://localhost:8000 becomes http://localhost:8000/#/bottom(why is it not going to the div i mentioned).
The 2nd time i click the button, the url becomes
http://localhost:8000/#/bottom#bottom and it goes to the div bottom(which is what i want).
How do i deal with this ?
code snippet
$location.hash('bottom');
$anchorScroll();

Thanks in advance
Do ask for more explanation if required . . .

A: I don't know if you still need help, but have you checked this question?
Anyway, I also use one button to do a anchor scroll:
<button ng-click="app.gotoAnchor('destination')">GO!</button>
(...)

And I just used a combination of AngularJS documentation examples and the SO question I mentioned before, to make this function:
function gotoAnchor(anchor){
      if ($location.hash() !== newHash) {
        // set the $location.hash to `newHash` and
        // $anchorScroll will automatically scroll to it
        $timeout(function() {
          $location.hash(anchor);
        });
      } else {
        // call $anchorScroll() explicitly,
        // since $location.hash hasn't changed
        $anchorScroll();
      }
    }

Being the $timeout call the one that made this work better.
Hope this helps.

A:
BOTTOM

 this is boby

JOIN NOW!


text:
Q: How to detect current active page in Property sheet (C++/VS) I am using Visual Studio C++ 2010, and I need to detect current active page of Property Sheet. I expect there should be send some message to tell when user activated the Page. But I did not found that message and where to place it in dialog process.
In the program which I work with, there is this main dialog process:
INT_PTR CALLBACK MainDlgProc(HWND hSheet, UINT msg, WPARAM wParam, LPARAM lParam)
{
    INT_PTR ret = FALSE;

    switch (msg)
    {
    // bla bla
    case WM_COMMAND:
        ret = 0;    //processing message
        if (!Sheet_HandleCommand(hSheet, HIWORD(wParam), LOWORD(wParam), (HWND)lParam))
            CALLPROC();
        break;

    case WM_DESTROY:
        // bla bla
        return CALLPROC();
    default:
        return CALLPROC();
    }

    return ret;
}

I know how to get the handle but I don't know where to "install" it in the code. What's the name of the message to include it into the MainDlgProc?

A: Use PSM_GETTABCONTROL (or the PropSheet_GetTabControl macro) to get a handle to the tab control, and then use the TCM_GETCURSEL message (or the TabCtrl_GetCurSel macro) to query the currently selected tab index.
Note this is documented not to work if using the Aero wizard style (PSH_AEROWIZARD), presumably because there is no tab control in that case.


text:
Q: NSOperationQueue: a sequence of NSOperation's with dependencies VS (maxConcurrentOperationCount == 1)? For example I have 3 objects:
NSOperation *op1 = ...;
NSOperation *op2 = ...;
NSOperation *op3 = ...;

[op3 addDependency:op2];
[op2 addDependency:op1];

NSOperationQueue *queue = ...;
queue.maxConcurrentOperationCount = 1;
[queue addOperations:@[op1, op2, op3] waitUntilFinished:NO];

I could simply add all the operations in correct order. But for example if op2 is cancelled then I should also cancel op3 and I can't fully clear a queue in this case.
My questions:
1)Is it safe to combine such sequences of operations with maxConcurrentOperationCount == 1?
2)What will the program actually do if I swap around op1 and op2? (op2 should be performed after op1 but the queue is able to take only one from the operations simultaneously)
P.S. In my application I use AFHTTPRequestOperation. Its inheritance hierarchy:
AFHTTPRequestOperation -> AFURLConnectionOperation -> NSOperation
So I can't simply take other subclass of NSOperation.

A: To answer your questions:

*

*It's safe to combine this particular sequence of operations with the dependencies you have given with maxConcurrentOperations = 1.

*The queue will run op2, op3 and op1 or op2, op1, op3 if you reverse the dependency order of op1 and op2.

Theres nothing tricky in the dependency chain you've specified and NSOperationQueue can take care of things automatically.  You can only really get into trouble if you specify a circular dependency (e.g op3 depends on op1), or you have an operation that isn't added to the queue, and so can't get executed to satisfy a dependency.
Apple has this to say about cancellation in the NSOperationQueue class reference:

Canceling an operation causes the operation to ignore any dependencies it may have. This behavior makes it possible for the queue to execute the operation's start method as soon as possible. The start method, in turn, moves the operation to the finished state so that it can be removed from the queue.

All NSOperation subclasses should handle cancellation correctly by first checking to see if it has been cancelled and then immediately finish the operation without performing any actions.  If this isn't done then it's a bug, and operations may execute even though they have been cancelled.
(Interestingly this also applies for NSBlockOperation, which I didn't realise.  You explicitly need to check self.isCancelled in the block).
I used CodeRunner on the App Store to try this all out and modified your program slightly.  It's reproduced below.
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op1"); }];
        NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op2"); }];
        NSOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op3"); }];

        [op3 addDependency:op2];
        [op2 addDependency:op1];

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        queue.maxConcurrentOperationCount = 1;

        [queue addOperations:@[op1, op2, op3] waitUntilFinished:YES];
    }
}

For a NSBlockOperation to refer to itself you need to do this, which is a bit disgusting but looks better in a NSOperation subclass as you can refer to self.
__block NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op1 cancelled=%d", op1.cancelled); }];


text:
Q: Matplotlib LaTeX text rendering exclusively for axis labels Using Matplotlib, how can I apply LaTeX text rendering exclusively for axis labels, while tick labels and other texts are not affected and rendered as usual? Or, is there a way to use different font families for axis and tick labels?
Edit:
Thanks to commenters, I found following code works
# code A
import matplotlib.pyplot as plt
_, ax = plt.subplots()
ax.plot(range(5))
ax.set_xlabel('$x$', usetex=True)
plt.show()

to produce a figure like this which is the one desired. But I have a trouble with following code that affects the tick rendering too as in this example.
# code B
import matplotlib.pyplot as plt
plt.rcParams.update({'text.usetex': True, })
_, ax = plt.subplots()
ax.plot(range(5))
ax.set_xlabel('$x$', usetex=True)
plt.show()

I want to configure my custom style sheet such that it produces results like the code A's. But I can't find an option that applies the LaTeX rendering exclusively for axis labels (an option text.usetex: True works identically to the code B).


text:
Q: CSRF error on djangorestfull while ajaxing for /api-auth/login I'm in server side of web project that use djangorestfull. Our UI team runs UI with gulp on port 3000 and Django server runs on port 8000. For login we use /api-auth/login url for ajax. Answer of option method from /api-auth/login contains csrftoken and a form but post method (that contains username and password) faces with CSRF error. How can I check the source of this problem? Is it in server side or the token won't send with post method?
Here is my setting.py:
REQUIRED_APPS = [
    'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'rest_framework',
]

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ]
}

and urls.py:
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('User.urls', namespace='User')),
    url(r'^schedule/', include('Schedule.urls', namespace='Schedule')),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

A: The problem seems to come from the UI team. Chances are high they are not including the CSRF token in the POST request. Kindly confirm that. Here are some docs from Django on how to add the token. https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax


text:
Q: Unconditionally fail unit test Is there a shorthand in jasmine equivalent to:
expect(true).toBe(false)
So the unit test can fail whenever it reaches this?

A: I throw errors. I usually do this when I have created new test functions that are not implemented yet.
it('should test something when I have implemented it', function() {
    throw new Error('Not implemented yet');
});

This lets you use any explanation you want.


text:
Q: Can I detect Facetime screen shots? Can I somehow know if the other caller is taking a photo (screenshot) while we are on FaceTime? I need to know if they are secretly taking photos of me.

A: No, there's no way to tell...unless, of course, they have their volume cranked and you can hear the camera shutter sound.

A: Yes, if you hold the volume down button and home button at same time and hold during FaceTime it will tell you if someone if taking a screenshot of you.
edit: sorry, this is wrong. -owlswipe

A: You can detect if somebody screenshots you during Facetime.


text:
Q: What is a relationship between System class and PrintStream Class I'm trying to know what exactly System.out.println(). I read these two articles
What is System, out, println in System.out.println() in Java and What's the meaning of System.out.println in Java?. I know what is System,out,and print, But i don't know how System class can connect to PrintStream class. How they are related to each other?
System is a class in the java.lang package.out is a static member of the System class, So how its becomes an instance of java.io.PrintStream ?How System and PrintStream are related to each other ?

A: The relation between System class and PrintStream class is HAS-A relation.
Here System class HAS-A PrintStream class.
To understand the relation understand the program.
class A
{
    void display()
    {
        System.out.pritln("this is display method");
    }

}

class B

{
    static A ob=new A();
}

class demo
{
    public static void main()
    {
    B.ob.display();
    }
}

It prints this is display method.
B.ob.display() is just like System.out.println().
A object is created in B class.
PrintStream class object is created in System class.
ob is static object reference of A class.
out also static reference of PrintStream class.

A: System class has static object of PrintStream class which is declared in System class as out and the println() is the method of PrintStream class.
So we can access static object as System.out and the println() is the method of PrintStream class. That's why we can write System.out.println() and how both classes are related.


text:
Q: Can I dynamically create subdomains (PHP, .htaccess) with GoDaddy Hosting? I am trying to use a combination of .htaccess and PHP to create subdomains on-the-fly on my GoDaddy Hosting account. I've run into a problem of trying to modify the zone using the wildcard asterisk. I am not at all familiar with how this works and have only found the zone stuff about the domain by exploring the domain manager extensively. I'm not sure I know what I'm doing. I'm slightly more acquainted with .htaccess, although it's still a big challenge for me to write RegEx.
I've researched another tutorial that will use .htaccess to reroute a subdomain to a folder in the root of my domain (e.g. sub.domain.com to domain.com/sub). Here's my code:
#Grab the subdomain from the domain
RewriteCond %{HTTP_HOST} ^([^.]+).MY-DOMAIN.com$
#Make sure the subdomain is not www or example
RewriteCond %{1} !^(www)$
#Check if the directory actually exists before we go there
RewriteCond /home/content/X/Y/Z/XYZ-MY-GODADDY-ACCT/html/%1 -d
#This stops it from looping
RewriteCond %{REQUEST_FILENAME} !^/home/content/X/Y/Z/XYZ-MY-GODADDY-ACCT/html/
#Finally, this is the actual rewrite
RewriteRule (.*) /home/content/X/Y/Z/XYZ-MY-GODADDY-ACCT/html/%1 [L]

As of right now, I've done the following:

*

*Logged into GoDaddy Domain Manager.

*Went to Tools > DNS Manager.

*Opened the Zone File Editor for my domain.

*Added an A (Host) Record with Host Name * and in Points to IP Address I copied the value from the @ entry's IP address, since that should be the same as my domain...?

*Now, after waiting until the nameservers or whatever updated and propogated and stuff, I get a 403 error when I try to access a subdomain.

Any suggestions?

A: DNS is only 1 part of the configuration. You need to have a ServerAlias for *.mydomain.com in the configuration for the virtual host in Apache, otherwise Apache will not have any idea where to route requests for *.mydomain.com - which means the .htaccess never has a chance to work at all.
If GoDaddy provides a way to manually edit your virtual hosts' directives, or at least the ability to add server aliases through their GUI, then it's easy enough. If you can't find it, you should contact GoDaddy for information.

A: I was advised to move my answer from here to this question:
While not the same as being able to create a new vhost entry for each subdomain dynamically added, you should be able to set this up using a Wildcard DNS record and adding a dedicated IP to your hosting account. You can add a dedicated IP to your hosting account using this method:

*

*Click Web Hosting.

*Click Options, and then click Customize tab.

*From the Server IP menu, select Dedicated.

*If you already purchased a dedicated IP address credit, click Apply Dedicated IP Credit. OR If you need a dedicated IP address credit, click Checkout, and then complete your purchase.

NOTE: Dedicated IPs can take 24 hours to become active on your hosting account.
You can setup *.yourdomain.com to use the dedicated IP of your shared hosting account in our DNS Manager.

*

*Go to the Zone File Editor for the domain name you want to update.

*Click Add New Record. The Add DNS Record window displays.

*From the Record type list, select A (Host).

*Complete the following fields: Host Name — Enter * Points to IP Address — Enter the Dedicated IP address of your hosting account. TTL — Select how long the server should cache the information.

*Click OK.

*Click Save Zone File, and then click OK. The new A record displays in the A (Host) section.

A: I just got off the phone with GoDaddy tech support, and was given a brilliant solution that doesn't require using mod_rewrite or upgrading to a dedicated server.
From your account login at https://gateway.godaddy.com select Hosting from the dropdown and then on the page that opens, select Settings. In the modal window that opens, click the Change Domain button and enter in a dummy domain (note the dummy domain does not need to be registered or entered in DNS. This will then change your default domain to the dummy domain which will reside in the public_html folder.
After you have done that, go to the cPanel and choose Addon Domains from the green menu bar at the top. Enter a new domain and type the name of your registered domain, then specify the document root (DocRoot). The path can be a directory location completely outside of the public_html folder so you can create a Laravel friendly path such as webroot/mydomain.com/public and install Laravel in webroot/mydomain.com.
Likewise, you can specify similar paths for subdomains.
Hope this helps everyone looking at this.


text:
Q: How to write "conditional one" in Latex I want to write a "conditional one" in Latex but I don't know the precise name. It is a one with a double vertical dash that is equal to 1 if a condition is satisfied and 0 otherwise (a kind of Kronecker delta).
Could someone tell what is the name of this symbol and how to write it in Latex ?


text:
Q: An ordered basis for a finite-dimensional $F$-vector space $V$ establishes a bijection between $V$ and $F^n$.
To summarize, each ordered basis of $V$ determines a one-one correspondence $\alpha \to (x_1,…,x_n)$ between the set of all vectors in $V$ and the set of all $n$-tuples in $F^n$.

Question: How to prove bijective map between $V$ and $F^n$ explicitly?
My attempt: $(V,F,+,\cdot)$ is finite dimensional vector space. Let $B=\{\alpha_1,…,\alpha_n\}$ be an ordered basis of $V$. $B=\{\alpha_1,…,\alpha_n\}$ is basis of $V$$\iff$$\forall \alpha \in V$, $\exists !x_\alpha =(x_{\alpha ,1},…,x_{\alpha ,n})\in F^n$ such that $\sum_{i\in J_n} x_{\alpha ,i}\cdot \alpha_i=\alpha$. So $f:V\to F^{n}$ defined by $f(\alpha)=x_\alpha = (x_{\alpha ,1},…,x_{\alpha ,n})$ is a well-defined map, i.e. $\forall \alpha \in V$, $\exists !x_\alpha \in F^n$ such that $f(\alpha)=x_\alpha$. Claim: $f$ is invertible, i.e. $\exists g:F^n \to V$ such that $g\circ f=\text{id}_V$ and $f\circ g=\text{id}_{F^n}$. Proof: We define $g:F^n \to V$ such that $g(y)=\sum_{i\in J_n}y_i \cdot \alpha_i$. Let $\alpha \in V$. Then $g\circ f(\alpha)=g(f(\alpha))=g(x_\alpha)$$= \sum_{i\in J_n} x_{\alpha ,i}\cdot \alpha_i=\alpha$. Thus $g\circ f=\text{id}_V$. Let $y=(y_1,…,y_n)\in F^{n}$. Then $f\circ g(y) =f(g(y))=f(\sum_{i\in J_n}y_i \cdot \alpha_i)$. Let $\sum_{i\in J_n}y_i \cdot \alpha_i =\beta \in V$. Since $\exists !x_\beta =(x_{\beta ,1},…,x_{\beta ,n})$ such that $\sum_{i\in J_n} x_{\beta ,i} \cdot \alpha_i =\beta$, we have $y=(y_1,…,y_n)=(x_{\beta ,1},…,x_{\beta ,n})=x_\beta$. So $f\circ g(y)=f(\sum_{i\in J_n}y_i \cdot \alpha_i)=f(\beta)=x_\beta=y$. Thus $f\circ g=\text{id}_{F^n}$. Hence $f$ is invertible, or, equivalently, bijective. Is my proof correct?

A: Your proof is overall correct. However, you can enhance it by

*

*From the form standpoint, separate topics in lines with headers. As currently written, it is hard to read.

*From the substance, you're missing the point that $f$ is in fact a linear map as $\mathbb F^n$ is a linear space. From this, you can study bijectivity by looking at the kernel as we're dealing with finite-dimensional linear spaces.

A: Alternative : You can put your whole argument in the form :
$\dim(V) =n$ and let $\mathcal{B}=\{v_1,v_2,\ldots ,v_n\}$ basis for $V$.
$v\in V$ implies $v=\sum_{i=1}^{n} x_{v,i}v_i$ where $x_{v,i}\in F$
Now define a map $f:V\to F^n$ by
$f(v) =(x_{v,1},x_{v,2}, \ldots ,x_{v,n})$
• Then $f$ is linear as for all $ v, u\in V$ and $\lambda\in F$ $\begin{align}f(v+\lambda u) &=(x_{v,1}+\lambda x_{u,1},x_{v,2}+\lambda x_{u,2}, \ldots +x_{v,n}+\lambda x_{u,n)}\\&=f(v)+\lambda f(u) \end{align}$
• $f$ is injective.
$\ker(f) =\{v\in V : f(v) =(0,0,\ldots, 0)\}$
Let $v\in \ker(f)$. Then $f(v) = (x_{v,1},x_{v,2}, \ldots ,x_{v,n}) =(0,0,\ldots ,0)$
Which implies $x_{v,i}=0 , \forall 1\le i\le n$. Thus $v=\sum_{i=1}^n x_{v,i}v_i=0$.
Hence $\ker(f) =\{\textbf{0}\}$
•$f$ is onto.
Since $f$ is a linear map between two same dimensional vector spaces, $f$ is injective iff $f$ is onto iff $f$ is bijective (consequence of Rank-nullity theorem)
Hence $f$ is an invertible linear map i.e an isomorphism.

Note: If you are not familiar with $\ker$ of a linear map,proof injectivity and surjectivity as the same way we do for any map between two sets.
•Injective
$f(v) =f(u) $ implies $(x_{v,1},x_{v,2}, \ldots ,x_{v,n})=(x_{u,1},x_{u,2}, \ldots ,x_{u,n})$
Then $x_{v,i}=x_{u,i}$ for all $1\le i\le n$.Hence $v=u$
•Surjective:
Given any $(x_1, x_2, \ldots, x_n) $ , consider $v=\sum_{i=1}^{n} x_i v_i$ . Then $f(v) =(x_1, x_2, \ldots, x_n) $ .

A: We can use this result to prove $V$ is isomorphic to $F^n$. Which is precisely theorem 10 section 3.3. Proof: By theorem 7 section 3.2, it is suffice to show, either $f$ or $g$ is a linear map. I will show both $f$ and $g$ are linear map. Let $c\in F$ and $\alpha, \beta\in V$. Then $\exists !x_\alpha =(x_{\alpha ,1},…,x_{\alpha ,n})\in F^n$ such that $\sum_{i\in J_n} x_{\alpha ,i}\cdot \alpha_i=\alpha$ and $\exists !x_\beta =(x_{\beta ,1},…,x_{\beta ,n})\in F^n$ such that $\sum_{i\in J_n} x_{\beta ,i}\cdot \alpha_i=\beta$. So $c\cdot \alpha +\beta$ $=c\cdot (\sum_{i\in J_n} x_{\alpha ,i} \cdot \alpha_i)$ $+ \sum_{i\in J_n} x_{\beta ,i}\cdot \alpha_i$. By distributive axiom of vector space, $c\cdot (\sum_{i\in J_n} x_{\alpha ,i} \cdot \alpha_i)$ $+ \sum_{i\in J_n} x_{\beta ,i}\cdot \alpha_i$ $= \sum_{i\in J_n} (c\cdot x_{\alpha ,i}+x_{\beta ,i})\cdot \alpha_i$. By uniqueness, $c \cdot x_{\alpha ,i}+x_{\beta ,i}=x_{c\cdot \alpha+\beta, i}$, $\forall i\in J_n$. Thus $f(c\cdot \alpha +\beta)=x_{c\cdot \alpha +\beta}$ $=(c\cdot x_{\alpha ,1}+x_{\beta ,1},…, c\cdot x_{\alpha ,n}+x_{\beta ,n})$ $=c\cdot f(\alpha)+f(\beta)$. Hence $f$ is a linear map. Let $c\in F$ and $x,y\in F^n$. Then $x=(x_1,…,x_n)$ and $y=(y_1,…,y_n)$. So $c\cdot x+y$ $=(c\cdot x_1+y_1,…,c\cdot x_n+y_n)$. So $g(c\cdot x+y)$ $= \sum_{i\in J_n} (c\cdot x_{i} +y_{i})\cdot \alpha_i$. By distributive axiom of vector space, $\sum_{i\in J_n} (c\cdot x_{i} +y_{i})\cdot \alpha_i$ $=c\cdot (\sum_{i\in J_n} x_{i}\cdot \alpha_i)$ $+ \sum_{i\in J_n} y_{i}\cdot \alpha_i$ $= c\cdot g(x)+g(y)$. Thus $g(c\cdot x+y)= c\cdot g(x)+g(y)$. Hence $g$ is a linear map.


text:
Q: Nested fragment and back stack I have a fragment in which there is a nested fragment which I add in this way:
            if (home == null) {
                home = new MyFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.addToBackStack(MyFragment.class.getName());
                transaction.add(R.id.child_fragment, home).commit();
            }

When I enter another fragment and go back the child fragment from above is not there. I checked and the instance is different from null.
UPDATE: I changed the code as suggested by Ashwin S Ashok but it's still not working.

A: Try using these methods:
// Use this if you don't want to retain the fragment.
protected void replaceFragmentStack(int container, Fragment fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(container, fragment);
    fragmentTransaction.commit();
}

// Use this if you want to add the fragments in a stack.
protected void addFragmentStack(int container, Fragment fragment, String tag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fragmentTransaction.add(container, fragment, tag);
    fragmentTransaction.addToBackStack(tag);
    fragmentTransaction.commit();
}

A: I would suggest you to use getChildFragmentManager() when making transactions inside a fragment. And its a bug i guess.
You can check out this thread it will help you alot Android 4.2: back stack behaviour with nested fragments
Also you need to go through The Curious Techizen's blog
Here is the link for the github project sample for same mechanism
I hope this will help you.


text:
Q: How are the parameters passed in this function? Doing a text book exercise where:
let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween(a, b) {
  return function(x) {
    return x >= a && x <= b;
  };
}

alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

The textbook also states that the filter syntax to be:
let results = arr.filter(function(item, index, array) {
  // should return true if the item passes the filter
});

So I'm not completely understanding how the inBetween(a,b) function works... like in this line:
arr.filter(inBetween(3,6))

It seems to me like a is the item parameter, b is in the index parameter, but obviously that's not how it's working... Can someone break down this syntax and why it's working?

A: So the filter method accepts a function that should return true or false, whether to keep the item or not.
In this example, instead of writing that function inside the filter, it's written outside and passed in. However you can still think about it like this:
let results = arr.filter(function(item, index, array) {
    return item >= 3 && item <= 6;
});

The reason you would define inBetween outside the filter is so you can pass in values instead of hard coding them into the filter like above.
When you call inBetween(3,6) returned is :
function(x) {
    return x >= 3 && x <= 6;
}

Like above that's then put into the filter (just without the index/array parameter since they are not needed:
let results = arr.filter(function(x) {
    return x >= 3 && x <= 6;
});

A: a and b, 3, 6 are defined in the scope of inBetween and referenced within the returned anonymous function which is the callback of .filter(), as indicated by 4castle, x is item at the callback function


text:
Q: how to acess nested STDClasses with the string path in php? Imagine you have a variable $a which is Stdclass with nested Stdclasses and so on, like the following:
<?php
$json = '{ "foo": {
    "foo":{
            "foo":"bar"
    }
} }';
$a = json_decode($json);
$b="foo.foo.foo";

print_r($a->foo->foo->foo);
print_r($$b});

?>

Now in the variable $b I have the path that I want to access.
Is there a way to tell PHP to get the value for that path?

A: Explode on dot, then iterate, using each segment as an object property.
$path = explode('.', $b);

$current = $a;
foreach ($path as $segment) {
    $current = $current->$segment;
}

var_dump($current);   // bar

If the path contains segments that don't map properly to the object properties, you'll get undefined property notices and end up with a null value.
Note that this will only work for nested objects. If your input JSON includes arrays at any level this can't handle it, and you'll need something a bit more complex.


text:
Q: Definition of cotan function
Possible Duplicate:
Define additional math operators to be typeset in roman

Is the cotan function defined somewhere? I cannot find it. It is defined as cotan(x)=cos(x)/sin(x). Should it be \newcommand{\cotan}{\mathrm{cotan}}? I'm suspecting somewhere a declareoperator command or something.

A: Check the amsopn.sty file.
and define the the tag
\def\cotan{\qopname\relax o{cotan}}


text:
Q: Difference btw PERFORM_PLAYBACK_IN_INTERACTIVE_MODE and INTERACTIVE options in RFT IOptionName interface provides these 2 fields, what is the difference?

A: Both are essentially the same but they correspond to the two different places from where user can set  the interactive mode.
One place where we could set the Interative mode is in the
Window->Preferences->FunctionalTest->Playback   .
The flag : IOptionName.PERFORM_PLAYBACK_IN_INTERACTIVE_MODE  is for this preference.
The second place to set the Interactive mode is the Specify Playback Options" page which comes when after clicking Play/Run button for a script if we click "Next" in the Select Log page.
The flag: IOptionName.INTERACTIVE    is for this preference.
We can Test both these flags  (by checking/unchecking the checkboxes  in the two places mentioned above) and playing back a script that has following code:
 System.out.println(OptionManager.getBoolean(IOptionName.PERFORM_PLAYBACK_IN_INTERACTIVE_MODE));
 System.out.println(OptionManager.getBoolean(IOptionName.INTERACTIVE));


text:
Q: Return Group From Regex, not the whole line
Possible Duplicate:
Regex matching too much

Test String:
[TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]

The general format of this string comes in 3 groups:

*

*group1 => "[TA:" + 1 or 0  repeated + "]"

*group2 => "[FN:" + A-Z or a-z + "]"

*group3 => "[IP:" + (.*) + "]"

I have tried many variations of a regex and can either get the whole test string to return or nothing... I can figure out how to actually segment it and return just substrings.
Attempted Patterns including but certainly not limited to:

*

*@"^.*$"

*@"^[.*].*$"

*@"^(\[.*\])(.*)$"

*@"^(\[.*\])(\[.*\])(\[.*\])$"

*@"^(\[TA{[10],}\])(\[.*\])(\[.*\])$"
... etc.

calling code:
BindingList<Tuple<bool[], IFactory>> Recipe = new BindingList<Tuple<bool[], IFactory>>();

var amp = new Factory.AmplifySignal();
amp.Destination = "DestTest";
amp.Source = "Sourcetest";
amp.Factor = 1.5;
bool[] Ts = new bool[] { true, false, true, false, true, false, false };

var CI = new CompactInstruction(Ts, amp.GetFactoryKey(), amp.GetProperties());

string TestString = CI.ToString();
Console.WriteLine(TestString);

string pattern = @"^(\[.*\])?"; //Have been adjusting in debug mode
while (true)
{
    try
    {
        Match Result = Regex.Match(TestString, pattern, RegexOptions.IgnoreCase);
        if (Result.Success)
        {
            for (int i = 0; i < Result.Groups.Count; i++)
            {
                Console.WriteLine("G{0} - \r\n\t{1}", i, Result.Groups[i]);
            }
        }
    }
    catch { }
}

A: test

[TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]

pattern

string pattern = @"^(\[.*?\])?(\[.*?\])?(\[.*?\])?$";

Output:

G0 -
    [TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]
G1 -
    [TA:1010100]
G2 -
    [FN:AmplifySignal]
G3 -
    [IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]


text:
Q: VideoDeviceController: ExposureControl vs. Exposure. Which is better? Info of the VideoDeviceController class' available properties can be found here: https://learn.microsoft.com/en-us/uwp/api/windows.media.devices.videodevicecontroller
I'm confused about the distinction between ExposureControl and Exposure within the VideoDeviceController class. They seem quite similar. Why would Microsoft provide both? Are there pros for one over the other?
"Gets the exposure control for this video device," represented below:
private MediaCapture _mediaCapture;
var exposureControl = _mediaCapture.VideoDeviceController.ExposureControl;

exposureControl.Auto
exposureControl.Min
exposureControl.Max
exposureControl.Supported

Source: https://learn.microsoft.com/en-us/uwp/api/windows.media.devices.exposurecontrol
"Gets a MediaDeviceControl object that can be used to get or set the camera's exposure time," represented below:
private MediaCapture _mediaCapture;
var otherExposureControl = _mediaCapture.VideoDeviceController.Exposure;

otherExposureControl.capabilities.auto;
otherExposureControl.capabilities.min;
otherExposureControl.capabilities.max;
otherExposureControl.capabilities.supported;

Sources: https://learn.microsoft.com/en-us/uwp/api/windows.media.devices.mediadevicecontrol
And https://learn.microsoft.com/en-us/uwp/api/windows.media.devices.mediadevicecontrolcapabilities

A:
The ExposureControl gives apps additional control over the exposure settings on a device.

This is the line which gives you your answer, it is written in the Expore Control docs -> remarks. Read that and you will see how ExporeControl is the better way to do this.
Also exposureControl deals with capturing device which can be any attached capturing device to your Windows 10 device, while exposure only deals with built in camera of device as per the docs first line of each.


text:
Q: What types can Doctrines2's bindValue take? I have a hard time navigating through Doctrine's Documentation for the DBAL. I would like to know what string values I can put in the $type value of this:
    bindValue($pointername, $variable, $type);

I did not find anything in the documentation that discusses the types.
I'm working with MySQL so I'd like to know the types I can put in the bindValue function that would equate to types like varchar, tinyint, text, datetime, mediumtext, float, etc.

A: According to http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/statement.html#bindValue() the $type parameter can be either a PDO type (see http://au.php.net/manual/en/pdo.constants.php) or a dbal mapping type (see http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/types/type.html).
So you could use PDO::PARAM_INT or Doctrine\DBAL\Types\Type::Integer by the looks of things.


text:
Q: Check Box value post based checked or unchecked I am using two page in my project one page  calculate.php and another page name defaults results.php
calculate page i have called input page . i have checkbox looks like

    <input name="upfrontMIPPc" id="upfrontMIPPc1" type="text" class="txt" size="3" maxlength="3" onChange="javascript:upfrontMIPPcChanged(true)" />
    <input type="text" name="upfrontmipamt" id="upfrontmipamt" class="txt" size="7"
  onChange="javascript:upfrontMIPAmountChanged(true)" maxlength="7"/>

    <input id="chkUFtoLoan-1" type="checkbox" />

My question  if the user checked the Include In Calc button from the input page.  They should all be defaulted to checked (as we are defaulting to adding the UPFRONT MIP balance to the loan).  But if they uncheck the checkboxes, then the value gets placed in the Buyer Costs To Close Section.
they value post depends user check box selection this value post another page defaults results page
About your Loan:

About Your Loan

    Financed Upfront MIP
    $<?php echo round($arrSecondBox["ssupfrontmipamt"],2);?>

Buyer close to section

Buyer Cost To Close

     Upfront MIP Financed
     $<?php echo round($arrSecondBox["ssupfrontmipamt"],2);?>

if the user checked the Include In Calc button from the input page.  They should all be defaulted to checked (as we are defaulting to adding the UPFRONT MIP balance to the loan).  But if they uncheck the checkboxes, then the value gets placed in the Buyer Costs To Close Section?
MY script for checkbox or uncheck box:

$('input[Name="S"]').mouseenter(function() {
    if ($(this).is(':checked')) {
        $(this).prop('checked',false);
      //  alert("is checked");
    } else {
         $(this).prop('checked',true);
       // alert("not checked");
    }
});
</script>

Fiddle Here
please give any idea about it? thanks in advance .


text:
Q: Statement of result for binomial confidence intervals Confidence intervals for binomial proportions have irregular coverage over the range of possible population parameters (e.g. see Brown et al. 2001 <Link>). How can I formally and usefully describe the properties of the confidence intervals?
Say I toss a coin ten times and obtain seven heads. Are the following statements accurate?
For the Clopper-Pearson method:
The interval 0.3475–0.9333 has been generated by a method that will on at least 95% of occasions, for any true population proportion, contain the true population proportion. The long-run frequency with which this method would yield confidence intervals containing the true population proportion pertaining to this particular experiment is at least 95%.
For the Wilson's scores method:
The interval 0.3968–0.8922 has been generated by a method that will on 95% of occasions, averaged over all population proportions, contain the true population proportion. The long-run frequency with which this method would yield confidence intervals containing the true population proportion pertaining to this particular experiment may be more or less than 95%.

A: You ask how to 'formally and usefully' present your conclusions
Formally: Your answer is an accurate summary of some of the results from Brown et al. as I understand them.  (I note you do not offer their preferred small n method).
Usefully: I wonder who you audience is.  For professional statisticians, you could state your two intervals directly with only citations to the original papers - no further exposition needed.  For an applied audience, you would surely rather pick an interval on whatever substantive grounds you (or they) have, e.g. a preference for conservative coverage or good behavior for small proportions, etc., and just present that interval alone, noting its nominal and perhaps also its actual coverage much as you do above, perhaps with a footnote to the effect that other intervals are possible.
As it stands you offer a choice of intervals but not much explicit guidance for an applied audience to make use of that information.  In short, for that sort of audience I would suggest either more information about the implications of choice of interval.  Or less!

A: When using confidence intervals, my response is always as follows:
In repeated sampling % of intervals so constructed will contain _. Thus, we have % confidence that the true  lies within __-_.
One example is
In repeated sampling, 95% of all intervals so constructed will contain Mu, the true population mean. Thus we have 95% confidence that the population GPA lies between 2.72 and 3.07.
I don't see anything particularly wrong with your response, except I would imagine the last sentence should be 95%, not more or less, or at least.


text:
Q: Is there a way to create multiple columns from existing columns of a dataframe in Scala? I am trying to ingest an RDBMS table into Hive. I have obtained the dataframe in the following way:
val yearDF = spark.read.format("jdbc").option("url", connectionUrl)
                                                   .option("dbtable", "(select * from schema.tablename where source_system_name='DB2' and period_year='2017') as year2017")
                                                   .option("user", devUserName)
                                                   .option("password", devPassword)
                                                   .option("numPartitions",15)
                                                   .load()

These are the columns of the dataframe:
geography:string|
project:string|
reference_code:string
product_line:string
book_type:string
cc_region:string
cc_channel:string
cc_function:string
pl_market:string
ptd_balance:double
qtd_balance:double
ytd_balance:double
xx_last_update_tms:timestamp
xx_last_update_log_id:int
xx_data_hash_code:string
xx_data_hash_id:bigint

The columns ptd_balance, qtd_balance, ytd_balance are double datatypes which are precision columns. Our project wants to convert their datatype from Double to String by creating new columns: ptd_balance_text, qtd_balance_text, ytd_balance_text with same data inorder to avoid any data truncation.
withColumn will create a new column in the dataframe.
withColumnRenamed will rename the existing column.
The dataframe has nearly 10 million records.
Is there an effective way to create multiple new columns with same data and different type from the existing columns in a dataframe ?

A: You can do this creating query from all columns like below
import org.apache.spark.sql.types.StringType

//Input:

scala> df.show
+----+-----+--------+--------+
|  id| name|  salary|   bonus|
+----+-----+--------+--------+
|1001|Alice| 8000.25|1233.385|
|1002|  Bob|7526.365| 1856.69|
+----+-----+--------+--------+

scala> df.printSchema
root
 |-- id: integer (nullable = false)
 |-- name: string (nullable = true)
 |-- salary: double (nullable = false)
 |-- bonus: double (nullable = false)

//solution approach:
val query=df.columns.toList.map(cl=>if(cl=="salary" || cl=="bonus") col(cl).cast(StringType).as(cl+"_text") else col(cl))

//Output:

scala> df.select(query:_*).printSchema
root
 |-- id: integer (nullable = false)
 |-- name: string (nullable = true)
 |-- salary_text: string (nullable = false)
 |-- bonus_text: string (nullable = false)

scala> df.select(query:_*).show
+----+-----+-----------+----------+
|  id| name|salary_text|bonus_text|
+----+-----+-----------+----------+
|1001|Alice|    8000.25|  1233.385|
|1002|  Bob|   7526.365|   1856.69|
+----+-----+-----------+----------+

A: If i was in your shoes, i would make changes in the extraction query or ask BI team to put some effort :P for adding and casting the fields on the fly while extracting, but any how what you are asking is possible.
You can add the columns from the existing columns as below. Check the addColsTosampleDF dataframe. I hope the comments below will be enough to understand, if you have any questions feel free to add in the comments and i will edit my answer.
scala> import org.apache.spark.sql.functions._
import org.apache.spark.sql.functions._

scala> import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.{DataFrame, Row, SparkSession}

scala> val ss = SparkSession.builder().appName("TEST").getOrCreate()
18/08/07 15:51:42 WARN SparkSession$Builder: Using an existing SparkSession; some configuration may not take effect.
ss: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@6de4071b

//Sample dataframe with int, double and string fields
scala> val sampleDf = Seq((100, 1.0, "row1"),(1,10.12,"col_float")).toDF("col1", "col2", "col3")
sampleDf: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 1 more field]

scala> sampleDf.printSchema
root
 |-- col1: integer (nullable = false)
 |-- col2: double (nullable = false)
 |-- col3: string (nullable = true)

//Adding columns col1_string from col1 and col2_doubletostring from col2 with casting and alias
scala> val addColsTosampleDF = sampleDf.
select(sampleDf.col("col1"),
sampleDf.col("col2"),
sampleDf.col("col3"),
sampleDf.col("col1").cast("string").alias("col1_string"),
sampleDf.col("col2").cast("string").alias("col2_doubletostring"))
addColsTosampleDF: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 3 more fields]

//Schema with added columns
scala> addColsTosampleDF.printSchema
root
 |-- col1: integer (nullable = false)
 |-- col2: double (nullable = false)
 |-- col3: string (nullable = true)
 |-- col1_string: string (nullable = false)
 |-- col2_doubletostring: string (nullable = false)

 scala> addColsTosampleDF.show()
+----+-----+---------+-----------+-------------------+
|col1| col2|     col3|col1_string|col2_doubletostring|
+----+-----+---------+-----------+-------------------+
| 100|  1.0|     row1|        100|                1.0|
|   1|10.12|col_float|          1|              10.12|
+----+-----+---------+-----------+-------------------+