text:
Q: Data loader missing field, but data is present I exported an Account from one sandbox with the intention of inserting it into another (i.e. I am copying data between orgs). This is a simple CSV file with two lines: the first has the field names (header row), the second is the data for the Account.
When data loader attempts to load it, the record errors out because Name is missing. However, it is there in the fourth field, plain as day. When I select the CSV file, data loader shows the fields and Name is there.
Header:
"ID","ISDELETED","MASTERRECORDID","NAME",...

Data:
"","false","","Test Data",...

How do I resolve this error? Is it procedural on my part? Bug in data loader? Is there a better way of copying data between orgs?

A: Please TRY to use jitterBit data loader just as an alternative and if it still errors out then  it confirms that there is something wrong with the file or the mapping file.
use the same data to create via UI, so it confirms whether the data in the file/mapping file is correct or NOT.
If the data load using JitterBit loader works then it is not a bug with salesforce.

A: This was an RTFM moment. Despite the fields existing in the CSV file, that does not actually map them into the org's data. It is possible that the two orgs have slightly different data layouts, and Data Loader cannot know that.
In this case the layouts were the same, so I told it to auto-detect the field mapping and it easily figured it out (the field names are identical between these two orgs).
Thanks to @crop1645 and @varum guruvugari for the hints that made me go back and comb through the documentation.


text:
Q: JavaScript sleep Yes, I know - that question has thousands of answers. please, don't tell me about setTimeout method because - yes, everything is possible with that but not so easy as using sleep() method.
For example:
function fibonacci(n) {
    console.log("Computing Fibonacci for " + n + "...");
    var result = 0;

    //wait 1 second before computing for lower n
    sleep(1000);
    result = (n <= 1) ? 1 : (fibonacci(n - 1) + fibonacci(n - 2));

    //wait 1 second before announcing the result
    sleep(1000);
    console.log("F(" + n + ") = " + result);

    return result;
}

if you know how to get the same result using setTimeout - tell me ;) fibanacci is pretty easy task, because there aren't more than 2 recursions, but how about n-recursions (like fib(1) + fib(2) + .. + fib(n)) and sleep after every "+"? Nah, sleep would be muuuuuch easier.
But still I can't get working example of implementing it. while (curr - start < time) { curr = (...) } is tricky, but it won't work (just stops my browser and then throw all console logs at once).

A: The question is asking how to implement sleep() in JavaScript, right?
function sleep(ms) {
  var start = new Date().getTime(), expire = start + ms;
  while (new Date().getTime() < expire) { }
  return;
}

I just tested it like so:
console.log('hello');
sleep(5000);
console.log('world');

Works for me.
(As a meta comment: I landed here because I have a particular need for this function. Such needs do come up when you need to block while waiting for a value. Even in JavaScript.)

A: The trouble with a sleep() type function within a browser (or any other GUI environment for that matter) is that it is an event-driven environment, and wouldn't be able to sleep() in the way you're describing it.
The setTimeout() method works because it is creating an event, and setting the trigger for that event to be a point in time. Therefore the system can give over control of the waiting to the event handler and Javascript itself is free to carry on doing other things.
In the web browser, virtually everything works this way. Mouse click/hover/etc functions are event triggers. Ajax requests don't sit and wait for the response from the server; they set an event to trigger when the response is received.
Time based actions are also done with event triggers, using functions like setTimeout().
This is how it's done. In fact this is how it's done in pretty much any well-written GUI application, because all GUI interfaces must be able to respond to events such as mouse clicks virtually instantly.
A Javascript sleep() function (especially the way it's been implemented in another answer here!) would basically have the effect burn up your CPU cycles while it waited for the clock. The sleep() would remain the active process, meaning that other events may not be processed straight away - which means your browser would appear to stop responding to mouse clicks, etc for the duration of the sleep. Not a good thing.
setTimeout() is the way to go. There is always a way to do it; the resulting code may not be neat and linear like your example code, but event-driven code very rarely is linear - it can't be. The solution is to break the process down into small functions. you can even embed the subsequent functions inside the setTimeout() call, which may go some way to helping you keep your code at least having some appearance of being linear.
Hope that helps explain things a bit for you.

A: I dont fully understand what you're asking, but I'm going to answer this part:

if you know how to get the same result
  using setTimeout - tell me

The fundamental difference is that sleep (as used in many other languages) is synchronous, while setTimeout (and many other JavaScript-concepts, like AJAX for example) are asynchronous. So, in order to rewrite your function we have to take this into account. Mainly, we have to use a callback to fetch the "return value", rather than an actual return-statement, so it will be used like this:
fibonacci(7, function(result) {
  // use the result here..
});

So, as for the implementation:
function fibonacci(n, callback) {
  console.log("Computing Fibonacci for " + n + "...");
  var result = 0;

  var announceAndReturn = function() {
    setTimeout(function() {
      // wait 1 second before announcing the result
      console.log("F(" + n + ") = " + result);
      callback(result); // "returns" the value
    }, 1000);
  };

  // wait 1 second before computing lower n
  setTimeout(function() {
    if (n <= 1) {
      result = 1;
      announceAndReturn();
    }
    else {
      var resultsLeft = 2;

      var handler = function(returned) {
        result += returned;
        resultsLeft--;
        if (resultLeft == 0)
          announceAndReturn();
      }

      fibonacci(n-1, handler);
      fibonacci(n-2, handler);
    }
  }, 1000);
}

I would also like to point out that, no, this is not an easier solution than using sleep. Why? Because this code is asynchronous and that's simply more complicated than synchronous code for what most people are used to. It takes practice to start thinking in that way.
The upside? It allows you to write non-blocking algorithms that outperforms their synchronous counterparts. If you haven't heard of Node.js before, you could check it out to further understand the benefits of this. (Many other languages have libraries for dealing with async IO as well, but as long as were talking about JavaScript..)

A: Just use a better algorithm without loops or recursion, and avoid the need for setTimeout() / sleep().
function fibonacci(n) {
  return Math.round(Math.pow((Math.sqrt(5) + 1) / 2, Math.abs(n)) / Math.sqrt(5)) * (n < 0 && n % 2 ? -1 : 1);
}

Usage example:
// Log the first 10 Fibonacci numbers (F0 to F9) to the console
for (var i = 0; i < 10; i++) {
  console.log(fibonacci(i));
}

A: Why do you want to 'sleep' while computing anything? Sleeping for any time is nearly always a bad idea in any language. It essentially tells the thread to stop doing anything for that period of time.
So, in a language like javascript that only has one thread (forgetting 'web workers'), what benefit would you reap for pausing ALL computation? It's a bad idea, forget it.
Now to the problem that you've written, though I don't think this is your actual problem. Why do you want to pause for a second while computing this sequence? Even to compute the first 6 numbers in the sequence, it's going to take 8 or so seconds. Why? What possible reason is there to pause for a second between recursive calls? Stop it. Remove it.
If you want to just yield the final result a second after it completes, then use setTimeout with a function uses the answer in some way.
function fib(n) {
    ...
    result = fib();
    ...
    setTimeout(function() {
        console.log("Fib for " + n + " is " + result);
    },1000);
}

Do not try to implement 'sleep'. Do not pause during computation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: search a question or answer in my profile page
Possible Duplicate:
TextBox to search our own questions and answers instead of playing around with the URL?

I need to search on my profile page for question or answer I have asked or answered previously.  If I come across a familiar question and I think I have answered it previously, then I need to search and post the link to my answer. I cannot go through all the answers or questions manually.

A: You can look for your posts using the search textfield.
You can use "user:me" to look for your posts, and "is:answer" or "is:question" to search only your answers, or your questions.

A: Yes, that's why the search field on your profile page has "user:857361" text in it. Add some search keywords to it and you will search in your posts only.


text:
Q: What is the difference between Lucene query language and KQL Kibana ver >= 7.0 offers KQL by default for the search dropdown but also supports what seems to be old Lucene syntax.
Often it complains annoyingly that "You might be using Lucene but KQL is selected" when trying to search.
Going to the suggested links:

*

*https://www.elastic.co/guide/en/kibana/7.7/lucene-query.html

*https://www.elastic.co/guide/en/kibana/7.7/kuery-query.html
I don't see any differences. What are the key differences between them? Can someone give query examples highlighting these differences?

A: The current documentation for KQL and Lucene query syntax shows the syntax of both for various types of queries. I will summarize the main differences:
1. Dropdown Suggestions
It seems that KQL enables getting suggestions for fields, values and operators as you type your query, while this feature is not present when using Lucene. (This feature requires the "Basic Tier" or above.)
2. Range Queries
To find content where count is greater than or equal to 5: the KQL syntax is count:>=5, while the Lucene syntax is count:[5 TO *].
To find content where account_number is greater than or equal to 100, but less than 200: the KQL syntax is account_number:>=100 and account_number:<200, while the Lucene syntax is account_number:[100 TO 200}.
3. Operators
The KQL documentation outlines the Boolean operators or, and and not. The upper case versions (OR, AND and NOT) also work. The documentation specifies that and has a higher precedence over or, which is the usual operator precedence rule.
The Lucene documentation specifies the following:

The preferred operators are + (this term must be present) and - (this term must not be present).

For example, brown +fox -news specifies that brown is optional, fox must be present, and news must not be present.
Lucene also supports AND, OR and NOT, but only in uppercase. So, if you try using and, it will be taken as the literal word. Also, Lucene supports &&, || and !. However, the documentation states that all of these operators do not honor the usual operator precedence rules, and advises the use of parentheses whenever multiple operators are used together.
4. Exist queries
To find documents that contain the field response: the KQL syntax is response:*, and the Lucene syntax is _exists_:response (response:* also works in Lucene, but the behavior if the value of the field is an empty string might be different).
5. Wildcards
For KQL, the documentation only mentions the * wildcard, which matches zero or more characters. There is no mention of ?, so I assume it does not exist. In Lucene, ? exists and matches a single character.
In KQL, escaping the wildcard character is never necessary when using it as a wildcard, so we can have something like book.*:(quick or brown). In Lucene, it seems that the wildcard needs to be escaped when used as part of the field name. The example given is book.\*:(quick OR brown).
6. Nested queries
The syntax for nested queries seems to be different as per the documentations.
7. Extra Features in Lucene
The KQL documentation does not mention regular expressions, fuzzy search, nor boosting; so they are probably not supported. Lucene supports them.


text:
Q: Grouping numbers in a list of floats in ascending order I have a list of floats in random number like this:
float_list=[7.1, 7.1, 8.3, 8.5, 6.7,6.8, 6.9, 4.0, 4.2, 9.0]

I want to organize the list with tuples as below:
float_list=[(7.1, 7.1, 8.3, 8.5), (6.7, 6.8,6.9), (4.0, 4.2, 9.0)]

I tried using group_by method from itertools but could not get the expected results. I have indedd see this solution but this is not what i'm asking,I have float with varying deltas.


text:
Q: Playing a Sound While App Runs EDITED
still not sure whats wrong please help
hi there I'm creating and iOS application and trying to make it play a sound when running I've type up my code in the app delegate .h , .m and it plays the sound fine but the thing is it goes to a black screen when my ViewController.xib has a blue background heres heres the code i have
AppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class ViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate, AVAudioPlayerDelegate> {
    UIWindow *window;
    ViewController *viewController;
    AVAudioPlayer *_backgroundMusicPlayer;
    BOOL _backgroundMusicPlaying;
    BOOL _backgroundMusicInterrupted;
    UInt32 _otherMusicIsPlaying;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet ViewController *viewController;

- (void)tryPlayMusic;

AppDelegate.m
#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Set up the audio session
    // See handy chart on pg. 55 of the Audio Session Programming Guide for what the categories mean
    // Not absolutely required in this example, but good to get into the habit of doing
    // See pg. 11 of Audio Session Programming Guide for "Why a Default Session Usually Isn't What You Want"
    NSError *setCategoryError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];

    // Create audio player with background music
    NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:@"ticktock" ofType:@"wav"];
    NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
    NSError *error;
    _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
    [_backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [_backgroundMusicPlayer setNumberOfLoops:-1];   // Negative number means loop forever

    // Override point for customization after app launch
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
    _backgroundMusicInterrupted = YES;
    _backgroundMusicPlaying = NO;
}

- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
    if (_backgroundMusicInterrupted) {
        [self tryPlayMusic];
        _backgroundMusicInterrupted = NO;
    }
}

- (void)applicationDidBecomeActive:(NSNotification *)notification {
    [self tryPlayMusic];
}

- (void)tryPlayMusic {

    // Play the music if no other music is playing and we aren't playing already
    if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
        [_backgroundMusicPlayer prepareToPlay];
        [_backgroundMusicPlayer play];
        _backgroundMusicPlaying = YES;
    }
}

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}

@end

ok so thats all the code

and heres what i get when app loads and the sound works fine

and this is what i want to get (ViewController.xib)

Thank in advanced
- (void)applicationDidFinishLaunching:(UIApplication *)application {

    NSError *setCategoryError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
    self.viewController = [[ViewController alloc] init];
    // Create audio player with background music
    NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:@"ticktock" ofType:@"wav"];
    NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
    NSError *error;
    _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
    [_backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [_backgroundMusicPlayer setNumberOfLoops:-1];   // Negative number means loop forever

    // Override point for customization after app launch
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

new code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

A: You never initialized your view controller.
Somewhere before you do
[window addSubview:viewController.view];

You need to do
self.viewController = [[ViewController alloc] init];

I see that you declared the property as an IBOutlet.. is it actually hooked up to something in Interface Builder?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    NSError *setCategoryError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
    // Create audio player with background music
    NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:@"ticktock" ofType:@"wav"];
    NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
    NSError *error;
    _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
    [_backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [_backgroundMusicPlayer setNumberOfLoops:-1];   // Negative number means loop forever

    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

Copy that function and just delete this one - (void)applicationDidFinishLaunching:(UIApplication *)application completely.
You should also consider converting your project to use ARC. It will remove the need to retain/release/autorelease statements.

A: You have two targets - are all your resources included in the target that you're building?


text:
Q: Write after end error when launch server in nodejs I am beginner at NodeJS and I'm doing a "NodeJS and Express.js full course" at freecodecamp yt and I copied author code which for him works perfectly, but I got an error.
Code:
const http = require('http')
const server = http.createServer((req, res)=> {
if(req.url === '/') {
    res.end('Home Page')
}
if(req.url === '/about') {
   res.end('About us')
}
res.end('Error')
})

server.listen(3000, ()=>{
    console.log('Server listening...');
})

I don't know why he got home, about and error page when user goes to the wrong page it should throw "Error" text on page, but instead my program is throwing an error in nodeJS program:
events.js:377
    throw er; // Unhandled 'error' event
     ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (internal/errors.js:322:7)
    at writeAfterEnd (_http_outgoing.js:694:15)
    at ServerResponse.end (_http_outgoing.js:815:7)
    at Server.<anonymous> (C:\Users\jonat\Desktop\nodejs\app.js:10:5)
    at Server.emit (events.js:400:28)
    at parserOnIncoming (_http_server.js:900:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:127:17)
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:753:7)
  at processTicksAndRejections (internal/process/task_queues.js:83:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

Can someone explain this to me? I would be appreciate. Thank you in advance.

A: That's caused by the res.end('Error'), which gets always executed. Try to put it into an else clause, or put a return before each res.end(…)


text:
Q: how to support multiple screens in a Android theme I am currently working on an Android theme aka launcher. I have my first page ready to go but my question is how can I add additional screens so the user can swipe to them. I tried googling but with no luck. Any help is greatly appreciated.

A: This is greatly dependent on the structure of your views.  Have you used Fragments?
If you've used Fragments for your current view, you can create Fragments for the other ones and simply put them all in a ViewPager.
I'd recommend checking out this training session.


text:
Q: Unrecognized selector error in SWIFT I have a custom class "MyTask" that gets called from other classes like class "ViewController". Inside "MyTask" I have function "startTask" that takes parameters required to start NSTimer to execute function "doStuff"
However when I use function startTask and set the selector for other function it crashes
 class MyTask {
            var timer = NSTimer()
            var timerInterval = 0.0
            var target: AnyObject!
            var selector = Selector()

            func startTask(time: Double, target target: AnyObject, selector: Selector) {
                self.timerInterval = time
                self.target = target
                self.selector = selector
                doStuff()
            }
func doStuff() {
//....some code here to run
//====Crash happens on this line=====
self.timer = NSTimer.scheduledTimerWithTimeInterval(self.timerInterval, target: self, selector: self.selector, userInfo: nil, repeats: true)

}

In my other class here is what I do
class ViewController {
   let mynewClass = MyTask()
   mynewClass = startTask(2, target: self, selector_: #selector(updateLabel))

func updateLabel() { print("") }
}

I am getting an error *** NSForwarding: warning: object 0x7fe90242f6f0 of class 'abc' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[.abc timerAction]
What I am doing wrong ?

A: The class that is to be the target of the selector must derive from NSObject. You're using an Objective-C feature here; you have to have an Objective-C-compatible class.


text:
Q: Where is the email address for maillog set? I've got a CentOS 6.7 system that currently emails a certain address to send system messages (for example, it emailed with the body "Terminated" to indicate a process spawned by cron that was killed when I restarted the server). However, I honestly have no idea where the email address it sends to was configured at.
If I look at /var/log/mailog I can see where it tries/does send the mails to that email address. But it doesn't seem to give me any good clues as to where it's configured to send to that specific address. Does anyone know where I might find that? I'd like to change it to a different address.

A: Not sure 100% about what you are asking for, but if I understood, you want to send emails to whatever@example.com instead of current@example.com.
As they are system messages, you'd only need to edit /etc/aliases. There will probably be a line there saying:
root:    current@example.com
So, you would only need to change the email adress to your preference and then execute
newaliases
I think it's not needed to restart/reload postfix but I always like to do so for every service
service postfix restart
Documentation about /etc/aliases can be found here


text:
Q: Estimating pi with a Monte Carlo method results in a larger value than expected I'm trying to estimate pi by dividing the areas of a square and its embedded circle, but I get ~3.66.
Does anyone see what I'm doing wrong?
inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    if r>0.5*L:
        outCount=outCount+1
    if r==0.5*L:
        inCount=inCount+1
        outCount=outCount+1
pigen=inCount/outCount
print('pi generated: '+np.str(pigen))

A: You have
pigen=inCount/outCount

which gives the proportion of hits inside to outside the radius.
Note that pi/(4-pi) = 3.659792... which is what your code is currently estimating.
You need
pigen=4*inCount/(inCount+outCount)

which will give you four times the proportion of hits inside compared to the total, i.e. pi.

Also note that your code is currently
if r<0.5*L:
    inCount=inCount+1
if r>0.5*L:
    outCount=outCount+1
if r==0.5*L:
    inCount=inCount+1
    outCount=outCount+1

which can be simplified with elif/else. Since r cannot be both greater than, and less than, L, the second if can become an elif. Likewise, if r is neither less than, or greater than, L then it must be equal so the third if can simply become an else.
if r<0.5*L:
    inCount=inCount+1
elif r>0.5*L:
    outCount=outCount+1
else:
    inCount=inCount+1
    outCount=outCount+1

This will prevent unnecesary comparisons of r and L in your code.

Your final code would then be
inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    elif r>0.5*L:
        outCount=outCount+1
    else:
        inCount=inCount+1
        outCount=outCount+1
pigen=pigen=4*inCount/(inCount+outCount)
print('pi generated: '+np.str(pigen))

A: inCount+outCount = 4*r^2
inCount = pi*r^2

So if you need to get pi
pigen=inCount/(outCount+inCount)*4

A: Wai Ha Lee was almost right! I also had forgotten to add a 4.
If anyone wants to know how it goes, it's like that (and yes, L can be whatever you want):
import numpy as np
import random as rnd
inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    if r>0.5*L:
        outCount=outCount+1
    if r==0.5*L:
        inCount=inCount+1
        outCount=outCount+1
pigen=4*inCount/(inCount+outCount)
print('pi generat: '+np.str(pigen))

A: inCount shows the number of points within a circle of radius r = L/2 and outCount shows the number of points in a square exactly containing that circle, but not in the circle itself.
inCount is proportional to pi * r**2 and outCount is proportional to L**2 - pi * r**2 = (4 - pi) * r**2. When you take the ratio you get pi / (4 - pi) = 3.66.
As Wai Ha Lee pointed out, you need to calculate 4 * inCount / (inCount+outCount) = pi.


text:
Q: How to use Prime31 Google In App Billing Plugin I just bought "Google In App Billing Plugin for unity3d" by Prime31. I don't understand how to use it in the game that I want to develop.
Can you please show me a code example? I understand I need to use my app key, but I don't know what to do next.
And how to a I make test purchases with this plugin?
Please help as much as you can, because I am really stuck on this subject for quite a while.
This is some of my "purchase maker" object called MoneyTakerScript (inherits from MonoBehaviour):
void Start()
{

    string key = "My App Key...";

    GoogleIAB.init(key);

    var skus = new string[] { "cl.48931", "tp.58932", "mmm.68393" };
    GoogleIAB.queryInventory( skus );

    TPS = GameObject.Find("TPBtn").GetComponent(typeof(TPScript)) as TPScript;
    CLS = GameObject.Find("CLBtn").GetComponent(typeof(CLScript)) as CLScript;
    MMM = GameObject.Find("MMBtn").GetComponent(typeof(MMMScript)) as MMMScript;
}

public void Purchase(string ProductId)
{
    GoogleIAB.purchaseProduct(ProductId);

}

public void UseProduct(string ProductId)
{

    if (ProductId.Contains("cl"))
    {
        CLS.MakeCL();

    }
    if (ProductId.Contains("tp"))
    {
        TPS.MakeTP();

    }
    if (ProductId.Contains("mmm"))
    {
        MMM.MakeMMM();

    }

    GoogleIAB.consumeProduct(ProductId);
}

And this is some of my "purchase listner" object code:
 void purchaseSucceededEvent(GooglePurchase purchase)
{
    //Debug.Log( "purchaseSucceededEvent: " + purchase );
    MoneyScript.UseProduct(purchase.productId);

}

  void Start()
{
    MoneyScript = GameObject.Find("MoneyTaker").GetComponent(typeof(MoneyTakerScript)) as
    MoneyTakerScript;
}

A: I found the problem and solved it!
This line was missing in my AndroidManifest.Xml for some reason:
<activity android:name="com.prime31.GoogleIABProxyActivity"></activity>

Just added the line and now I have In App Purchase!!


text:
Q: using column names when appending data in write.table I am looping through some data, and appending it to csv file. What I want is to have column names on the top of the file once, and then as it loops to not repeat column names in the middle of file.
If I do col.names=T, it repeats including column names for each new loop. If I have col.names=F, there are no column names at all.
How do I do this most efficiently? I feel that this is such a common case that there must be a way to do it, without writing code especially to handle it.
write.table(dd, "data.csv", append=TRUE, col.names=T)

A: You may or may not also see a problem with the row names being identical, as write.table does not allow identical row names when appending. You could give this a try.  In the first write to file, try write.table with row.names = FALSE only.  Then, starting from the second write to file, use both  col.names = FALSE and row.names = FALSE
Here's the first write to file
> d1 <- data.frame(A = 1:5, B = 1:5)                ## example data
> write.table(d1, "file.txt", row.names = FALSE)

We can check it with read.table("file.txt", header = TRUE).  Then we can append the same data frame to that file with
> write.table(d1, "file.txt", row.names = FALSE,
              col.names = FALSE, append = TRUE)

And again we can check it with read.table("file.txt", header = TRUE)
So, if you have a list of data frames, say dlst, your code chunk that appends the data frames together might look something like
> dlst <- rep(list(d1), 3)                              ## list of example data
> write.table(dlst[1], "file.txt", row.names = FALSE)
> invisible(lapply(dlst[-1], write.table, "file.txt", row.names = FALSE,
                   col.names = FALSE, append = TRUE))

But as @MrFlick suggests, it would be much better to append the data frames in R, and then send them to file once.  This would eliminate many possible errors/problems that could occur while writing to file.  If the data is in a list, that could be done with
> dc <- do.call(rbind, dlst)
> write.table(dc, "file.txt")

A: See ?file.exists.
write.table(dd, "data.csv", append=TRUE, col.names=!file.exists("data.csv"))

Thus column names are written only when you are not appending to a file that already exists.

A: Try changing the column names of the data frame using names() command in R and replace with the same names as existing and then try the dbWriteTable command keeping row.names = False. The issue will get solved.
e.g.
if your data frame df1 has columns as obs, name, age then
names(df1) <- c('obs','name','age')

and then try
dbWriteTable(conn, 'table_name', df1, append = T, row.names = F)


text:
Q: Can I call ajax function inside another ajax function? I am using jquery for getting ajax responses from server side functions.
I am in a situation where I need to make two ajax calls one after another and the second one is dependent on the response of the first one.
I have tried to use a code which is similar to this one?
$.ajax({
        type: 'GET',
        url: 'myURL',
        success: function(data1)
        {
               if(data1==1)
               {
                   $.get('newURL', function(data2)
                   {
                       $('#myElement').html(data2);
                   });
                   $('#myElement').html(data1);
               }
        }
});

Is it possible to get two have two ajax calls , one dependent on the other?
if it's possible please explain with demo code . i am new in jquery
Thanks.


text:
Q: Javascript and Cross Origin i've been working on a lookup using a third party API, so someone completes a form, submits it, this then looks up the record at the third party and returns an array.
I've got it working on 2 seperate pages but i'd like to roll it into one page and remove the need for a refresh, I looked at converting the code and using and xhr request to get the data but the thrid party have said it wont work because they don't support Cross Origin data/lookups.
I know tha PHP and Javascript are totally different and that PHP is executed server side but is there a way to use OnClick on the button to pass the form data using php get the results then pass that to javascript?
any help or pointers would be greatly appreciated
so in short i wanted to be able to condense these 2 pages into one so they enter the lookup details, click submit, it then runs the lookup from page 2 and fills in the second form.
Code is as followS:
page 1:
<?php
//login and get authtoken
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://thirdpartyurl.com",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\r\n\"grant_type\" : \"client_credentials\",\r\n\"client_id\" : \"NEWTOCODE\",\r\n\"client_secret\": \"PASSHERE\"\r\n}\r\n",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: Bearer da97e45a4690fb34fe409571a40ef325412d576b",
    "cache-control: no-cache",
    "content-type: application/json",

  ),
));

