Q: Mongodb findOne - return value I need to fetch id of user from collection 'users' by calling a function and return it's value.
fetchId = (name) => {
        User.findOne({name: name}, (err, user) => {
            return user._id;
        });
    };

But this implementation returns null. What is the way to fix it?

A: following your example, if you don't want to use promises, you can simply pass a callback from the caller and invoke the callback when you have the result since the call to mongo is asynchronous.
fetchId = (name, clb) => {
  User.findOne({name: name}, (err, user) => {
    clb(user._id);
  });
};

fetchId("John", id => console.log(id));

Otherwise you can use the promise based mechanism omitting the first callback and return the promise to the caller.
fetchId = name => {
  return User.findOne({name: name}).then(user => user.id);
};

fetchId("John")
 .then(id => console.log(id));

A: A third way is a variation of suggestion #2 in @Karim's (perfectly good) answer.  If the OP wants to code it as if results are being assigned from async code, an improvement would be to declare fetchId as async and await its result...
fetchId = async (name) => {
    return User.findOne({name: name}).then(user => user.id);
};

let someId = await fetchId("John");
console.log(id)

edit
For any method on an object -- including a property getter -- that works asynchronously, the calling code needs to be aware and act accordingly.
This tends to spread upward in your system to anything that depends on caller's callers, and so on.  We can't avoid this, and there's no syntactic fix (syntax is what the compiler sees). It's physics: things that take longer, just take longer.  We can use syntax to partially conceal the complexity, but we're stuck with the extra complexity.
Applying this to your question, say we have an object representing a User which is stored remotely by mongo. The simplest approach is to think of the in-memory user object as unready until an async fetch (findOne) operation has completed.
Under this approach, the caller has just one extra thing to remember: tell the unready user to get ready before using it.  The code below employs async/await style syntax which is the the most modern and does the most to conceal -- but not eliminate :-( -- the async complexity...
class MyMongoUser {
    // after new, this in-memory user is not ready
    constructor(name) {
        this.name = name;
        this.mongoUser = null;  // optional, see how we're not ready?
    }

    // callers must understand: before using, tell it to get ready!
    async getReady() {
        this.mongoUser = await myAsyncMongoGetter();
        // if there are other properties that are computed asynchronously, do those here, too
    }

    async myAsyncMongoGetter() {
        // call mongo
        const self = this;
        return User.findOne({name: self.name}).then(result => {
            // grab the whole remote object. see below
            self.mongoUser = result;
        });
    }

    // the remaining methods can be synchronous, but callers must
    // understand that these won't work until the object is ready
    mongoId() {
        return (this.mongoUser)? this.mongoUser._id : null;
    }

    posts() {
        return [ { creator_id: this.mongoId() } ];
    }
}

Notice, instead of just grabbing the mongo _id from the user, we put away the whole mongo object.  Unless this is a huge memory hog, we might as well have it hanging around so we can get any of the remotely stored properties.
Here's what the caller looks like...
let joe = new MyMongoUser('joe');
console.log(joe.posts()) // isn't ready, so this logs [ { creator_id: null } ];
await joe.getReady();
console.log(joe.posts()) // logs [ { creator_id: 'the mongo id' } ];


Q: Overwrite data frame value I have two data frame  df and ddff
df data frame have 3 row and 5 columns
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[0,1,0,0,1], [1,0,0,1,0], [0,1,1,0,0]]))
df

     0   1   2   3   4
0    0   1   0   0   1
1    1   0   0   1   0
2    0   1   1   0   0

ddff data frame consist of neighbour columns of a particular columns which have 5 row and 3 column where the value of ddff data frame represent the column name of df
ddff = pd.DataFrame(np.array([[3,2,1], [4,2,3], [3,1,4], [4,1,2], [2,3,1]]))
ddff

    0   1   2
0   3   2   1
1   4   2   3
2   3   1   4
3   4   1   2
4   2   3   1

Now I need a final data frame where where df column neighbour's set to 1 (overwrite previous value)
expected output
    0  1  2  3  4
0   0  1  1  1  0
1   1  0  0  1  0
2   0  1  1  0  0

A: You can filter the relevant column numbers from ddff, and set the values in those columns in the first row equal to 1 and set the values in the remaining columns to 0:
relevant_columns = ddff.loc[0]
df.loc[0,relevant_columns] = 1
df.loc[0,df.columns[~df.columns.isin(relevant_columns)]] = 0

Output:
   0  1  2  3  4
0  0  1  1  1  0
1  1  0  0  1  0
2  0  1  1  0  0

A: You can use:
s = ddff.loc[0].values
df.loc[0] = np.where(df.loc[[0]].columns.isin(s),1,0)

>>> df

   0  1  2  3  4
0  0  1  1  1  0
1  1  0  0  1  0
2  0  1  1  0  0

Breaking it down:
>>> np.where(df.loc[[0]].columns.isin(s),1,0)
array([0, 1, 1, 1, 0])

# Before the update
>>> df.loc[0]
 0    0
1    1
2    0
3    0
4    1

# After the assignment back
0    0
1    1
2    1
3    1
4    0


Q: Azure Functions functionAppScaleLimit of 1 isn't working as expected to limit concurrency on Queue Trigger I have a Function App with multiple queue triggers set up and am trying to limit concurrency by setting functionAppScaleLimit to 1. After testing this, I'm getting timeouts because two queue triggers will execute at around the same time, but only one is allowed to do work while the other one waits.
For example, I have two queue triggers: QueueTrigger1 and QueueTrigger2 that are executed when blobs are created in two separate places in Azure Storage. I only want one of the queue triggers to be able to run at a time. I've already set the batchSize parameter to 1 so only one message is processed at a time. Each queue trigger can take up to 8 minutes for the scripts to complete execution. If both triggers are executed at around the same time, one will complete and the other will time out and then retry with a successful completion.
Here's an example log from QueueTrigger1:
2020-10-26 07:37:49.201 Executing 'Functions.QueueTrigger1' (Reason='New queue message detected on 'etl-queue-items-1'.', Id=<queue-trigger-1-id>)
//processes work in Python
2020-10-26 07:45:49.472 Executed 'Functions.QueueTrigger1' (Succeeded, Id=<queue-trigger-1-id>, Duration=480291ms)
And QueueTrigger2:
2020-10-26 07:37:56.922 Executing 'Functions.QueueTrigger2' (Reason='New queue message detected on 'etl-queue-items-2'.', Id=<queue-trigger-2-id>)
//8 minutes later
2020-10-26 07:45:49.439 Python queue trigger function processed a queue item:
//attempts to process work in Python
2020-10-26 07:47:56.927 Timeout value of 00:10:00 exceeded by function 'Functions.QueueTrigger2' (Id: '<queue-trigger-2-id>'). Initiating cancellation.
2020-10-26 07:47:56.987 Executed '{functionName}' ({status}, Id={invocationId}, Duration={executionDuration}ms)
2020-10-26 07:47:56.987 Executed 'Functions.QueueTrigger2' (Failed, Id=<queue-trigger-2-id><queue-trigger-2-id>, Duration=600043ms)
It seems unfair that the 10 minute limit is being applied to QueueTrigger2 before it even starts doing any work. How can I ensure that each queue trigger runs independently so I can be sure not to exceed the 1.5GB memory limit and not have to rely on retries?
Edit: I'm on the Linux Consumption plan so my functionTimeout is limited to only 10 minutes.

A: You have already set functionAppScaleLimit to 1, another thing you should do is setting the batch size to 1 in host.json file according to this document :

If you want to minimize parallel execution for queue-triggered
functions in a function app, you can set the batch size to 1. This
setting eliminates concurrency only so long as your function app runs
on a single virtual machine (VM).


Q: Best way to populate large file list in c# DataGridView I have a program which fills a DGV with file details such as name, date etc, and also a few extra custom columns that give info about the files.  This works fine until there is a huge amount of files in which case the DGV seems to get slower as it populates.
From reading about DGV, it seems the best way to fill these with large amounts of data is to bind the contents to a database source.
So, the question is, would the most effective way for me to do this be to parse the files (and fill in my own custom data) then write these to a temp database, then use this to fill the DGV?  Or am I making heavy work of something much simpler?
Thanks for any advice.

A: You can speed up the responsiveness of a DGV by using VirutalMode
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx

A: If you have a huge amount of rows, like 10 000 and more,
to avoid performance leak - do the following before data binding:
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dataGridView1.RowHeadersVisible = false; // set it to false if not needed
after data binding you may enable it.


Q: Finding parameters of a system of non-linear equations in R using BB package I am trying to solve a system of equation to find parameters (x[1] and x[2]) using BB package but R outputs Unsuccessful convergence precisely it is:
Iteration:  0   ||F(x0)||:  469.829
iteration:  10  ||F(xn)|| =   0.5105992
iteration:  20  ||F(xn)|| =   0.05530002

$`par`
[1] 26.2772128 -0.9905601

$residual
[1] 0.01809358

$fn.reduction
[1] 664.413

$feval
[1] 31

$iter
[1] 25

$convergence
[1] 3

$message
[1] "Failure: Error in function evaluation"

Warning message:
In dfsane(par = p0, fn = f3) : Unsuccessful convergence.

Simburr.f1 <- function(n, tau) {
  u=runif(n)
  x<- runif(n)
  lambda = exp(1+x)
  y= (1/(u^(1/lambda))-1)^(1/tau)
  y
}

y = Simburr.f1(300,0.5)
x = runif(300)

f3 <- function(x) {
  n=300
  x1 <- x[1]
  x2 <- x[2]
  F <- rep(NA, 2)
  F[1] <- n/sum(log(1+y^(x[1])))
  F[2] <- n/-sum(log(y))+(x[2]+1)*sum((log(y)*y^x[1])/(1+y^x[1]))
  return(F)
}
p0 <- c(0.5,1)
dfsane(par=p0, fn=f3)


Q: Why won't the browser cache my http response? I have a REST api developed with django-tastypie. I have a couple of resources that are quite heavy but are not mutable, so I would like the browser to cache them to avoid unnecesary requests.
I've set the HTTP Expire header to a date far two years in the future, this is what the browser gets:
HTTP/1.1 200 OK

Date: Wed, 16 May 2012 17:29:33 GMT
Server: Apache/2.2.14 (Ubuntu)
Vary: Cookie,Accept-Encoding,User-Agent
Expires: Tue, 06 May 2014 17:29:33 GMT
Cache-Control: no-cache, public
Content-Encoding: gzip
Access-Control-Allow-Origin: *
Content-Length: 1051
Keep-Alive: timeout=15, max=82
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

I'm using jQuery.ajax to issue the request. The expires header looks good, but the request is made each time I refresh the page.

A: This is your problem:
Cache-Control: no-cache
from the spec:

