text:
Q: Document classification with very few documents I wanted to know if there is any method in state of art that deals with document classification methods with very few training samples in R.
I have just 20 documents and need to classify them into 3 different classes.
I know it would be great to have a large corpus as part of the training data for every class, but the reality is that I have just 20. So I am assuming that approaches like topic modelling will have very little value add.
I am thinking of a simple approach like taking the term document matrix and running a logistic regression.
Wondering what others would like to suggest.


text:
Q: Box.com - not getting results from new BoxFolder(apiConnection, id) when using As-User header I am using the As-User header to simulate a subset of users on Box.com as the service account so I can access each one of their files.
So I go:
      res.setRequestInterceptor((RequestInterceptor) request -> {
        request.addHeader("As-User", asUser);
        // Returning null means the request will be sent along with our new header.
        return null;
      });

Where asUser is a user ID which is always something like 7352356
Now when I go new BoxFolder(apiConnection, "0"); I am expecting the root of asUser's files.
But I get
com.box.sdk.BoxAPIException: The API returned an error code: 401
    at com.box.sdk.BoxAPIResponse.<init>(BoxAPIResponse.java:70) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxJSONResponse.<init>(BoxJSONResponse.java:30) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxAPIRequest.trySend(BoxAPIRequest.java:423) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:209) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:184) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxFolder.getInfo(BoxFolder.java:161) ~[box-java-sdk-2.1.1.jar:?]
    at com.box.sdk.BoxFolder.getInfo(BoxFolder.java:23) ~[box-java-sdk-2.1.1.jar:?]

I must be missing a step yes? From this link I think I am: Using As-User in Box Request

A: ok see https://docs.box.com/reference#as-user-1

To enable this functionality for applications using OAuth2, please file a support ticket with your API key. To enable this functionality for applications using OAuth2 with JWT, please navigate to the Advanced Features section in the developer console and enable the "Perform actions on behalf of users" permission.

So I'm guessing our box admin just forgot to check the box.
UPDATE:
Looks like you have to regenerate the api key after changing the permissions. If you don't do that, the new permissions will not take effect. So if you are getting this issue where you are getting a 401 error when accessing box... go back into the box admin console, make sure the permissions are correct, delete the old api key, create a new one, then try again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restrict access to images on my website except through my own htmls On my website I store user pictures in a simple manner such as:
"image/user_1.jpg".
I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)
So far I have three solutions in mind:

*

*I tried using .htaccess to password protect the "images" folder. That helped me up to some point but some of the images started popping up a username and password request on my htmls (while amazingly some images did not) so this seems to be an unpredictable method.

*I can start converting my user_id's to an md5 hash with some salt. The images would be named as: /image/user_e4d909c290d0fb1ca068ffaddf22cbd0.jpg. I don't like this solution. It makes the file system way complicated.

*or I can user PHP's readfile() function or maybe something similar in Perl or Python. For instance I could pass a password using an md5 string to validate visitors as loggedin users with access to that image.
I'm leaning towards option 3 but with a Perl or Python angle (assuming they would be faster than PHP). However I would like to see other ideas on the matter. Maybe there is a simple .htaccess trick to this?
Basically all I want to make sure is that no one can view images from my website unless the images are directly called from within htmls hosted on my site.
Thanks a lot,
Haluk

A: Any method you choose to determine the source of a request is only as reliable as the HTTP_REFERER information that is sent by the user's browser, which is not very. Requiring authentication is the only good way to protect content.

A: Method #1 is not viable as it will ask for user name and password on each and every image requested. You probably got the prompt for some of the images and not for others due to caching issues.
Method #2 looks the most appealing to me by being the least processor intensive, but with only the user_id passed through the md5 function the file name still quite easily guessable. You should go for md5('my secret string'.$user_id) for a better solution.
Why are you picking #3 via Perl or Python? What's wrong with PHP's speed? Indeed if you're protecting your images this way you should go to the extra length of moving them out and above your webroot so they're only accessible via your script which first checks if the user is authenticated and then passes the avatar by reading it and outputting it. Alternatively, you could protect the directory with an htaccess file saying deny from all.
Plus you should go for a HTTP_REFERER security either via PHP or via .htaccess.
Good luck!

A: You can look up "Hotlinking prevention" via htaccess and i think that should be a simple solution for the type of protection you need. However its not fool proof , people who will really want to get those images will find a work around by faking the referrer.
http://altlab.com/htaccess_tutorial.html

A: You are right considering option #3. Use service script that would validate user and readfile() an image. Be sure to set correct Content-Type HTTP header via header() function prior to serving an image. For better isolation images should be put above web root directory, or protected by well written .htaccess rules - there is definitely a way of protecting files and/or directories this way.

A: As has been said hotlinking protection does not protect your files from listing just by altering their id. Plus Refferer can be easily faked.
In this case I would recommend some kind of authentication. You must create PHP script that will serve images only if it verify logged user via COOKIES or SESSION. (I wouldn't recommend using md5 of user password).
Maybe you'll need some SQL table to save access permissions.
Oh and to protect your images you can just place .htaccess with
deny from all

to the images folder.


text:
Q: applying bounce animation to div elements manually using js Here, I am trying to apply bounce animation to my dynamically generated messages called by API but no effect is coming. Also, I tried using effect() but it was also of no use. Here is the link to my Codepen. Link
$(document).ready(function () {

    $("#getMessage").on("click",function () {
        //(".message").effect("bounce", {times:300}, 300);
        move();
    });

    var divObj = null;

    function init () {
        divObj = document.getElementById("message");
        //   $("#message").toggle("bounce", {times: 6}, "slow");
        divObj.style.position = "relative";
        divObj.style.top = "0px";
    }

    function move () {
        divObj.style.top = parseInt(divObj.style.top) + 10 + "px";
    }

});

A: What you've supplied above isn't too far off from the result(s) you're looking for. Essentially the {times:300} you are supplying is far too many for the speed/ratio - resulting in no visible animation.
From what I have just tested, any bounces >10 with the speed @300 seem to display in an abnormal manner.
Please see this codepen: http://codepen.io/anon/pen/BWyqpY
Give this a try:
$("#getMessage").on("click",function () {
    $(".message").effect("bounce",{times:3},300);

    // I'm not sure if you still want this method.
    move();
});


text:
Q: SQL get all Rows with Value VB.net I have developed a word export function within my VB.net application which returns all rows that have a specific value in the column (service_name). However when looping through the function the cells in word always grabs the first service name instead of cycling through each one. I need a way in which I can point to the next value for the specific service_name.

I have given previews of the table I am grabing the value from and the word export knowing that there are 3 rows which match the value but always returning the first one.
Function used for returning SQL data:
Function getdataapplication(ByVal recordnum As Integer, ByVal fieldnum As Integer)
        ds.Reset()
        GC.Collect()

        Dim dbtable
        dbtable = "application_portfolio"

        Dim sql As MySqlCommand

        sql = New MySqlCommand("Select * from application_portfolio where service_name = '" & Wordexport.tbservicename.Text & "' ", dbcon)

        Dim DataAdapter1 As MySqlDataAdapter = New MySqlDataAdapter()
        DataAdapter1.SelectCommand = sql

        DataAdapter1.Fill(ds, dbtable)
        dbcon.Close()
        sql.Dispose()
        Return ds.Tables(dbtable).rows(recordnum).Item(fieldnum - 1)
            'Return reader
    End Function

Public Sub Word_Click(sender As Object, e As EventArgs) Handles Word.Click

        Dim sqlrowcount As Integer
        sqlrowcount = CountRecords()
        tbcount.Text = sqlrowcount

        If application_portfolio.Checked = True Then
            'oWord.NewDocument.Application.Equals(Nothing)
            Dim oPara2application As Word.Paragraph
            Dim oTableapplication As Word.Table

            For i As Integer = 1 To sqlrowcount
                j = j + 1
                oTableapplication = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, j, 7)
                oTableapplication.Range.ParagraphFormat.SpaceAfter = 6
                oTableapplication.Rows(1).Range.Font.Bold = True
                oTableapplication.Cell(1, 1).Range.Text = "ID"
                oTableapplication.Cell(1, 2).Range.Text = "Service Name"
                oTableapplication.Cell(1, 3).Range.Text = "Application Name"
                oTableapplication.Cell(1, 4).Range.Text = "Application Type"
                oTableapplication.Cell(1, 5).Range.Text = "Cost"
                oTableapplication.Cell(1, 6).Range.Text = "Year Released"
                oTableapplication.Cell(1, 7).Range.Text = "Version"

                Dim tempdatastore = getdataapplication(0, 1)
                ListBox1.Items.Add(tempdatastore)
                oTableapplication.Cell(j, 1).Range.Text = functions.getdataapplication(0, 1)
                oTableapplication.Cell(j, 2).Range.Text = functions.getdataapplication(0, 2)
                oTableapplication.Cell(j, 3).Range.Text = functions.getdataapplication(0, 3)
                oTableapplication.Cell(j, 4).Range.Text = functions.getdataapplication(0, 4)
                oTableapplication.Cell(j, 5).Range.Text = functions.getdataapplication(0, 5)
                oTableapplication.Cell(j, 6).Range.Text = functions.getdataapplication(0, 6)
                oTableapplication.Cell(j, 7).Range.Text = functions.getdataapplication(0, 7)
                oTableapplication.Rows.Item(1).Range.Font.Italic = True
            Next
        End If
End function

A: Every time you call getdataapplication, you are passing the value 0 for the recordnum parameter.  Therefore, it is always going to output the data from the first row.  Inside your For loop, you probably want to be using i instead of 0, for instance:
Dim tempdatastore = getdataapplication(i, 1)

However, this seems like a really terrible design.  Every time you are calling the getdataapplication method, which happens multiple times per iteration of the loop, it is both forcing the garbage collector to do its thing AND re-querying the database.  It would make far more sense to query the database once and then loop through the contents of the returned DataSet.  It's doubtful that you should not need to call GC.Collect.