//  $response = curl_exec($curl);

curl_close($curl);

?>

For demo purposes only

       <form method="post" action="page2.php">
  Name  <input type="text" name="Name" value="">

  Email  <input type="text" name="Email" value="">

 <input type="submit" value="Submit">
</form>

Page 2:
<?php
$NAME1= $_POST["name"];
$Email= $_POST["email"];
$curl = curl_init();
// complete lookup using posted data
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://thirdpartyurl.com/lookup",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\r\n   \"NAME\": \"$NAME1\",\r\n   \"EMAIL\":\"$EMAIL1\"\r\n}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/thirdpartyurl.com.v2+json",
    "authorization: Bearer 6323arad0",
    "cache-control: no-cache",
    "content-type: application/thirdpartyurl.com.v2+json",

  ),
));

$response = curl_exec($curl);

curl_close($curl);

$userData = json_decode($response, TRUE);

?>
<form>
 Name  <input type="text" name="Name" value="">

  Mileage  <input type="text" name="Email" value="">

 address1  <input type="text" name="add1" value="">

 address2  <input type="text" name="add2" value="">

</form>


text:
Q: how to remove JDBC debug logs The following log is constantly thrown to the console:
09:36:53.456 [CloseConnectionsTimer] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource

09:36:53.456 [CloseConnectionsTimer] DEBUG o.s.jdbc.core.StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [0], value class [java.lang.Long], SQL type -5

09:36:53.456 [CloseConnectionsTimer] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource

09:36:53.472 [CloseConnectionsTimer] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL query

09:36:53.472 [CloseConnectionsTimer] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement..

09:36:53.472 [CloseConnectionsTimer] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource

09:36:53.472 [CloseConnectionsTimer] DEBUG o.s.jdbc.core.StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [0], value class [java.lang.Integer], SQL type 2

09:36:53.472 [CloseConnectionsTimer] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource

How can i stop these logs/Change the logging level to INFO or ERROR?

A: Anything less than debug level will make those logs disappear. eg. INFO, WARN, ERROR

A: First of all, those are not JDBC logs, those are Spring logs.
Anyway, this should do the job in slf4j or log4j:
<logger name="org.spring.jdbc" level="OFF"/>


text:
Q: Can't open Inkscape file in Adobe Illustrator CS 3 I have an Inkscape file that I need to open in Illustrator but it won't work.
I tried to save the Inkscape file as .svg but when I open it up in Illustrator I get

"bitstream vera sans: a unknown error
  has occurred"
"the document "document.svg" uses
  fonts or characters which are not
  available or are in a different format
  that originally specified."

A: You can download the font here.

A: Bitstream Vera Sans is a free font, you should be able to download a copy if you don't have it installed on your computer.

A: If installing the font does not produce identical results (often the case when switching between vector editors), you can convert text to path. Select your text in Inkscape and do

Path -> Object to path

or ctrlshiftc
Note that this means you can no longer edit the text; it behaves as a graphic.


text:
Q: fetchone vs fetchone[0] in python sqlite3 I have a function like the below to get data from SQLite3 table.
def remedysql(crop, disease):
    try:
        conn = sqlite3.connect('plant_protection.db')
        mycur = conn.cursor()
        sql=f'select remedy from pp_remedy WHERE crop="{crop}" and disease="{disease}"'
        #remedy = mycur.execute(sql).fetchone()[0]
        mycur.execute(sql)
        remedy = mycur.fetchone()[0]
        return remedy
    except sqlite3.Error as error:
        print("Error while connecting to sqlite plantprot DB")

For the combination of "crop" and "disease", there will only be one record or none. The above function works fine when I give fetchone()[0], but does not work when I give only fetchone() without [0].
Also please advise how to handle the NoneType (no record) exception here.

A: From the doc:

fetchone()
Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.

The return value is a tuple, so remedy will be found at the first element, i.e. fetchone()[0]. In the case where the query returns None, there is no 0th element, so program will give a TypeError.
One solution would be to use fetchone() and make sure it has returned a row before accessing the index. E.G.
remedy = mycur.fetchone()
if remedy:
    return remedy[0]
else:
    return None