This allows an origin server to prevent caching even by caches that
  have been configured to return stale responses to client requests.

A: If this content can change, try to use ifModified: true in the jQuery.ajax

A: In your .ajax call, set the cache: attribute to true, like this:
$.ajax({
        url: postUrl,
        type: 'POST',
        cache: true, /* this should be true by default, but in your case I would check this*/
        data: stuff
    });


Q: How Do Jedi/Sith Stay In Shape? Do Jedi/Sith use gyms or observe exercise regimens? Are there any examples in-universe (Legends or Canon) of common exercise being performed by either sect/group?
Yes we know they tend to run and be active during battles, obviously, but what about downtime? A Jedi/Sith are bound to have a lot of that between incidents of combat/action out in the field. In that life, one would need to stay in shape somehow, as it would demand it.


Q: is it possible to embed a blogger comment? I have tow questions

*

*is it possible to embed a blogger comment ?

*how can I call blogger comments automatically . I wont to make like this code :

<script src='www.exemple.com/feeds/IDscomments/comments/default?alt=json&callback=showtopcomment&max-results=5' type='text/javascript'>

using like this :
 ex :
data:comments.id
data:comments.url ...

I use this api

<script style=text/javascript src="http://helplogger.googlecode.com/svn/trunk/recent comments widget.js"></script>
<script style=text/javascript>
    var a_rc = 5;
    var m_rc = false;
    var n_rc = true;
    var o_rc = 100;
</script>
<script src=http://helplogger.blogspot.com/feeds/comments/default?alt=json-in-script&callback=showrecentcomments></script>

<style type="text/css">
.rcw-comments a {
    text-transform: capitalize;
}

.rcw-comments {
    border-bottom: 1px dotted;
    padding-top: 7px!important;
    padding-bottom: 7px!important;
}
</style>

thanks in advance