A: Found the problem of your error. you keep on search for row 0 in your function getdataapplication
oTableapplication.Cell(j, 1).Range.Text = functions.getdataapplication(0, 1)
oTableapplication.Cell(j, 2).Range.Text = functions.getdataapplication(0, 2)
oTableapplication.Cell(j, 3).Range.Text = functions.getdataapplication(0, 3)
oTableapplication.Cell(j, 4).Range.Text = functions.getdataapplication(0, 4)
oTableapplication.Cell(j, 5).Range.Text = functions.getdataapplication(0, 5)
oTableapplication.Cell(j, 6).Range.Text = functions.getdataapplication(0, 6)
oTableapplication.Cell(j, 7).Range.Text = functions.getdataapplication(0, 7)

What you need to do is as follows
oTableapplication.Cell(j, 1).Range.Text = functions.getdataapplication(i, 1)
oTableapplication.Cell(j, 2).Range.Text = functions.getdataapplication(i, 2)
oTableapplication.Cell(j, 3).Range.Text = functions.getdataapplication(i, 3)
oTableapplication.Cell(j, 4).Range.Text = functions.getdataapplication(i, 4)
oTableapplication.Cell(j, 5).Range.Text = functions.getdataapplication(i, 5)
oTableapplication.Cell(j, 6).Range.Text = functions.getdataapplication(i, 6)
oTableapplication.Cell(j, 7).Range.Text = functions.getdataapplication(i, 7)


text:
Q: The Big O notation what is the explanation? I studying discrete mathematics to use it's knowledge further in programming. Unfortunately one of the most complex things is the littlemost of what is explained.
The definition of the theorem is given as:
Let f and g be the functions from the set of integers or the set of
real numbers to the set of real numbers.
We say that f(x) is O(g(x)) if there are constants C and k such that
|f(x)| <= C|g(x)|, when x > k.

There are confusions here in itself:
I know that the big O notation is used to deduce the number of steps required to solve a problem by an algorithm, and hence can be used to compare two algorithms and find their relative efficiency. So,
1) What are f(x) and g(x), are they the algorithms we are comparing?
2) What is this C and k in the definition?
3)What is the validity of the definition?
Furthermore, it gives an examples like:
Show that f(x) = x2+2x+1 is O(x2)
I apologize, but I've got to write the solution given:
It says,
"We observe that we can readily estimate the size of f(x) when x > 1  whenever x < x2 and 1 < x2 when x > 1. It follows that, 0<= x2+2x+1 <= 4x2, when x > 1. So, we can take c=4 and k = 1 as witnesses."
This solution is all a mystery to me.(And this is not my homework, really).
What I don't understand:
1)Why not take x = 0? We could still estimate the value of f(x), right?
2) "x < x2 and 1 < x2" when x > 1 , where I think it should had been "x <= x2" and where did the second even come from?
3)  where did the  0 ≤  x2 +2x+1, even come from?
4) And most importantly How in the world does it even tell me how many steps do I need to take to solve any problem?(f(x) maybe?)

A: Suppose we have two algorithms each of which sorts an array of length $n$. Suppose the first takes $f(n) = n^2 + n + 1 $ steps and the second takes $g(n) = 1000n \log(n) + 200n$ steps. Which is a better (faster) algorithm?
Well for small values of $n$ the first one is faster, while for large values of $n$, which is what matters in a lot of computing situations, the second one will be faster.
This is the essence of what the "big-O" notation conveys.
Other answers may connect this idea to the formal definition. (I might later today.)

A: Broadly speaking, $f(x)$ is the runtime of some algorithm as a function of the "size" of the input $x$. You're interested in a brief, approximate description of the behavior of $f(x)$ for large $x$ (because in computing we're frequently dealing with large problems). Big O notation provides such a description, by saying that $f$ is no more than $Cg(x)$ if $x$ is large, for some $C$.
For your specific questions:

*

*$f$ and $g$ are arbitrary functions. In the algorithm context, $x$ is some descriptor of the size of the input to the algorithm, $f$ is the runtime of your algorithm as a function of the size of the input, and $g$ is a reference function that you're comparing $f$ to.

*$C$ and $k$ are arbitrary constants. The role of $k$ intuitively is to restrict attention to "large $x$". The role of $C$ is to allow for a hidden constant factor, so that for example $5x=O(x)$.

*I don't really know what this means, so I can't help you there.
As for the solution:

*

*Big O notation is all about comparing two functions in some limit (in your context the limit is as $x \to \infty$). Accordingly, small values of the input (less than some fixed constant) may be ignored.

*The distinction between $<$ and $\leq$ in this context does not really matter, but indeed if $x>1$ then $x^2>x>1$.

*All the terms in $x^2+2x+1$ are positive if $x$ is positive.

*$x^2+2x+1$ is the exact number of steps required for some unspecified algorithm to run. The point of Big O notation is to give a more approximate expression (usually because such an exact expression is not available).

A: Broadly speaking what Big Oh provides (in the context of algorithm estimation) is an estimate for how long a program is going to take to execute to arrive at a particular result. The formal notation provided simply says.
Some function f(x), in this case the algorithm's runtime, will be no greater than some function g(x) multiplied by some arbitrarily large constant factor for all values x greater than k.
This is often done by taking n to be equal to the size of the input, and then express the runtime of an algorithm as O(f(n)) for some function f(n). For example:
Let's take the following code:
function example1(inputArray) {
  inputArray.forEach(function(item) {
    return item + 1
  })
}

We would say that this code is O(n), as for an array of size n, the number of distinct computations taken is also n, and therefore, the function best representing the number of distinct computations is f(n) = n
Now let us take another example:
function example1(inputArray) {
  for(var x = 0; x <= inputArray.length; x+=2) {
    console.log(item + 2)
  }
}

In this case we would say that this algorithm if O($\frac{n}{2}$) as the number of computations taken is obviously going to be equivalen the half the length of the input array. Except that that statement is a lie! We would actually still say, that this algorithm is O(n). Why? This is where the C in the definition comes in. Not all operations take the same amount of time! If our code looked something like this:
function example1(inputArray) {
  inputArray.forEach(function(item) {
    return incrediblySlowDatabaseOperation
  })
}

The distinction between n and $\frac{n}{2}$ would stop being significant as the constant error inherent in doing some slow operation would come to dominate any possible error we would accrue by dropping the constant factor $\frac{1}{2}$.
However, if we take something like
function example1(inputArray) {
  inputArray.forEach(function(item) {
    inputArray.forEach(function(item) {
      return item + 1
    })
  })
}

We would now have O(n^2) which would no longer be a negligible difference.
So to reiterate.
f(x) is a function representing how long your code takes to run for input of size x. g(x) is a function representing how many pure computational steps your code has to take for an input of size x. C is some constant multiplier, representing non algorithmically time bound things your program has to do. k simply implies that your upper bound estimate (may) only start working beyond some minimum input size.


text:
Q: Go: command line flags I know you can specify command line flags and run your binary file against them like this:
./binary -output=html -type=doc

However, I was looking at the implementation of this Go package: https://github.com/jteeuwen/go-bindata
I'm wondering how the author is able to enable the user to run the commands like this
go-bindata /data

instead of
./go-bindata -target=/data

Appreciate some help in case I missed out anything!

A: The trick is to use flag.Args() which is, simply, the non flag arguments following the flags. You can either fetch the entire list, or get a specific arg with flag.Arg(i). See http://golang.org/pkg/flag/#Args
And from the source of the program you posted:
// Create input configurations.
c.Input = make([]bindata.InputConfig, flag.NArg())
for i := range c.Input {
    c.Input[i] = parseInput(flag.Arg(i))
}

A: Easy as pie using the flag package. Checkout flag.Args


text:
Q: Call Back Of Custom Delegate with share Object is not working My Custom Delegate (With Share Object) call back is not working? I pasted the code below ...
ViewController.h
#import <UIKit/UIKit.h>
#import "UserLocation.h"
@interface ViewController : UIViewController
@end

ViewController.m
#import "ViewController.h"
@interface ViewController () @end
@implementation ViewController

- (IBAction)fetchLocation:(id)sender{
    UserLocation *obj = [UserLocation new];
    [[UserLocation LocationObject] FetchLocation];
}

@end

UserLocation.h  (Custom Delegate File)
#import <Foundation/Foundation.h>

@protocol UserLocationDelegate <NSObject>

-(void)userLocationCallBack;

@end

@interface UserLocation : NSObject <UserLocationDelegate>
{
    // Delegate to respond back
}

+ (UserLocation *) LocationObject;

+ (void)removeSharedHelper;

- (void)FetchLocation;

@property (nonatomic,strong)   id<UserLocationDelegate>UserLocationDelegate;

@end

UserLocation.m
#import "UserLocation.h"

@implementation UserLocation

static UserLocation * _sharedActivityObject;

+ (UserLocation *) LocationObject
{
    if(_sharedActivityObject != nil){
        return _sharedActivityObject;
    }
    _sharedActivityObject = [[UserLocation alloc] init];
    [_sharedActivityObject initializeActivityView];

    return _sharedActivityObject;
}

+ (void)removeSharedHelper {
    if (_sharedActivityObject != nil) {
        _sharedActivityObject = nil;
    }
}

-(void)initializeActivityView{

}

- (void)FetchLocation{
    [_UserLocationDelegate userLocationCallBack];
}

-(void)userLocationCallBack
{
    NSLog(@"Good");
}

@end

What mistake did I do?

A: You haven't made your viewController to be delegate of UserLocation among the many other things wrong with your code. Anyways, addressing the issue at hand, Adjust your code in ViewController.h as per following (I have added comments for each step):
@interface ViewController () <UserLocationDelegate> //Make your VC adopt delegate of UserLocation
@end
  @implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)fetchLocation:(id)sender{
UserLocation *obj = [UserLocation new];
obj.delegate = self; //Set your VC to be delegate of UserLocation
[obj FetchLocation]; //Call the method on obj instance
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];

}
//Add delegate method to your VC
-(void)userLocationCallBack
{
//Your code here will run when delegate is fired.
}

Also you don't need implementation of -(void)userLocationCallBack in UserLocation.m. When you call delegate method, it will look for implementation of that method in the VC which is the delegate of UserLocation. Learn about delegates in a very interesting way here. Also see apple Documentation on it to clear your concepts. Also Learn about Design patterns at this highly recommended link.
Adding up, as recommended sagely by trojanfoe and I quote:

"If this is the only use of the delegate then it's unnecessary in this
  case; if all that's being done is create instance > call method on
  instance > get something back, then returning an object is enough. If
  the delegate can be called at any time then I would expect it to be an
  instance variable, not a local variable."

A: You never assign anything to UserLocationDelegate. First note: use camel case for variable names (userLocationDelegate).
Assuming you want to assign something to the delegate you have to create some class that adopts the actual protocol UserLocationDelegate. I am going to assume that you want to assign a instance of the ViewController as delegate. Therefore you have to

*

*make the ViewController adopt UserLocationDelegate

*write a custom userLocationCallBack method

*assign the ViewController to the UserLocationDelegate
All that should look like the following:
Change the ViewController header file
#import <UIKit/UIKit.h>
#import "UserLocation.h"
@interface ViewController : UIViewController <UserLocationDelegate>
@end

Change the UserLocation header file:
#import <Foundation/Foundation.h>

@protocol UserLocationDelegate <NSObject>
    -(void)userLocationCallBack;
@end

@interface UserLocation : NSObject

+ (UserLocation *) LocationObject;
+ (void)removeSharedHelper;
- (void)fetchLocation;

@property (nonatomic,strong) id<UserLocationDelegate> userLocationDelegate;

@end

Change the ViewController implementation file by adding the following:
- (void)userLocationCallBack {
    NSLog(@"delegate called");
}

You additionally have to assign the delegate somewhere, the correct place would probably be the constructor of ViewController, but I will use the place where you actually instantiate the UserLocation:
- (IBAction)fetchLocation:(id)sender{
    UserLocation *obj = [UserLocation new];
    obj.userLocationDelegate = self;
    [obj fetchLocation];
}

Last but not least make use of the renamed property:
- (void)fetchLocation{
    [self.userLocationDelegate userLocationCallBack];
}

Most important note: Read up on singletons, how to (not) use them and how they should be implemented correctly. You are messing it up pretty badly. Additionally read up on protocols and how they are supposed to be used. Your current code (even with above corrections) will probably not work as expected because you messed up pretty much every pattern you try to incorporate.

A: Change this you are not setting delegate to self...
@interface ViewController ()<UserLocationDelegate> @end
  @implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)fetchLocation:(id)sender{
UserLocation *obj = [UserLocation new];
obj.delegate = self;
[[UserLocation LocationObject] FetchLocation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)userLocationCallBack
{
    NSLog(@"Good in viewController");
}

@end

In UserLoaction.h
#import "UserLocation.h"

@implementation UserLocation

static UserLocation * _sharedActivityObject;

+ (UserLocation *) LocationObject
{

    if(_sharedActivityObject != nil){
        return _sharedActivityObject;
    }
    _sharedActivityObject = [[UserLocation alloc] init];
    [_sharedActivityObject initializeActivityView];

    return _sharedActivityObject;
}

+ (void)removeSharedHelper {
    if (_sharedActivityObject != nil) {
        _sharedActivityObject = nil;
    }
}

-(void)initializeActivityView{

}

- (void)FetchLocation{
    [self userLocationCallBack];
    [_delegate userLocationCallBack]; // this will call your userLoacationCallBack implementation in viewcontroller
}

-(void)userLocationCallBack
{
    NSLog(@"Good");
}

@end

Btw why do you want your callback method to be implemented in the same class. You changed the meaning of it completely by implementing it in same class. you should implement -(void)userLocationCallBack body in  viewcontroller.m file


text:
Q: Admob capping is not respected I'm working on a project where Admob has been implemented and capping is set at no more than 1 impression per user every 5 minutes (for my tests).
But the ads are spamming.
i've followed the documentation here :
https://developers.google.com/admob/ios/interstitial
but the capping is not respected.
The previous developer has implemented the call in the interstitialDidReceiveAd, which is strongly NOT recommended by the doc
- (void)interstitialDidReceiveAd:(GADInterstitial *)ad {
   NSLog(@"interstitialDidReceiveAd");
   if (self.interstitial.isReady) {
    [self.interstitial presentFromRootViewController:self];
   }
}

What i've tried to do is to make the call from my viewDidAppear method but now my ads are never shown
-(void)viewDidAppear:(BOOL)animated {
   [super viewDidAppear:YES];

   [newtopicsBtn.titleLabel setFont:PANTON_SEMIBOLD([UniversalMethod setFontsize:12])];
   [newtopicsBtn.titleLabel setTextColor:[UIColor whiteColor]];
   [newtopicsBtn.titleLabel setText:NSLocalizedString(@"home_newtopics_title", @"")];

   if(self.interstitial.isReady) {
   [self.interstitial presentFromRootViewController:self];
   }
 }

Did you guys already face to that kind of issue ?


text:
Q: Making a View's width based on screen width I am trying to let a View's width be based on the width of the screen. Depending on a value from 0 to 100, the width will be that percentage of the screen width. Here is how I am getting the screen width in DP:
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density  = context.getResources().getDisplayMetrics().density;
float screenWidthDP = outMetrics.widthPixels / density;

This returns 360dp for my device which is correct. I then use this to set the width of my view, where timeCountNewRange() returns a value from 0 - 100:
int timeCountNewRange = getNewRangeTimeCount(timeCount, min, max);
int widthDP = (int) (((double)timeCountNewRange / 100.0) * screenWidthDP);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widthDP, 15);
params.setMargins(5, 0, 0, 0);
appHolder.timeBar.setLayoutParams(params);

For some reason, when the "timeCountNewRange" value is 100 it is only about 60% of the screen width, and everything else is shorter as well. If replace
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widthDP, 15);

with
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(360, 15);

the view is still only around 60% of the screen width. This error differs from device to device based on screen size. How do I properly set the width to be based upon the screen width?

A: The layout params will be set in pixels if set programmatically. You will have to convert the dp to pixels again and set the width


text:
Q: Not understanding this Python script In this example of Django project, and in the templates section (book_detail.html), I do not understand this code:
book.genre.all|join:", "

"book.genre.all" are List of all objects from the Genre class that are connected to the book object (from Book class) by a ManyToMany key.
Why are pipe characters being used to join or split these objects? Why not use ", ".join(book.genre.all)?

A: They called as template filters in django. You can check here for custom filter also here for built-in join filter.


text:
Q: How to fix the Type error: unsupported operand type(s) for +: 'function' and 'int'? I'm trying to make a weird potato counter with discord.py and save it to .json file.
Code is below:
@client.command()
async def get(ctx):
    with open('get.json', 'r') as f:
        get = json.load(f)

    get[str(ctx.author.id)] = bal + 1

    with open('get.json', 'w') as f:
        json.dump(get, f, indent=4)
    await ctx.send('You got 1 potato!')

but it gives me this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'function' and 'int'

A: The error message rather clearly states you're trying to add (+) a function (bal I would guess) and an int, and you can't do that.
So don't do that? Maybe call the function or something? Since you don't provide all the code, let alone in a runnable / replicable state, it's difficult to provide more help than that.


text:
Q: Python 2.7: shift a dataframe by day and a column value I have a dataframe named  df1 as following:
df1:
               a   b    id
2010-01-01     2   3    21
2010-01-01     2   4    22
2010-01-01     3   5    23
2010-01-01     4   6    24
2010-01-02     1   4    21
2010-01-02     2   5    22
2010-01-02     3   6    23
2010-01-02     4   7    24
2010-01-03     1   8    21
2010-01-03     2   9    22
2010-01-03     3   10    23
2010-01-03     4   11   24
...........................

I want to shift the value of a, b and id, the i rows value become the i+1 rows value. As you can see the df1, the same date have several rows, and the id is different. I want to shift the df1, I mean the 2010-01-02 value to be the 2010-01-03 value based on the id(I mean that 2010-01-02 value of id 21, to be the  2010-01-03 value of id 21). Thanks!
My desired answer:
                a   b    id
2010-01-01     Nan   Nan    Nan
2010-01-01     Nan   Nan    Nan
2010-01-01     Nan   Nan    Nan
2010-01-01     Nan   Nan    Nan
2010-01-02     2   3    21
2010-01-02     2   4    22
2010-01-02     3   5    23
2010-01-02     4   6    24
2010-01-03     1   4    21
2010-01-03     2   5    22
2010-01-03     3   6    23
2010-01-03     4   7    24
...........................

A: One of the way is with the help of shape if the dates are sorted i.e
df.shift(df.loc[df.index[0]].shape[0])
# Or len
df.shift(len(df.loc[df.index[0]]))

Output :

              a    b    id
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-02  2.0  3.0  21.0
2010-01-02  2.0  4.0  22.0
2010-01-02  3.0  5.0  23.0
2010-01-02  4.0  6.0  24.0
2010-01-03  1.0  4.0  21.0
2010-01-03  2.0  5.0  22.0
2010-01-03  3.0  6.0  23.0
2010-01-03  4.0  7.0  24.0

A: If all groups are same length (in sample 4) and DatetimeIndex is sorted:
df2 = df.shift((df.index == df.index[0]).sum())
print (df2)
              a    b    id
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-01  NaN  NaN   NaN
2010-01-02  2.0  3.0  21.0
2010-01-02  2.0  4.0  22.0
2010-01-02  3.0  5.0  23.0
2010-01-02  4.0  6.0  24.0
2010-01-03  1.0  4.0  21.0
2010-01-03  2.0  5.0  22.0
2010-01-03  3.0  6.0  23.0
2010-01-03  4.0  7.0  24.0

But if need shift values of index by one day:
df3 = df.shift(1, freq='D')
print (df3)
            a   b  id
2010-01-02  2   3  21
2010-01-02  2   4  22
2010-01-02  3   5  23
2010-01-02  4   6  24
2010-01-03  1   4  21
2010-01-03  2   5  22
2010-01-03  3   6  23
2010-01-03  4   7  24
2010-01-04  1   8  21
2010-01-04  2   9  22
2010-01-04  3  10  23
2010-01-04  4  11  24


text:
Q: How to fire a method when UISlider stops? I've got a UISlider that allows the user to changes values. I want a UILabel to continuously update as the slider moves from left to right.
So, I wrote my UISlider method like this:
    - (IBAction)yearsSlider:(UISlider *)sender
{
    self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

}