text:
Q: Intersect method not working, keeps returning true My intersect method keeps returning true and setting my "score text" to intersect detected when my images do not collide, instead it changes the text as soon as the emulator starts. Please notify me if more code is needed and check back within 10 minutes. Thanks! -this is all my code and collision code starts at line 163, something is wrong with my collision code because collision isn't being detected, what should I do to fix my collision code.
here is my code:
public class MainActivity extends AppCompatActivity {

//Layout
private RelativeLayout myLayout = null;

//Screen Size
private int screenWidth;
private int screenHeight;

//Position
private float ballDownY;
private float ballDownX;

//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();

//Images
private ImageView net = null;
private ImageView ball = null;

//for net movement along x-axis
float x;
float y;

//points
private int points = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    myLayout = (RelativeLayout) findViewById(R.id.myLayout);

    //score
    TextView score = (TextView) findViewById(R.id.score);

    //imageviews
    net = (ImageView) findViewById(R.id.net);
    ball = (ImageView) findViewById(R.id.ball);

    //retrieving screen size
    WindowManager wm = getWindowManager();
    Display disp = wm.getDefaultDisplay();
    Point size = new Point();
    disp.getSize(size);
    screenWidth = size.x;
    screenHeight = size.y;

    //move to out of screen
    ball.setX(-80.0f);
    ball.setY(screenHeight + 80.0f);

    //start timer
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    changePos();
                }
            });
        }
    }, 0, 20);
}

public void changePos() {
    //down

    ballDownY += 10;
    if (ball.getY() > screenHeight) {
        ballDownX = (float) Math.floor((Math.random() * (screenWidth -
ball.getWidth())));
        ballDownY = -100.0f;

    }
    ball.setY(ballDownY);
    ball.setX(ballDownX);

    /*INTERSECT METHOD
    Rect rc1 = new Rect();
    net.getDrawingRect(rc1);
    Rect rc2 = new Rect();
    ball.getDrawingRect(rc2);
    if (Rect.intersects(rc1, rc2)) {

    TextView score = (TextView) findViewById(R.id.score);
    score.setText("INTERSECT DETECTED");

    }*/

    //make net follow finger
    myLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            MainActivity.this.x = event.getX();
            y = event.getY();

            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                net.setX(MainActivity.this.x);
                net.setY(y);

            }
            return true;
        }

    });

}

public boolean Collision(ImageView net, ImageView ball)
{
    Rect AR = new Rect();
    net.getHitRect(AR);
    Rect BR = new Rect();
    ball.getHitRect(BR);
    Render();
    return AR.intersect(BR) || AR.contains(BR) || BR.contains(AR);
}

public void Render()
{
    if(Collision(net, ball))
    {
        points++;
        TextView score = (TextView)findViewById(R.id.score);
        score.setText("Score:" + points);
    }
}

}

A: Something like this:
boolean collision = net.getRect().intersect(ball.getRect());

Collision is a boolean
if(boolean) //Action

Then
if(collision) score.setText("INTERSECT DETECTED");

OR
public boolean Collision(ImageView a, ImageView b)
{
  Rect AR = new Rect();
  a.getHitRect(myViewRect);
  Rect BR = new Rect();
  b.getHitRect(otherViewRect1);
  return Rect.intersects(AR, BR);
}

--
if(Collision(net, ball))
{
   //Do action
}

--
ImageView ball = (ImageView) findViewById(R.id.Ball);
ImageView net = (ImageView) findViewById(R.id.Net);

if(Collision(net, ball))
{
   //Collision detected
}

--
import android.graphics.Rect;

public boolean Collision(ImageView ball, ImageView net)
{
Rect ballRect = new Rect();
ball.getDrawingRect(ballRect);
Rect netRect = new Rect();
net.getDrawingRect(netRect);
return Rect.intersects(ballRect, netRect);
}

Check this post how to detect when a ImageView is in collision with another ImageView?

A: I have reformed your code, try now
public class MainActivity extends AppCompatActivity
{
   //Layout
   private RelativeLayout myLayout = null;

   //Screen Size
   private int screenWidth;
   private int screenHeight;

   //Position
   private float ballDownY;
   private float ballDownX;

   //Initialize Class
   private Handler handler = new Handler();
   private Timer timer = new Timer();

   //Images
   private ImageView net = null;
   private ImageView ball = null;

   //score
   private TextView score = null;

   //for net movement along x-axis
   public float x = 0;
   public float y = 0;

   //points
   private int points = 0;

   @Override
    protected void onCreate(Bundle savedInstanceState)
    {
         super.onCreate(savedInstanceState);

         this.setContentView(R.layout.activity_main);
         this.myLayout = (RelativeLayout) findViewById(R.id.myLayout);

         this.score = (TextView) findViewById(R.id.score);

         this.net = (ImageView) findViewById(R.id.net);
         this.ball = (ImageView) findViewById(R.id.ball);

         //retrieving screen size
         WindowManager wm = getWindowManager();
         Display disp = wm.getDefaultDisplay();
         Point size = new Point();
         disp.getSize(size);
         screenWidth = size.x;
         screenHeight = size.y;

         //move to out of screen
         this.ball.setX(-80.0f);
         this.ball.setY(screenHeight + 80.0f);

          //Error here
         /*//Run constantly
         new Handler().postDelayed(new Runnable()
         {
           @Override
           public void run()
           {
              Render();
           }
         }, 100); //100 is miliseconds interval than sleep this process, 1000 miliseconds is 1 second*/

     Thread t = new Thread() {
     @Override
     public void run() {
     try {
        while (!isInterrupted()) {
             Thread.sleep(100);
             runOnUiThread(new Runnable() {
             @Override
             public void run(){Render();}});}
             }catch (InterruptedException e) {}}};

     t.start();

    }

    public void Render()
    {
        changePos();
        if(Collision(net, ball))
        {
          points++; //You dont need findView Textview score for that exists in OnCreate Method
          this.score.setText("Score:" + points);
        }
    }

    public void changePos()
    {

        //down
        ballDownY += 10;
        if (ball.getY() > screenHeight) {
        ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth())));
        ballDownY = -100.0f;

    }
    ball.setY(ballDownY);
    ball.setX(ballDownX);

      //make net follow finger
      myLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            x = event.getX();
            y = event.getY();

            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                net.setX(x);
                net.setY(y);
            }
            return true;
        }

    });

    public boolean Collision(ImageView net, ImageView ball)
    {
       Rect BallRect = new Rect();
       ball.getHitRect(BallRect);
       Rect NetRect = new Rect();
       net.getHitRect(NetRect);
       return BallRect.intersect(NetRect);
    }
}


text:
Q: Is there a word or phrase for giving something to a highly respected person? I am looking for a better word choice for give when we give something to a highly respected person (or an entity, such as an organization, a government, or a country).
The basic sense of the word give is usually sufficient to describe the act of giving something to someone. However, in most Asian cultures, we usually use different words for giving something to a person with equal or lower social status (in this case give is quite perfect), from giving something to a person who has higher social status, especially when that person is highly respectable in the society. (A venerable person might be an appropriate term here.) This "something" could be abstract, such as respect, loyalty, an honorable title, or concrete, such as money, a souvenir, a celebration, a tribute, and so on.
Some words I found in dictionaries are offer, dedicate, and consecrate are close, but not quite.
Is there a word, or a short phrase, for this verb in English?

A: The word bestow comes to mind.
to convey as a gift —usually used with on or upon

The university bestowed on her an honorary degree.

Google:

Confer or present (an honor, right, or gift).
  "the office was bestowed on him by the chief of state"
  synonyms:   confer on, grant, accord, afford, endow

A: Present comes to mind. It's also part of the definition of bestow in mplungjan's answer.
Particularly the definition:

Give or award formally or ceremonially.

"They presented him with extravagant gifts"

  You will present something to them.

I have tried to think of how it could be applied to non physical gifts such as respect, but in those cases I don't think it works well, though I think it could fit if the sentence was structured right.
Something like:

He was presented with a display of respect and loyalty.

A: You can "flatter" someone with words, gifts or compliments.


text:
Q: How to avoid blocking of queue browsing after ActiveMQ checkpoint call There's a problem when Using ActiveMQ with a large number of Persistence Queues (250) á 1000 persistent TextMessages á 10 KB.
A scenario requires these messages to remain in the storage over a long time (days), until they are consumed (large amounts of data are staged for distribution for many consumer, that could be offline for some days).
After the Persistence Store is filled with these Messages and after a broker restart we can browse/consume some Queues  until the #checkpoint call after 30 seconds.
This call causes the broker to use all available memory and never releases it for other tasks such as Queue browse/consume. Internally the MessageCursor seems to decide, that there is not enough memory and stops delivery of queue content to browsers/consumers.
=> Is there a way to avoid this behaviour by configuration or is this a bug?
The expectation is, that we can consume/browse any queue under all circumstances.
Settings below are in production for some time now and several recommendations are applied found in the ActiveMQ documentation (destination policies, systemUsage, persistence store options etc.)

*

*Behaviour is tested with ActiveMQ: 5.11.2, 5.13.0 and 5.5.1.

*Memory Settings: Xmx=1024m

*Java: 1.8 or 1.7

*OS: Windows, MacOS, Linux

*PersistenceAdapter: KahaDB or LevelDB

*Disc: enough free space (200 GB) and physical memory (16 GB max).

Besides the above mentioned settings we use the following settings for the broker (btw: changing the memoryLimit to a lower value like 1mb does not change the situation):
<destinationPolicy>
    <policyMap>
        <policyEntries>
            <policyEntry queue=">" producerFlowControl="false" optimizedDispatch="true" memoryLimit="128mb" timeBeforeDispatchStarts="1000">
                <dispatchPolicy>
                    <strictOrderDispatchPolicy />
                </dispatchPolicy>
                <pendingQueuePolicy>
                    <storeCursor />
                </pendingQueuePolicy>
            </policyEntry>
        </policyEntries>
    </policyMap>
</destinationPolicy>
<systemUsage>
    <systemUsage sendFailIfNoSpace="true">
        <memoryUsage>
            <memoryUsage limit="500 mb" />
        </memoryUsage>
        <storeUsage>
            <storeUsage limit="80000 mb" />
        </storeUsage>
        <tempUsage>
            <tempUsage limit="1000 mb" />
        </tempUsage>
    </systemUsage>
</systemUsage>

If we set the cursorMemoryHighWaterMark in the destinationPolicy to a higher value like 150 or 600 depending on the difference between memoryUsage and the available heap space relieves the situation a bit for a workaround, but this is not really an option for production systems in my point of view.
Screenie with information from Oracle Mission Control showing those ActiveMQTextMessage instances that are never released from memory:
http://goo.gl/EjEixV