A: First, web APIs can not be called as script source. The output from a web API is the data as a string. Because the web API does not know (and doesn't want to assume) how the data is being called, it just dumps it. That way a CURL request can handle it just as well as an AJAX. It is up to you to determine how best to request the data for your needs.
The blogger API for comments is very well handled. Check it out.
If you update your question with some code and specific questions, I am positive the community will help with specific help.
SO answer on PHP CURL
jQUery documentation on getJson() function


Q: scalacheck: lift custom random generator Is it possible to lift custom generating function into Gen?
For example, generating ObjectIds for mongo.
import org.mongodb.scala.bson.ObjectId
import org.scalacheck.Gen

val genObjectId: Gen[ObjectId] = Gen.lift(() => new ObjectId)

The only possible solution I've found is to hack the generator like:
val genObjectId: Gen[ObjectId] = Gen.numChar.map(_ => new ObjectId)

Generating ObjectIds using Gen.hexChar is irrelevant because:

*

*I need unique value each time

*Mongo could treat some of the generated hex strings as invalid

A: Gen.delay(Gen.const(new ObjectId))

delay's argument is by-name, so every attempt to generate a value will construct a new ObjectId.


Q: Color Changing on click tracker I added a color on the first click and disabled the color on the second click. What I want to be able to do is when the color is already changed I would like to be able to change the color and add that color like as though it is on its first click. For example, I already clicked on a cell and now have a black color. I want to able to change the color from black to red immediately, but also keep my functionality of being to click on something twice to remove the color. Here is my project:
https://codepen.io/frederickalcantara/pen/XVqZep
let color = 1;
    cell.addEventListener('click', () => {
        if (color) {
            cell.style.backgroundColor = colorPicker.value;
            color = 0;
        } else {
            cell.style.backgroundColor = "";
            color = 1;
        }
    });

A: You could just check if the color match the colorPicker value or not
if (cell.dataset.color !== colorPicker.value) {
    cell.style.backgroundColor = colorPicker.value;
    cell.dataset.color = colorPicker.value;
} else {
    cell.style.backgroundColor = "";
    cell.dataset.color = ""
}

https://codepen.io/anon/pen/EoLELd?editors=0010
Reason to why I'm setting a dataset color here is because backgroundColor converts the hexadecimal from the colorPicker value to RGB so a check between the two won't work.


Q: Не устанавливается eth-brownie Пытаюсь установить eth-brownie с помощью pipx, выводит ошибку
PIP STDOUT
----------

PIP STDERR
----------
C:\Users\Алекс\.local\pipx\venvs\eth-brownie\Scripts\python.exe: No module named pip

Порядок моих действий:
python -m pip install --user pipx
python -m pipx ensurepath --force
pipx install eth-brownie

Пробовал удалять pipx, удалять папки с ним вручную, переустанавливал python 3 раза, ничего не помогает.
Работаю в vscode.
Путь до python: C:\Users\Алекс\AppData\Local\Programs\Python\Python310
Путь до pipx(pip show pipx): c:\users\алекс\appdata\roaming\python\python310\site-packages


Q: Angular ui Tour - not scrolling I just implemented Angular Ui Tour (https://github.com/benmarch/angular-ui-tour) on my site, everything seems to work, except scrolling to the opened dialog.
I created and started the tour like that:
uiTourService.createDetachedTour('myTour');
this._uiTourService.getTourByName('myTour').start();

And the tour steps are defined like so:

Everything is shown correctly, i also managed to use my keyboard to navigate (arrow keys), setting useHotkeys to true. But the scrolling thing won't work, even if I try to set scrollIntoView to true manually.
Does anybody know, what the issue could be?

A: I just run into this.
The scrolling part is the angular-smooth-scroll's job (angular-ui-tour uses it properly).
The minified version is the problematic, also it shows no error :/
So I switched to the source version (/dist/angular-smooth-scroll.min.js -> /lib/angular-smooth-scroll.js) and it's working just fine.


Q: Linker errors after upgrade to xcode 3.2.3 for iphone app I've just upgraded to XCODE 3.2.3 and upgraded my base sdk from 3.0 to 3.2 iphone sdk. After doing this I started getting a bunch of link errors with barely any info, here's what I got:
".objc_class_name_CATransition", referenced from:

".objc_class_name_NSObject", referenced from:

".objc_class_name_NSFileManager", referenced from:

".objc_class_name_NSString", referenced from:

".objc_class_name_NSError", referenced from:

".objc_class_name_CABasicAnimation", referenced from:

".objc_class_name_NSOperation", referenced from:

".objc_class_name_CJSONDeserializer", referenced from:

".objc_class_name_UIWindow", referenced from:

".objc_class_name_NSException", referenced from:

".objc_class_name_UIColor", referenced from:

".objc_class_name_CATransaction", referenced from:

".objc_class_name_CLLocationManager", referenced from:

".objc_class_name_MPMoviePlayerController", referenced from:

".objc_class_name_NSMutableSet", referenced from:

".objc_class_name_UIFont", referenced from:

".objc_class_name_NSFileHandle", referenced from:

".objc_class_name_MFMailComposeViewController", referenced from:

".objc_class_name_CAKeyframeAnimation", referenced from:

".objc_class_name_UIImage", referenced from:

".objc_class_name_UIApplication", referenced from:

".objc_class_name_UILabel", referenced from:

".objc_class_name_UIView", referenced from:

".objc_class_name_CLLocation", referenced from:

".objc_class_name_NSMutableString", referenced from:

".objc_class_name_CJSONSerializer", referenced from:

".objc_class_name_NSTimer", referenced from:

".objc_class_name_NSValue", referenced from:

".objc_class_name_NSMutableData", referenced from:

".objc_class_name_NSNumber", referenced from:

"_objc_exception_match", referenced from:

".objc_class_name_UINavigationItem", referenced from:

".objc_class_name_UIViewController", referenced from:

".objc_class_name_NSMutableArray", referenced from:

".objc_class_name_UIScreen", referenced from:

".objc_class_name_NSHTTPCookieStorage", referenced from:

".objc_class_name_MKPinAnnotationView", referenced from:

".objc_class_name_NSNotificationCenter", referenced from:

"_OBJC_CLASS_$_QWAdView", referenced from:

".objc_class_name_NSProcessInfo", referenced from:

".objc_class_name_UITableViewCell", referenced from:

".objc_class_name_CAAnimationGroup", referenced from:

".objc_class_name_NSInvocation", referenced from:

".objc_class_name_NSURL", referenced from:

".objc_class_name_NSSet", referenced from:

"_objc_exception_extract", referenced from:

".objc_class_name_UISearchBar", referenced from:

".objc_class_name_NSMutableURLRequest", referenced from:

".objc_class_name_NSRunLoop", referenced from:

".objc_class_name_NSData", referenced from:

".objc_class_name_NSDate", referenced from:

".objc_class_name_UIBarButtonItem", referenced from:

".objc_class_name_UITableView", referenced from:

".objc_class_name_NSURLRequest", referenced from:

".objc_class_name_NSOperationQueue", referenced from:

".objc_class_name_UIActionSheet", referenced from:

".objc_class_name_UIDevice", referenced from:

".objc_class_name_MKMapView", referenced from:

".objc_class_name_UIToolbar", referenced from:

".objc_class_name_NSXMLParser", referenced from:

".objc_class_name_NSHTTPCookie", referenced from:

".objc_class_name_UIImageView", referenced from:

".objc_class_name_CAMediaTimingFunction", referenced from:

".objc_class_name_NSScanner", referenced from:

"_objc_exception_try_exit", referenced from:

".objc_class_name_NSDateFormatter", referenced from:

".objc_class_name_UIAccelerometer", referenced from:

"_objc_exception_try_enter", referenced from:

".objc_class_name_NSCharacterSet", referenced from:

".objc_class_name_UIScrollView", referenced from:

".objc_class_name_UIButton", referenced from:

".objc_class_name_UINavigationBar", referenced from:

".objc_class_name_UIAlertView", referenced from:

".objc_class_name_NSUserDefaults", referenced from:

".objc_class_name_NSThread", referenced from:

".objc_class_name_NSPropertyListSerialization", referenced from:

"_OBJC_CLASS_$_GANTracker", referenced from:

".objc_class_name_NSMutableDictionary", referenced from:

".objc_class_name_CALayer", referenced from:

".objc_class_name_UIWebView", referenced from:

".objc_class_name_NSBundle", referenced from:

".objc_class_name_NSURLConnection", referenced from:

".objc_class_name_NSAutoreleasePool", referenced from:

".objc_class_name_UIPageControl", referenced from:

".objc_class_name_NSAssertionHandler", referenced from:

".objc_class_name_MKAnnotationView", referenced from:

".objc_class_name_NSDictionary", referenced from:

".objc_class_name_NSLocale", referenced from:

".objc_class_name_NSArray", referenced from:

".objc_class_name_UIActivityIndicatorView", referenced from:

"_OBJC_CLASS_$_AdMobView", referenced from:

Any ideas?
UPDATE:
Seems like 3rd party libraries are causing the issues. These include libraries for admob, quattro, and Google Analytics. Only admob has updated their libraries so will have to remove the other ones

A: Same problem.  Tons of link errors when compiling for simulator; device works fine.
Checked frameworks as suggested by Sim but looked fine.
Edit: All of the problems seem to be with pre-compiled 3rd party libraries (in my case that means the Facebook Three20.a library and Occipital's libRedLaserSDK.a).  Anybody know if I need to use versions of those libraries recompiled for 4.0, or if there is there another fix?
Edit2: And one more clue, which suggests some of the other posters are on the right track: in my project "Groups & Files" list, all of my frameworks appear in red text.  Yet if I check any one of them, the target checkbox is checked.

A: I don't know why this suddenly started happening when you upgraded, but these link errors mean that your link line is missing some frameworks.  It would be very helpful to see the full compiler output (expand the transcript in Build Results to get this).
Looks like QuartzCore, Foundation, MediaPlayer, UIKit and others are missing, based on the symbols which are undefined.  I figured this out by searching for the missing symbols (e.g. "NSOperation") in the iPhone developer site.  The documentation for each function lists the framework that defines the function.

A: Check Frameforks is checked for the new build target. Select UIkit.framework -> Get Info and check general and targets tabs

A: I would try reinstalling XCode.
Backup your /Developer folder first then give these steps a go.
From the terminal use:
sudo /Developer/Library/uninstall-devtools --mode=all

to uninstall XCode and the iPhone SDKs, then delete the /Developer folder after you've done this to ensure that XCode and the iPhone SDK have been cleanly removed from your system. Reinstall Xcode afterwards.

A: I had this same problem a couple of days ago, but for me just restarting Xcode fixed it, I could build my app without any problems. I have no idea what caused this to happen in the first place, though.


Q: ntfs external HD works read-only on Arch I only have read-only access to my external hard-drive which is using NTFS filesystem. How do I fix this problem to get full access to my hard drive?

A: You need to install the ntfs-3g filesystem driver and mount your drive using that instead of your current ntfs driver.


Q: Why this 10 threads always output the same thread name? I ran this code
NUM = 0
def count():
    global NUM
    NUM += 1
    time.sleep(1)
    print(t.getName()+":"+"NUM is "+str(NUM))

for i in range(10):
    t = threading.Thread(target=count)
    t.start()

The output is
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10

I know why the NUM is always 10, but why is the thread name always the same? Every thread runs print(t.getName()+":"+"NUM is "+str(NUM)); the t should not be the thread that gets the cpu time's one?  I think the name should not be the same.
When I changed to this
NUM = 0
def count():
    global NUM
    NUM += 1
    name = t.getName()
    time.sleep(1)
    print(name+":"+"NUM is "+str(NUM))

for i in range(10):
    t = threading.Thread(target=count)
    t.start()

It works as I expect:
Thread-1:NUM is 10
Thread-3:NUM is 10
Thread-2:NUM is 10
Thread-4:NUM is 10
Thread-5:NUM is 10
Thread-7:NUM is 10
Thread-10:NUM is 10
Thread-9:NUM is 10
Thread-6:NUM is 10
Thread-8:NUM is 10

A: It's because you're referencing the global name t.  By the time the sleeps end, the loop is over, and t remains bound to the last thread (the 10th thread) the loop created.
In your alternative, the results aren't actually defined.  There you reference the global t while the loop is still running, so it's likely to be bound to the most recent thread created - but doesn't have to be.
Note:  if you don't have convenient access to the thread object currently running, you can use
threading.currentThread()

to get it.  Then
threading.currentThread().getName()

will return the name of the thread running it.

A: Your function queries for a t, but no t is defined in the function:
def count():
    global NUM
    NUM += 1
    name = t.getName() # use outer t
    time.sleep(1)
    print(name+":"+"NUM is "+str(NUM))
The fallback mechanism of Python thus will look for a t in the direct outer scope. And indeed, you assign to a t in the outer scope, so it will take that value.
Now since you write t = ... in a for loop, that t changes rapidly. It is very likely that the for loop has already reached the last value - especially because of the threading mechanism of Python - before the first thread actually fetches that t. As a result, all the threads fetch the t referring to the last constructed thread.
If we however rewrite the function to:
NUM = 0
def count():
    name = t.getName() # t fetched immediately
    global NUM
    NUM += 1
    time.sleep(1)
    print(name+":"+"NUM is "+str(NUM))

I get:
Thread-11:NUM is 10
Thread-12:NUM is 10
Thread-13:NUM is 10
Thread-14:NUM is 10
Thread-15:NUM is 10
Thread-17:NUM is 10
Thread-16:NUM is 10
Thread-19:NUM is 10
Thread-18:NUM is 10
Thread-10:NUM is 10

on my machine. Of course this does not guarantee that every thread will grab the correct thread, since it is possible that only later in the process, the thread will start working and fetches the t variable.

A: You have the same problem for both the thread name and the count NUM: by the time you get to the first print statement, all 10 threads have been started.  You have only one global variable t for the thread, and one global NUM for the count.  Thus, all you see is the last value, that for the 10th thread.  If you want separate values printed, you need to supply your code with a mechanism to report them as they're launched, or keep a list through which you can iterate.

A: I advice you to try this:
NUM = 0
def count():
    global NUM
    NUM += 1
    num = NUM
    name = t.getName()
    time.sleep(1)
    print("t.getName: " + t.getName() + ", name: " + name + ":" + ", NUM: " + str(NUM) + ", num: " + str(num))

for i in range(10):
    t = threading.Thread(target=count)
    t.start()

Result:
t.getName: Thread-10, name: Thread-10:, NUM: 10, num: 10
t.getName: Thread-10, name: Thread-6:, NUM: 10, num: 6
t.getName: Thread-10, name: Thread-3:, NUM: 10, num: 3
t.getName: Thread-10, name: Thread-5:, NUM: 10, num: 5
t.getName: Thread-10, name: Thread-4:, NUM: 10, num: 4
t.getName: Thread-10, name: Thread-9:, NUM: 10, num: 9
t.getName: Thread-10, name: Thread-7:, NUM: 10, num: 7
t.getName: Thread-10, name: Thread-2:, NUM: 10, num: 2
t.getName: Thread-10, name: Thread-1:, NUM: 10, num: 1
t.getName: Thread-10, name: Thread-8:, NUM: 10, num: 8

t.getName() is a function call, which is a reference. By the time the print functions reached the console, t references to the latest thread.


Q: Lemma 4.1. Do Carmo's Riemannian Geometry A question about the lemma in the title:

Lemma 4.1. For any $p \in M$ there exists a number $c > 0$ such that any geodesic in $M$ that is tangent at $q \in M$ to the geodesic sphere $S_r(p)$ of radius $r < c$ stays out of the geodesic ball $B_r(p)$ for some neighborhood of $q$.

I'll write down the proof and write the question after

Proof. Let $W$ be a totally normal neighborhood of $p$. Using the lemma of homogeneity, we can suppose, by conveniently restricting the the interval of definition, that all of the geodesics of $W$ have velocity one. We can, therefore, restrict ourselves to the unit tangent bundle $T_1 W$ given by
  $$
T_1 W = \left\{(q,v) : q \in W, v \in T_q M, |v| = 1 \right\}
$$
  Let $\gamma : I \times T_1 W \to M$, $I = (-\epsilon,\epsilon)$, be the differentiable mapping such that $t \to \gamma(t,q,v)$ is the geodesic that at the instant $t=0$ passes through $q$ with velocity $v, |v| = 1$. Define $u(t,q,v) = \exp_p^{-1}(\gamma(t,q,v))$ and
  $$
F:I\times T_qW \to \mathbb{R}, \;\;\;\; F(t,q,v) = |u(t,q,v)|^2.
$$
$F$ measures the square of the "distance" from $p$ to a point that is moving along the geodesic $\gamma$. It is clear that $u$ and $F$ are differentiable, and that
  $$
\begin{array}{l}
\frac{\partial F}{\partial t} = 2 \left\langle \frac{\partial u}{\partial t}, u\right\rangle \\
\frac{\partial^2 F}{\partial t^2} = 2 \left\langle \frac{\partial^2 u}{\partial t^2}, u\right\rangle + 2 \left| \frac{\partial u}{\partial t} \right|^2
\end{array}
$$
  Now let $r > 0$ be chosen so that
  $$
\exp_p B_r(0) = B_r(p) \subset W
$$
  If a geodesic $\gamma$ is tangent to the geodesic sphere $S_r(p)$ at the point $q = \gamma(0,q,v)$, then, from the Gauss lemma
  $$
\left\langle \frac{\partial u}{\partial t}(0,q,v), u(0,q,v) \right\rangle = 0
$$

Question : How is the Gauss lemma exactly applied here?

A: Let us write it out in detail. We begin with a few observations:

*

*$\displaystyle\frac{\partial \gamma}{\partial t}(0,q,v)$ is the velocity of the geodesic that at the instant $t = 0$ passes through $q$ with velocity $v$, which is to say that $\displaystyle\frac{\partial \gamma}{\partial t}(0,q,v) = v$ is a tangent vector based at $\gamma(0,q,v) = q$.

*Let us write $\tilde v = u(0,q,v) = \exp_p^{-1}\big(\gamma(0,q,v)\big) = \exp_p^{-1}(q)$. Then $\tilde v$ is a tangent vector based at $p$, and if we assume, as do Carmo does, that $q\in S_r(p)$, and all geodesics under consideration have unit speed, then by our definitions, $\tilde v = \tilde \gamma'(r)$ for an appropriate choice of geodesic $\tilde\gamma$.

*By the last two points and the chain rule, $\displaystyle\frac{\partial u}{\partial t}(0,q,v) = \big(d \exp_p^{-1}\big)_{q}(v) = \big( (d \exp_p)_\tilde v\big)^{-1}(v)$ is a tangent vector based at $p$.
Now, we can write
\begin{align*}
\left<\frac{\partial u}{\partial t}(0,q,v),u(0,q,v)\right>_p &= \left<\big( (d \exp_p)_\tilde v\big)^{-1}(v),\tilde v\right>_p \\
&= \left<\big(d \exp_p\big)_\tilde v\big( (d \exp_p)_{\tilde v}\big)^{-1}(v),\big(d\exp_p\big)_{\tilde v}(\tilde v)\right>_q \\
&= \left<v,\big(d\exp_p\big)_{\tilde v}(\tilde v)\right>_q\\
&= \left<v,\tilde \gamma'(r)\right>_q,
\end{align*}
where we applied Gauss' lemma (p. 69 of do Carmo) on the second line. (Implicitly we have used the common identification, as do Carmo does in his proof of Gauss' lemma, that $T_qM\approx T_\tilde vT_qM$.) Our assumption that $v$ be tangent to the geodesic sphere $S_r(p)$ tells us that the last expression in the display above is $0$.


Q: Draw sphere and curved surface with TikZ I want to draw this picture, can anyone help me complete it?

\documentclass[a4paper,11pt]{article}

\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
        \shade[ball color = brown, opacity=0.7] (0,0) circle (2cm);
        \draw (0,0) circle (2cm);
        \draw[thick, -latex] (-130:1cm) -- (-130:3.5cm) node [below] {$ x $}; % x axis
        \draw[thick, -latex] (-20:1cm) -- (-20:3.5cm) node [right] {$ y $}; % y axis
        \draw[thick, -latex] (90:1cm) -- (90:3.5cm) node [above] {$ z $}; % z axis
        \draw (60:1.5cm) -- (60:3.5cm) node [anchor=south west, xshift=-2em]
        {$ x^2 + y^2 + z^2 - a^2 = 0 $};
    \end{tikzpicture}
\end{document}

A: The figure is suitable for 3D Asymptote: an elliptic cylinder and a sphere. The elliptic cylinder x^2-z^2=1 can be parameterized by x=cosh(t) and y=sinh(t).

unitsize(1cm);
import graph3;
currentprojection=orthographic(3,2,3,zoom=.9);
draw(unitsphere,yellow);
real a=3;
draw(Label("$x$",EndPoint),O--a*X,Arrow3());
draw(Label("$y$",EndPoint),O--a*Y,Arrow3());
draw(Label("$z$",EndPoint),O--a*Z,Arrow3());

// parabolic cylinder x^2 - z^2 = 1
triple f(pair M) {
real t=M.x, y=M.y;
real x=sinh(t);
real z=cosh(t);
return (x,y,z);
}
triple g(pair M) {
real t=M.x, y=M.y;
real x=-sinh(t);
real z=-cosh(t);
return (x,y,z);
}

real tmax = 1, tmin =-1;
real ymax = 2, ymin =-2;
surface elliptic_cylinder1=surface(f,(tmin,ymin),(tmax,ymax),Spline);
surface elliptic_cylinder2=surface(g,(tmin,ymin),(tmax,ymax),Spline);

draw(parabolic_cylinder1,cyan+opacity(.7));
draw(parabolic_cylinder2,cyan+opacity(.7));

A: I'g go for a 3d approach here. I think that it is almost as simple but it looks a little better. I left the labels for you.
\documentclass[border=2mm]{standalone}
\usepackage    {tikz}
\usetikzlibrary{3d}

\begin{document}
\begin{tikzpicture}[line cap=round,line join=round,x={(-0.3590cm,-0.4278cm)},y={(0.9333cm,-0.1646cm)},z={(0cm,0.8887cm)}]
  % coordinates
  \coordinate (A1) at ({-3+2*cos(60)}, 1.75,{ 2*sin(60)});
  \coordinate (C1) at ({-3+2*cos(60)},-1.75,{-2*sin(60)});
  \coordinate (A2) at ({ 3-2*cos(60)}, 1.75,{ 2*sin(60)});
  \coordinate (C2) at ({ 3-2*cos(60)},-1.75,{-2*sin(60)});
  % cylinder behind
  \begin{scope}[canvas is xz plane at y=-1.75]
    \shade [opacity=0.5,left color=blue!10,right color=blue!70,shading angle=0]
      (A1) arc (60:-60:2) -- (C1) arc (-60:60:2) -- cycle;
  \end{scope}
  % sphere
  \shade[draw,ball color=brown!70] (0,0,0) circle (1cm);
  % y,z axis
  \draw [-latex] (0,1,0) -- (0,3,0) node [right] {$y$};
  \draw [-latex] (0,0,1) -- (0,0,3) node [above] {$z$};
  % front cylinder
  \begin{scope}[canvas is xz plane at y=-1.75]
    \shade [opacity=0.5,left color=green!10,right color=green!70,shading angle=0]
      (A2) arc (120:240:2) -- (C2) arc (240:120:2) -- cycle;
  \end{scope}
  % little dot and x axis
  \draw [fill=red] (1,0,0) circle (0.025 cm);
  \draw [-latex]   (1.025,0,0) -- (3,0,0) node [left]  {$x$};
\end{tikzpicture}
\end{document}

This is the result:


Q: Printing numbers I am writing a program to display as below
when n=3
1 2 3
7 8 9
4 5 6

when n=5
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10

my program is
#include<stdio.h>
#include<conio.h>
int main()
{
    int n=5,r=1,c=1,i=1,mid=0;
    if(n%2==0)
      mid=(n/2);
    else
      mid=(n/2)+1;
      printf("mid = %d\n",mid);
    while(r<=n)
    {
      while(c<=n)
      {
        printf("%d ",i);
        c++;
        i++;
      }
      r++;
      if(r<=mid)
       i=i+n;
      else
       i=i-(2*n);
      printf("\n");
      c=1;
    }
    getch();
    return 0;
}

when I give n=3, I am getting my expected output. but when I give n=5 I am getting as below
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
11 12 13 14 15

Could someone please help how to achieve expected output.

A: Using you code the solution is
#include<stdio.h>
#include<conio.h>
int main()
{
    int n=5,r=1,c=1,i=1,mid=0;
    int maxRow = n;
    if(n%2==0){
      mid=(n/2);
      maxRow--;
    }
    else
      mid=(n/2)+1;
      printf("mid = %d\n",mid);
    while(r<=maxRow)
    {
      while(c<=n)
      {
        printf("%d ",i);
        c++;
        i++;
      }
      r++;
      if(r<=mid)
       i=i+n;
      else if (r >= n)
        i=n+1;
      else
        i=i-((1+(r-mid))*n);

      printf("\n");
      c=1;
    }
    getch();
    return 0;
}

As you can see:

*

*the i=i-(2*n); is changed. What you wrote wasn't generic, but specific for the n=3 case.

*I added else if (r >= n).

*Last thing you must use a specific variable for the outer while because of n must be decremented if n is even.

Some tips:

*

*Give to your variables explanatory names

*To make your code more readable declare variables 1 per line, if you want to init them.

*Live empty lines between code chunks.

int main ()
{
    int squareDim=5;
    int row=1;
    int col=1;
    int valueToPrint=1;
    int mid=0;
    int maxRow = squareDim;

    if(squareDim%2==0)
    {
        mid=(squareDim/2);
        maxRow--;
    }
    else
    {
        mid=(squareDim/2)+1;
    }

    printf("mid = %d\n",mid);

    while(row<=maxRow)
    {
        while(col<=squareDim)
        {
            printf("%d ",valueToPrint);
            col++;
            valueToPrint++;
        }

        row++;

        if(row<=mid)
        {
            valueToPrint=valueToPrint+squareDim;
        }
        else if (row >= squareDim)
        {
            valueToPrint=squareDim+1;
        }
        else
        {
            valueToPrint=valueToPrint-((1+(row-mid))*squareDim);
        }

        printf("\n");

        col=1;
    }
    return 0;
}


Q: Can we present data from venn diagram as combinations? We have venn diagram and is it possible to write data as combinations? i.e k from n objects we have for example this diagram. I think we can

A: A Venn diagram is useful for representing intersecting sets.  We can define a Venn diagram where:

*

*the elements are the subsets of a set $S$,

*the sets in the Venn diagram are sets of subsets containing a given element, i.e., $\{T \subseteq S:s \in T\}$ for each $s \in S$.

When $S=\{1,2,3\}$, the Venn diagram looks like:

And $\binom{3}{2}$ counts the number of regions which intersect exactly two sets.
This is probably the closest useful relationship between "combinations" and "Venn diagrams" you're going to get.  Venn diagrams are defined according to intersections, whereas combinations count $k$-element subsets:
$$
\big\{\{1,2\},\{1,3\},\{1,4\},\{2,3\},\{2,4\},\{3,4\}\big\}
$$
and
$$
\big\{\{1,2,3\},\{1,2,4\},\{1,3,4\},\{2,3,4\}\big\}
$$
for example.  These subsets have empty intersections, but "intersections" is the defining feature of the Venn diagram.
A more appropriate tool is the lattice, where combinations can be viewed as the number of subsets at a given "level".


Q: Return String value from Activity to a Fragment I'm trying to figure out how to get the value from a method in the Activity class into the Fragment of that Activity.
I have set up three files: AsyncTaskActivity.java, EventsList.java, and ListFragment.java.
AsyncTaskActivity.java has the method getOtakuEvents() that returns a string value.
package com.leobee;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.MapActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncTasksActivity extends MapActivity implements EventsList{

        LocationManager locationManager;

           String stxtLat ;
           String stxtLong;
           double pLong;
           double pLat;
           String x;

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

        // Acquire a reference to the system Location Manager
           locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

           // Define a listener that responds to location updates
           LocationListener locationListener = new LocationListener() {
               public void onLocationChanged(Location location) {
                   pLong=location.getLongitude();
                   pLat=location.getLatitude();
                   stxtLat=Double.toString(pLat);
                   stxtLong=Double.toString(pLong);
                   Toast.makeText(AsyncTasksActivity.this, stxtLong, Toast.LENGTH_SHORT).show();
                   Toast.makeText(AsyncTasksActivity.this, stxtLat, Toast.LENGTH_SHORT).show();

               }

               public void onStatusChanged(String provider, int status, Bundle extras) {}

               public void onProviderEnabled(String provider) {}

               public void onProviderDisabled(String provider) {}

             };

           // Register the listener with the Location Manager to receive location updates
           locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
           DownloadWebPageTask task = new DownloadWebPageTask();

           double numRand = Math.floor(Math.random()*1000);
             String userLat= stxtLat;
            String userLong= stxtLong;
            task.execute(new String[] { "http://www.leobee.com/otakufinder/scripts/geoloco.php?userLat="+userLat+"&userLong="+userLong+"&randNum="+numRand });

        }

        private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                String response = "";
                for (String url : urls) {
                    DefaultHttpClient client = new DefaultHttpClient();
                    //HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

                    HttpGet httpGet = new HttpGet(url);
                    try {
                        HttpResponse execute = client.execute(httpGet);
                        InputStream content = execute.getEntity().getContent();

                        BufferedReader buffer = new BufferedReader(
                                new InputStreamReader(content));
                        String s = "";
                        while ((s = buffer.readLine()) != null) {
                            response += s;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return response;
            }

        @Override
        protected void onPostExecute(String result) {

             x =result;

                Log.v("values",x);

            }

        }

        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
        @Override
        public String getOtakuEvents() {
            // TODO Auto-generated method stub
            return x;
        }
}

EventsList.java is an interface that helps the classes to know getOtakuEvents()  value is available to them.
package com.leobee;

public interface EventsList {

    String getOtakuEvents();

}

Lastly, the fragment has a method that gets the value from the getOtakuEvents() called getStringfromActivity().
 package com.leobee;

    import android.content.Intent;
    import android.content.res.Configuration;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;

    // shows list view of items if fragment is not null this class will also show the item selected form Detailfragment class
    public class ListFragment  extends android.app.ListFragment{
    String events;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            String events =getStringfromActivity();

        }
public String getStringfromActivity() {
        String i;
        i=EventsList.getOtakuEvents();
            return i;
        }

    /*  public String getStringfromActivity() {

        return getActivity().getOtakuEvents();

        }*/

        @Override
        public void onActivityCreated(Bundle savedInstanceState){

            super.onActivityCreated(savedInstanceState);

        String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,values);
            setListAdapter(adapter);

        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id){

            String item =(String)getListAdapter().getItem(position);
            DetailFragment fragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment);

            if (fragment != null && fragment.isInLayout()){

            fragment.setText(item);
            }else{Intent intent = new Intent(getActivity().getApplicationContext(),
                    DetailActivity.class);
            intent.putExtra("value", item);
            startActivity(intent);

            }

        }
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            Log.e("text","config change detail fragment");
            // Checks the orientation of the screen

        }

    }