This works just fine.  I need to fire a different method when the user stops the slider.
I thought about using NSTimer for this - so rewrote the above method like so:
     - (IBAction)yearsSlider:(UISlider *)sender
    {
        self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

 if (!self.timer){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];]
    }

    }

Then in the requestCalculation method I invalidate the timer and set it to nil = like so:
 [self.timer invalidate];
self.timer = nil;

This slows it down - but the method is called while the slider is moving. Which is not what I want.
I am aware that I can use self.mySlider.continuous = NO; which means the target method is only fired once when the user lifts their finger off the slider. The problem with this is my UILabels are not updated as the user sliders their left and right on the slider.

A: set self.mySlider.continuous = YES;, and update your label in the method corresponding to UIControlEventValueChanged.
Then, add a method with a different selector for the events UIControlEventTouchUpInside and UIControlEventTouchUpOutside and perform the (apparently expensive) computation in there.

A: You can use the UIControlEvent UIControlEventTouchUpInside to fire an action when the user lifts the finger (maybe you need to check touch cancelled and touch up outside too)
[self.mySlider addTarget:self action:@selector(_ended) forControlEvents: UIControlEventTouchUpInside];

A: You have the right idea. But you are canceling the timer in the wrong method. You want to cancel the (previous) timer in the yearsSlider: method, not the requestCalculation method.
- (IBAction)yearsSlider:(UISlider *)sender {
    // Cancel the current timer
    [self.timer invalidate];

    self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

    // Start a new timer in case this is the last slider value
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];
}

BTW - two seconds seems to be a rather long delay for this check. Something smaller would probably be better.
Do not invalidate the timer in requestCalculation. Just set it to nil.
FYI - Use NSNumberFormatter to convert the slider value to a user displayed value. Doing this will ensure the value is formatted properly for the user's locale.


text:
Q: Unable to load the dropdown list on a kendo window from a method using Webservice On clicking Edit button on a Page a method is triggered and a window which uses a kendo template is opened . One of the control on the kendo window is Kendo dropdown list which needs to have values comming from the webmethod.The error i am getting on clicking of the edit button is 'Object doesn't support property or method 'slice'. Below is my code for the Edit button.
function edit(item) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
    .html(editTemplate({ node: node}))
    .appendTo("body")
    .kendoWindow({
        modal: true,
        activate:function(){

            $("#roles").kendoDropDownList({
                dataTextField: "Countryname",
                dataValueField: "CountryId",
                dataSource: {
                    transport: {
                        read: {
                            url: "/Services/MenuServices.asmx/getcountries",
                            contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
                            type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
                        }
                    }
                }
            })
            },
        deactivate: function () {
            this.destroy();
        }
    })
 .on("click", ".k-primary", function (e) {
    var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
    var textbox = dialog.element.find(".k-textbox");
    var Id = $('#ID').val();
    node.set("id", Id);
    dialog.close();
    var treenode = treeview.dataSource.get(itemid);
    treenode.set("id", Id);
    treenode.ID = Id;

    console.log(JSON.stringify(treenode));
        })

}
IS there any property for Kendo window that triggers this service when its opened.Right now i am using activate event but its not working.tried using 'Open' event also.
Thanks

A: I added the Schema part to the datasource and it worked.
schema: {
                        data: function (response) {
                            return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
                        },
                        model: { // define the model of the data source. Required for validation and property types.
                            id: "CountryId",
                            fields: {
                                CountryId: { editable: false, nullable: false, type: "string" },
                                Countryname: { editable: true, nullable: true, type: "string" },
                               }
                        },
                    },


text:
Q: Prepopulate form in Struts1 I have a jsp as my view, which displays a form for adding a new user/ updating the user, if one is selected. I can't figure out how to prepopulate my form if a user is selected. I read about the solution using 2 actions, with the same form, one of which is just used to populate the fields, and on for submitting the data.
  However, this doesn't work for me, as my action (the one defined in action attribute for the form) isn't called when loading the jsp (can't really explain this either, the menu and pages are defined in an xml file). I don't understand how to specify the second action in my jsp, and how to make sure that the action is called when first loading the jsp. I would prefer a solution not involving AJAX, if possible. Thanks.

A: Why do you want to go for AJAX, when you have the power of Struts. I have a simple example (it is tested) for you.
MyForm.java
    package com.tusar.action;

    import java.io.Serializable;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.http.HttpServletRequest;

    public class MyForm extends ActionForm implements Serializable{

        private static final long serialVersionUID = 1043346271910809710L;
        private String fullName = null;

        public String getFullName() {
          return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        /*This method will be called when you press the reset button
              or load the form. You may want to populate the form here also*/

        public void reset(ActionMapping mapping, HttpServletRequest request){
        String reset = (String)request.getAttribute("myForm.reset");
            if ((null != reset)|| ("true".equals(reset))) {
                fullName = null;
            }
        }
    }

MyFormSetupAction.java
    package com.tusar.action;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    public class MyFormSetupAction extends Action{

        /*Set your form-bean properties here*/

        @Override
        public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
            MyForm hwForm = (MyForm) form;
            hwForm.setFullName("tusar");
            return mapping.findForward("success");
        }

    }

MyFormSuccessAction.java
package com.tusar.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class MyFormSuccessAction extends Action{

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        return mapping.findForward("success");
    }

}

struts-config.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>

    <!DOCTYPE struts-config PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
      "http://struts.apache.org/dtds/struts-config_1_3.dtd">

     <struts-config>

     <form-beans>
     <form-bean name="myForm" type="com.tusar.action.MyForm">
     <form-property name="fullName" type="java.lang.String"/>
     </form-bean>

     <global-forwards>

     <forward name="home" path="/home.do"/>
     </global-forwards>

     <action-mappings>

     <action path="/home"
        type="com.tusar.action.MyFormSetupAction"
        name="myForm"
        validate="false"
        input="/WEB-INF/jsp/home.jsp">

        <forward name="success" path="/WEB-INF/jsp/home.jsp" />
     </action>

     <action path="/successAction"
         type="com.tusar.action.MyFormSuccessAction"
         name="myForm"
         validate="true"
         input="/WEB-INF/jsp/home.jsp">

        <forward name="success" path="/WEB-INF/jsp/success.jsp" />
     </action>

     </action-mappings>

     <message-resources parameter="MessageResources" />

     </struts-config>

home.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false"%>

<title>Struts 1</title>

    Name:

success.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false"%>

<title>Successful !</title>

Your details:

    Name:

    <bean:write name="myForm" property="fullName" />

Everytime you call the home.do action, the fullName property is populated with "tusar". Just comment if you need any further association, I'll be happy to help you. Thanks!

A: There should be an action called when selecting the user. The properties of that user should be copied into the action form before returning the action forward.
Without any configuration information it's difficult to help beyond that.


text:
Q: Coordinate of a graphics object in java My question is: how to find the coordinate of a graphic object that are drawn on a buffered image?
for example: I have a rectangle drawn on screen by using BufferedImage. So when I rotate it by using affine transform, the coordinate of the top left corner is stay the same because AffineTransform rotate the axis of that BufferedImage.
So how can I find the coordinate of the rectangle after rotating at its centre?
Thank in advanced!


text:
Q: Removing strings from a list dependent on their length? I am trying to remove any strings from this list of strings if their length is greater than 5. I don't know why it is only removing what seems to be random strings. Please help. The item for sublist part of the code just changes the list of lists, into a normal list of strings.
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist]
var=0
for words in li:
if len(li[var])>5:
    li.pop()
var+=1
print(li)

The output is: ['name', 'number', 'continue', 'stop', 'signify']

A: Just include the check when flattening the list:
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist if len(item) <= 5]

['name', 'stop', 'racer']

A: You can use a list comprehension to build a new list with only items that are 5 or less in length.
>>> l = ['123456', '123', '12345', '1', '1234567', '12', '1234567']
>>> l = [x for x in l if len(x) <= 5]
>>> l
['123', '12345', '1', '12']

A: list(filter(lambda x: len(x[0]) <= 5, list2))


text:
Q: Hibernate named query re-parsed We are using hibernate named query as follows :
named_query :   Select this_  from  TableA this_  where this_.id  in( select max(id) from TableA where COLA is null group by COLB ) and rownum=1
Query query = getNamedQuery("nq.select.DirtySubject.onMaxDirtySubjectRecId");
List<SomeObject>  objectList       = query.list();

The query has been flagged by the DBAs and the comments verbatim are as follows

These indicate the SQL statements that are consuming the most parsing
  resources every time they execute.
  The SQL statements that appear in
  this report are probably being reparsed. Excessively-parsed SQL
  statements should be optimized to reduce their parsing frequency. This
  involves using bind variables and identical statement syntax and case,
  in order to be able to reuse any previously-parsed statements in the
  SQL cache.
  Examine these queries to see if any SQL optimization is
  possible and reasonable.

Other material facts:
This query is part of a polling logic and gets fired repeatedly.
Database:Oracle 11G
Technology stack : Java,Hibernate,Tomcat,Linux,Oracle 11G
Questions:
1: Behind the scene- Hibernate will be using Prepared statement - correct ?
2: What can we possibly do more from the application side - to avoid re-parsing of this query ?
3: Anything we can do on the Database server to avoid re-parsing ?

A: The comment talks about parsing resources (in contrast to execution time/resources), but the statement itself does not really look that difficult to parse. The most interesting information would be the execution plan. I assume that the query is always the same (but the comment contains the word "probably").
As for question 1:
If you want to make sure that prepared statements do help, you can try to run the same query without Hibernate - just plain java.sql, PreparedStatement.
If so, there is a Hibernate prepared statement cache, but I have never used it.
As for question 2:
If this is your hotspot, you can use "direct SQL" with Hibernate (if it and your connection pool allows the caching of prepared statements) or even without it: Then you have full control.
As for question 3: Have a look on Oracle 11g result cache.


text:
Q: How to know if song available in a country or not How can I find out if a song is available in a country or not so I can enable/disable features of my app based on this information using the Android Spotify SDK or web API.