A: I had a similar issue and ActiveMQ is not really designed to be a "database"; messages must flow through ActiveMQ and for these long-term storage I'd recommend using a database or exchange files using FTP.
I'd also recommend using producerFlowControl="true" so if ActiveMQ is not able to process messages, it will slow down the producer.

A: We have a solution for our problem by changing the (queue) destination
policyEntry.
After a thorough investigation (w/o changing ActiveMQ source code) the result is for now that we need to accept the limitations defined by the single memoryLimit parameter used both for the #checkpoint/cleanup process and browsing/consuming queues.
1.) Memory
There is not a problem, if we use a much higher memoryLimit (together
with a higher max-heap) to support both the message caching per
destination during the #checkpoint/cleanup workflow and our requirements to
browse/consume messages.
But more memory is not an option in our scenario, we need to deal with 1024m max-heap and 500m memoryLimit.
Besides this, constantly setting higher memoryLimits just because of more persistent queues containing hundreds/thousands of pending messages together with certain offline/inactive consumer scenarios should be discussed in detail (IMHO).
2.) Persistent Adapters
We ruled out persistent adapters as the cause of the problem, because the behaviour doesn't change, if we switch different types of persistent stores (KahaDB, LevelDB, JDBC-PostgreSQL).
During the debugging sessions with KahaDB we also see regular checkpoint handling, the storage is managed as expected.
3.) Destination Policy / Expiration Check
Our problem completely disappears, if we disable caching and the expiration check, which is the actual cause of the problem.
The corresponding properties are documented and there is a nice blog article about Message Priorities with a description quite suitable for our scenario:

*

*http://activemq.apache.org/how-can-i-support-priority-queues.html

*http://blog.christianposta.com/activemq/activemq-message-priorities-how-it-works/
We simply added useCache="false" and expireMessagesPeriod="0" to the
policyEntry:
<destinationPolicy>
    <policyMap>
        <policyEntries>
            <policyEntry queue=">" producerFlowControl="false" optimizedDispatch="true" memoryLimit="128mb" timeBeforeDispatchStarts="1000"
                                   useCache="false" expireMessagesPeriod="0">
                <dispatchPolicy>
                    <strictOrderDispatchPolicy />
                </dispatchPolicy>
                <pendingQueuePolicy>
                    <storeCursor />
                </pendingQueuePolicy>
            </policyEntry>
        </policyEntries>
    </policyMap>
</destinationPolicy>

The consequences are clear, if we don't use in-mem caching anymore and never
check for message expiration.
For we neither use message expiration nor message priorities and the current message dispatching is fast enough for us, this trade-off is acceptable regarding given system limitations.
One should also think about well-defined prefetch limits for memory consumption during specific workflows. Message sizes in our scenario can be 2 Bytes up to approx. 100 KB, so more individual policyEntries and client consumer configurations could be helpful to optimize system behaviour concerning performance and memory usage (see http://activemq.apache.org/per-destination-policies.html).


text:
Q: Proxy/convert existing GraphQL API to REST We have an existing private GraphQL server that powers our React application and would like to possibly expose a subset of the functionality as REST endpoints. This way we do not have to support 2 code bases, one for GraphQL and one for the REST APIs.
How would I take an existing GraphQL server and create a wrapper/proxy layer to expose of the schema as REST endpoints?

A: Check out this package (graphql2rest): https://github.com/sisense/graphql2rest
You can use it to automatically generate a REST API from your existing GraphQL API - just what you need.
"GraphQL2REST is a Node.js library that reads your GraphQL schema and a user-provided manifest file and automatically generates an Express router with fully RESTful HTTP routes — a full-fledged REST API."

A: (Edit: Someone ended up building a library to do pretty much what I described below! Try it here: https://www.npmjs.com/package/rest-graphql)
I think the best way to do this is not to generate the API from the types in the schema, but to expose specific queries as endpoints. That way, you can return the exact shape of data you want to send to the client. The best part is, GraphQL already has all of the tools you need, including handling for parameters!
So for example you want to create an endpoint:
/posts/1

Let's say you want that to map onto this query:
const postByIdQuery = `
  query postById($postId: Int!) {
    post(id: $postId) {
      title
      description
      author {
        name
      }
    }
  }
`;

Then in your server-side REST API library (for example express), you could do something like:
app.get('/posts/:postId', function (req, res) {
  graphql(
    schema, // same schema as your graphql api
    postByIDQuery, // the query from above
    rootValue, context, // set these same way as for your graphql endpoint
    req.params // use the route params as variables!
  ).then((result) => {
    res.send(result);
  }).catch((error) => {
    // something to handle errors
  });;
})

If you have a lot of endpoints you want to create, I'd make a helper function, something like:
function addEndpointFromQuery(app, path, query) {
  // generates endpoint like the above sample
}

The really neat thing here is that your route params (:postId in this case) just need to match up with your declared query variables ($postId) and then they can be wired together automatically! Then you could simply call your helper function to do the above:
addEndpointFromQuery(app, '/posts/:postId', `
  query postById($postId: Int!) {
    post(id: $postId) {
      title
      description
      author {
        name
      }
    }
  }
`);

If you wanted to, you could also add an extra parameter to transform the results to fit your desired REST response format.
I think someone could build a library to do this, but it feels like it will be pretty specific to the app, with a particular response format, way of generating context, etc. So personally I would suggest writing your own helper like the above, and it could probably be done in less than 50 lines of code.


text:
Q: Signal noise cancelled by touching the leads I have a pressure sensor that outputs 0.5V with a +/- 20 mV noise.  I am trying to identify the root cause of the noise using an oscilloscope.
The noise occurs in waves of twice the mains frequency, and each noise wave pulse is made of smaller pulses of much higher fequency.
The noise used to be much higher when I was using a "wall wart" 12V power supply to the sensor than when I used the bench top power supply or a proper 12 V dedicated power supply.
Weird clue 1)  although the noise was partially related to the power supply used, the power output of the wall wart supply didnt show any noise.EDIT: the noise is there, but catching a 50mV noise on a 12V signal was just difficult on my oscilloscope.
Weird clue 2) when I touch with my finger the conductive probes (either positive or negative) of the oscilloscope, while measuring the sensor signal, the noise decreases
I got minor improvement in the noise by putting capacitors between the signal and the ground, but I have a feeling my main issue is elsewhere. Can you please clarify the root cause of the noise ?
Edit: after suggestions, please find the oscillo screen using different power supplies

A: If a conductor is coupled to mains power through a very small capacitor, then within that conductor the noise appears to have a high source impedance. If a conductor with noise with a high source impedance is coupled to ground through a "low" (relatively speaking) impedance, such as a larger capacitor, then the two impedances will form an attenuator or voltage divider.
The fact that the noise in your case becomes significantly attenuated when you touch the leads, or attach capacitors to ground tells me that in your case, the noise does indeed have a high source impedance. It could be caused by capacitance in the windings of the transformer or inductor of your power supply. It could be caused by intentionally added capacitors in your power supply. Often such capacitors are added to eliminate one kind of noise, (often required by law or regulation) but have the side effect of facilitating another kind of noise (the noise you are seeing). Or the noise could be coupled to your circuit through some other "stray" capacitance.

A: A capacitance from the DC output to the table kills all the 50hz noise


text:
Q: Laravel check if attributes have products I have model Attribute, and I have model AttributeValue. I have relation products in AttributeValues belongsToMany. I want check in model Attribute if products exists in AttributeValues. I tried:
public function values()
{
    return $this->hasMany(AttributeValue::class);
}

public function getProductsExistsAttribute()
{
    return $this->values->each->products()->exists();
}

AttributeValue model:
public function attribute()
{
    return $this->belongsTo(Attribute::class);
}

public function products()
{
    return $this->belongsToMany(Product::class, 'product_attribute_values');
}

But is not work. I get error: Method Illuminate\Database\Eloquent\Collection::exists does not exist.. How I can resolve this issue?


text:
Q: How to perform coefficient test in linear model with robust covariance matrix? I estimate a linear model and then calculate a (White) heteroscedasticity robust variance covariance matrix.  This allows me to do the following (where hr.cov is the robust covariance matrix):
> coeftest(model, hr.cov)

t test of coefficients:

              Estimate Std. Error t value  Pr(>|t|)
(Intercept) 157.146959  14.760426 10.6465  8.99e-15 ***
x             0.134499   0.033050  4.0696 0.0001575 ***
d            20.921722  16.043356  1.3041 0.1978438
x:d           0.068120   0.047416  1.4366 0.1566992
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I would like to do a one sided test whether d<0 (as opposed to different from 0 in both directions which is what is shown above).  I would like to be able to type something like test(model,d<0,hr.cov).  How should I go about this?


text:
Q: How to send integer as a string with WriteFile for serialport I want to send an integer as a string buffer to a serial port with WriteFile. This data value is result from the sensor, this data max has 2 characters.
I have tried to convert with itoa
for example:
 DWORD nbytes;
 int a,b,c;
 a=10;