I get error: Cannot make a static reference to the non-static method getOtakuEvents() from the type EventsList.
This is confusing because I did not declare static type in getOtakuEvents() or in the fragment.
Alternatively, I also tried this version of the method in the fragment :
  public String getStringfromActivity() {

        return getActivity().getOtakuEvents();

        }

I am getting an error :The method getOtakuEvents() is undefined for the type Activity. This is baffling to me because the method is defined in the parent activity.
Specifically, I need to be able to send the string value from the activity to the fragment. I am trying to do it using an interface or the getActivity method.  Can you look over my code and let me know where I'm going wrong and how to fix it? I've been at this for the majority of 2 days and can't seem to figure it out. Any help is appreciated.

A: You could probably store and retrieve it from SharedPreferences


Q: How can I make a real purchase from my webapp from localhost:4200? I am using stripe checkout in an angular app. When I make a purchase from my app running in localhost using my stripe test account, everything works fine. When I switch to a production client token, my request is denied by stripe. The message says that localhost is not whitelisted for my account. I went to my account dashboard and tried to add localhost but it wouldn't allow it.
Does anyone know how to make this happen. I want to do some testing on my localhost making real purchases before i publish my app.

A: Stripe Checkout with your live mode keys only works over HTTPS (or security reasons [0]), it works in localhost only in test mode.
You should swap in your live mode keys only when you are ready for production and have your web page/app deployed.
There is a handy checklist that you can reference so that you're meeting all the requirements before going live [1]
[0] https://stripe.com/docs/security#tls
[1] https://stripe.com/docs/payments/checkout/live