A: Have to use the web-api
I found this forum post that helped me find the answer on a forum post in quora with the title "What website lists Spotify music availability per country"
I would have linked it but I don't have enough reputation to post more than 2 links.
Go to for an explanation of the features available through the web-api
https://developer.spotify.com/web-api/migration-guide/
Can test looking up track availability at this link
https://developer.spotify.com/web-api/console/get-track/#complete

A: I found web api to solve your problem that provide you a country code,
have look this https://github.com/spotify/web-api/issues/535 link, this link provide you available_markets
https://labs.spotify.com/2015/03/09/understanding-spotify-web-api/
Parse JSON object with multiple levels Android


text:
Q: How do you log Console output from a subprocess launched with Start-Process? If I have a script like this
sillyscript.ps1
Start-Process ping.exe -ArgumentList www.google.com -NoNewWindow -Wait
And I run it, I will see the ping instructions print out to the console, but if I run.
.\sillyScript.ps1 > log.txt
Nothing gets written to log.txt
I tried the following without success as well
.\sillyScript.ps1 | Out-File log.txt

A: You could workaround this like so:
Start-Process ping.exe -NoNewWindow -Wait -RedirectStandardOutput sillyscript.log

Or:
powershell.exe .\sillyscript.ps1 > sillyscript.log


text:
Q: Regular expression for Japanese char with Alphabets I want to add a Validation Rule to validate the Text either it should be any one of the following rules

*

*Japanese character (Any Japanese letter) => 北海道

*Alphabets (A-Z) => Kantname

*Japanese character with Alphabets =>   北海道AB