char *tempa ="";
tempa = itoa(a, tempa,0);
if(!WriteFile( hnd_serial, a, 2, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}

This code is not working.
Unhandled exception at 0x1024d496 (msvcr100d.dll) in ENVSConfig.exe: 0xC0000094: Integer division by zero.

Also I have tried the suggestion from this website:
convert int to string but still does not working to.
Is there any clue to do this?

A: You are not using itoa properly, you need to allocate space for your string, you need to provide a proper radix (this is where your divide-by-zero error is happening) and finally you need to use the buffer, not your original a value, as the buffer in your write.
Try the following:
DWORD nbytes;
int a,b,c;
a = 10;
char tempa[64];  // Randomly picked 64 characters as the max size
itoa(a, tempa, 10);
if(!WriteFile(hnd_serial, tempa, 2, &nbytes, NULL))
{
    MessageBox(L"Write Com Port fail!");
    return;
}


text:
Q: function for complex assignment of number to letters ORIGINAL QUESTION: I'm struggeling to write a function for assigning numbers to letters under complex conditions. Please have a look at the example tibble. I need a way to get the values in df$nr.
library(tidyverse)
df <-tibble(word=c(rep("Hobbies", 17), rep("tate", 11)),
            let=c("H1","H1","H2","H2","o","o","b","b","b","b","i","i","e","e","iP","iP","s",
                  "t1","t1","a","a","t1","t1","e","e","t2","t2","t2"),
            tra=c(NA,"H2",NA,"o",NA,"b",NA,"b",NA,"i",NA,"e",NA,"iP",NA,"s",NA,
                  NA,"a",NA,"t1",NA,"e",NA,"t2",NA,"t2",NA),
            nr= c(1,1,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6,6,6.5,7,
                  1,1.5,2,2.5,3,3.5,4,4,4,4,4) )

UPDATE / SOLUTION
I'm not using a function, but I found a solution based on dplyr::case_when. There are still two errors: In eval_bare(f[[2]], env) : NAs introduced by coercion. They come from checking a substring that's not present in all cases, but I don't know how to get rid of them.
df <- df %>%
  group_by(word) %>%
  mutate(
    test = cumsum(
      case_when (
        # first letter per word -> 1
        row_number()==1L                            ~ 1,
        # tra is NA -> full letter, should result in an integer in the end
        # special case: dots (e.g. on 'i' -> "iP", this is not a full letter -> do nothing
        is.na(tra) & str_sub(let,2,2)=="P"          ~ 0,
        # special case: fraction of a letter (e.g. "H2" or "t2"), i.e. number is > 1 -> do nothing
        is.na(tra) & as.integer(str_sub(let,2,2))>1 ~ 0,
        # full letter -> 0.5
        is.na(tra)                                  ~ 0.5,
        # tra is present -> trajectory towards next letter, should result in .5 in the end
        # special case: tra to dot -> do nothing
        str_sub(tra,2,2)=="P"                       ~ 0,
        # special case: tra to fraction -> do nothing
        as.integer(str_sub(tra,2,2))>1              ~ 0,
        # all other tra
        TRUE                                        ~ 0.5
        )
      )
    )

all.equal(df$nr, df$test)
[1] TRUE


text:
Q: Xcode6 how to set class prefix when create a new project? Unlike Xcode5, when create new project, there is not a input field for class prefix.
Did Apple abandon it?

A: Yes, Apple abandoned it.

After much deliberation, engineering has removed this feature.
This was removed intentionally. We are no longer encouraging the use of prefixes for app code, and for frameworks, you can create a prefix in the Project Inspector after creating the project.

Additional information can be found in this article.


text:
Q: apex:selectList inside a table column does not display correctly I've added an apex:selectList inside of a table column in a visualforce page.  The rendered output is wrong - the selectList doesn't show up in the correct column - it actually gets rendered in a new row along with some other misc table row / column tags:
Visualforce page markup:

            Item
            Lead Source

            Item 1

                <apex:selectList value="{!item1LeadSource}" size="1">
                    <apex:selectOptions value="{!leadSources}"/>
                </apex:selectList>

Rendered output

            Donation Source
            Lead Source

            Item 1

                <select name="j_id0:j_id28:j_id33:j_id34:j_id39" size="1">
                    <option value="Web" selected="selected">Web</option>
                    <option value="Phone Inquiry">Phone Inquiry</option>
                    <option value="Partner Referral">Partner Referral</option>
                    <option value="Purchased List">Purchased List</option>
                    <option value="Other">Other</option>
                </select>

Is this normal?

A: In response to the comment thread, going the raw HTML route, this page:
<apex:page controller="TestController">
    <select>
        <apex:repeat value="{!options}" var="o">
            <option value="{!o.value}">{!o.label}</option>
        </apex:repeat>
    </select>
</apex:page>

and this controller:
public class TestController {
    public SelectOption[] options {
        get {
            return new SelectOption[] {
                    new SelectOption('abc', 'abc'),
                    new SelectOption('def', 'def')
                    };
        }
   }
}

will output this HTML:
<select>
        <option value="abc">abc</option>
        <option value="def">def</option>
</select>

(You don't have to use the SelectOption class especially if the values and labels are the same.)


text:
Q: Reload/refresh image dont work I am automatically generating images, but the file with the same name is updated but not have browser updates
$("#imagem_teste").attr("src", data)

I try:
d = new Date();
$("#imagem_teste").attr("src", data+d.getTime());

,
$("#imagem_teste").attr("src", data + new Date().getTime());

,
$("#imagem_teste").removeAttr("src").attr("src", data);

and
$("#imagem_teste").attr("src", $("#imagem_teste").attr("src")+"?timestamp=" + new Date().getTime());

But still can not solve.
Thank help

A: You can execute this code to set a unique image source on some event. It is reading the existing src attribute value and appending a unique timestamp.
var name = $("#imagem_teste").attr("src");
name = name + '?'+$.now();
$("#imagem_teste").attr("src", name);

$.now() method generates a unique timestamp and is a shorthand for the number returned by the expression (new Date).getTime()
Working sample here


text:
Q: How to know when a WPF Window has snapped/unsnapped in Windows? Im using a WPF Window in the WindowsStyle='none';
With this I create my own custom window by giving the 'root' grid (the highest in the XAML-tree) a Margin of 20px and a DropShadow. The window itself is transparant, the grid has a white background.
When I set the WindowsStyle.Maximized, I remove the extra Margin and the DropShadow . When I set WindowsStyle.Normal I add the extra Margin and the DropShadow again.
But when I snap my WPF window in Windows 10 to a corner or side of my screen. It snaps but I dont get an Window.StateChanged event.
My question is: Is there anyway to figure out when my Window has snapped in Windows and when it Unsnapped?


text:
Q: Actualizar el valor de una columna de una BBDD Mi problema es que tengo que actualizar el campo TOTAL_IMPORTE de la tabla Clientes con la suma de los albaranes (que coincidan con el código de cliente, de la tabla Clientes, que meta el usuario)que se encuentran en la tabla Lineas.El código de cliente que introduce el usuario primero tengo que ver si existe en la BBDD. Y cuando ejecuto el programa me da el error de Before start of result set. Todo esto en la BBDD de Almacen.
Aquí dejo el código:
package BBDD;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class Ejer9 {

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        String cliente;
        int suma=0;
        System.out.println("Introduce el cod de cliente al que quieras que se le actualice el importe:");
        cliente=sc.nextLine();
        try {

            Connection primeraConexion=DriverManager.getConnection("jdbc:mysql://localhost/almacen","root","");

            Statement a=primeraConexion.createStatement();

            ResultSet segundo=a.executeQuery("SELECT count( * ) as BINGO FROM `clientes` WHERE cliente LIKE "+"'"+cliente+"'");

            while(segundo.next()) {

                if (Integer.parseInt(segundo.getString("BINGO"))>0) {
                        //2. Crear objeto statement y metemos la sentencia SQL en un string para luego mediante el .executeUpdate insertarlo en la BBDD
                    Statement b=primeraConexion.createStatement();
                    Statement c=primeraConexion.createStatement();
                    ResultSet loQueActualiza=c.executeQuery("SELECT sum( precio ) as suma FROM lineas WHERE albaran = (SELECT albaran FROM albaranes WHERE cliente = (SELECT cliente FROM clientes WHERE cliente ="+"'"+cliente+"' ) )");
                    suma = Integer.parseInt(loQueActualiza.getString("suma"));
                    String actualizar="UPDATE `clientes` SET `TOTAL_FACTURA`="+"'"+suma+"' WHERE cliente LIKE "+"'"+cliente+"'";
                    //3. Comprobamos si se inserto la nueva tabla
                    b.executeUpdate(actualizar);
                    System.out.println("Datos insertados correctamente");
                } else {
                    System.out.println("El cliente introducido no existe");
                }

            }

        }catch(Exception e) {
            System.out.println("No es posible conectar con la BBDD.");
            System.out.println(e.getMessage());
        }

    }

}

A: Te falta llamar a .next() sobre loQueActualiza:
    package BBDD;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class Ejer9 {

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        String cliente;
        int suma=0;
        System.out.println("Introduce el cod de cliente al que quieras que se le actualice el importe:");
        cliente=sc.nextLine();
        try {

            Connection primeraConexion=DriverManager.getConnection("jdbc:mysql://localhost/almacen","root","");

            Statement a=primeraConexion.createStatement();

            ResultSet segundo=a.executeQuery("SELECT count( * ) as BINGO FROM `clientes` WHERE cliente LIKE "+"'"+cliente+"'");

            while(segundo.next()) {

                if (Integer.parseInt(segundo.getString("BINGO"))>0) {
                        //2. Crear objeto statement y metemos la sentencia SQL en un string para luego mediante el .executeUpdate insertarlo en la BBDD
                    Statement b=primeraConexion.createStatement();
                    Statement c=primeraConexion.createStatement();
                    ResultSet loQueActualiza=c.executeQuery("SELECT sum( precio ) as suma FROM lineas WHERE albaran = (SELECT albaran FROM albaranes WHERE cliente = (SELECT cliente FROM clientes WHERE cliente ="+"'"+cliente+"' ) )");
if (loQueActualiza.next()){
                    suma = Integer.parseInt(loQueActualiza.getString("suma"));
}
                    String actualizar="UPDATE `clientes` SET `TOTAL_FACTURA`="+"'"+suma+"' WHERE cliente LIKE "+"'"+cliente+"'";
                    //3. Comprobamos si se inserto la nueva tabla
                    b.executeUpdate(actualizar);
                    System.out.println("Datos insertados correctamente");
                } else {
                    System.out.println("El cliente introducido no existe");
                }

            }

        }catch(Exception e) {
            System.out.println("No es posible conectar con la BBDD.");
            System.out.println(e.getMessage());
        }

    }

}


text:
Q: C# Threading - Multiple threads spawned, only 1 or 2 are executing others waiting I've got this code below, where I spawn several threads, normally about 7, and join them to wait until all are done:
            List<Thread> threads = new List<Thread>();
            Thread thread;
            foreach (int size in _parameterCombinations.Keys)
            {
                thread = new Thread(new ParameterizedThreadStart(CalculateResults));
                thread.Start(size);
                threads.Add(thread);
            }

            // wait for all threads to finish
            for (int index = 0; index < threads.Count; index++)
            {
                threads[index].Join();
            }

When I check this most of the time only one or two threads are running at the same time, only once or twice when I rerun the app all of them executed.
Is there any way to force all the threads to start executing?
Many thanks.