Q: Timer in winform with an iteration        foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
        {
            makeSelfMoves = replay[item.Key];
            codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
            PrintPieces(codeFile.PieceState());
            // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a);

        }

i want to execute this whole iteration, that i responsible for a game replay, in 1 second intervals. i put a timer in my form and set it to 1 second (this should make the pieces to be moved at 1 second intervals). i made an event, and before the loop i put the statement, timer1.enabled=true. The iteration will reach the end in a quick manner.. how do you use a timer to set iteration to execute each second using the timer?

  public void ReplayGame()
    {
        Class2.replayIsOn = true;
        replay=serializeMeh.giveBackDictionary();
        int[] makeSelfMoves=new int[4];

        //Timer t = new Timer();
        //t.Interval = 1000;
        //t.Tick += timer1_Tick;
        //t.Enabled = true;
        //t.Start();
        if (backgroundWorker1.IsBusy != true)
        {
            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync();
        }

        //foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
        //{

        //    makeSelfMoves = replay[item.Key];
        //    codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
        //    PrintPieces(codeFile.PieceState());

        //    MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] );

        //}

    }

The above method is activated if i want a replay.
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        int[] makeSelfMoves = new int[4];

        foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
        {
            makeSelfMoves = replay[item.Key];// delivers an array of a single move location startrow,startcolumn,endrow,endcolun
            codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
            PrintPieces(codeFile.PieceState());// prints the code on the board

            System.Threading.Thread.Sleep(1000);
        }

    }

it does the work, but the problem that i had is after the loop finishes, the pieces that existed disappear. is it because of the background worker, cause without it , i have no pieces disappear at the end of the process. The second time that i activate the method, it happens

A: Run it in a background thread and put Thread.Sleep(1000) in the loop.
This way it will be time based and not freeze your app.

A: We need to see more of your code, but it's pretty simple:
using System.Windows.Forms;
SomeMethod(...)
{
    Timer t = new Timer();
    t.Interval = 1000;
    t.Tick += t_Tick;
    t.Enabled = true;
    t.Start();
}

void t_Tick(...)
{
    foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
    {
        makeSelfMoves = replay[item.Key];
        codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
        PrintPieces(codeFile.PieceState());
        // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a);
    }
}

A: Personally, I would put this into a seperate thread and use Thread.sleep(). In combination with accessing GUI-elements, I would suggest a BackgroundWorker instead (see MSDN, easy to implement).
If you insist in using a timer, I would suggest you use the suggestion of 'Ed S.'. The timer could also be placed on your form, instead of creating it in code of course. Just what you prefer.


Q: How to predict the labels for the test set when using a custom Iterator in MXnet? I have a big dataset (around 20GB for training and 2GB for testing) and I want to use MXnet and R. Due to lack of memory, I search for an iterator to load the training and test set by a custom iterator and I found this solution.
Now, I can train the model using the code on this page, but the problem is that if I read the test set with the save iterator as follow:
test.iter <- CustomCSVIter$new(iter = NULL, data.csv = "test.csv", data.shape = 480, batch.size = batch.size)

Then, the prediction command does not work and there is no prediction template in the page;
preds <- predict(model, test.iter)

So, my specific problem is, if I build my model using the code on the page, how can I read my test set and predict its labels for the evaluation process? My test set and train set is in this format.
Thank you for your help

A: It actually works exactly as you explained. You just call predict with model and iterator:
preds = predict(model, test.iter)

The only trick here is that the predictions are displayed column-wise. By that I mean, if you take the whole sample you are referring to, execute it and add the following lines:
test.iter <- CustomCSVIter$new(iter = NULL, data.csv = "mnist_train.csv", data.shape = 28, batch.size = batch.size)
preds = predict(model, test.iter)

preds[,1] # index of the sample to see in the column position

You receive:
 [1] 5.882561e-11 2.826923e-11 7.873914e-11 2.760162e-04 1.221306e-12 9.997239e-01 4.567645e-11 3.177564e-08 1.763889e-07 3.578671e-09

This show the softmax output for the 1st element of the training set. If you try to print everything by just writing preds, then you will see only empty values because of the RStudio print limit of 1000 - real data will have no chance to appear.
Notice that I reuse the training data for prediction. I do so, since I don't want to adjust iterator's code, which needs to be able to consume the data with and without a label in front (training and test sets). In real-world scenario you would need to adjust iterator so it would work with and without a label.


Q: Trouble with WebClient and Thread management I've been scratching my hair out trying to figure out this problem. I'm using a WebClient control that reads in a dynamic URL. There is data that I am trying to extract that isn't in the HTML source when retrieved from the Server but is rendered later with Javascript/AJAX.
I've used multiple methods including Thread.Join() and BackgroundWorker with zero results.
I'm now trying to use a async method but to be honest I'm totally lost as to what I'm doing.
Here is my code:
protected void retrieveDataSource(int matchId_val)
{
ManualResetEvent completionEvent = new ManualResetEvent(false);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
{
source = e.Result;
completionEvent.Set();
};
wc.DownloadStringAsync(new Uri("http://na.lolesports.com/tourney/match/" + matchId_val));
}

protected void LoadWebPage()
{
retrieveDataSource(matchId_val);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(source);
}

source is a global variable that is set to null initially. When I run this code the DownloadStringCompleted argument is never triggered and thus the source is never changed from null. When it reaches doc.LoadHtml(source) I'm given a null exception. IT SHOULD BE NOTED that if I hit 'Continue' then the breakpoint will arrive at the DownloadStringCompleted function which is beyond me.
If anyone can help me I'd greatly appreciate it as I've already spent my entire morning trying to wrap my mind around the issue.

A: There are ultimately a number of difficulties you may well run into as you attempt this. The bottom line is that to get at dynamically-generated content, you have to render the page, which is a lot different operation from simply downloading what the HTTP server gives you for a given URL.
In addition, it's not clear what you're using to render the web page. You are using a class named HtmlDocument and a method named LoadHtml(). This suggests that you are using Html Agility Pack, but your question is silent on that point. To my recollection, that library doesn't render HTML; but I could be wrong or have out of date information.
All that said, there is a very clear bug in your code. You create an event handle, which is apparently used to signal the completion of the asynchronous operation, but you never wait on it. This means that the thread that started the I/O will just keep going and attempt to retrieve the result before it is actually available.
One way to address that would be to wait on the event handle:
protected void retrieveDataSource(int matchId_val)
{
    ManualResetEvent completionEvent = new ManualResetEvent(false);
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
    {
        source = e.Result;
        completionEvent.Set();
    };
    wc.DownloadStringAsync(new Uri("http://na.lolesports.com/tourney/match/" + matchId_val));
    completionEvent.WaitOne();
}

Of course, if you're just going to make the thread block while you wait for the operation to complete, that raises the question of why are you using asynchronous I/O at all? Why not just call DownloadString() instead, which will automatically block until the operation is done.
I also advise against the use of a class field for the purpose of passing data from a called method to the caller. It would make more sense here for retrieveDataSource() to return the result to the caller directly. Were the code written in that way, the issue with the thread synchronization would have been more readily apparent, as you likely would have noticed the method returning before that value was actually available.
But if you insist on using the asynchronous method, the above change should at least resolve your thread synchronization issue.


Q: Есть ли какие-нибудь классы\методы, чтобы изменять URL-путь в браузере не вручную, а программно? Например, изначально URL-путь был таким http://localhost:xxxx/, потом я его поменял вручную на http://localhost:xxxx/home и сработала кое-какая логика. Но я хочу, чтобы я не вручную изменял URL-путь, а за меня это делал какой-нибудь класс\метод, который может изменять и обращаться к пути. Подскажите, пожалуйста, что-нибудь, а то в инете найти не могу, потому что с "техническим языком" всё плохо.