I written the below Regular Expression but its not working as expected
/^[a-zA-Z]+$|[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;

If I tried the below its returning TRUE
console.log(pattern.test('北海道 <script>'));

A: You are using anchors in a wrong way: you need to merge all character classes into one single class and apply anchors to this superclass:
/^[a-zA-Z\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\u2605-\u2606\u2190-\u2195\u203B]+$/

See the regex demo

var re = /^[a-zA-Z\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\u2605-\u2606\u2190-\u2195\u203B]+$/;
var strs = ['北海道AB', 'Kantname', '北海道', '北海道 <script>'];

for (var s of strs) {
  if (re.test(s)) {
    console.log(s, " matches the regex");
  } else {
    console.log(s, " does NOT match the regex");
  }
}


text:
Q: Applications installed on another hard disk Here is my setup: I have three hard disks, one for Windows 10 (SSD, C:), one for my documents (HDD, D:) and another HDD for my applications (F:, ranging from Microsoft office to Steam games, FTP clients ...)
I want to reinstall windows, so I am going to format my SSD and install a clean Windows 10.
Is there any way I can mount D:\ to "my documents" and F:\ to "Program Files" as if these applications have been installed in the "new" Windows using the installer , and can I keep these applications' preferences & data from the "old" Windows ?

A: Any application that you install will have to be installed again. If you install it to a different location in the new windows, that does not matter.
Make sure you backup your profile entirely, including the AppData folder. This'll be where most of your settings are.
Do note that if you want, you can reset windows to a fresh state, and choose to keep your files. This will ensure that everything you need to backup will be moved to a folder windows old.
To do this, open start and search for Refresh Windows.

A: (IMPORTANT: read the second half!)

Is there any way I can mount D:\ to "my documents" and F:\ to "Program Files"

Yes, that is possible. Go to "Disk Management" (search for "Computer Management" in start menu, it is in there). Right-click the drive (technically I should say "partition") you want to mount and choose "Change Drive Letter and Paths..."

After that click the Add-button and in the window that pops up you can select a path to mount it on:

Optionally you can remove the drive-letter, since you don't really need it any more.

Having said all this: I am not so sure it is a smart idea to do this. Maybe if you did this from the very beginning, but now there is both data on that drive and in the "My Documents"/"Program Files" folder and the drive. No matter what you do, if you (re)install windows, there will always be data there. And as you can see in the latest screenshot, the folder you want to mount to HAS to be empty (makes sense right?)
So I suggest just not doing it and just whenever you install a program install it in your other drive (at least, that's what I'm doing) that way I can also choose to install a program on my SSD if I want to (for some programs/games it gains quite a bit of performance, and I didn't buy an SSD to put absolutely nothing on it ^^)
And for "My Documents": I know there is a way to tell windows to use an other location for that, I don't know how to do it off the top of my head, but I know for sure that is possible. (If not I have a reaaaly weird memory....)
P.S. don't mind me having windows classic theme

A: When you format the Windows partition, you'll lose the registry.  Missing registry entries will render most applications unusable -- there's actually a term for programs that work anyway, xcopy install.  In addition to COM registrations, many user preferences are stored in the registry.
You can attempt to export parts of the registry and restore them to the new system, but that defeats the purpose of having a clean Windows install, and the only reliable way to preserve registry content is to do an upgrade (not clean) install anyway.


text:
Q: Remove underline for Drilldown labels How do you remove the underlined data labels for a drilldown pie chart in Highcharts? Adding:
textDecoration: 'none'

to the dataLabels doesn't seem to work

A: text {
    text-decoration: none !important;
}

will work.
here's your fiddle: http://jsfiddle.net/jkn79qut/
Edit: This answer is better by the way - if you can avoid polluting your css with !important, you should.

A: Style for active axis label is set through drilldown.activeAxisLabelStyle
$('#container').highcharts({
    drilldown: {
        activeAxisLabelStyle: {
            textDecoration: 'none',
...

API: http://api.highcharts.com/highcharts#drilldown.activeAxisLabelStyle
Demo: http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/drilldown/labels/

A: Actually, it's "activeDataLabelStyle" the parameter to change.
drilldown: {
        activeAxisLabelStyle: {
            textDecoration: 'none',
            fontStyle: 'italic'
        },
        activeDataLabelStyle: {
            textDecoration: 'none',
            fontStyle: 'italic'
        },
        series: [{.....

jsfiddle
Regards,

A: I don't know to do it the "highcharts" way, but you can do it in CSS with this:
text {
    text-decoration: none !important;
}

The chart has inline code giving it text-decoration: underline;, so you need the !important hack to override it, in this case.
Updated JSFiddle
Here's an embedded example:

$(function () {
    // Create the chart
    $('#container').highcharts({
        chart: {
            type: 'pie'
        },
        title: {
            text: 'Browser market shares. January, 2015 to May, 2015'
        },
        subtitle: {
            text: 'Click the slices to view versions. Source: netmarketshare.com.'
        },
        plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    format: '{point.name}: {point.y:.1f}%'
                }
            }
        },

        tooltip: {
            headerFormat: '{series.name}
',
            pointFormat: '{point.name}: {point.y:.2f}% of total
'
        },
        series: [{
            name: "Brands",
            colorByPoint: true,
            data: [{
                name: "Microsoft Internet Explorer",
                y: 56.33,
                drilldown: "Microsoft Internet Explorer"
            }, {
                name: "Chrome",
                y: 24.03,
                drilldown: "Chrome"
            }, {
                name: "Firefox",
                y: 10.38,
                drilldown: "Firefox"
            }, {
                name: "Safari",
                y: 4.77,
                drilldown: "Safari"
            }, {
                name: "Opera",
                y: 0.91,
                drilldown: "Opera"
            }, {
                name: "Proprietary or Undetectable",
                y: 0.2,
                drilldown: null
            }]
        }],
        drilldown: {
            series: [{
                name: "Microsoft Internet Explorer",
                id: "Microsoft Internet Explorer",
                data: [
                    ["v11.0", 24.13],
                    ["v8.0", 17.2],
                    ["v9.0", 8.11],
                    ["v10.0", 5.33],
                    ["v6.0", 1.06],
                    ["v7.0", 0.5]
                ]
            }, {
                name: "Chrome",
                id: "Chrome",
                data: [
                    ["v40.0", 5],
                    ["v41.0", 4.32],
                    ["v42.0", 3.68],
                    ["v39.0", 2.96],
                    ["v36.0", 2.53],
                    ["v43.0", 1.45],
                    ["v31.0", 1.24],
                    ["v35.0", 0.85],
                    ["v38.0", 0.6],
                    ["v32.0", 0.55],
                    ["v37.0", 0.38],
                    ["v33.0", 0.19],
                    ["v34.0", 0.14],
                    ["v30.0", 0.14]
                ]
            }, {
                name: "Firefox",
                id: "Firefox",
                data: [
                    ["v35", 2.76],
                    ["v36", 2.32],
                    ["v37", 2.31],
                    ["v34", 1.27],
                    ["v38", 1.02],
                    ["v31", 0.33],
                    ["v33", 0.22],
                    ["v32", 0.15]
                ]
            }, {
                name: "Safari",
                id: "Safari",
                data: [
                    ["v8.0", 2.56],
                    ["v7.1", 0.77],
                    ["v5.1", 0.42],
                    ["v5.0", 0.3],
                    ["v6.1", 0.29],
                    ["v7.0", 0.26],
                    ["v6.2", 0.17]
                ]
            }, {
                name: "Opera",
                id: "Opera",
                data: [
                    ["v12.x", 0.34],
                    ["v28", 0.24],
                    ["v27", 0.17],
                    ["v29", 0.16]
                ]
            }]
        }
    });
});
text {
    text-decoration: none !important;
}

Browser Version Total Market Share
Microsoft Internet Explorer 8.0 26.61%
Microsoft Internet Explorer 9.0 16.96%
Chrome 18.0 8.01%
Chrome 19.0 7.73%
Firefox 12 6.72%
Microsoft Internet Explorer 6.0 6.40%
Firefox 11 4.72%
Microsoft Internet Explorer 7.0 3.55%
Safari 5.1 3.53%
Firefox 13 2.16%
Firefox 3.6 1.87%
Opera 11.x 1.30%
Chrome 17.0 1.13%
Firefox 10 0.90%
Safari 5.0 0.85%
Firefox 9.0 0.65%
Firefox 8.0 0.55%
Firefox 4.0 0.50%
Chrome 16.0 0.45%
Firefox 3.0 0.36%
Firefox 3.5 0.36%
Firefox 6.0 0.32%
Firefox 5.0 0.31%
Firefox 7.0 0.29%
Proprietary or Undetectable 0.29%
Chrome 18.0 - Maxthon Edition 0.26%
Chrome 14.0 0.25%
Chrome 20.0 0.24%
Chrome 15.0 0.18%
Chrome 12.0 0.16%
Opera 12.x 0.15%
Safari 4.0 0.14%
Chrome 13.0 0.13%
Safari 4.1 0.12%
Chrome 11.0 0.10%
Firefox 14 0.10%
Firefox 2.0 0.09%
Chrome 10.0 0.09%
Opera 10.x 0.09%
Microsoft Internet Explorer 8.0 - Tencent Traveler Edition 0.09%


text:
Q: unable to encrypt message in matrix-js-sdk I'm used 'olm' version '3.1.4' and 'matrix-js-sdk' version '2.4.6'
Trying use end to end encryption supported in matrix using olm
I'm using the following code snipping:
    const cryptoStore = new sdk.MemoryCryptoStore(window.localStorage);
         const webStorageSessionStore = new sdk.WebStorageSessionStore(window.localStorage);
         var matrixStore = new sdk.MatrixInMemoryStore();

         matrixClient = sdk.createClient({
           baseUrl: 'SERVER_HOME',
           accessToken: token,
           userId: 'USER_ID',
           store: matrixStore,
           sessionStore: webStorageSessionStore,
           cryptoStore: cryptoStore,
           deviceId: 'DEVICE_ID'});

matrixClient.initCrypto()
       .then(() => {
         matrixClient.startClient({ initialSyncLimit: 10 });
       })

1- I have error with post key/upload API bad request
REQUEST: POST Request URL: https://SERVER_HOME/_matrix/client/r0/keys/upload/DEVICE_ID?access_token=XXXX

RESPONSE: 400 Bad Request {"errcode":"M_UNKNOWN","error":"One time key signed_curve25519:XXXX already exists. Old key: {\"key\":\"64zJVMH61Toei8Kaz2SRXEZ4VyNBjjG2vfaGjSXXXX\",\"signatures\":{\"@USER_ID\":{\"ed25519:869254020336060\":\"HBnlhazYGY+IrvImq5d4OcIYsXeo094St2p/SMYWobMfteML1gH1jMSUmAh9o7EYIXQMnshiPSh6FSdL4XXXXw\"}}}; new key: {'key': 'VSfPQ7NFzdPl0owA1pVK8CqTzLCyF6NQCuS8aTIIYmc', 'signatures': {'@USER_ID': {'ed25519:869254020336060': 'rIQHea/3kh5w8PaC91H83zsTKQDevbkPpnJ5Dpj7YHv3o4Jzq1O3AmgMzfhFzhlXBwn1N6gRPfC+jNMCIPXXXX'}}}"}

2- When I test it with encryption Roit room and try to send message from sdk to Roit find this is error get this error
Error sending event UnknownDeviceError: This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.

3- When I test it with encryption Roit room and send message from Roit to sdk I get this error
Error decrypting event (id=xxxx): DecryptionError[msg: The sender's device has not sent us the keys for this message., session: FoIZTb4W906iFiQofhzgyZlkjeR9XazjN9vfIC9uzFQ|nCwWvT+VU/FVz7uNLojW51+PtkrXj++eMC1d/Xxxxxxx]


text:
Q: hibernate-ogm-ignite-5.3.1.Final start ignite failed. Can not perform the operation because the cluster is inactive Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: igniteWithJpa] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:895)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at org.hibernate.ogm.jpa.HibernateOgmPersistence.createEntityManagerFactory(HibernateOgmPersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.ignite.jpa.MainIgnite_jpa.StartApp.main(StartApp.java:17)
Caused by: org.hibernate.HibernateException: OGM001709: Unable initialize cache 'Department'
at org.hibernate.ogm.datastore.ignite.impl.IgniteCacheInitializer.initializeEntities(IgniteCacheInitializer.java:85)
at org.hibernate.ogm.datastore.ignite.impl.IgniteCacheInitializer.initializeSchema(IgniteCacheInitializer.java:63)
at org.hibernate.ogm.service.impl.SchemaDefiningObserver.sessionFactoryCreated(SchemaDefiningObserver.java:42)
at org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:374)
at org.hibernate.ogm.boot.impl.OgmSessionFactoryBuilderImpl.build(OgmSessionFactoryBuilderImpl.java:55)
at org.hibernate.ogm.boot.impl.OgmSessionFactoryBuilderImpl.build(OgmSessionFactoryBuilderImpl.java:23)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
... 5 more
Caused by: class org.apache.ignite.IgniteException: Can not perform the operation because the cluster is inactive. Note, that the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes join the cluster. To activate the cluster call Ignite.active(true).
at org.apache.ignite.internal.IgniteKernal.checkClusterState(IgniteKernal.java:3749)
at org.apache.ignite.internal.IgniteKernal.cache(IgniteKernal.java:2746)
at org.hibernate.ogm.datastore.ignite.impl.IgniteDatastoreProvider.getCache(IgniteDatastoreProvider.java:105)
at org.hibernate.ogm.datastore.ignite.impl.IgniteDatastoreProvider.getEntityCache(IgniteDatastoreProvider.java:99)
at org.hibernate.ogm.datastore.ignite.impl.IgniteCacheInitializer.initializeEntities(IgniteCacheInitializer.java:76)
... 12 more


text:
Q: Power Series Method on Heat Equation I'm interested in solving the heat equation: d[K[z] d[T[z],z],z]=0, equipped with T(-h/2)=Tm and T(h/2)=Tc.
Is it possible to get a symbolic solution in Mathematica using the power series method?
The solution they provide in literature is attached in the picture.
Where: K(z)=Km+(Kc-Km)(1/2+z/h)^n

A: As mentioned in comment, neither Maple nor Mathematica can solve the heat pde analytically with the $K$ coefficient (thermal conductivity of the material) as function of space. Mathematica can solve it for scalar $k$ which I show below so you can use if you want to try for yourself.
Heat PDE depends on time and space. You have not said what the initial conditions are. Assuming $u(x,0)=f(x)$ then
ClearAll[u, x, t, Tm, Tk, h, f, n, z, k];
pde = D[u[z, t], t] == k*D[u[z, t], {z, 2}]
bc = {u[-h/2, t] == Tm, u[h/2, t] == Tc}
ic = u[z, 0] == f[z]
sol = DSolve[{pde, bc, ic}, u[z, t], {z, t}, Assumptions -> {h > 0, t > 0, k > 0}];

In the steady state (which you showed), i.e. as $t \to \infty$ then we see due to the term $e^{-\frac{\pi ^2 t K[1]^2}{h^2}}$ it will go to zero. Hence the sum term vanish and the solution at steady state solution $u(z,t)$ becomes
$$
  u(z,\infty) =T_m-\frac{\left(-\frac{h}{2}-z\right) (T_c- T_m)}{h}
$$
This does not match what you showed, but $k$ used here is not function of space.
May be Mathematica in next version could solve the heat pde with $k$ function of space.
If you try to make $k$ function of space, then Mathematica can not solve it
ClearAll[u, x, t, Tm, Tk, h, f, n, z, k];
pde = D[u[z, t], t] == k[z]*D[u[z, t], {z, 2}]
bc = {u[-h/2, t] == Tm, u[h/2, t] == Tc}
ic = u[z, 0] == f[z]
sol = DSolve[{pde, bc, ic}, u[z, t], {z, t}, Assumptions -> {h > 0, t > 0}];


text:
Q: Object oriented programming vs. the split function... which is better? here is the non-oop way of doing it:
When someone presses a day on a calendar, we need to find out the day, and path. Here is the non-oop way of storing that information:
A string was created with a "-" delimiter between each piece of info we need, like this:
 12-c:\files\john_doe.png

Then it was stored in an array. However, to retrieve the data, we then use the "split" function like this.
for (int t = 0;t < day_and_path.length;t++)

{
String[] day_from_db = day_and_path[t].split("-");
String day_db = day_from_db[0];
String path_db = day_from_db[1];

However the OOP way is, make a class with properties: day, path. Then store them into an array of objects.
Which way is better and why?

A: If you use String#split, you'll be dealing with an array of strings. If all you do is assign the strings to local variables, then there is no point in making a class for that.
If you want to hold on to the string parts and pass them around to other methods, then it begins to make sense to have an object which will conveniently encapsulate those strings.


text:
Q: Only able to run DinD containers in detached mode I am trying to setup a docker container that runs docker as a jenkins slave.
docker run -d --privileged jenkinsdockerdockerslave

When I try to kick it off like this
docker run -ti --privileged jenkinsdockerdockerslave

Here are the errors:
ERRO[0000] There are no more loopback devices available.
FATA[0000] Error starting daemon: error initializing graphdriver: loopback mounting failed

The CMD from the Dockerfile is CMD[/jenkins-slave-start.sh]
Why would one work but not the other?

A: I when with DooD Docker outside of Docker


text:
Q: "Location is not set" JavaFX Tenho estudado javafx recentemente e fiquei travado ao escrever um código bem simples para abrir um arquivo .fxml, segue o código e o erro respectivamente, procurei pela internet e já tentei a solução proposta no stackoverflow americano, e mesmo assim o problema persiste, alguém sabe como conserto isso? Obrigado!
Obs. Perdoem a minha formatação, é minha primeira vez postando aqui.

package projeto;

public class MainApp extends Application {
    private Stage primaryStage;
    private static BorderPane rootLayout;

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("CineTudo");

    initRootLayout();

    showFilmeOverview();
}

public void initRootLayout(){
    try {
        //Carrega o layout root do arquivo fxml
        FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("/fxml/RootLayout.fxml"));
        rootLayout = (BorderPane) loader.load();

        Scene cena = new Scene(rootLayout);
        primaryStage.setScene(cena);
        primaryStage.show();
    } catch(IOException e) {
        e.printStackTrace();

    }
    }
    public static void showFilmeOverview() {

    try {

        FXMLLoader loader = new FXMLLoader(MainApp.class.getClassLoader().getResource("/fxml/FilmeOverview.fxml"));
        AnchorPane filmeOverview = (AnchorPane) loader.load();
        rootLayout.setCenter(filmeOverview);
    }catch (IOException e){

        e.printStackTrace();
    }

    }
    public Stage getPrimaryStage() {
        return primaryStage;
    }
}

Exception in Application start method
    java.lang.reflect.InvocationTargetException
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
      at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
  Caused by: java.lang.RuntimeException: Exception in Application start method
      at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
      at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
      at java.lang.Thread.run(Thread.java:748)
  Caused by: java.lang.IllegalStateException: Location is not set.
      at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
      at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
      at projeto.MainApp.initRootLayout(MainApp.java:34)
      at projeto.MainApp.start(MainApp.java:25)
      at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
      at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
      at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
      at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
      ... 1 more
  Exception running application projeto.MainApp

A: Para carregar um .fxml certifique-se de informar o caminho deste arquivo relativo à pasta src do projeto. O exemplo abaixo considera que dentro da pasta src possui as seguintes subpastas que contém o arquivo .fxml: br/com/view.
public class MainApp extends Application {
    ...
    public void initRootLayout(){
        try {
            String caminhoPagina = "/br/com/view/FilmeOverview.fxml";
            Parent root = FXMLLoader.load(getClass().getResource(caminhoPagina));
            ...
        }
        ...
}

Espero ter ajudado.


text:
Q: How can I determine a state with a given zip code in Stata? Currently, my line of code is really long and I was curious to know if there was a more efficient way of doing this.

A: As Nick has pointed out your question is missing most of the information that would make it answerable. Please read more here, and add more information to your question.
In the meantime, a useful approach is to merge your zipcode data with a dataframe (or dataset) with the state-zipcode link in it.
* first you need to get the zipcode data from somewhere.
* Here is one way:
!wget "https://www2.census.gov/geo/docs/maps-data/data/rel/zcta_county_rel_10.txt"

* now put this data in a frame
frame create zctaFrame
frame zctaFrame{
    import delimited "zcta_county_rel_10.txt"
}

* now I'm making up a dataset (share some of yours with dataex from ssc

input str10 name zip
"sam" 55901
"sasha" 84101
"saul" 84111
end

frlink 1:1 zip, frame(zctaFrame zcta5)
frget state, from(zctaFrame)

If this doesn't match what you're trying to do, please add more detail to the question.


text:
Q: Error with XP-PEN G430S tablet on Ubuntu I'm using a XP-PEN G430S tablet on Ubuntu and I've noticed the following error:

*

*When I plug it into my notebook, the usb mouse (which is already plugged in) becomes dead; it resumes working after plugging the tablet out and plugging the mouse out and in again. However, the touchpad of the notebook works well.

So, it seems that the two input devices cannot coexist. Why is that? Is it a problem with the driver installation?


text:
Q: Python: What is the best structure that allows functions to access information across calls I'm currently writing an agent function that is designed to compete in competition and will get called every turn to perform a series of moves. There is data that I'd like to save between turns (calls of the function).
My question is what is the best way to store this data so that my function can access it between calls without having to recompute it every call. I was thinking about making a global class object that would store everything I needed, but suspected there might be other ways.
To give an example, let's say I want to store a long list that took a bit of time to compute inside that function, where can I put/store that list so that I can access it again the next time the function is called, without having to recompute it.

A: You seem to be onto the right track. Why not create an object class, make instances of it to store different 'save data', and see how it goes?
class saveFile:
    def __init__(self, data):
        self.data = data

def main():
    data = something.compute() #whatever that took a bit of time to compute...
    #create an instance of a saveFile class object
    file_1 = saveFile(data)
    #to recall the data in the form of file_1.data
    print(file_1.data)

A: There are two straightforward solutions, if I understand the question correctly. You can use a closure--an inner function--so you can do your preprocessing of your data and return a function that has access to it in its scope.
Here, with a rather silly example of an accumulated sum that you can initialise when you create the closure:
def make_acc_sum(init_elements):
    # initial preprocessing
    s = sum(init_elements)

    # function that knows the preprocessed data
    def acc_sum(new_val):
        nonlocal s
        s += new_val
        return s

    return acc_sum

ac = make_acc_sum([1, 2, 3])
for i in range(5):
    print(ac(i))

This is a fine technique in many applications, when you don't want to do too much with the data in the enclosing scope. If you just want to access it when invoking a function and nothing more, it can handle your needs.
If you want your "function" to support more general manipulation of your pre-processed data, you can turn it into an object. Objects from a class that implements __call__ can be called just as functions can:
class acc_sum:
    def __init__(self, init_elements):
        # initial preprocessing
        self.s = sum(init_elements)

    def __call__(self, new_val):
        # function that knows the preprocessed data
        self.s += new_val
        return self.s

ac = acc_sum([1, 2, 3])
for i in range(5):
    print(ac(i))

but this version of ac is still an object that can have attributes and additional methods on it, so you can do more with it than you can with a plain closure (even though the example doesn't exploit that).


text:
Q: Locate command can't find anything inside Documents folder on mac As it says in the description. I first check our database is up to date
mh547:bin crashandburn4$ sudo /usr/libexec/locate.updatedb
Password:       #password entered and function executed without errors

I then try and search for something inside my Documents folder
mh547:bin crashandburn4$ cd ~/Documents/
mh547:Documents crashandburn4$ ls
    Mamp_workspace/                         Scenarios.docx                          gc01/
mh547:Documents crashandburn4$ locate Scenarios.docx    #nothing returned

I then try another random folder:
mh547:Documents crashandburn4$ cd ..
mh547:~ crashandburn4$ ls
    Applications/                Movies/                      drawable/                    untitled-2.pdf
    Desktop/                     Music/                       drawable-xhdpi/              untitled-2.synctex.gz
    Documents/                   Pictures/                    dwhelper/                    untitled-2.tex
    Downloads/                   Public/                      linux_ssh*                   website-terminal-copy-paste
    Dropbox/                     Samsung/                     scripts/                     workspace/
    Google Drive/                Sites/                       untitled-2.aux               workspace_copy_to_linux*
    Library/                     android-sdks/                untitled-2.log
mh547:~ crashandburn4$ locate website-terminal-copy-paste
/Users/crashandburn4/website-terminal-copy-paste #correct result returned

can anyone help me? I've been stuck on this for a good half hour or so.

A: It's because your Documents-folder isn't world readable, which is a good thing, specially on shared systems.
The BUGS section of the locate(1) man-page explains it:

The locate database is typically built by user ''nobody'' and the
  locate.updatedb(8) utility skips directories which are not readable
  for user ''nobody'', group ''nobody'', or world.  For example, if your
  HOME directory is not world-readable, none of your files are in the
  database.

Try running ls -ld ~/Documents and you'll see the permissions. Wikipedia have an article on Unix permissions if you are unfamiliar with these.

A: As pointed out by plundra, that's because the locate OSX ships with is old and crippled and doesn't index and/or report files which are not readable by nobody, even when run as root. What you can do though is either install homebrew and then GNU locate, or, as suggested here use mdfind -name instead (I don't have an OSX box at hand to test this).

A: You can do sudo ln -s /usr/libexec/locate.updatedb /usr/local/bin/updatedb to make the updatedb command available


text:
Q: How many possibilities are there to distribute $8$ students to $5$ round tables, if minimum $1$ student sits at each table? How many possibilities are there to distribute $8$ students to $5$ round tables, if minimum $1$ student sits at each table? It is irrelevant, which table is allocated to which group.
I think that there are $3$ possible distributions:
1) 4-1-1-1-1
2) 3-2-1-1-1
3) 2-2-2-1-1
So I have for the first case (I divide by $4$ because the table is round so I have to remove the renundant possibilities):
$Perm_4(8) \cdot \frac{1}{4} = \frac{8!}{(8-4)!} \cdot \frac{1}{4}$
second case:
$Perm_3(8) \cdot \frac{1}{3} \cdot Perm_2(5) \cdot \frac{1}{2} = \frac{8!}{(8-3)!} \cdot \frac{1}{3} \cdot \frac{5!}{(5-2)!} \cdot \frac{1}{2}$
third case:
$Perm_2(8) \cdot \frac{1}{2} \cdot Perm_2(6) \cdot \frac{1}{2} \cdot Perm_2(4) \cdot \frac{1}{2} = \frac{8!}{(8-2)!} \cdot \frac{1}{2} \cdot \frac{6!}{(6-2)!} \cdot \frac{1}{2} \cdot \frac{4!}{(4-2)!} \cdot \frac{1}{2}$
so in sum:
$ \frac{8!}{(8-4)!} \cdot \frac{1}{4} + \frac{8!}{(8-3)!} \cdot \frac{1}{3} \cdot \frac{5!}{(5-2)!} \cdot \frac{1}{2} + \frac{8!}{(8-2)!} \cdot \frac{1}{2} \cdot \frac{6!}{(6-2)!} \cdot \frac{1}{2} \cdot \frac{4!}{(4-2)!} \cdot \frac{1}{2} = 4060$
which is wrong. The correct solution is $1960$. How can I achieve that?


text:
Q: Unable to 'relative import' a local Python library using a symbolic link My project has two main folders: sourceCode and lib: Highlighted file tree here
I'm working in \sourceCode\mainFile.ipynb and would like to import a library residing in lib called modifiedLibrary, which has an __init__.py file.
Currently, I'm using a symbolic link for relative-importing the library. The symbolic link is located in \sourceCode and called sym_link with the following content:
../lib/modifiedLibrary/modifiedLibrary

In the project, the library and the symbolic link have the same name.
but when I import in python using
import modifiedLibrary

I receive ModuleNotFoundError: No module named 'modifiedLibrary'
I understand that the same code functions on another device that I do not have access to right now, and I do not seem to find what the issue is.
I successfully included the needed library by:

*

*changing the working directory temporarily to where the library's __init__.py is located,

*importing the library

*then reverting back to my original directory

but I would like to know what the issue is with the current symbolic link.
Windows 10 / Python 3.7.3 / Jupyter
Relevant Question: Interactive Python - solutions for relative imports

A: The other solution I found, rather than changing the working directory temporarliy to include a local module, was to add the location of the module on my device to sys.path before importing it:
import sys
sys.path.append('C:/Users/user/myProject/../modifiedLibrary/')

import modifiedLibrary

It doesn't make use of the symbolic link but it seems to do the trick for now. Would be an issue when the code is shared and ran on another device.


text:
Q: Why HTML file that I got from Google Translate using my script, is different from what I really want? I want to make a web scraper that will automatically take the translation of a word from Google Translate, in my console environment using my python script.
I saw that HTML code which I got from python Requests module, is very different from what it is on the website, you can see the differences.
After some researches about this subject, I learned from this answer that Google has some security features that won't let me have access to its HTML contents using my scripts.
But I have a chrome extension ImTranslator, which can give me translate of whatever word I selected from a web page, directly from Google Translate.
So, how this extension can do this?! Why I can't have a script that will do this for me?
I also tried using urllib for making requests and sending headers with my request.
Also, this is my code:
First, using urllib module:
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'
}
url = 'https://translate.google.com/#view=home&op=translate&sl=en&tl=fa&text=space'
req = urllib.request.Request(url, None, headers)
respone = urllib.request.urlopen(req)

Second, using Requests:
url = 'https://translate.google.com/#view=home&op=translate&sl=en&tl=fa&text=space'
res = requests.get(url)

A: You can use googletrans module of Python to translate some text through free API.
But if you want to scrape the Google Translate then you can do the following
import requests_html
from bs4 import BeautifulSoup as BS

url = "https://translate.google.com/#view=home&op=translate&sl=en&tl=hy&text={}"

text = input("text: ")

with requests_html.HTMLSession() as session:
    response = session.get(url.format(text))
    response.html.render()
    content = response.html.html
    soup = BS(content, "html.parser")
    translation = soup.find("span", "translation").text
    print(translation)

Using asynchronous programming
import asyncio
import pyppeteer
from bs4 import BeautifulSoup as BS

URL = "https://translate.google.com/#view=home&op=translate&sl=en&tl=hy&text={}"

async def main() -> None:
    text = input("text to translate: ")
    browser = await pyppeteer.launch(headless=True)
    page = await browser.newPage()
    await page.goto(URL.format(text))
    html = await page.content()
    soup = BS(html, "html.parser")
    tranlation = soup.find("span", "translation").text
    print(tranlation)
    await browser.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()


text:
Q: bin/dev: 8: exec: foreman: not found Hello I am currently following a tutorial in order to connect react to my rails app that uses https://github.com/rails/jsbundling-rails and went with esbuild, however when I run bin/dev in my terminal I get the above error any help is appreciated as this is my first time trying to use react along with a rails app

A: You need to install foreman gem. You can install it in the terminal with this command:
gem install foreman


text:
Q: what is the function of .strip() in this code am more interested on func_input.strip and func_map.keys
why do I have to use the .strip
are there alternatives?
it actually worked for me but i just need an explanation.
thank you. Please I need an explanation for the code below
if func_input.strip() == 'exit':
        print('goodbye! ')
        exit()
if func_input.strip() in func_map.keys():
        func_map[func_input]()


text:
Q: What is the relationship between speed and torque in a separately excited DC motor? When a DC motor is powered by an external voltage source, as opposed to using shunt, series or compound configuration, how does speed relate to torque?

A: *

*No load speed is linear with Voltage

*Torque is somewhat linear with current above excitation currents.

*Since stall current is 8~10x rated load current, speed will reduce as load - increases to rated current by more than 10% beyond this exceeds the rated current with conduction losses dominating thermal rise.

*This assumes driver and power supply ESR is much lower than DCR of motor coils which is not often the case so speed drops much more than 10%.

*since max power transfer occurs when load matches available electro-mechanical power, this max power occurs at half speed

*

*but this may exceed the thermal rating of the motor.

*torque declines with rising speed due to back EMF.


text:
Q: how to make web browser in Xcode load a web page automatically I am building a web browser in Xcode cocoa application, using the interface builder. I have it all working when it comes to typing in web address and clicking go.
but I would like for it to automatically load a web page instead of seeing white when I open my project, I looked in inspector to see if you can set a specific web address but I couldn't find anything to do this.

A: How about if you load the URL that you would like in the viewdidload function:
    - (void)viewDidLoad {
    [super viewDidLoad];
 NSURL *targetURL = [NSURL fileURLWithPath:WebsitePath];
         NSURLRequest *WebRequest = [NSURLRequest requestWithURL:targetURL];
        [self.WebViewer loadRequest:WebRequest];
        self.WebViewer.scalesPageToFit = YES;
}

A: Maybe you can try to load the WebView when the application finish launching,just add the URL Request in the applicationDidFinishLauching parameter,else if your WebView is on the MainView you can add a loadingScreen that appear while the webView is loading!
Lucky!


text:
Q: Get back onto stackoverflow account I thought I was answering or helping a PHP developer and got a post ban. Thx for fixing this.

A: You're not "read only". The only thing you're prevented from doing right now is posting more answers because the ones you've posted so far have been downvoted, deleted, or not voted on at all. This block is fully automated.
Among other things, we use votes as a measure of how much the community values and trusts your input. So to get your ability to post answers reinstated, you need to get the system to trust you again. You can do this by posting questions that attract upvotes, suggesting edits to improve others' posts, and/or editing our existing answers to improve them and get other users to upvote them.
Looking at your answers, I see that you primarily post short suggestions, sometimes with a barely described link. While you make improvements to get your access re-enabled, you should strongly consider reading the following:

*

*the How to Answer page

*How can I link to an external resource in a community-friendly way?

*What can I do when getting "We are no longer accepting questions/answers from this account"?
I also suggest paying close attention to spelling, punctuation, etc. All of that matters when someone is trying to read and learn from your answers.


text:
Q: Alert in php and Mysql? I am with a code where the user connects using his username and password and what I would like to do is that once he is logged in, he will see an alert message where it says:
"Welcome + username +"
I have tried to do it in this way but it is not possible:
<?php  if (isset($_SESSION['username'])) : ?>

The alert appears but not with the message I want but with 'undefined'
However, if I don't put an alert but only a message with the corresponding username, it appears correct:
    <?php  if (isset($_SESSION['username'])) : ?>

Welcome <?php echo $_SESSION['username']; ?>

Could you help me?
Thank you

A: You are using PHP concatenation operator inside your JavaScript, you should directly write the username string in the welcome string:

To concatenate strings in JavaScript you should use +, but this is not useful in your case.
Also note that this won't be secured and you should sanitize the username to prevent XSS attacks.


text:
Q: Remove My Custom MKMapView from UIViewController I have created a custom MKMapView of size 200x200 on my UIViewController to show the path from current location to destination location. It is showing location and path. But now i want to dismiss this MKMapView and i want to see my UIViewController.
So i have created a button on the right corner of MKMapView but i am not able to remove MKMapView.
I have tried this code below on action of button.
func close() {
    mapView!.removeFromSuperview()
}

I Have declare map view like this:
    var mapView:MKMapView? = MKMapView()

then i have called a method showMap() from viewDidLoad() like this:
       func showMap() {
    //Setup our Map View
    mapView!.mapType = .Standard
    mapView!.showsUserLocation = true
    mapView!.frame = CGRectMake(topView.frame.origin.x, topView.frame.origin.y, topView.frame.size.width, topView.frame.size.height)
    mapView!.delegate = self
    view.addSubview(mapView!)
}

After this i called showCloseButtonForMap() like this:
      func showCloseButtonForMap() {
    let mapCrossBtn = UIButton()
    mapCrossBtn.frame = CGRectMake(crossBtn.frame.origin.x+20, crossBtn.frame.origin.y+20, crossBtn.frame.size.width, crossBtn.frame.size.height)
    if let image = UIImage(named: "X@2x.png") {
        mapCrossBtn.setImage(image , forState: .Normal)
    }
    mapCrossBtn.backgroundColor = UIColor.blackColor()
    mapCrossBtn.addTarget(topView, action: "close", forControlEvents: .TouchUpInside)
    view.addSubview(mapCrossBtn)
}

Here crossBtn is another button which is hidden right now.
Any help will be appreciated.
Error Log:
          Communications error:  { count = 1, contents =
    "XPCErrorDescription" =>  { length = 22, contents = "Connection interrupted" }
}>
2015-11-19 15:02:27.390 YEWADemo[2328:235956] -[UIView close]: unrecognized selector sent to instance 0x7fc6d0c32270
2015-11-19 15:02:27.408 YEWADemo[2328:235956] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView close]: unrecognized selector sent to instance 0x7fc6d0c32270'
* First throw call stack:
(
    0   CoreFoundation                      0x0000000107175f45 exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000108e9cdeb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010717e56d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x00000001070cbeea ___forwarding_ + 970
    4   CoreFoundation                      0x00000001070cba98 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x0000000107995e91 -[UIApplication sendAction:to:from:forEvent:] + 92
    6   UIKit                               0x0000000107b014d8 -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x0000000107b017a4 -[UIControl _sendActionsForEvents:withEvent:] + 311
    8   UIKit                               0x0000000107b008d4 -[UIControl touchesEnded:withEvent:] + 601
    9   UIKit                               0x0000000107a03ed1 -[UIWindow _sendTouchesForEvent:] + 835
    10  UIKit                               0x0000000107a04c06 -[UIWindow sendEvent:] + 865
    11  UIKit                               0x00000001079b42fa -[UIApplication sendEvent:] + 263
    12  UIKit                               0x000000010798eabf _UIApplicationHandleEventQueue + 6844
    13  CoreFoundation                      0x00000001070a2011 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
    14  CoreFoundation                      0x0000000107097f3c __CFRunLoopDoSources0 + 556
    15  CoreFoundation                      0x00000001070973f3 __CFRunLoopRun + 867
    16  CoreFoundation                      0x0000000107096e08 CFRunLoopRunSpecific + 488
    17  GraphicsServices                    0x000000010b993ad2 GSEventRunModal + 161
    18  UIKit                               0x000000010799430d UIApplicationMain + 171
    19  YEWADemo                            0x0000000106c2cdfd main + 109
    20  libdyld.dylib                       0x000000010c27a92d start + 1
    21  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

A: Your mapCrossBtn target should be self(which usually is current view controller), your topView without 'close' function.
Try to change:
  mapCrossBtn.addTarget(topView, action: "close", forControlEvents: .TouchUpInside)

to
mapCrossBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)