A: Your code is fine.. i changed it abit to show you that the execution of the thread is not limited to 2 threads.
I would look for problems in the calculation process..
class Program
{
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        Thread thread;
        for (int i = 0; i < 7; i++)
        {
            thread = new Thread(new ParameterizedThreadStart(CalculateResults));
            thread.Start();
            threads.Add(thread);
        }

        // wait for all threads to finish
        for (int index = 0; index < threads.Count; index++)
        {
            threads[index].Join();
        }
    }

    static void CalculateResults(object obj)
    {
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is alive");
        Thread.Sleep(1000);
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is closing");
    }
}


text:
Q: Scoreboard Death caused by Players Setup My friends and I are setting up a lucky block skywars game, but it is really common to die from a lucky block, so how do I set up a death counter that would only count deaths caused by players?
I can easily change to any version so i just need a way to do this, i chose the older versions because they don't have the new PvP system as Quijibo said, and i chose 1.7.10 specifically because there are more kinds of lucky blocks atleast i think so
sorry for the inconvenience this is my first time making one of these posts

A: This nostalgic contraption was hard to make, is not very pretty, but works.
First of all, create 3 scoreboard objectives: a death count, a player kill count and a dummy objective. Let's call them ActualDeaths, PlayerKills and Deaths:
/scoreboard objectives add AcutalDeaths stat.deaths

/scoreboard objectives add PlayerKills stat.playerKills

/scoreboard objectives add Deaths dummy

Now, onto the command blocks:

I will be referring to the command blocks on the screenshot according to the colorful blocks I assigned to them, so for example, the one on the far right is the "blue" command block (and the two command blocks on the left-most are GREEN and PURPLE, not lime and magenta).
Anyways, let's get to the commands:
The blue command block is powered by a redstone clock, and simply tests if anyone has killed a player:
/testfor @a[score_PlayerKills_min=1]

The yellow command block is powered by the same redstone clock as the blue one, and tests if anyone has died:
/testfor @a[score_ActualDeaths_min=1]

The purple command block resets the ActualDeaths scores, so that the comparators leading from the yellow command block are reset:
/scoreboard players set @a ActualDeaths 0

The red and green command blocks run their commands only if both the blue and yellow command blocks have passed their /testfor commands at once (that's why the piston is there). Here's what they do:
The red command block adds 1 Deaths scoreboard point to every player that has a score of ActualDeaths at least 1 (in other words, it gives the point to anyone that has died in the last few gametics):
/scoreboard players add @a[score_ActualDeaths_min=1] Deaths 1

The green command block resets the PlayerKills scoreboard, so that the blue command block's comparator is reset:
/scoreboard players set @a PlayerKills 0

That's it! Be aware that it may not be perfect and it might fail counting in all deaths in cases like two players dying in the same tick, since the only way I was testing this was by shooting myself to death by arrows.


text:
Q: Как сделать взаимодействие между пользователями в Django Делаю веб приложение, которое предоставляет возможность соревноваться в прохождении викторины. Я хочу сделать так, чтобы у каждого пользователя загружался очередной вопрос, если кто-то из них уже ответил правильно. У меня совершенно нет идей, как сделать взаимодействие между пользователями. Полагаю, что должен быть создан компонент, который обращается к view, чтобы загрузить страницу всем пользователям, а view перед этим обращается к нему, чтобы дать сигнал к переменам. Предложите пожалуйста варианты решений.

A: Для етого вы можете использовать Websocket, в Django ecть Channels https://channels.readthedocs.io/en/latest/
В кратце вы загружаете страницу и подписываетесь на websocket канал и уже по каналу сможете отправлять данные с сервера на клиент в любое время. Ибо без етого вы не можете менять содержимое страницы в браузере без запроса к серверу.
Когда кто-то ответит то вы сможете по каналу отправить в браузер другого игрока следующий вопрос, а потом наоборот.
Пытался как можно проще написать ответ, что бы вы поняли куда вам копать.


text:
Q: How to initialize MPJ Express Outside main method? I'm trying to initialize the MPJ inside a function but I cant make the MPI.Init(args) work. I tried dragging along the args like this
    import mpi.*

    public class Test {
        String [] args
        public static void main(String [] args){
            Test.args = args;
            t.testFunction();
        }

        public void testFunction() {
            MPI.Init(args);
        }
    }

but I get an exception like this

Exception in thread "AWT-EventQueue-0" mpi.MPIException: Usage: java
  MPI    conf_file can be,
  ../conf/xdev.conf OR
  http://holly.dsg.port.ac.uk:15000/xdev.conf
      at mpi.MPI.Init(MPI.java:232)

The problem is my program works with an action listener on timer interrupts so I cant put it all inside the main method.
Thanks in advance for any solutions or even ideas.


text:
Q: Subdomain Issue in Django I'm trying to setup a middleware that will read the subdomain in requests and serve up a different app's urls.py depending on the subdomain...but I'm getting some erratic behavior
Here's my middleware:
class SubdomainsMiddleware:
def process_request(self, request):
    request.domain = request.META['HTTP_HOST']
    request.subdomain = ''
    parts = request.domain.split('.')

    if len(parts) == 3 or (re.match("^localhost", parts[-1]) and len(parts) == 2):
        request.subdomain = parts[0]
        request.domain = '.'.join(parts[1:])

    # set the right urlconf
    if request.subdomain == 'foo':
        settings.ROOT_URLCONF = 'bqsite.urls'
    else:
        settings.ROOT_URLCONF = 'dhsite.urls'

My understanding is that if this is working, then the root urls.py for the project should never be hit.  Is that correct?  I'm getting really weird and erratic behavior where, if i restart apache, the site shows the django welcome screen but after refrshing uses the right urls file.

A: You shouldn't alter your settings at runtime.
A better approach would be to set the request urlconf setting, as hinted in the section how django processes a request in the url docs.
if request.subdomain == 'foo':
    request.urlconf = 'bqsite.urls'
else:
    request.urlconf = 'dhsite.urls'


text:
Q: how seaborn changes the behavior of pyplot by just importing the package? I am very curious to know how seaborn changes the behavior of matplotlib functions by just import seaborn as sns.
I want to realize the same function to change the behavior of imshow() function in pyplot, for example, i want to show the pixel value at the figure's low left corner.
It is of course possible to just redefine the imshow() function, and import the redefined ones, but the thing is I have multiple scripts that calls imshow() in many different ways, e.g., plt.imshow(), imshow(), and the OOP style axes.imshow(). Is there a simple way to do this like seaborn does?
Read seaborn's source code would of course give me some clue if I have the time luxury ...

A: Seaborn does not change the behavior of matplotlib functions in the way you describe. Matplotlib exposes a number of options for customization that take effect by changing the default values of various plot parameters. When seaborn is imported, it runs some code that uses this functionality to change the global defaults.
There is an important distinction between changing default parameter values and altering the behavior of functions. What you are proposing is the latter, and it is sometimes called monkey patching. It is possible, but it would be different than what seaborn is doing, and it isn't something I would recommend in any kind of production environment.

A: you can override whatever you want in python
my_pyplot.py
import matplotlib as mpl
def myPyPlot(*args,**kwargs):
    print "You Said:",args,kwargs

mpl.pyplot = myPyPlot

main.py
import my_pyplot as mpp
from matplotlib import pyplot
print pyplot("arg1","arg2",axes="yellow")

note that you need to import your stuff before you import the modified stuff


text:
Q: Find local minimum in n x n matrix in O(n) time So, this is not my home work question, but it is taken from an ungraded homework of the coursera course on algorithms and data structures (which is now complete).
You are given an n by n grid of distinct numbers. A number is a local minimum if it is smaller than all of its neighbors. (A neighbor of a number is one immediately above, below, to the left, or the right. Most numbers have four neighbors; numbers on the side have three; the four corners have two.) Use the divide-and-conquer algorithm design paradigm to compute a local minimum with only O(n) comparisons between pairs of numbers. (Note: since there are n2 numbers in the input, you cannot afford to look at all of them. Hint: Think about what types of recurrences would give you the desired upper bound.)
Since the numbers are not in any order, I don't see how we can get away with any thing but O(n2) comparisons.

A: I think this is actually really easy.
Turn the problem into 3-D one to see why the algorithm works.  Put the matrix on a table.  Pretend there are pillars extending out of each cell and that the height of the pillar is directly proportional to its value.  Put a ball on any pillar. Have the ball always fall onto the adjacent pillar that is the lowest altitude until it is at a local minimum.

A: We can adapt Words Like Jared's answer, by looking at how it can go wrong.
The idea in that answer -- which is a good one -- is to "roll downhill". This just means, if you are on an element, check if it is a local minimum. If so, you are done; otherwise, step to the smallest of its nearest neighbors. Eventually this must terminate because every step is to a smaller element, and that cannot go on forever in a finite array.
The problem with this approach is that the "rolling" can meander all over the place:
20 100 12  11 10 100  2
19 100 13 100  9 100  3
18 100 14 100  8 100  4
17  16 15 100  7   6  5

If you start at the upper left and "roll downhill", you will visit around half of the elements in the array. That is too many, so we have to constrain it a bit.
Start by examining the middle column and middle row. Find the smallest element among all of those and start there.
Roll one step "downhill" from there to enter one of the four quadrants. You will enter one of the quadrants, because the adjacent elements in the middle column and/or row are larger, so only one of the two adjacent quadrants could be "downhill".
Now consider what would happen if you "rolled downhill" from there. Obviously, you would eventually reach a local minimum. (We will not actually do this because it would take too long.) But, in the course of rolling around, you would never leave that quadrant... Because to do so, you would have to cross either the middle column or middle row, and none of those elements are smaller than where you started. Therefore that quadrant contains a local minimum somewhere.
Thus, in linear time, we have identified a quadrant that must contain a local minimum, and we have cut n in half. Now just recurse.
This algorithm takes time 2n + 2n/2 + 2n/4 + ..., which equals 4n, which is O(n) so we are done.
Interestingly, we did not use "rolling downhill" very much at all, except for the critical part: Proving that the algorithm works.
[Update]
As Incassator points out, this answer is not entirely correct, because after you "just recurse" you might roll out of the quadrant again...
The simplest fix is to find the smallest element among the middle row, middle column, and boundary before you "roll downhill".

A: The accepted answer by Nemo is nice but not fully correct:

Thus, in linear time, we have identified a quadrant that must contain a local minimum, and we have cut n in half. Now just recurse.

I am referring to "just recurse" bit. The problem is we cannot do that directly because on next iteration we might find a local minimum which is not a local minimum for original grid (x below means some arbitrary large numbers):
 x  x 39  x  x 50  x  x  x  x  x
 x  x 38  x  x 49  x  x  x  x  x
37 36 33 34 35 48  x  x  x  x  x
 x  x 32  x  1 10  x  x  x  x  x
 x  x 31  x  x 47  x  x  x  x  x
46 45 30 44 43 60 51 52 53 54 55
 x  x  2  x  x 56  x  x  x  x  x
 x  x  x  x  x 57  x  x  x  x  x
 x  x  x  x  x 58  x  x  x  x  x
 x  x  x  x  x 59  x  x  x  x  x

At first iteration we find 10 to be a minimum of middle row and middle column. We go to the left (as 1 is less than 10). So our next iteration is on upper-left quadrant. But now minimum of middle row and column is going to be 31 (or 30 if quadrant's borders are considered to be part of it). You will then conclude that it is a local minimum. But it is not for the full grid.
We can rectify this unfortunate defect in variety of ways. I solved it like this:
At each iteration in addition to the grid itself we keep track of current minimum candidate (that is the 1 in the example above after    first iteration; in the initial state we can say minimum candidate is    plus infinity). We calculate minimum of middle row and column and    compare it to minimum candidate. If the latter is smaller we recurse    into the quadrant containing minimum candidate. Otherwise we forget    previous candidate and only then check whether new middle row/column    minimum is actually a local minimum. And if not then recurse as usual    to whatever quadrant we slope down from it (and track new minimum    candidate).
Alternatively, you can modify the procedure as described in this    presumably MIT lecture: at each iteration instead of looking at    middle row/column you can look at middle row/column and grid    boundary. Then the algorithm once again is correct.
You choose which way you like.

A: Well, this is how you divide and conquer it.
1) Divide the n x n matrix into four n/2 x n/2 sub matrices.
2) Keep dividing the sub matrices recursively until you end up with a 2 x 2 matrix
3) Check if any element of 2 x 2 matrix is a local Minimum.
Recurrence equation is : T(n) = 4*T(n/2) + O(1)
4*T(n/2) for 4 n/2 x n/2 sub matrices and O(1) for checking if 2 x 2 sub matrix has a local minimum
Master theorem says this is a O(n^2) worst case bound.
But I think we can get a best case O(n) bound,
(" RED ALERT! ---BEST CASE IS BOGUS, JUST BOGUS---RED ALERT!").
if we exit the recursion stack after we have have found a local minimum in step 3.
Pseudocode:
private void FindlocalMin(matrix,rowIndex,colIndex,width){
    if(width == 1){ checkForLocalMinimum(matrix,rowIndex,colIndex); return;} //2x2 matrix
    FindlocalMin(matrix,rowIndex,colIndex,width/2);
    FindlocalMin(matrix, (rowIndex + (width/2) + 1) ,colIndex,width/2);
    FindlocalMin(matrix,rowIndex, (colIndex + (width/2) + 1) ,width/2);
    FindlocalMin(matrix,(rowIndex + (width/2) + 1), (colIndex + (width/2) + 1) ,width/2);
}