A: Денис Бредун. Если я правильно понял вас, то редирект с сервера не поможет. Человек открыл страницу, а затем ему нужно перейти куда-то. По сути это другая страница и чтоб перейти туда нужна либо готовая ссылка, на которую нужно нажать,перейти либо отложенный вызов, редирект из браузера.


Q: Auto cell update with use of intersect So basically I have a column in my spreadsheet that tracks the status of bearing conditions. 800+ bearings spread across 8 or so sheets (different areas of a facility) and will continue to increase in the future.
There is a corresponding column that tracks the date that the status last changed.
I have several active x controls and user forms on a dashboard/homepage for the work book that allow the user to make these changes automatically, however I would like to be able to go into the sheets and manually change the status (drop down list) and have the date in corresponding cell change automatically.
I found some code I modified and it appears to work which is good
    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim xRg As Range, xCell As Range
    On Error Resume Next
    If (Target.Count = 1) Then
        If (Not Application.Intersect(Target, Me.Range("G5:G80")) Is Nothing) Then _
            Target.Offset(0, 1) = Date
        Application.EnableEvents = False
        Set xRg = Application.Intersect(Target.Dependents, Me.Range("G5:G80"))
        If (Not xRg Is Nothing) Then
            For Each xCell In xRg
                xCell.Offset(0, 1) = Date
            Next
        End If
        Application.EnableEvents = True
    End If
End Sub

Having got the code working as I wanted I realised I would like it to to add the date to additional cells in that row but dependent on what the cell is changed to (for example if the cell is change to "Good" also add the current date in a cell offset by 4).
I have modified the code further and it now also adding the date too cells dependent on what the change value was.
    Private Sub Worksheet_Change(ByVal Target As Excel.Range)

    Dim xRg As Range, xCell As Range
    Dim UpperIndex As Integer
    Dim LowerIndex As Integer
    Dim Rows As Integer

    Set tbl = ThisWorkbook.Worksheets("Route 1").ListObjects("Route_1_Table")
    Rows = tbl.Range.Rows.Count
    UpperIndex = 5
    LowerIndex = Rows - 3

    On Error Resume Next
    If (Target.Count = 1) Then
        If (Not Application.Intersect(Target, Me.Range("G" & UpperIndex & ":G" & LowerIndex)) Is Nothing) Then _
            Target.Offset(0, 1) = Date
            If Target.Value = "Good" Then _
            Target.Offset(0, 5) = Date
            If Target.Value = "Pending Baseline" Then _
            Target.Offset(0, 4) = Date
    End If
End Sub

As you can see I removed the last section of the code but I don't know what it did, any ideas? Just wondering if it comes back to bite me later. Bit removed shown below
        Application.EnableEvents = False
        Set xRg = Application.Intersect(Target.Dependents, Me.Range("G5:G80"))
        If (Not xRg Is Nothing) Then
            For Each xCell In xRg
                xCell.Offset(0, 1) = Date
            Next
        End If
        Application.EnableEvents = True

A: A Worksheet Change: Date Stamp To Multiple Columns

Sheet Module e.g. Sheet1
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    AddDateStamp Target, "Route_1_Table", 7, 8, 3, 3, _
        Array(11, "Pending Baseline"), Array(12, "Good")
End Sub

Standard Module e.g. Module1
Option Explicit

Sub AddDateStamp( _
        ByVal Target As Range, _
        ByVal TargetTableName As String, _
        ByVal TargetColumn As Long, _
        ByVal DateColumn As Long, _
        ByVal TopRowsSkipped As Long, _
        ByVal BottomRowsSkipped As Long, _
        ParamArray DateColumnCriteriaPairs() As Variant)

    On Error GoTo ClearError ' start error-handling routine

    Dim tws As Worksheet: Set tws = Target.Worksheet
    Dim trg As Range: Set trg = tws.ListObjects(TargetTableName).DataBodyRange

    ' Exclude top and bottom rows.
    Set trg = trg.Resize(trg.Rows.Count - TopRowsSkipped - BottomRowsSkipped) _
        .Offset(TopRowsSkipped)

    ' Reference the intersecting cells.
    Dim irg As Range: Set irg = Intersect(trg.Columns(TargetColumn), Target)
    If irg Is Nothing Then Exit Sub ' no intersection

    Dim AnyDcPairs As Boolean
    AnyDcPairs = Not IsMissing(DateColumnCriteriaPairs)

    Dim dcIndex As Long, ccIndex As Long ' Date Column Index

    If AnyDcPairs Then
        dcIndex _
            = LBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs)))
        ccIndex _
            = UBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs)))
    End If

    Dim urg As Range, iCell As Range, dcPair, iString As String

    For Each iCell In irg.Cells
        Set urg = RefCombinedRange( _
            urg, iCell.Offset(, DateColumn - TargetColumn))
        iString = CStr(iCell.Value)
        If AnyDcPairs Then
            For Each dcPair In DateColumnCriteriaPairs
                If StrComp(iString, dcPair(ccIndex), vbTextCompare) = 0 Then
                    Set urg = RefCombinedRange( _
                        urg, iCell.Offset(, dcPair(dcIndex) - TargetColumn))
                    Exit For ' match found, stop looping
                End If
            Next dcPair
        End If
    Next iCell

    Application.EnableEvents = False

    urg.Value = Date

ProcExit: ' Exit Routine
    On Error Resume Next ' prevent endless loop if error in the following lines
        If Not Application.EnableEvents Then Application.EnableEvents = True
    On Error GoTo 0
    Exit Sub ' don't forget!
ClearError: ' continue error-handling routine
    Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
    Resume ProcExit ' redirect to exit routine
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      References a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
    ByVal urg As Range, _
    ByVal arg As Range) _
As Range
    If urg Is Nothing Then Set urg = arg Else Set urg = Union(urg, arg)
    Set RefCombinedRange = urg
End Function


Q: Get image Height and Width I am displaying an image which if small, will fill the size of the control area. I want to display the actual original width and height of the image.
How can I do that?

A: ImageSource.Width and ImageSource.Height

A: You actually kind of answered your own question.  There are two dependency properties that you can use: ActualWidth and ActualHeight.
This will give you the size that the picture is using on the screen, not what is currently set, which is what Width and Height give you.
Also, these dependency properties are useable by any FrameworkElement I believe.
FrameworkElement.ActualWidth
FrameworkElement.ActualHeight

A: You can set the Stretch property to "None" to have an Image element use the actual source image size:
<Image Source="/Resources/MyImage.png" Stretch="None"/>


Q: Why my app get different expiration time of Facebook access token? I have a web application, which needs user's Facebook permissions, and perform some actions in the background. For most users, this app can get an access token with 2 months expiration time through oAuth process. But today I found it gets only one day expiration time access token from a few people.
Since the application is still under development, and testers are all my colleagues. So, I checked their Facebook permission settings, but I didn't find something particular which will affect the expiration time I get from oAuth. So, is there any possible reason why some people can get a longer expiration time, but some other people will only get a shorter one?


Q: Understanding Convolution Summation in Discrete time signals General definition of convolution states:
$$
u(n)*s(n) = \sum_k u(k)s(n-k)
$$
However, unable to grasp the fundamental over here, I am wondering what summation would the following represent: $u(n-1)*s(n)$?

A: If you define the shifted version of $u[n]$ as another signal $v[n]\triangleq u[n-1], n \in \mathbb{Z}$, it follows from the convolutions formula that
$$
v[n]*s[n]=\sum_k v[k] s[n-k]
$$
Now, by replacing $v[n]$ with $u[n-1]$ in the above formula, we have
$$
u[n-1]*s[n]=\sum_k u[k-1] s[n-k]
$$

A: Let's say the impulse response of the system is $y[n]=s[n]$. Also, we can write any discrete signal as the sum of impulse functions such as
$$u[n] = \sum_{k=0}^\infty u[k] \delta[n-k]$$
Now using linearity and time invariance, we can see that
$$y[n] = \sum_{k=0}^\infty u[k] s[n-k]$$
This is so fundamental so it has a name.


Q: Html wrapper issue My Flex application is built using ant. The html wrapper task is as follows:
<target name="wrapper">
    <html-wrapper
        title="{$title}"
        file="login.htm"
        height="300"
        width="400"
        application="app"
        swf="Main.swf"
        version-major="9"
        version-minor="0"
        version-revision="0"
        history="true"
        template="express-installation"
        output="${APP_ROOT}"/>
</target>

My purpose is to display a message to the user in case their browser has JavaScript disabled.
I modified the index.template.html file within the express-installation folder to include the following in the  tag:
<noscript><my message here/></noscript>

The message does not get displayed. Is there a way I could find out which index.template.html file is used by ant task or is the file being overridden somehow?
Can anyone resolve this? Any help would be appreciated. :)

A: It should be coming from the SDK that you are using to build the wrapper. It'll be somewhere like...
${FLEX_HOME}/templates/express-installation/index.template.html

A: As of Flex SDK 4.5:
The template file used when building your project via html-wrapper ant task unfortunately does NOT come from ${FLEX_SDK_HOME}/templates/swfobject.
The template file used by the ant task is actually baked into the flexTasks.jar file found in ${FLEX_SDK_HOME}/ant/lib. As you know, there is no convenient option you can apply on the task  to use a different template.
Because my needed changes were minor (and presumably useful on all of my projects) I simply unzipped flexTasks.jar and re-zipped it with my modified template.

A: Since you did use the history="true" you need change the template inside
P:\ath\to\sdks\X.Y.Z\templates\express-installation-with-history

as documented here.


Q: Uploading in React and Redux I'm uploading multiples images and I wanted to display the correct percentage "50%".
However I'm calling the API one by one. Meaning I upload the image one by one.
The problem is the percentage keeps getting back and forth like 0 - 50%, then going back again to 0 and so on... The reason for this is because I'm dispatching the setProgress multiples times.
What will be the correct calculation to achieve the correct percentage?
Reducer
case SET_UPLOAD_PROGRESS:
  return {
    ...state,
    uploadProgress: action.payload,
  }

Actions
export const uploadImages =
  ({ images }) =>
  (dispatch) => {
    images.forEach(async (image) => {
      const formData = new FormData();
      formData.append(image.name, image.imageFile);

      try {
        dispatch({ type: UPLOAD_IMAGES_REQUEST });

        const response = await axios.post("http://test.com", formData, {
          onUploadProgress(progressEvent) {
            const { loaded, total } = progressEvent;
            const percentage = Math.floor((loaded / total) * 100);

            dispatch(setUploadProgress(percentage));   <- GETTING PERCENTAGE. IT IS WORKING ALREADY. EXAMPLE OUTPUT: 50
          },
        });

        dispatch({
          type: UPLOAD_IMAGES_SUCCESS,
          payload: [...(images || [])],
        });
      } catch (error) {
        dispatch({ type: UPLOAD_IMAGES_FAILURE });
      }
    });
  };

Component
   const uploadProgress = useSelector(state => state.images.uploadProgress);

    <LinearProgress variant="determinate" value={uploadProgress} />

A: FormData can handle multiple files, even under the same field name. If the API supports it, build up your request payload and send it once
export const uploadImages =
  ({ images }) =>
  async (dispatch) => { // async here
    const formData = new FormData();
    images.forEach(image => {
      formData.append(image.name, image.imageFile);
    })

    // as per usual from here...
  };

Otherwise, you'll need to chunk the progress by the number of images, treating the average as the total progress.
export const uploadImages =
  ({ images }) =>
  async (dispatch) => {
    const imageCount = images.length;
    const chunks = Array.from({ length: imageCount }, () => 0);

    await Promise.all(images.map(async (image, index) => {
      // snip...

      await axios.post(url, formData, {
        onUploadProgress({ loaded, total }) {
          // for debugging
          console.log(
            "chunk:", index,
            "loaded:", loaded,
            "total:", total,
            "ratio:", loaded / total
          );

          // store this chunk's progress ratio
          chunks[index] = loaded / total;

          // the average of chunks represents the total progress
          const avg = chunks.reduce((sum, p) => sum + p, 0) / chunks.length;

          dispatch(setUploadProgress(Math.floor(avg * 100)));
        }
      });

      // snip...
    });

    // snip...
  };

Note that the upload progress can reach 100% before the request actually completes. To handle that, you may want something in your store that detects when the uploadProgress is set to 100 and set another state (finalisingUpload = true for example) that you can clear after the request complete.
Here's a quick demo using mocks showing how the logic works ~ https://jsfiddle.net/rtLvxkb2/


Q: Enable only dates that are in the array I have just started using jQuery UI's datepicker and I am looking for a way to enable dates that are only in the data array... I tried everything but it doesn't seem to disable any dates. I checked data array and it display everything in the following format if I use console.log(data):
["2017-04-28", "2017-05-19", "2017-04-03", "2017-04-05", "2017-04-07", "2017-04-04", "2017-04-12"]
$.ajax({
    url: '/getDoctorsAppointments/'+doctor_id+'/',
    type: "GET",
    dataType: "json",
    success:function(data) {
       // enable only dates in the "data" array
    }
});

Any ideas how I can achieve that only dates in the array are enabled/can be selected in the datepicker?


Q: How can i add a Person and Group control to Workflow Initiation From in SharePoint Designer 2010 x64 For some reason there is no Person and Group type in Add Field dialog on workflow's Initiation Form creation process in SharePoint Designer 2010.
I assume it should be there as it shown in screenshot in this tread but it's not. Does anyone know how can i fix this?

A: To solve this issue you need to navigate to site collection's Site Settings page, click 'Site collection features' link, then activate a feature called "Workflows".


Q: how to get (this) element's parent index and pass it as a value? In the following example,how would i get the parent
 index inside the wrapper div and pass it as a value in the li's innerText ?
tried something like $(this).closest("ol").index() but did'nt work

$("li").text("this ol's index is " + $(this).closest("ol").index());

A: You are not in any event handling or callback context here, so $(this) simply refers to the window object (wrapped in jQuery.)
Go through the li in a loop, then $(this) will have the proper context inside the callback function.

$("li").each(function() {
  $(this).text("this ol's index is " + $(this).closest("ol").index());
})


Q: Avoid permanent redirect to login page http://127.0.0.1:3000/login I have a problem using nuxt/auth v4.9.1.
when I logged in and I enter a URL for example http://127.0.0.1:3000/configuration/locations it redirects me to the login page http://127.0.0.1:3000/login while I I'm already logged in and my token hasn't expired yet.
Please how to avoid this redirect?
Nuxt.config.js
router: {
        middleware: ['auth']
      },
      // Auth Strategies
      auth: {
        redirect: {
            login: '/login',
            logout: false,
            callback: false,
            home: '/'
        },
        token: {
            property: 'accessToken',
            global: true,
            maxAge: 1800
        },
        refreshToken: {
            property: 'refreshToken',
            data: 'refreshToken',
            maxAge: 60 * 30
          },
        strategies: {
            local: {
                endpoints: {
                    login: { headers: { 'Content-Type': 'application/x-www-form-urlencoded'}, url:'oauth/v2/token', method: 'post', propertyName: "accessToken" },
                    refresh: { headers: { 'Content-Type': 'application/x-www-form-urlencoded'}, url: '/oauth/v2/token/refresh', method: 'post', propertyName: 'refreshToken'},
                    user: { url: 'security/users/me', method: 'get', propertyName: false}
                },
                /* user: {
                    property: 'data'
                }, */
                tokenType: 'Bearer'
            }
        }
      }

Someone to help me please?


Q: How i can open (.it) file? I am doing a Project in Communication field by using Ubuntu 13.04. The project executed by simulation and the output will be in the format of .it files.
some body could help me , how can I open these files ?

A: About IT++

IT++ is a C++ library of mathematical, signal processing and
  communication classes and functions. Its main use is in simulation of
  communication systems and for performing research in the area of
  communications. The kernel of the library consists of generic vector
  and matrix classes, and a set of accompanying routines. Such a kernel
  makes IT++ similar to MATLAB, GNU Octave or SciPy.

Writing and reading data from files

Here we will use the it_file class to store some data. The program
  write_it_file.cpp looks as follows: ... When you run this program you
  will obtain a file called it_file_test.it in your current directory.
  You can read the file into Matlab/Octave to view the data by using the
  following commands:
itload('it_file_test.it')
figure(1);
clf;
plot(a)

And then they give an example of a C++ program to read an .it file. So it seems your options are:

*

*Use Matlab

*Use GNU Octave

*Write a reader in C++


Q: Permission denied (publickey) - bitnami at AWS (Wordpress site) - Connecting with PC I face following issues when trying to connect from my PS using either PowerShell or Cygwin to AWS on which my Wordpress site is hosted (Bitnami).
(I simply what to log in to the server either this way or using Putty as described here ([LINK][1] Putty is throwing an error "using username bitnami. Server refused our key. No supported authentication methods available. server sent publickey")
What I tried so far:
I execute either or both of the following commands...
chmod 600 <key-pair-from-aws>.pem
chmod 400 <key-pair-from-aws>.pem

(When I logged in to ec2 instance, under Key Pairs section I saw an entry, but I could not download it. That's why I generated a new key pair and that is the file I am using in the commands below.)
Then I enter the following command...
ssh bitnami@<public-ip-address> -i <key-pair-from-aws>.pem

... I get the following error:

Permissions for '(key-pair-from-aws).pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key ".pem": bad permissions
bitnami@(public-ip-address): Permission denied (publickey).

Now, if I select the file on the PC "Properties -> Security -> Advanced -> disable inheritance", and then remove every user except my user, and then execute the same command ...
ssh bitnami@<public-ip-address> -i <key-pair-from-aws>.pem

... I get the following error:
bitnami@<public-ip-address>: Permission denied (publickey).

here I am stuck because I do not have any idea how to proceed further.
Searching on Stackoverflow and google I could not find anything to help me solve this issue.
can anyone please help with concrete, step-by-step instructions?
Thank you!
Update: here is the result of the command
$ ssh -v -i "pem-file-name.pem" bitnami@
> OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2
debug1: Connecting to <public-ip-address> [<public-ip-address>] port 22.
debug1: Connection established.
debug1: identity file kljuc_par_ime.pem type -1
debug1: identity file kljuc_par_ime.pem-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_for_Windows_8.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.4p1 Debian-
5+deb11u1
debug1: match: OpenSSH_8.4p1 Debian-5+deb11u1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to <public-ip-address>:22 as 'bitnami'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit>
compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit>
compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: <deleted for sec purposes> SHA256:<deleted for security purposes>
debug1: Host '<public-ip-address>' is known and matches the ECDSA host key.
debug1: Found key in C:\\Users\\My-User/.ssh/known_hosts:1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: pubkey_prepare: ssh_get_authentication_socket: No such file or directory
debug1: Will attempt key: kljuc_par_ime.pem  explicit
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,sk-ssh-ed25519@openssh.co
m,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp38
4,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,webauthn-sk-ecdsa-sha2-ni
stp256@openssh.com>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: kljuc_par_ime.pem
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
bitnami@<public-ip-address>: Permission denied (publickey)


Q: Несколько экземпляров одной формы Необходимо вызывать множество экземпляров одной формы в приложении, то есть при такой реализации
ProcessInfo.PropertyProcess StartForm = new ProcessInfo.PropertyProcess();
StartForm.Owner = this;
StartForm.Text = dataGridView4.SelectedCells[1].Value.ToString();
StartForm.Show();
StartForm.MainMethod(dataGridView4.SelectedCells[1].Value.ToString(), dataGridView4.SelectedCells[2].Value.ToString(), dataGridView4.SelectedCells[3].Value.ToString());

он у меня запускает несколько форм, но все динамические данные переменных обрабатываемые в формах(Chart,backgroundWorker, множества Label) становятся равными во всех формах последней запущенной, за то статистические данные обрабатываются корректно, как запустить экземпляр формы с разными данными динамического типа, дайте хотя бы ссылочку.
Основные переменные:
private static string[] ArrayProperty = new string[13];
private static string Information = string.Empty;
private static string Name = string.Empty;
private static double ResultIOMax = 100;
private static double ResultIOIntetval = 0;
private static Image ImageTables;

и единственная глобальная переменная, не перезаписываемая в этой форме(только чтение)
MainForm.ValueProcessInfo.DataStatisticOld.Rows[i]["DataGraph"])

A: Поля, отмеченный static, являются общими для всех экземпляров класса. Если вам нужно чтобы каждый экземпляр формы имел свой набор полей - просто уберите static:
private string[] ArrayProperty = new string[13];
private string Information = string.Empty;
private string Name = string.Empty;
private double ResultIOMax = 100;
private double ResultIOIntetval = 0;
private Image ImageTables;


Q: Image used for wordpress posts on Facebook I've seen it several times on my facebook timeline where the image of a shared link is not in the post itself. Example:
https://www.facebook.com/BarakaBits/posts/1065758210116791 - Image has text on it.
screenshot
Here's the post itself: http://www.barakabits.com/2015/01/beauty-moroccos-diversity-captured-stunning-photo-series
Is this a hidden image? I'm using a wordpress blog, how can I do this? Do I need a special plugin?
Thank you in advance!
Wil

A: I don't know exactly what this site is doing, but you can suggest that Facebook use a specific image (not necessarily one found on the page) by using the og:image Open Graph tag.  For example, something like this would go in the <head> portion of your site:
<meta property="og:image" content="http://www.barakabits.com/wp-content/uploads/2015/01/Moroccos-faces-featured-6.jpg">

As you can see from the site you referenced, you can have multiple og:image tags, and the user will be able to choose which one is displayed in the post.
Here's Facebook's guide to Open Graph tags: https://developers.facebook.com/docs/sharing/best-practices


Q: Can't call async method synchronously from MeasureOverride I need to call an async method from MeasureOverride. This call should be synchronous because I need to return the value of the async method.
I tried about a dozen different calls from these threads:
Synchronously waiting for an async operation, and why does Wait() freeze the program here
How would I run an async Task<T> method synchronously?
They all failed, some wouldn't compile in Universal Windows Applications, some weren't synchronous, some provoked a deadlock etc..
I feel strongly against async/await because of how it contaminates the call hierarchy prototypes. At the override level I'm stuck with no async keyword and I need to call await synchronously from the blackbox. Concretely how should I go about it?

A: The first thing you should do is take a step back. There should be no need to call asynchronous code from within a MeasureOverride in the first place.
Asynchronous code generally implies I/O-bound operations. And a XAML UI element that needs to send a request to a remote web server, query a database, or read a file, just to know what its size is, is doing it wrong. That's a fast track to app certification rejection.
The best solution is almost certainly to move the asynchronous code out of the element itself. Only create/modify the UI elements after the necessary asynchronous work completes.
That said, if you feel you must block the UI thread while asynchronous operations complete, I've compiled a list of every hack I know of, published in my MSDN article on brownfield asynchronous development.


Q: Bootstrap carousel news slides timing wrong I've been developing a wordpress template with a bootstrap (3.3.6.) carousel news slider. But the slides timing is all wrong after a few seconds. I already set a timer in custom.js, but it only worked on the news button (replacement of indicator), while the slides are moving way too fast after a few seconds.The weirdest thing is, if I change the bootstrap link to the cdn, the slides move properly but the news button are not moving at all. Any ideas on how to fix this?
This is the website for you to review: http://tfcakalimantan.org
The front-page.php
        <?php

      $args = array(
        'post_type'         => 'post',
        'tag'               => 'featured',
        'posts_per_page'    => 5
      );
      $the_query = new WP_Query( $args );

    ?>

 <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
      <li data-target="#myCarousel" data-slide-to="<?php echo $the_query->current_post; ?>" class="list-group-item <?php if( $the_query->current_post == 0) echo 'active'; ?>">
<?php the_title(); ?>

<?php endwhile; endif; ?>

<?php rewind_posts(); ?>

             <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
             <?php
                $thumbnail_id = get_post_thumbnail_id();
                $thumbnail_url = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail-size', true );
                $thumbnail_meta = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true);
              ?>
        <div class="item <?php if( $the_query->current_post == 0) echo 'active'; ?>">

          <img src="<?php echo $thumbnail_url[0]; ?>" class="img-responsive" alt="<?php echo $thumbnail_meta; ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

          <?php endwhile; endif; ?>

The custom.js
// Carousel

$(document).ready(function(){
    var clickEvent = false;
    $('#myCarousel').carousel({
        interval: 2000
    }).on('click', '.list-group li', function() {
            clickEvent = true;
            $('.list-group li').removeClass('active');
            $(this).addClass('active');
    }).on('slid.bs.carousel', function(e) {
        if(!clickEvent) {
            var count = $('.list-group').children().length -1;
            var current = $('.list-group li.active');
            current.removeClass('active').next().addClass('active');
            var id = parseInt(current.data('slide-to'));
            if(count == id) {
                $('.list-group li').first().addClass('active');
            }
        }
        clickEvent = false;
    });
});

$(window).load(function() {
    var boxheight = $('#myCarousel .carousel-inner').innerHeight();
    var itemlength = $('#myCarousel .item').length;
    var triggerheight = Math.round(boxheight/itemlength+1);
    $('#myCarousel .list-group-item').outerHeight(triggerheight);
});

The style.css
    /* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
#myCarousel .carousel-caption {
    left:0;
    right:0;
    bottom:0;
    text-align:left;
    padding:10px;
    background:rgba(0,0,0,0.6);
    text-shadow:none;
    font-family: 'Droid Sans', sans-serif;
    color: #FFFFFF;
}

#myCarousel .list-group {
    position:absolute;
    top:0;
    right:0;
    font-family: 'Pontano Sans', sans-serif;
}
#myCarousel .list-group-item {
    border-radius:0px;
    cursor:pointer;
}
#myCarousel .list-group .active {
    background-color:#6D9755;
}

#myCarousel .item {
    height: 300px;
}
.carousel-controls {display:none;}


Q: Dispatch controller zf2 event manager I have a base controller named MyController
I extend my Controller from MyController instead of AbstractActionController
What's wrong with this code ?
It doesn't work :
$sharedEventManager->attach('MyController', 'dispatch', function ($e) {
    $controller = $e->getTarget();
},100) ;

but this does :
$sharedEventManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function ($e) {
    $controller = $e->getTarget();
},100) ;

A: The first parameter of the SharedEventManager::attach() is the identity of the event manager to target. This identity is dynamically assigned for any class that is event capable (implements Zend\EventManager\EventManagerAwareInterface) or has otherwise had it's identity set via $eventManager->setIdentity().
The question refers to the \Zend\Mvc\Controller\AbstractActionController; this itself is an identity given to any controller that extends \Zend\Mvc\AbstractActionController (among others), allowing for just one id to attach() to target all controllers.
To target just one controller (which is perfectly valid, there are many use cases), you can do so in two ways:

*

*via the SharedEventManager, external to the controller class (as you have been doing)

*directly fetching said controller's event manager and handling the events within the controller class.

via SharedEventManager
Use the fully qualified class name as this is is added as an identity to the event manager
$sharedEventManager->attach(
    'MyModule\Controller\FooController', 'dispatch', function($e){
    // do some work
});

Within controller
I modify the normal attachDefaultListeners() method (which is called automatically), this is where you can attach events directly.
namespace MyModule\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\EventManager\EventInterface;

class FooController extends AbstractActionController
{
    protected function attachDefaultListeners()
    {
      // make sure you attach the defaults!
      parent::attachDefaultListeners();

      // Now add your own listeners
      $this->getEventManager()->attach('dispatch', array($this, 'doSomeWork'));
    }

    public function doSomeWork(EventInterface $event) {
      // do some work
    }

}

A: Why do you use your own base controller? there is no real benefit of doing that, unless you have rare edge case scenario.
Your base controller class is missing this part from AbstractController:
/**
 * Set the event manager instance used by this context
 *
 * @param EventManagerInterface $events
 * @return AbstractController
 */
public function setEventManager(EventManagerInterface $events)
{
    $events->setIdentifiers(array(
        'Zend\Stdlib\DispatchableInterface',
        __CLASS__,
        get_class($this),
        $this->eventIdentifier,
        substr(get_class($this), 0, strpos(get_class($this), '\\'))
    ));
    $this->events = $events;
    $this->attachDefaultListeners();

    return $this;
}

See setIdentifiers call there? That is why second example works.
Also i suspect you might not actually trigger dispatch event in dispatch() method of your controller
As side note: you should never create classes without top level namespace. Eg all my classes use Xrks\ vendor namespace


Q: NodeJS writes to MongoDB only once I have a NodeJS app that is supposed to generate a lot of data sets in a synchronous manner (multiple nested for-loops). Those data sets are supposed to be saved to my MongoDB database to look them up more effectively later on.
I use the mongodb - driver for NodeJS and have a daemon running. The connection to the DB is working fine and according to the daemon window the first group of datasets is being successfully stored. Every ~400-600ms there is another group to store but after the first dataset there is no output in the MongoDB console anymore (not even an error), and as the file sizes doesn't increase i assume those write operations don't work (i cant wait for it to finish as it'd take multiple days to fully run).
If i restart the NodeJS script it wont even save the first key anymore, possibly because of duplicates? If i delete the db folder content the first one will be saved again.
This is the essential part of my script and i wasn't able to find anything that i did wrong. I assume the problem is more in the inner logic (weird duplicate checks/not running concurrent etc).
var MongoClient = require('mongodb').MongoClient, dbBuffer = [];
MongoClient.connect('mongodb://127.0.0.1/loremipsum', function(err, db) {
    if(err) return console.log("Cant connect to MongoDB");
    var collection = db.collection('ipsum');
    console.log("Connected to DB");

    for(var q=startI;q<endI;q++) {
        for(var w=0;w<words.length;w++) {
            dbBuffer.push({a:a, b:b});
        }
        if(dbBuffer.length) {
            console.log("saving "+dbBuffer.length+" items");
            collection.insert(dbBuffer, {w:1}, function(err, result) {
                if(err) {
                    console.log("Error on db write", err);
                    db.close();
                    process.exit();
                }
            });
        }
        dbBuffer = [];
    }
    db.close();
});

Update

*

*db.close is never called and the connection doesn't drop

*Changing to bulk insert doesn't change anything

*The callback for the insert is never called - this could be the problem! The MongoDB console does tell me that the insert process was successful but it looks like the communication between driver and MongoDB isn't working properly for insertion.

A: I "solved" it myself. One misconception that i had was that every insert transaction is confirmed in the MongoDB console while it actually only confirms the first one or if there is some time between the commands. To check if the insert process really works one needs to run the script for some time and wait for MongoDB to dump it in the local file (approx. 30-60s).
In addition, the insert processes were too quick after each other and MongoDB appears to not handle this correctly under Win10 x64. I changed from the Array-Buffer to the internal buffer (see comments) and only continued with the process after the previous data was inserted.
This is the simplified resulting code
db.collection('seedlist', function(err, collection) {
    syncLoop(0,0, collection);
    //...
});

function syncLoop(q, w, collection) {
    batch = collection.initializeUnorderedBulkOp({useLegacyOps: true});
    for(var e=0;e<words.length;e++) {
        batch.insert({a:a, b:b});
    }
    batch.execute(function(err, result) {
        if(err) throw err;
        //...
        return setTimeout(function() {
            syncLoop(qNew,wNew,collection);
        }, 0); // Timer to prevent Memory leak
    });
}


Q: How to test akismet in a Rails app? I'm using the rakismet gem to submit user content to Akismet for spam testing.
So far every test I have done has classified the content as spam.
I'm starting to think I'm doing something wrong.
Does anyone know why I might be getting all false positives on my test data?

A: ... Because they're test data ?
You can't rely on real rakismet data in your test. Because any test can be detected as spam one day or an other.
Or just because using rakismet requires that you have an internet connection, which can sometimes not be the case.
You should mock the rakismet methods and force them to return what you expect them to.
For example you can use mocha. And do something like the following :
Object.stubs(:spam?).returns(false)

So your objects will never be spams.