private void checkForLocalMinimum(.........){
    if(found Local Minimum in 2x2 matrix){ exit recursion stack;}
}

Here is a java implementation

A: Code Works for 3*3 or greater matrix, developed as per exercise of Algorithms 4th Edition Book Exercise .
It works as Following

*

*Look for middle row of given matrix and find minimum out of it

*for that minimum look for above and below element to ensure that it's local minimum

*if not restrict search matrix by

*

*Row : choose half side of row in which the lesser element than middle row's element is.

*colmun : choose the index at which minimum in the row was found.

*Repeat step 1-3

public class MinimumOfMatrix {
private static int findLocalMinimum(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd) {

    int midRow = (rowStart + rowEnd) / 2;
    int minPos = findMin(matrix, midRow, colStart, colEnd);

    if (minPos >= (colStart + colEnd) / 2)
        colStart = (colStart + colEnd) / 2;
    else
        colEnd = (colStart + colEnd) / 2;

    if (matrix[midRow][minPos] < matrix[midRow + 1][minPos]
            && matrix[midRow][minPos] < matrix[midRow - 1][minPos]) {
        return matrix[midRow][minPos];
    } else if (matrix[midRow][minPos] > matrix[midRow + 1][minPos]) {
        return findLocalMinimum(matrix, midRow, rowEnd, colStart, colEnd);
    } else {
        return findLocalMinimum(matrix, rowStart, midRow, colStart, colEnd);
    }

}

private static int findMin(int[][] matrix, int midRow, int colStart, int colEnd) {
    int min = Integer.MAX_VALUE;
    int pos = -1;

    for (int i = colStart; i < colEnd; i++) {
        if (matrix[midRow][i] < min) {
            min = matrix[midRow][i];
            pos = i;
        }

    }

    return pos;
}

public static void main(String[] args) {
    // Best Case
    /*
     * int[][] matrix= { {1,-2,4,-6,1,8}, {-3,-6,-8,8,1,3}, {1,2,6,-2,-8,-6},
     * {-2,9,6,3,0,9}, {9,-1,-7,1,2,-6}, {-9,0,8,7,-6,9} };
     */

    // Two Iteration Down Case
    /*
     * int[][] matrix= { { 1,-2, 4,-6, 1, 8}, {-3,-6,-8, 8, 1, 3}, { 1, 2, 6, 9, 0,
     * 6}, {-2, 9, 6,-1,-1, 9}, { 9,-1,-7, 1, 2,-6}, {-9, 0, 8, 7,-6, 9} };
     */

    /*
     * //Left Down Case int[][] matrix= { { 1,-2, 4,-6, 0, 8}, {-3,-6,-8, 8,-2, 3},
     * {-2, 9, 6,-1, 1, 9}, { 1, 0, 6, 9, 2, 6}, { 9,-1,-7, 1, 2,-6}, {-9, 0, 8,
     * 7,-6, 9} };
     */

    int[][] matrix = { { 1, -2, 4, }, { -3, -6, -8, }, { -2, 9, 6, }

    };

    System.out.println(findLocalMinimum(matrix, 0, matrix.length, 0, matrix.length));

}

}

A: If you have a worst case time complexity of O(n^2), then you could simply iterate over the entire matrix and find the smallest element that way - which kind of defeats the purpose because we are mereley looking for a local minimum.


text:
Q: Problem with thesis class When I am trying to use the thesis class file for my thesis I am getting this error:
File `thesis.cls' not found. \usepackage

My codes
\documentclass[12pt]{thesis}
\usepackage{blkarray}
\usepackage{amsmath}
\begin{document}
\chapter{How long you want the title }

\end{document}

How to correct this error?

A: If you have access to thesis.cls:
Most of the time an error File foo.cls not found leads to two possible problems:
First, the cls file is a "classic" file that is part of TeXlive or other TeX distribution. In this case, you should update it. The way to do it depends if you are using TeXlive, MikTeX, macTeX or other system.
If your file comes from internet, or from another source as an University, you should have a copy of the file in your folder.
If the problem is still present, you should verify typo (thesis, Thesis or THESIS). The name depends on the file name.
If you don't have any thesis.cls file:
In this case you should use another document class as book or report:
\documentclass[12pt]{report} %you can modifies report with book
\usepackage{blkarray}
\usepackage{amsmath}
\begin{document}
\chapter{How long you want the title }

\end{document}


text:
Q: python error handling filepath is incorrect when run as a module So I have a 2 files.
test.py
import sys
import error_handler
sys.excepthook = error_handler;
value = 23/0; #this line will throw Zero division error

error_handler.py
def custom_error_handler(ex_class, ex, tb):
    fileName = os.path.split(tb.tb_frame.f_code.co_filename)[1];
    lineNo = tb.tb_lineno;
    print fileName;
    print lineNo;

These are the outputs when I run the file and when I run it as a module.

python test.py
test.py
4

But if I run

python -m test
runpy.py
162

Any ideas on why running it the second way produces that result? is there another way I should be doing this?
Thankyou.

A: ok I solved this by following viraptors comment and the python documentation.
I had to import traceback, split the traceback into an array
import traceback;
tb_array = traceback.extract_tb(tb);

each element in the array is an array that contains:

*

*file path

*line number

*method name

*line string


text:
Q: How to count the mean of the Poisson process I am given Poisson process $X_t$ which has intensity $\lambda$. Is there a way to count the mean for it? I am terribly confused. I am able to count the mean of a variable which has a Poisson distribution (and that is $\lambda$), but as I understand it is not the same.

A: A main property of a Poisson proces with parameter $\lambda$ is that $X_t\sim \text{po}(\lambda t)$ for every $t>0$. Especially we have $E[X_t]=λt$ for $t>0$.


text:
Q: How to merge two git branches entirely remotely? I have two branches on Google cloud repository. One is stable master branch and other is feature branch in which all new changes are done.
What i have to do is to merge feature branch with master branch.
I have search on SO for merging two git branches but all solution is about to do merge locally. it seems complicated to pull down the feature branch and the stable master branch, merge them, and then push the changes back.
Is there a git command to ask a remote git server to commit a merge of two branches and can i merge two branches remotely or there is only one option to merge branches locally?
any help will be appreciated.

A:
I have search on SO for merging two git branches but all solution is about to do merge locally. it seems complicated to pull down the feature branch and the stable master branch, merge them, and then push the changes back.

Actually, I think it is preferable to do all the merging locally, because if any conflicts arise then one is in a good position to handle them.  Most IDEs now have Git plugins which make it easy to resolve conflicts.

Is there a git command to ask a remote git server to commit a merge of two branches and can i merge two branches remotely or there is only one option to merge branches locally?

As far as I know, there is no Git command to perform a remote merge.  However, most Git repositories do support remote merging in some form.  For example, it is possible to merge one branch into another on GitHub.  But the caveat is that there cannot be any conflicts during the merge.  The typical way to avoid such conflicts is to perform the merge locally first, then push out the feature branch.  The other requirement is that the merge must be initiated on the GitHub server.


text: Q: Android cameraX analyzer ImageProxy dimensions I am using the camera preview along with an face analyzer (mlkit face detection). I noticed that the dimensions of the ImageProxy returned from the analyze function are not the same as the resolution i ve set in the config. That is causing issues with the bounding box for the FaceGraphic. Is there something i am missing with setting the resolution in the analysis config?