text:
Q: I don't understand these errors im getting with my on_member_join/on_member_remove functions I've been working on discord bot coded in python. And i've been trying to get my bot to say a message when a user joins the server and leaves the server. But when i tested it out, i got 2 errors which i don't understand the errors. And im not sure what i did wrong. If anybody could help explain these errors, and point me in the right direction for my code i would greatly appreciate it.
I have looked into the discord rewrite api and have tested it in my server with a friend which is when i got the errors
@client.event
async def on_member_join(member):
    channel = member.server.get_channel("499457708978864151")
    msg = 'Welcome to the {1.name} Server, {0.mention}'
    await client.say(channel, msg.format(member, member.server))

@client.event
async def on_member_remove(member):
    channel = member.server.get_channel("499457708978864151")
    msg = '{0.mention} has left the server'
    await client.say((channel, msg.format(member, member.server)))

I expected my bot to say Welcome to the (the name of the server) Server, @username when they entered the server, and @username has left the server when the user left but i received these errors:
TypeError: send_message() takes from 2 to 3 positional arguments but 4 were given
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Received NoneType

Here is my full traceback
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:/Users/Chris/PycharmProjects/untitled1/RomaniBot.py", line 37, in on_member_join
    await client.say(channel, msg.format(member, member.server))
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\ext\commands\bot.py", line 350, in say
    coro = self.send_message(destination, *args, **kwargs)
TypeError: send_message() takes from 2 to 3 positional arguments but 4 were given
Ignoring exception in on_member_remove
Traceback (most recent call last):
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:/Users/Chris/PycharmProjects/untitled1/RomaniBot.py", line 43, in on_member_remove
    await client.say((channel, msg.format(member, member.server)))
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\ext\commands\bot.py", line 309, in _augmented_msg
    msg = yield from coro
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\client.py", line 1145, in send_message
    channel_id, guild_id = yield from self._resolve_destination(destination)
  File "C:\Users\Chris\PycharmProjects\untitled1\venv\lib\site-packages\discord\client.py", line 289, in _resolve_destination
    raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Received NoneType

A: One easy fix for your code would be to, instead of using client.say, to use channel.send. So
@client.event
async def on_member_join(member):
    channel = member.server.get_channel(499457708978864151)
    msg = 'Welcome to the {1.name} Server, {0.mention}'
    await channel.send(msg.format(member, member.server))

In addition, according to the documentation,

get_channel(id)
Returns a abc.GuildChannel or abc.PrivateChannel with
  the following ID.
If not found, returns None.

So you did not select the channel successfully. The reason is that the ID in rewrite is an int, not a string.

A: member.server returns you the server, where the member joined. And you tried accessing the channel with the ID 499457708978864151, this would definetly not working in other servers than the server where the channel is with the ID 499457708978864151, so you have to get the server too client.get_server("ID") would do this.


text:
Q: User Defined aggfunc DataFrame Python i need to replace the aggfunc in my dataframe pivot as i cannot simply sum the daily returns to provide a monthly return
df2=df2.pivot_table(index='EOM',columns='factor',values='return',aggfunc=
[np.sum])

I need to use something like this instead
np.exp(np.log1p(df['return']).cumsum()-1)

What is the best way to replace this aggfunc?

A: I would try this:
my_aggfunc = lambda x: np.exp(np.log1p(x).cumsum()-1)

df2=df2.pivot_table(index='EOM',columns='factor',values='return',aggfunc=
my_aggfunc)

alternatively, you can define a function with def my_aggfunc(x):...etc

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an approximation to $\frac{1}{-\log(1-e^{-\beta})}$ Is there a way to simplify $$\frac{1}{-\log(1-e^{-\beta})}$$ where $\beta>0$ on the real line
I considered the taylor series for $log(1-t)$ but since it is divided by 1, I'm not sure how to proceed
Thank you

A: Approximations (by their nature) work for some special cases only, in other words we can't find an approximation for the whole $\beta>0$, we need to consider separate cases.
The most natural ones are:
1) $\beta \ll 1$
Then we expand the exponential function and get:
$$-\frac{1}{\log \left(1-1+\beta-\frac{\beta^2}{2}+\frac{\beta^3}{6}-\cdots \right)} \approx - \frac{1}{\log \beta}$$
2) $\beta \gg 1$
Then we have $e^{-\beta} \ll 1$ so we can expand the logarithm:
$$\frac{1}{e^{-\beta}+\frac{1}{2}e^{-2\beta}+\frac{1}{3}e^{-3\beta}+\cdots} \approx e^\beta$$
Here's both approximations plotted along the exact function to see where they fit:

A: You can use the Taylor series for 1/(1-u) = 1+u+u2 ...


text:
Q: Responsive menu opening on request I've written this js so the menu is responsive but doesn't break when js is not enabled.
I have 2 menu lists each inside their own nav element. For tablet and mobile devices I want only a menu button (first item in the list with ) to show but no list until the menu button is pressed.
At the moment the first list hides on opening the page but the other list is permanently showing. However, clicking either menu button does the same job of showing the first list. Neither nav has an id or class.
Why is only one of the lists responding?
This is the JS (its in the head)
function showLists() {
$('.nav').show();
$(".menu").hide();
}
$(document).ready(function() {
if ($(window).width() < 450) {
    $('.nav').hide();
    $(".menu").click(function () {(
        showLists()
        )})
    }
});

A: It sounds as if you are going after a basic toggle navigation.  A great starting point for basic and even more advanced responsive solutions is RWD Patterns by Brad Frost.
Also, you should in mostly all solutions be able to get away with defining only ONE navigation list and using CSS and JS to manipulate it to behave responsively.


text:
Q: How to alias multiple LEFT OUTER JOINs I have the following custom SQL that allows sorting custom post types by a taxonomy column. It works, but has an issue when the custom posts are filtered by another taxonomy. Basically, there is a conflict when filtering AND sorting by taxonomy.
Current code:
$clauses[ 'join' ] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID=object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING term_taxonomy_id
LEFT OUTER JOIN {$wpdb->terms} USING term_id
SQL;

$clauses[ 'where' ] .= " AND (taxonomy = '" . $orderby . "' AND taxonomy IS NOT NULL)";
$clauses[ 'groupby' ] = "object_id";
$clauses[ 'orderby' ] = "GROUP_CONCAT(name ORDER BY name ASC) " . $order;

Results in db error:
Not unique table/alias: 'wp_term_relationships'

This is because wp_term_relationships is already referenced due to the taxonomy filter.
A fix?
$clauses[ 'join' ] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID=tr.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} tt USING tr.term_taxonomy_id
LEFT OUTER JOIN {$wpdb->terms} tms USING tt.term_id
SQL;

$clauses[ 'where' ] .= " AND (tt.taxonomy = '" . $orderby . "' AND tt.taxonomy IS NOT NULL)";
$clauses[ 'groupby' ] = "tr.object_id";
$clauses[ 'orderby' ] = "GROUP_CONCAT(tms.name ORDER BY tms.name ASC) " . $order;

My attempted fix has problems, but I haven't been able to tell by examples where I've got it wrong. I suspect that not everything needs to be aliased. It just seems that it all needs to be isolated with the exception of {$wpdb->posts}.ID in the first JOIN.
The above sets the query's orderby. How can I use aliases for all of the above tables?

A: Try assigni an alias
$clauses[ 'join' ] .= <<<SQL
   LEFT OUTER JOIN {$wpdb->term_relationships}  as t_rel ON {$wpdb->posts}.ID= t_rel.object_id
   LEFT OUTER JOIN {$wpdb->term_taxonomy} USING t_rel.term_taxonomy_id
   LEFT OUTER JOIN {$wpdb->terms} USING term_id
SQL;

let's try with on condition instead of USING    (hope the column name are the rights one )
  $clauses[ 'join' ] .= <<<SQL
     LEFT OUTER JOIN {$wpdb->term_relationships}  as t_rel ON {$wpdb->posts}.ID= t_rel.object_id
     LEFT OUTER JOIN {$wpdb->term_taxonomy} as tt ON tt.id =  t_rel.term_taxonomy_id
     LEFT OUTER JOIN {$wpdb->terms} as te ON te.id =  tt.term_id
  SQL;


text:
Q: Java: Error: Could not find or load main class Hello when trying to import an external library I know it's a common question, but I have read all the other answers and couldn't find a solution. I am trying to understand the Java classpath, but I run into the Error: Could not find or load main class Hello when I try to specify an external library.
I started with this simple program, which resides directly in my home directory:
import java.util.*;

public class Hello {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("Hello world");
    }
}

This compiles and runs just fine...
[user ~]> ls -l
Hello.java
[user ~]> javac Hello.java
[user ~]> ls -l
Hello.java
Hello.class
[user ~]> java Hello
Hello world

...which tells me that the classpath environment variable is set correctly (because it finds the java.util package).
Yet when I try to import a random 3rd party package and specify its location in the -classpathI get the error:
[user ~]> cat Hello.java
import java.util.*;
import org.apache.commons.lang3.time.*;

public class Hello {
    public static void main(String[] args) {
        StopWatch sw = new StopWatch();
        Date date = new Date();
        System.out.println("Hello world");
    }
}
[user ~]> ls .m2/repository/org/apache/commons/commons-lang3/3.3.1
commons-lang3-3.3.1.jar
[user ~]> javac -classpath ~/.m2/repository/org/apache/commons/commons-lang3/3.3.1/commons-lang3-3.3.1.jar Hello.java
[user ~]> java -classpath ~/.m2/repository/org/apache/commons/commons-lang3/3.3.1/commons-lang3-3.3.1.jar Hello
Error: Could not find or load main class Hello

Could someone give me an idea what I'm doing wrong here?

A: First, java.util classes are part of the JRE itself, and are thus automatically available, whatever the classpath is.
The first example works fine because you're not specifying any classpath, and the default one (which is just ., i.e. the current directory) is thus used.
The second example specifies a classpath, but doesn't include . (the current directory) in it, so the commons-lang classes are available at runtime, but not your Hello class. Use
java -classpath .:~/.m2/repository/org/apache/commons/commons-lang3/3.3.1/commons-lang3-3.3.1.jar Hello

Also, in the future:

*

*don't ever, ever put a class in the default package

*create a real project structure, containing

*

*a root directory

*a source directory containing the .java files, properly organized in a package structure

*a classes directory, containing the compiled .class files, that you can just clear when you want to recompile everything from scratch

The next step would of course to use Gradle or Maven as a build tool, and follow their recommended project layout.


text:
Q: Multiple section open in jQuery accordion with themes/smoothness I am trying to achieve j query accordion from
    jsfiddle.net/soboaz/3gHrv
with multiple section on.
Multiple section are not opening after i added jquery css:
themes/smoothness/jquery-ui.css rel="stylesheet" type="text/css"

I think classes got changed . Please help.

A: i created a new snippet for you.
this problem occurs may be you have not added JQuery,JQuery-ui library properly.
use this code. use this code as new HTML file.

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.


text:
Q: creating new NSDictionaries programmatically I want to create a set of new NSDictionaries with different names dependant upon input data. Is this possible? E.g.
for (int i = 0; i < [holidayDestination length]; i++) {
      NSMutableDictionary *[NSString stringWithFormat:@"holidayDestination%d",  i] = [[NSMutableDictionary alloc] init];
      // Other code here...
  }
Thanks in advance.

A: No, while Objective-C strives to be like Smalltalk, it's only a thin veneer over C, so you really can't do these kinds of cool "meta" tricks. What you can do instead is set up a mutable array and for each element at i create your mutable dictionary. Something like this:
NSMutableArray *holidayDestinations = [NSMutableArray new];
for (int i = 0; i < [holidayDestination length]; i++)
{
    [holidayDestinations addObject:[NSMutableDictionary new]];
    NSMutableDictionary *working = [holidayDestinations objectAtIndex:i];
    // Add elements to "working"
}


text:
Q: Iterating over PHP array to create Javascript array with PHP foreach I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:
<?php
  $array = array(StdObject,StdObject,StdObject);
?>

//later that page...in JavaScript

var list = [
<?php foreach($array as $value):?>
  '<?=$value->some_letter_field?>',
<?endforeach;?>
];

Unfortunatly, what this code does is produce output that looks like this:
var list = ['a','b','c',];

Notice that extra comma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra comma doesn't get printed,  producing a properly formatted JavaScript array?
The expected output should be:
var list = ['a','b','c'];

I appreciate your help in advance.

A: You don't need to do this yourself, PHP has a function called json_encode that does what you want. If for some reason you don't have PHP 5.2.0, there are a lot of implementations in the comments of that page to get around that.

A: Use implode() to glue up array elements. It will take care about commas

//later that page..in JavaScript

var list = ['<?=implode("', '", $array)?>'];

A: You can use this to generate the json array:
$list = json_encode($array);

And then read it in Javascript:
var list = <?=$list?>

A: This will do the trick:
<?php
$filtered = array();
foreach($array as $value) {
    $filtered[] = $value->some_letter_field;
}
echo 'var list = ' . json_encode($filtered);
?>

A: How about converting array to a valid JSON object?
var list = JSON.parse("<?php echo json_encode($array); ?>");

Anyway, do you really need to generate JS code on the fly? Isn't there another way to complete your task? JS generation is often considered a hack, and it can be avoided easily in many cases.

A: If you insist in keeping your current code for whatever reason, just:
var list = [
<?php foreach($array as $value): ?>
  $output[] = "'".$value->some_letter_field."'";
<?php endforeach; ?>
  echo implode(',', $output);
];


text:
Q: Series convergence Question ( TIFR GS $2010$) Question is :

What i have done so far is :
I see that $\frac{\pi}{n}\rightarrow 0$ and so should be the sequence $u_n=\sin (\frac{\pi}{n})$.
i.e., $u_n$ converges to $0$ and so $(b)$ is true.
I remember that

$\sin \theta$ is same as $\theta$ for small angles

So, I Guess $\sin(\frac{\pi}{n})=\frac{\pi}{n}$ for large $n$
So, I guess $$\sum _{n -\text{large}}u_n=\sum _{n -\text{large}}\sin(\frac{\pi}{n})=\pi \sum _{n -\text{large}}\frac{1}{n}$$
But then $\sum \frac{1}{n}$ is divergent so should be the series $$\pi \sum _{n -\text{large}}\frac{1}{n}$$ i.e., $\sum u_n$ is divergent.
So, I wanted to conclude $(c)$ is true. But then for above question there is only one correct option.
So, If $c$ is true then both $(a),(d)$ should be false which is not possible according to question.
So, just with some sense I see that $(c)$ should be the only possibility for the correct option as this does not contradict anything while other would contradict.
So, $(c)$ should be false.. But, I am not sure how to see this.
please help me to see this in detail...
Thank you

A: the first and last options are false because consider the series $\sum sin(\pi/n)$ and use comparison test with $\sum{1/n}$,the limit comparison test of ratio of terms is $\pi$ which is non zero and the harmonic series is divergent,so the series diverges,so the series is not convergent.Before applying comparison test notice that the series has positive terms.


text:
Q: Cannot call a function in Javascript Hello I'm experimenting with Box2dWeb, and working with top-down car game.
My problem arises when I try to control the car, so it will move, at first only forwards. For simplicity I don't want to use wheels, and just apply the force to the car (a box).
For the controls I made a function for but for a reason it's not getting called... That's where I need a pointer or advice. (Creation and placement of objects works just fine)
Here's part of the code:
var GlobalVar={   }
var KEY = {
    UP: 87,//W
    DOWN: 83,//s
    LEFT: 65,//A
    RIGHT: 68//D
}
GlobalVar.pressedKeys = [];//an array to remember which key is pressed or not

$(function(){
   $(document).keydown(function(e){
     GlobalVar.pressedKeys[e.keyCode] = true;
 });
$(document).keyup(function(e){
  GlobalVar.pressedKeys[e.keyCode] = false;
 });

Rendering();
PlaceStuff(GlobalVar.currentLevel);//placing stuff, like car and boundaries/walls
moveCar();

});
function moveCar(){
 if (GlobalVar.pressedKeys[KEY.UP]){
   var force = new b2Vec2(0, -10000000);
   GlobalVar.car.ApplyForce(force, GlobalVar.car.GetWorldCenter());
  }
}

A: It doesn't look like the moveCar function is being called more than once.
You should do the following:
function moveCar(){

   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force, GlobalVar.car.GetWorldCenter());
    }

    requestAnimationFrame(moveCar);

}

You may also want to add a modifier to modify the amount of force added depending on the frame rate:
then = Date.now();

function moveCar(){

    var now = Date.now();
    var modifier = now - then; // Make modifier the time in milliseconds it took since moveCar was last executed.

    then = now;

   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force * modifier, GlobalVar.car.GetWorldCenter());
    }

    requestAnimationFrame(moveCar);

}

This will ensure the car doesn't move slower on slower systems.

If you also want the Rendering() function to be executed more than once, you may also want to create another function which gets called as often as possible and calls the other two functions.
then = Date.now();

function moveCar(modifier){
   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force * modifier, GlobalVar.car.GetWorldCenter());
    }
}

function update() {
    var now = Date.now();
    var modifier = now - then; // Make modifier the time in milliseconds it took since moveCar was last executed.

    then = now;

    moveCar(modifier);
    Rendering();

    requestAnimationFrame(update);
}

A: As pointed out in the comments, you only call moveCall once, but you probably want to do it after each key press:
$(document).on('keydown keyup', function(e){
    GlobalVar.pressedKeys[e.keyCode] = true;
    moveCar();
});


text:
Q: Migrate from TopicProcessor TopicProcessor has been removed since the 3.4+ reactor version and now I'm struggling how is the easiest way to replace it with a new API. I'd like to keep the implementation as reliable as possible, even if the performance will get worst. I don't want to struggle with loss events or an overflowing stream, just keep it stupid simple. I also need to buffer data, so I've used bufferTimeout for that and it worked perfectly with TopicProcessor.
How to achieve that with the new API?
I've tried to use Sinks but with a lot of pressure there was an overflow exception and the whole stream was terminated.
Below is my basic implementation before upgrade to Spring Boot 2.4.1.
package com.example.reactorplayground.config;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class TopicProcessor<T> implements Processor<T> {
    private final reactor.core.publisher.TopicProcessor<T> processor;

    public TopicProcessor() {
        this.processor = reactor.core.publisher.TopicProcessor.share("in-memory-topic-thread", 1);
    }

    @Override
    public Mono<T> add(T event) {
        return Mono.fromCallable(() -> {
            processor.onNext(event);
            return event;
        });
    }

    @Override
    public Flux<T> consumeWith() {
        return processor;
    }
}


text:
Q: How to refresh one random UITableViewCell of UITableView x times every x seconds. Objective-C I'm working on a game with a Table View.
That's the idea of the app:
I push a button starting a timer and I fill up the cells of the Table View with random images. I'm using 7 cells and 5 images. Depending of the cell I touch, I earn different points.  In 5 seconds I want show 5 different cells (1 second, 1 cell shown). Each time I show a cell, I hide the others cells and I have the possibility of touch this cell and earn Points. After these 5 seconds, I would like change the content of the Table View.
I know how unhide only one cell and hide the others with the hidden property.
The problem is I only have managed show the cells changing the data of the Table View every 1 second but not after 5 seconds.
Steps I do
1) Starts the timer. Every 5 seconds I call refreshTable
self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshTable) userInfo:nil repeats:YES];

2) In refreshTable I fill up one Array with 7 new objects. Every object is an UIImage. I get the 7 UIImages from an array of 53 UIImages. And I refresh the Table to fill up the Rows with the new images.
-(void)refreshTable
{

    self.valueImage=arc4random() % 52;

    self.value=arc4random() % [self.wackArray count];

    for (int n=0 ;n<7 ; n++){

        int random=arc4random() % 52;

        [self.randomArrayIndex addObject:[NSString stringWithFormat:@"%i", random]];
        int objectRandomArray = [[self.randomArrayIndex objectAtIndex:n] integerValue];

        [self.randomArrayImage insertObject:[self.imagesArray objectAtIndex:objectRandomArray] atIndex:n];

    }

    [self.tableView reloadData];

    [self.randomArrayIndex removeAllObjects];

}

To manage the time do I need a nest the NSTimer or use a performSelector? And to show the cells I have to use retriveCellForIndexPath or reloadRowsAtIndexPaths?
Its posible to call setNeedsDisplay to refresh/show the Cells?

A: That's my final refreshTable method. I awaked that I didn't used UICollectionViewCells.
-(void)refreshTable

{
    self.tableView.hidden=NO;

   //count returns number of cells
   self.value=arc4random() % [self.wackArray count];

   [self.tableView beginUpdates];

   NSIndexPath *indexPath0 = [NSIndexPath indexPathForRow:0 inSection:0];
   NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
   NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0];
   NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0];
   NSIndexPath *indexPath4 = [NSIndexPath indexPathForRow:4 inSection:0];
   NSIndexPath *indexPath5 = [NSIndexPath indexPathForRow:5 inSection:0];
   NSIndexPath *indexPath6 = [NSIndexPath indexPathForRow:6 inSection:0];

   UITableViewCell *cell0=[self.tableView cellForRowAtIndexPath:indexPath0];
   UITableViewCell *cell1=[self.tableView cellForRowAtIndexPath:indexPath1];
   UITableViewCell *cell2=[self.tableView cellForRowAtIndexPath:indexPath2];
   UITableViewCell *cell3=[self.tableView cellForRowAtIndexPath:indexPath3];
   UITableViewCell *cell4=[self.tableView cellForRowAtIndexPath:indexPath4];
   UITableViewCell *cell5=[self.tableView cellForRowAtIndexPath:indexPath5];
   UITableViewCell *cell6=[self.tableView cellForRowAtIndexPath:indexPath6];

   cell0.hidden=YES;
   cell1.hidden=YES;
   cell2.hidden=YES;
   cell3.hidden=YES;
   cell4.hidden=YES;
   cell5.hidden=YES;
   cell6.hidden=YES;

   cell0.userInteractionEnabled=NO;
   cell1.userInteractionEnabled=NO;
   cell2.userInteractionEnabled=NO;
   cell3.userInteractionEnabled=NO;
   cell4.userInteractionEnabled=NO;
   cell5.userInteractionEnabled=NO;
   cell6.userInteractionEnabled=NO;

   NSIndexPath *indexPathRandom = [NSIndexPath indexPathForRow:self.value inSection:0];
   UITableViewCell *cellRandom=[self.tableView cellForRowAtIndexPath:indexPathRandom];

   cellRandom.hidden=NO;
   cellRandom.userInteractionEnabled=YES;

   [self.tableView endUpdates];

}

A: If i have understand your question, you want to show just one cell for a time (ie 1 minute) and hide it again.
You can create a derived class from UICollectionViewCell and use them in your collectionViewDataSource.
Then, on your timer, you can use a NSIndexPath to get the wanted cell and tell it to animate for a certain time;
As example :
CollectionViewDataSource.m
-(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MyIdentifier";
MyCell *cell = (MyCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
[cell configureForItem:YourObjectToConfigure];
    return cell;
}

-(void)refreshTable
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:ROW inSection:SECTION];
    [collectionView cellForItemAtIndexPath:indexPath] animate];
}

MyCell.h
@interface MyCell : UICollectionViewCell
-(void) configureForItem:(NSObject*) item;
-(void) animate;

@end

MyCell.m
 @implementation MyCell
 -(void) configureForItem:(NSObject*) item{
        // Do your configuration stuff
 }

 -(void) animate{
        [UIView animateWithDuration:1 animations:^{
                  // Do your show stuff
            } completion:^{
                  // Do your hide stuff
            }];
  }
 @end


text:
Q: Incomplete data from a stream I am reading data from a process stream. Basically, I am running the process using Runtime.exec API and getting the process input stream.
Runtime rt = Runtime.getRuntime();
process = rt.exec("C:/cygwin/home/grec.exe");
InputStream is = process.getInputStream();

I am then collecting the output of the process as --
            BufferedReader in = new BufferedReader(is);
            char[] ls = new char[s.available()];
            ls.read(ls);
            String output = new String(ls);

However when I am printing the string output, I am getting --
  break [loc]     Add a breakpoint at [file:]line or template
  callflow [val]  Enable call flow tracing
  next            Execute the over instruction, stepping over calls
  over            Execute the current instruction hierarchy

But the actual output is --
  break [loc]     Add a breakpoint at [file:]line or template
  callflow [val]  Enable call flow tracing
  next            Execute the over instruction, stepping over calls
  over            Execute the current instruction hierarchy
  print <xpath>   Print the value of an XPath expression
 profile [val]   Turn profiler on or off
 reload          Reload the script contents
 run             Restart the script
 step            Execute the next instruction, stepping into calls
 verbose         Turn on verbose (-v) output logging
 where           Show the backtrace of template calls
 quit            Quit debugger

That is, a part of the output gets truncated, but no exception is thrown by the code. I have tried increasing the BufferedReader size and also increasing the size of the array ls.I am at a loss to find the cause of this behavior. Any hints or pointers on what might be the cause of this would be highly appreciated.

A: You are making the mistake of assuming that available() tells you how many bytes / characters are actually available.  In fact, it tell you that at least that many are available ... and it might be wrong because it is an estimate.
Then you are compounding the problem by accessing the InputStream after you've wrapped it in a BufferedReader.  So instead of getting the number of characters that can be read from the reader, you are getting the number of available bytes that haven't yet been read into the buffer yet.

You are probably better off simply reading from the BufferedReader a line at a time using readLine().

A: Use a loop to process all information and read till the end of the stream.
Inputstream.available() does not do what you expected:

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available%28%29


text:
Q: Styling Visual States I am using the VisualStateManager from the WPF Toolkit.  I've created a custom control, part of a reusable controls library, with numerous visual states.  Now I want to allow the client of my library to easily restyle the fonts and colors of these visual states.  What's the standard way of doing this?  Must I require the client to replace the entire control template and replace all the visual states, even if they're only interested in modifying just one?  Or is there a better way... like how could I make GoToState defer to a client-supplied trigger intended to override a visual state's default font and color?  Other ideas?

A: I got this working for the first case I tried.  The goal was to make it so that this code would have an effect:
  <l:MyControl>
    <l:MyControl.MyStateStyle>
      <Style>
        <Setter Property="Control.Background" Value="LightBlue"/>
        <Setter Property="TextElement.Foreground" Value="White"/>
        <Setter Property="TextElement.FontStyle" Value="Italic"/>
      </Style>
    </l:MyControl.MyStateStyle> </l:MyControl>

This is how I did it:

Style style = new Style();

if ( MyState == MyState.State1Normal )
    VisualStates.GoToState( this, useTransitions, State1Normal );
else if ( MyState == MyState.State2 ) {
    if ( Owner.State2Style != null )
        style = style.Merge( Owner.State2Style );
    else
        VisualStates.GoToState( this, useTransitions, State2 );
} else if ( MyState == MyState.State3 ) {
    if ( Owner.State3Style != null )
        style = style.Merge( Owner.State3Style );
    else
        VisualStates.GoToState( this, useTransitions, State3 );
}

Style = style;

Notice the Style.Merge extension method.  I got it from http://bea.stollnitz.com/blog/?p=384 .  It enables me to combine the effects of multiple visual state groups.


text:
Q: String replace in Android To try string replace in Android, I wrote a small snippet:
public class cs{
 public static void main(String[] args){
   String a,c;
   int b;
   b=1;
   c="12345";
   a="12345,54321";
   a.replace(c,String.valueOf(b));
   System.out.println(a);
}
}

Expected Output: 12345,54321 changes to 1,54321
Actual Output: 12345,54321
。Please help。

A: Is the . in c.String.valueOf(b) a typo for a comma, separating two parameters? Because it doesn't make much sense as stated. replace accepts two parameters, and furthermore, it doesn't change the string it's executed on, it merely returns a new one, so you need to pick up that return value and reassign it to the variable:
a = a.replace(c, String.valueOf(b));

A: If you expect output 1,54321 you need to write
a.replace("12345", c.String.valueOf(b));


text:
Q: 'iostream' file not found error occur in xcode 4.5? i m practising C++. i just add c++ files in XCode and write some string splitting functionality in it. After that i include that C++ file i.e. extension of .mm file in my AppDelegate file and call function from .h file of C++ class. But i found one static error in red line which is 'iostream' file not found . I used latest XCode version 4.5 and iOS 6.0. Please see screen shot of my error or xcode screen.

I m tried to modify my code as per given link information but no success. :(
also i followed this link information as well, but result is same.
Thanks
iHungry

A: Objective C having .m extensions for its implementation files. If you want to use C++ in Objective C it should have .mm extensions. you can include C++ header files in your .mm file. But if you want to include your C++ header files in your .h file, you need to check macro for that, like
#ifdef __cplus
#include <iostream>
#endif

But, I haven't tried any functions by including C++ header file in .h file. Hope it helps.


text:
Q: Visual Studio line highlight in Debug mode When I'm debugging my code, in most cases the the debugged line is highlighted (by Visual Studio debugger) with the Yellow background. Here is the screenshot:

But, in some case the debugged line is highlighted with Orange background: Here is the screenshot:

Also, sometimes when I'm pressed F10 button the code line background changed from Yellow to Orange and vise versa. What is the pattern behind those changes?
PS -
I wonder if this is somehow related to the fact that my program has two separate threads that are running in the background?

A:
I wonder if this is somehow related to the fact that my program has two separate threads

Yes, very much so.  The orange background color is meant to warn you that a thread context switch occurred and you are no longer debugging the thread you previously looked at.  Note the blue exclamation overlay on the arrow, an extra warning.
Some sample code that makes it crystal clear:
using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        new Thread(Example).Start();
        new Thread(Example).Start();
        Console.ReadLine();
    }

    static void Example() {
        var rng = new Random(Thread.CurrentThread.ManagedThreadId);
        for (int loop = 0; loop < 10000; ++loop) {
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
            Thread.Sleep(rng.Next(0, 100));
        }
    }
}

Set a breakpoint on one of the Thread.Sleep() calls.  Press F5 and execution will stop at the breakpoint.  The background is yellow.  Use Debug > Windows > Threads, note the yellow arrow on the current thread.
Now press F10.
One of three things can happen, the outcome is completely random:

*

*You step to the next statement in the same thread.

*The second thread might hit the breakpoint as well.

*The second thread might be the first to land on a statement and trigger a debugger break.

Also observe the yellow marker in the Threads debugger window.  In the first bullet that marker did not move, the same thread activated the break.  The background color is yellow.  If the marker did move, thus matching the last 2 bullets then the background color is orange.
Press F10 repeatedly to get all the possible outcomes.  And note that the background color choice is an exact match with whether or not the current thread changed in the Threads window.  The third bullet is the likeliest outcome in this sample program.
Next experiment you should try is right-clicking the other thread in the Threads window and selecting Freeze.  Pressing F10 now consistently hits the same thread and the highlight is always yellow.  The kind of thing you need to do when debugging threads becomes too difficult.
Long story short, knowing that you are debugging a different thread is rather important.  Local variables and stack trace might be quite different.  The orange background and the blue exclamation warns you about it.


text:
Q: gets function is causing an Invalid argument error I'm having to learn ruby (not rails) due to a device that only runs ruby installed code.
I'm currently using v 1.9.3 on my Windows 10 desktop to study the syntax and I can't run any examples with the gets() function.
example:
name = gets()

without getting the error

test.rb:1:in `gets': Invalid argument -  (Errno::EINVAL)

I haven't tried updating the version (Manufacturer's guide, though possible just out of date, listed installing 1.9) but I wouldn't think such a core function would be missing from this version.
puts() works just fine.
Thanks in advance for any direction...


text:
Q: "while you grow" or "while growing"? Which one do you think is appropriately stated? Or which one sounds better?

*

*Speed up customer service, while you grow your restaurant.

*Speed up customer service, while growing your restaurant.

A: Both examples sound more like fragments, rather than full sentences.
Regarding meaning, it is mostly the same.
Example 2 sounds slightly better and accents "growing", while example 1 accents "you". So depending on what you want to say, you can use either of them.


text:
Q: Secure keys in Java file like API keys, etc from hackers I am building an Android app and I am worried about app security of API and other keys. So I need a method to secure them from hackers!
I have already tried to store these keys on Firebase but it is not a perfect method as it uses a lot of data on Firebase and took time to receive.

A: A safe option would be saving the KEY API values inside the local.properties file.
Inside your app/build.gradle file add the reference to the API KEY:
android {
     ...

    defaultConfig {
        ...
        buildConfigField "String", "myAPI_KEY", "\"API_KEY_VALUE\""
        ...
    }
     ...

}

Inside the local.properties file add the entry that defines the value of the API KEY:
API_KEY_VALUE="AIzaSy..............."

then, build your project and you can get the value of the API KEY from the BuildConfig class, example:
 String myApiKey = BuildConfig.myAPI_KEY;


text:
Q: How can I access the lock-screen's owner-information of an Android device? I have CyanogenMod installed on my phone in one of the settings menus, it allows me to set some owner information that is displayed on the Lockscreen. Here's a screenshot:

I've seen a lot of questions regarding this but they all seem to confuse the owner information as the "Me" contact on ICS and JB devices. I'm referring to the owner-information as configured in the settings.
Is there a way I can access this information?
Thanks


text:
Q: ubuntu hang out with this message :blocked for more than 120 seconds I'm running a virtualMachine on ESXi -- Ubuntu as a webserver -- (apache2 with nginx as his proxy, php, mysql) and services keeps hanging/freezing causing the whole server to be unresponsive. It's not possible to connect to it by ssh, basicly it requires a reboot from vSphere to come back online.
Description: Ubuntu 10.04.1 LTS Release: 10.04 Codename: lucid
at vSphere I see this message when my server is unreachable:: INFO: task: apache2 (or mysql or nginx) blocked for more than 120 seconds. "echo 0 > /proc/sys/kernel/hung_task_sys_timeout_secs" disables this message
i think that likely it happens in high traffic on my sites what could i do?!
thanks

A: You are hitting a hung task time out, while your system is waiting for some resources (maybe I/O to complete) to complete which are not presently available. I would recommend first collecting some data checking with any sar data or using tools like iostats and vmstat to identify the loads and the times the freeze/hang occurs. You could possibly write a small cron job for this.
ex:
sar -A 1 30 > /tmp/sar_-A.out.txt &
vmstat 1 30 > /tmp/vmstat.out.txt &
iostat -tkx 1 30 > /tmp/iostat_-x.out.txt &
ps aufx > /tmp/ps_aux.out.txt &
Also get a kernel thread dump using: "echo t | sudo tee /proc/sysrq-trigger" as this would help in determining to some extent what the apache process is waiting for.
Alternatively, you could get configure crashdump when your system is in a hung state and obtain a vmcore file, if you are more adventurous to do a dump analysis.


text:
Q: migrate from react-native Navigator to React Navigation I'm trying to build a simple app from a tutorial I'm watching.
This tutorial is about 5 months old now and uses the old React Navigator method of Navigation as seen in the code below.
So I tried using the new React Navigation library, but I can't find any way to get the code below to fit into the new React Navgation method. In fact, I don't really know where to start.  I read through the intro docs at reactnavigation.org, but it's kind of overwhelming.
I was wondering if someone could point me in the right direction.
Thanks!
  <Navigator
    ref = {( ref ) => this._navigator = ref }
    configureScene = { this.configureScene.bind( this )}
    renderScene = { this.renderScene.bind( this )}
  />

 renderScene(route, navigator) {
   switch(route) {
     default: {
       return null;
     }
   }
 }
 configureScene(route, routeStack) {
   return Navigator.SceneConfig.PushFromRight;
 }

A: First of all, add your import :
import {
  StackNavigator
} from 'react-navigation';

Let s say that your app contains two screens, screen_1 & screen_2
(this code is not tested, debug if any compilation error arises)
class Screen_1 extends Component{
    render(){
        return(
            <View flex={1} justifyContent="center" alignItems="center" >
                <TouchableOpacity onPress={this.navigateToNextScreen.bind(this)}>
                    <Text>Screen 1</Text>
                </TouchableOpacity>
            </View>
            )
    }

    navigateToNextScreen(){
        this.props.navigation.navigate("SecondScreen")
        // notice that the "SecondScreen" is the name of the component
        // Screen_1 in the AppStack
    }
}

class Screen_2 extends Component{
    render(){
        return(
            <View flex={1} justifyContent="center" alignItems="center">
                <Text>Screen 2</Text>
            </View>
        )
    }
}

you create a stackNavigator Component as follows :
const AppStack = StackNavigator({
    FirstScreen : {
        screen : Screen_1,
        navigationOptions : {
            title : 'Screen 1'
        }
    },
    SecondScreen : {
        screen : Screen_2,
        navigationOptions : {
            title : 'Screen 2'
        }
    }
})

Then you can use the AppStack as any other component.
I can even believe that you can use it in the renderScene of your react-native Navigator as follows:
renderScene(route, navigator) {
   switch(route) {
     default: {
       return (<AppStack />);
     }
   }
 }

I'd really advise you this youtube tutorial, it got me up and running in less than twenty minutes.


text:
Q: using triggers as resources I want to define triggers as resources to use them later in my controls.
Like this:
<Window.Resources>
    <DataTrigger x:Key="Trigger1" Binding="{Binding ViewModelProperty1}" Value="Val1">
        <Setter Property="IsEnabled" Value="False"/>
    </DataTrigger>
    <DataTrigger x:Key="Trigger2" Binding="{Binding ViewModelProperty2}" Value="Val2">
        <Setter Property="IsEnabled" Value="False"/>
    </DataTrigger>
    ...
</Window.Resources>

However, when I try to run the code, the compiler complains that IsEnabled is not a valid member. I think this is because it cannot know if the control in question will even have the property "IsEnabled". Like with styles, I think I need to somehow specifiy the TargetType (which would be, in my case, FrameworkElement). But how?
NOTE:
Please do not suggest to use styles instead of triggers as resources. Since a control can only have ONE style, but I need to give SEVERAL triggers to one control, styles are no option here:
In my actual code I have a Button that should have trigger 1, 2 and 4 and a TextBox that should have trigger 1 and 3 and a Label that should have trigger 2, 3 and 4... I think you get it.

A: You can do it like this (note how I prepend IsEnabled with FrameworkElement and also how I reference those resources from style triggers):
<Window.Resources>
    <DataTrigger x:Key="Trigger1"
                 Binding="{Binding ViewModelProperty1}"
                 Value="Val1">
        <Setter Property="FrameworkElement.IsEnabled"
                Value="False" />
    </DataTrigger>
    <DataTrigger x:Key="Trigger2"
                 Binding="{Binding ViewModelProperty2}"
                 Value="Val2">
        <Setter Property="FrameworkElement.IsEnabled"
                Value="False" />
    </DataTrigger>
</Window.Resources>
<Button>
    <Button.Style>
        <Style>
            <Style.Triggers>
                <StaticResource ResourceKey="Trigger1" />
                <StaticResource ResourceKey="Trigger2" />
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


text:
Q: My function returns empty array in swift and parse HI there I am writing a function to get data from my parse server in swift everything is working alright and the data is getting read well. but when I try to return the array it returns me an empty array.
I also added a print in the "Get data in background" and there, the array was getting full.So the problem is not getting the data.
public func getthearray() -> Array<UIImage>
{
    let user = PFUser.current()
    let array = user?["Photos"] as! Array<PFFileObject>
    var imagearray = [UIImage]()

    for x in array
    {
        x.getDataInBackground
        { (dataa, error) in

            var img = UIImage(data: dataa!)
            imagearray.append(img!)
        }
    }

    return imagearray
}

A: The reason the function returns an empty array is the fact that the code in the x.getDataInBackground completion gets called asynchronously, and before any image will get added to the array, the faction will already return.
Here is the solution (in 2 versions), which is your function slightly refactored and rewritten with completion handler and Grand Central Dispatch
Approach 1. Semaphores
public func getTheArray(_ completion: @escaping ([UIImage]) -> Void) {
    let user: PFUser = .current()
    let array = user?["Photos"] as? [PFFileObject] ?? []
    var result = [UIImage]()

    let semaphore = DispatchSemaphore(value: 0)
    // dispatch to a separate thread which we can safely occupy and block
    // while waiting for the results from async calls.
    DispatchQueue.global().async {
        for file in array {
            file.getDataInBackground { (data, error) in
                if let data = data, let image = UIImage(data: data) {
                    result.append(image)
                }
                // the result have arrived, signal that we are ready
                // to move on to another x
                semaphore.signal()
            }

            // wait until the `signal()` is called, thread is blocked
            semaphore.wait()
        }
        // dispatch to main queue where we are allowed to perform UI updates
        DispatchQueue.main.async {
            // call the completion, but we are doing it only once,
            // when the function is finished with its work
            completion(result)
        }
    }
}

Approach 2. Dispatch Groups
public func getTheArray(_ completion: @escaping ([UIImage]) -> Void) {
    let user: PFUser = .current()
    let array = user?["Photos"] as? [PFFileObject] ?? []
    var result = [UIImage]()

    let group = DispatchGroup()
    for file in array {
        group.enter()
        file.getDataInBackground { (data, error) in
            if let data = data, let image = UIImage(data: data) {
                result.append(image)
            }
            group.leave()
        }
    }

    // notify once all task finish with `leave()` call.
    group.notify(queue: .main) {
        // call the completion, but we are doing it only once,
        // when the function is finished with its work
        completion(result)
    }
}

Usage
and you would call it like this
getTheArray { result in
    // do what you want with result which is your array of UIImages
}

Documentation:

*

*DispatchQueue

*DispatchSemaphore
Relevant blogposts:

*

*Grand Central Dispatch by John Sundell

*A deep dive into Grand Central Dispatch in Swift by John Sundell

A: You should use the completion handler closure as discussed by others, in order to asynchronously return the array of images when all the requests are done.
The general pattern is:

*

*Use @escaping completion handler closure.

*Use dispatch group to keep track of all of the asynchronous requests.

*Store the results in a dictionary as the individual requests finish. We use a dictionary for the results, because with concurrent requests, you do not know in what order the requests will finish, so we will store it in a structure from which we can efficiently retrieve the results later.

*Use dispatch group notify closure, to specify what should happen when all the requests are done. In this case, we will build a sorted array of images from our unsorted dictionary, and call the completion handler closure.

*As an aside, one should avoid using forced unwrapping operator (the ! or as!), especially when dealing with network requests, whose success or failure is outside of your control. We would generally use guard statement to test that the optionals were safely unwrapped.

Thus:
func fetchImages(completion: @escaping ([UIImage]) -> Void) {
    guard
        let user = PFUser.current(),
        let files = user["Photos"] as? [PFFileObject]
    else {
        completion([])
        return
    }

    var images: [Int: UIImage] = [:]                         // dictionary is an order-independent structure for storing the results
    let group = DispatchGroup()                              // dispatch group to keep track of asynchronous requests

    for (index, file) in files.enumerated() {
        group.enter()                                        // enter the group before asynchronous call
        file.getDataInBackground { data, error in
            defer { group.leave() }                          // leave the group when this completion handler finishes

            guard
                let data = data,
                let image = UIImage(data: data)
            else {
                return
            }

            images[index] = image
        }
    }

    // when all the asynchronous tasks are done, this `notify` closure will be called

    group.notify(queue: .main) {
        let array = files.indices.compactMap { images[$0] } // now rebuild the ordered array
        completion(array)
    }
}

And, you'd use it like so:
fetchImages { images in
    // use `images` here, e.g. if updating a model object and refreshing the UI, perhaps:

    self.images = images
    self.tableView.reloadData()
}

// but not here, because the above runs asynchronously (i.e. later)

But the idea is to embrace asynchronous patterns given that we are calling an asynchronous API, and use dispatch groups to keep track of when they are all done. But dispatch semaphores are generally discouraged, as they force the requests to be performed sequentially, one after another, which will slow it down (e.g., in my experience, between two and five times slower).

As an aside, we would generally want to report success or failure. So rather than [UIImage], we would have the closure's parameter to be a Result<[UIImage], Error> (if you want a single Error) or [Result<UIImage, Error>] if you want either a UIImage or Error for each file. But there's not enough here to know what error handling you want. But just a FYI.

While I've answered the tactical question above, we really should ask how many images might you be dealing with. If you are retrieving lots of images and/or the user is on a slow connection, this pattern (known as "eager" fetching of the images) is discouraged. First, it can be slow if there are a lot of them. Second, images take up a lot of memory, and you might not want to load all of them if you only need a subset of them at any given point in time. We would often refactor our app to employ "lazy" fetching of the images, retrieving them as needed, not all up front. Or, if you want to do eager fetch, download the assets as files to caches folder (reducing RAM consumption) and create UIImage instances when required in the UI.


text:
Q: List files with Unicode names in python 2.7 on windows I am new to python. I am using it to batch process a number of text files with Unicode characters in both filenames and content. I have declared the encoding in the beginning. I am able to process the Unicode content but when I try to list files on windows, this is what I get.
26-??????-P.txt

The actual name of the file is
26-देहजरी-P.txt

This is the script I am using
# -*- coding: utf-8 -*-
import re
from os import listdir

allfiles = [f for f in listdir('./')]
    for f in allfiles:
        if f.endswith('.txt'):
            print f;

I want to selectively open and process the text files and output new files with similar names as the input files (so that they can be matched later).
Please guide on how this can be accomplished. Thanks in advance.

A: One approach is to set Unicode on your path.
Ex:
import os
for i in os.listdir(u"C:\\Your\\Path\\Folder"):   #I have used 'u' before the path
    print i

Output:
26-देहजरी-P.txt


text:
Q: symfony built-in server high cpu usage I'm running Symfony's built-in server during development and noticed that CPU usage of CLI.exe (PHP's command-line interface that's called through php bin/console server:run) is always around 30%, even when idle.
I launch it from a Windows Powershell. Any idea why this happens during idle time?

A: PHP's built-in web server is only meant to be used during development:

Warning This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

It makes no performance guarantees, and I'm not surprised that it has high CPU utilization.
The Symfony documentation suggests that it is only meant as a convenience:

This way, you don't have to bother configuring a full-featured web server such as Apache or Nginx.

Of course, you are free to run a full-featured web server in development if you want something more tuned to real world use.


text:
Q: Is there a planar graph calculator? I just took a exam on graph theory and there was one question that I'm not sure if I answered correctly. Is there any tool I can use to check if a graph is planar or not? The graph was a $K_6$ graph where two vertices had an edge missing. So it had the degree sequence $5\,5\,5\,5\,4\,4$.

A: Kuratowski' Theorem states that a finite graph is planar if and only if it does not contain a subgraph that is a subdivision of K5 (the complete graph on five vertices) or of K3,3 (complete bipartite graph on six vertices, three of which connect to each of the other three, also known as the utility graph).

A: There is a whole wikipedia page on planarity testing.
The article contains for example the  classic path addition method of Hopcroft and Tarjan. You can find it in the LEDA c++ library.

A: Your graph $K_6-e$ ($K_6$ minus one edge) contains induced subgraphs isomorphic to $K_5$ and it contains spanning subgraphs isomorphic to $K_{3,3}.$
Hint. It doesn't matter which edge you remove from $K_6,$ the resulting graphs are all isomorphic; all edges are equivalent, because of the symmetry of $K_6.$ So, first find your Kuratowski subgraph of $K_6,$ and then decide which edge of $K_6$ to remove.


text:
Q: Why my button is shown and than quickly hidden onResume It's probably just a silly mistake but I cannot fix it. I have a Google+ sign in a button, which is shown when the user is not logged in. I also have a sign out button, which is GONE when the user is logged in.Everything works except that when I go back to the activity (onResume) I can see the red Google+ button for about a second and than it gets hidden and the sign out button appears. How can I remove this one second during which I can still see the Google+ button ?
This is my layout:

XML code:

<ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:id="@+id/startGameView"
    android:src="@drawable/play"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"/>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/startGameView"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="46dp">
    <!-- show achievements -->
    <Button
        android:id="@+id/show_achievements"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Achievements"/>

    <!-- show leaderboards -->
    <Button
        android:id="@+id/show_leaderboard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Leaderboard"/>
</LinearLayout>

Code in the activity:
public class StartActivity extends BaseGameActivity implements View.OnClickListener{
private ImageView mPlay;

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

    mPlay = (ImageView)findViewById(R.id.startGameView);
    mPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //play animations
            YoYo.with(Techniques.Pulse)
                    .duration(200)
                    .playOn(findViewById(R.id.startGameView));
            Intent intent = new Intent(StartActivity.this, MainActivity.class);
            startActivity(intent);
        }
    });
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.show_achievements).setOnClickListener(this);
    findViewById(R.id.show_leaderboard).setOnClickListener(this);
    //mSignOutButton = (Button)findViewById(R.id.sign_out_button);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_start, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onSignInFailed() {
    findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
    findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}

@Override
public void onSignInSucceeded() {
    findViewById(R.id.sign_in_button).setVisibility(View.GONE);
    findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}

@Override
public void onClick(View view) {
    if (view.getId() == R.id.sign_in_button) {
        beginUserInitiatedSignIn();
    }else if (view.getId() == R.id.sign_out_button) {
        signOut();
        findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_out_button).setVisibility(View.GONE);
    }else if (view.getId() == R.id.show_achievements){
        Toast.makeText(StartActivity.this,"achivements",Toast.LENGTH_SHORT).show();
        startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), 1);
    }else if(view.getId() == R.id.show_leaderboard){
        Toast.makeText(StartActivity.this,"leaderboard",Toast.LENGTH_SHORT).show();
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(
                getApiClient(), getString(R.string.number_of_solved_math_problems_leaderboard)), 2);
    }
}

BaseActivity code:
public abstract class BaseGameActivity extends FragmentActivity implements
    GameHelper.GameHelperListener {

// The game helper object. This class is mainly a wrapper around this object.
protected GameHelper mHelper;

// We expose these constants here because we don't want users of this class
// to have to know about GameHelper at all.
public static final int CLIENT_GAMES = GameHelper.CLIENT_GAMES;
public static final int CLIENT_APPSTATE = GameHelper.CLIENT_APPSTATE;
public static final int CLIENT_PLUS = GameHelper.CLIENT_PLUS;
public static final int CLIENT_ALL = GameHelper.CLIENT_ALL;

// Requested clients. By default, that's just the games client.
protected int mRequestedClients = CLIENT_GAMES;

private final static String TAG = "BaseGameActivity";
protected boolean mDebugLog = false;

/** Constructs a BaseGameActivity with default client (GamesClient). */
protected BaseGameActivity() {
    super();
}

/**
 * Constructs a BaseGameActivity with the requested clients.
 * @param requestedClients The requested clients (a combination of CLIENT_GAMES,
 *         CLIENT_PLUS and CLIENT_APPSTATE).
 */
protected BaseGameActivity(int requestedClients) {
    super();
    setRequestedClients(requestedClients);
}

/**
 * Sets the requested clients. The preferred way to set the requested clients is
 * via the constructor, but this method is available if for some reason your code
 * cannot do this in the constructor. This must be called before onCreate or getGameHelper()
 * in order to have any effect. If called after onCreate()/getGameHelper(), this method
 * is a no-op.
 *
 * @param requestedClients A combination of the flags CLIENT_GAMES, CLIENT_PLUS
 *         and CLIENT_APPSTATE, or CLIENT_ALL to request all available clients.
 */
protected void setRequestedClients(int requestedClients) {
    mRequestedClients = requestedClients;
}

public GameHelper getGameHelper() {
    if (mHelper == null) {
        mHelper = new GameHelper(this, mRequestedClients);
        mHelper.enableDebugLog(mDebugLog);
    }
    return mHelper;
}

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);
    if (mHelper == null) {
        getGameHelper();
    }
    mHelper.setup(this);
}

@Override
protected void onStart() {
    super.onStart();
    mHelper.onStart(this);
}

@Override
protected void onStop() {
    super.onStop();
    mHelper.onStop();
}

@Override
protected void onActivityResult(int request, int response, Intent data) {
    super.onActivityResult(request, response, data);
    mHelper.onActivityResult(request, response, data);
}

protected GoogleApiClient getApiClient() {
    return mHelper.getApiClient();
}

protected boolean isSignedIn() {
    return mHelper.isSignedIn();
}

protected void beginUserInitiatedSignIn() {
    mHelper.beginUserInitiatedSignIn();
}

protected void signOut() {
    mHelper.signOut();
}

protected void showAlert(String message) {
    mHelper.makeSimpleDialog(message).show();
}

protected void showAlert(String title, String message) {
    mHelper.makeSimpleDialog(title, message).show();
}

protected void enableDebugLog(boolean enabled) {
    mDebugLog = true;
    if (mHelper != null) {
        mHelper.enableDebugLog(enabled);
    }
}

@Deprecated
protected void enableDebugLog(boolean enabled, String tag) {
    Log.w(TAG, "BaseGameActivity.enabledDebugLog(bool,String) is " +
            "deprecated. Use enableDebugLog(boolean)");
    enableDebugLog(enabled);
}

protected String getInvitationId() {
    return mHelper.getInvitationId();
}

protected void reconnectClient() {
    mHelper.reconnectClient();
}

protected boolean hasSignInError() {
    return mHelper.hasSignInError();
}

protected GameHelper.SignInFailureReason getSignInError() {
    return mHelper.getSignInError();
}

A: As I see in GameHelper class, it disconnects from googleApiClient on onStop() and connect on onStart(). This is causing of blinking buttons.
If you don't want to change GameHelper implementation, make some UI improvement to make it less annoying.

A: If you cloned (or refreshed) the samples recently, you'll notice that GameHelper and BaseGameActivity are not longer used. There is an informative video about this change: Game On! - The death of BaseGameActivity.  If you just implement the interfaces to get the callbacks for the state: GoogleApiClient.ConnectionCallbacks and  GoogleApiClient.OnConnectionFailedListener your problem should go away.
More specific details on how to use these interfaces is at https://developers.google.com/games/services/training/signin


text:
Q: Proper type annotation for an object that can be unpacked with the * operator? What is the proper type annotation for an object that should be unpacked with the * operator, i.e. foo in this (random) example:
def some_function(foo):
    ... = bar(*foo)

I know that * can unpack tuples and lists, but is it limited to these two classes or does it have any kind of interface that would make it usable for other collections?

A: Python unpacks any iterable (so a list, string, tuple, dictionary, etc.). You thus can use an Iterable for that, like:
from typing import Iterable

def some_function(foo : Iterable):
    bar(*foo)
In case the items that are unpacked should be of a specific type, you can specify this between square brackets, like:
# given the items that are unpacked should all be ints

from typing import Iterable

def some_function(foo : Iterable[int]):
    bar(*foo)


text:
Q: Rspec tests keep failing with expected ... got nil I'm trying to get into TDD and i'm currently struggling with this error message:
UsersController GET 'show' should find the right user
     Failure/Error: expect(user).to eq(@user)

       expected: #<User id: 1, email: "example@example.com", encrypted_password: "$2a$04$AVGGS0XU1Kjmbdc/iZ86iOq2f4k992boP7xfqcg2nl6...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-06-08 19:43:41", updated_at: "2014-06-08 19:43:41", name: "Test User", confirmation_token: nil, confirmed_at: "2014-06-08 19:43:41", confirmation_sent_at: nil, unconfirmed_email: nil, account_id: 1, notify: nil>
            got: nil

       (compared using ==)
     # ./spec/controllers/users_controller_spec.rb:28:in `block (3 levels) in <top (required)>'

Here's the particular test:
require 'rails_helper'
include Devise::TestHelpers

describe UsersController do

  before (:each) do
    @user = FactoryGirl.create(:user)
    sign_in @user
  end

  describe "GET 'show'" do

    it "should find the right user" do
      get :show, :id => @user.id
      puts "user = #{@user.inspect}"
      user = assigns(:user)
      #assigns(:user).should == @user
      puts "assigns user = #{assigns(:user)}"
      expect(user).to eq(@user)
    end

  end

end

Here's the controller:
class UsersController < ApplicationController
...
    def show
        authorize! :show, @user, :message => 'Not authorized as an administrator.'
        @user = current_account.users.find(params[:id])
    end

...
end

application_controller.rb:
class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

    check_authorization :unless => :devise_controller?
    before_filter :authenticate_user!, :validate_subdomain
    helper_method :subdomain, :current_account
    layout :set_layout

# This will redirect the user to your 404 page if the account can not be found
    # based on the subdomain.  You can change this to whatever best fits your
    # application.
    def validate_subdomain
        current_account
    end

def current_account
        @current_account ||= Account.where(:subdomain => subdomain).first
        #puts @current_account

        if @current_account.nil?
            redirect_to('/accounts/invalid_site')
            return
        end

        @current_account
    end

def subdomain
        request.subdomain
    end

...
end

user factory:
FactoryGirl.define do
  factory :user do
    name 'Test User'
    account_id 1
    email 'example@example.com'
    password 'changeme'
    password_confirmation 'changeme'
    # required if the Devise Confirmable module is used
    confirmed_at Time.now
  end
end

How can I get around this error message? I have a feeling it has something to do with before_filters, but that's just a guess.

A: Do you have before_filter on your users controller where you need authentication to use the show method? Your before block is making two calls, creating a user and then "sign_in", some kind of authentication. But your test is just to see if the user was created and the show method returns the correct user record with the passed id.
So I would break down your before block. Start by testing that your Factory is being created successfully:
it 'has a valid factory' do
    FactoryGirl.create(:user).should eq(true) # or should be_valid..
end

If that passes, I'd comment out any constraint on your users controller (temporarily) for the sign_in method, and test if show receives the id and returns the correct user.
If that passes, then add the constraint back in for validation on your users controller, and figure out how to test your sign_in method. :)

A: Ok so i figured it out from debugging through the current_account not getting set. I found this answer Rails rspec set subdomain.
I guess i left out a major piece of the puzzle in my original question so i apologize about that as I had no idea that would affect my rspecs.
The trick was to
before(:each) do
  @account = FactoryGirl.create(:account)
  @request.host = "#{@account.subdomain}.example.com"
end


text:
Q: How to have datepicker set default year? I am using bootstrap datepicker and I only show the years. When I load the page, I would like to set a default year, tried the following but the current year (2018) is hightlited instead.
$('#sandbox-container div').datepicker({
  format: "yyyy",
  viewMode: "years",
  minViewMode: "years",
  updateViewDate: false,
  changeYear: true,
  defaultDate: '2014'
});

Thing is this is an Edit page, so the year is coming from the db, therefore I need to be able to set a default year as per the value I am getting from the db.

A: I had to change updateViewDate: false into updateViewDate: true, so:
$('#sandbox-container div').datepicker({
  format: "yyyy",
  viewMode: "years",
  minViewMode: "years",
  updateViewDate: true,
  changeYear: true,
  defaultViewDate: {year: '2014'}
});


text:
Q: CodeIgniter Active Record - Get number of returned rows and get the sum I'm new to CodeIgniter and Active Record in particular
How can I Get number of returned rows and get the SUM of two returned tables row counts.
I already have function to get row count like this
controller
 function newsletter (){
        $data = array();
        $data['subscriber_count'] =$this->mod_contactus->count_subscriber();
        $data['user_count'] =$this->mod_contactus->count_reg_users();
        $this->load->view('admin/admin_newsletter',$data);
    }

model
 public function count_subscriber() {
       return $this->db->get("tbl_subscribers")->num_rows();
    }

    public function count_reg_users() {
        return $this->db->get("tbl_customer_registration")->num_rows();
    }

A: It is not a big deal. You can do something like this. Assist PHP array_sum .This is php manual to array sum You already have the row counts
in your controller
function newsletter (){
    $data = array();
    $data['subscriber_count'] =$this->mod_contactus->count_subscriber();
    $data['user_count'] =$this->mod_contactus->count_reg_users();
    $data['count_both'] =  array_sum($data);
    $this->load->view('admin/admin_newsletter',$data);
}

in your view  echo $count_both ;

A: If that's really your only goal, just execute one query:
$query = $this->db->query("
    select
    ( select count(*) from table_1 ) +
    ( select count(*) from table_2 )
    as total_num_row
    from table_1
");

# $query->num_rows()


text:
Q: jquery event no change The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
    if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
    var information = '';
    var i = 1;
    $j("#cf20_field_1").html();
    //add new information to hidden field
    $j("#cforms20form .info_for_email").each(function(){
        var name = $j(this).find("INPUT[name='cf20_field_5']").val();
        var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
        var view = $j(this).find("SELECT[name='cf20_field_7']").val();
        //render
        information += i + ")";
        information += "Наименование организации: " + name + ".
\n";
        information += "Реквизиты организации: " + inn + ".
\n";
        information += "Стоимость заказа: выписка " + view + ".
\n";
        i++;
    })
    $j("#cf20_field_1").html(information);

    hovered = true;
}
    ,100
);

Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){

    $j("SELECT[name='cf20_field_7']").trigger('change');
    if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
    var information = '';
    var i = 1;
    $j("#cf20_field_1").html();
    //add new information to hidden field
    $j("#cforms20form .info_for_email").each(function(){
        var name = $j(this).find("INPUT[name='cf20_field_5']").val();
        var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
        var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
        //render
        information += i + ")";
        information += "Наименование организации: " + name + ".
\n";
        information += "Реквизиты организации: " + inn + ".
\n";
        information += "Стоимость заказа: выписка " + view + ".
\n";
        i++;
    })
    $j("#cf20_field_1").html(information);
}
    ,100
);

More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.

A: Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))

I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))

But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
    return false;
});

A: if ($j("SELECT[name='cf20_field_7']").on("change")) return false

Not clear what should be checked here.  I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
    //some other code?
    return jObj.val() == "some value to test";
}

Possibly some better approach may be used, but without more details it is hard to suggest something.


text:
Q: Unlimited organizations on Hyperledger Fabric Overview
My blockchain architecture requires each individual user to keep their data private. There can be unlimited number of users (say in millions). As per Hyperledger Fabric's documentation

An organization can be as large as a multi-national corporation or as small as an individual

Here is an architecture that comes to my mind:

*

*My company will have Organization A on business network

*Everytime a user signs up I will create a new Organization N, and new Channel C on business network.

*Each new channel will have two members: Organization A and user's newly added organization N

I purposely did not choose Private Data because Add an Org to Channel tutorial suggests that if N organizations exist in a particular channel then N-1 organizations must sign the transaction to allow new organization to come in. Because there is zero sharing of data between each user organization so I am creating unlimited channels (one channel for each user org).
Questions :

*

*I am trying to dodge the linear complexity that will kick in when I try to add new Org to existing channel. Is my architecture solving the linear increase of complexity effectively?

*Am I running into some other problem with this design?

*Something counterintuitive about my design?

A: There's no real issue from a technical perspective with having a huge number of bi-lateral channels.  The process for adding a new org would mean you need to create the new channel, join the user peer to the channel, join Org A to the channel and then instantiate any chaincode on that channel.  Pretty easy to automate.  At some point, you may need to create multiple peers for Org A and distribute the channels across those peers.
On the other hand, you could take a look at using private data combined with state-based endorsement.  Rather than create a channel between Org A and each user, you could create a collection Org A / Org N instead and then use state-based endorsement to only require endorsement from Org A and Org N.  The disadvantage here is that Org N+1 ... Org N + X would end up with hashes of all the keys/values for all users ... which you might not want (especially since it requires users to store data which is not relevant to them).

A: I would think it's pretty obvious that creating one org per user, when you have millions of users is not a good idea. In Hyperledger, an organisation would have its own peers and that's not something that makes sense at user level. In addition to this, managing a virtually unlimited network with an unlimited number of orgs and channels is simply not practical even from a maintenance point of view, let alone a build point of view.
I suggest you explore other ways of keeping users data secure. One way would be to encrypt it, hash it, whatever makes sense for your own scenario and only then store it on the ledger. But then, the users would still be part of one or more orgs, where the total number of orgs is something manageable.
From what you said so far, I am not convinced that Hyperledger is the way to go for you. Maybe your own Ethereum network would work better for this, as there you have user level accounts. If you don't need a blockchain solution, you might to want stick to a standard way of building something like this.


text:
Q: How to calculate the probability of many people tossing a fair coin many times will fall within specific range as a percentage? If 5 000 000 each people flip a fair coin 5000 times each. What is the percentage chance that every single person will get a result of 2000-3000 either heads or tails. In other words, no one can get 1800 heads and 3200 tails and vice versa.
Been working on this with a friend for a couple days and require a formula or reference to a program or site with sufficient accuracy or power please. The answer would also be helpful.
Layperson's terms or defined symbols please.
Also if you'd like to be credited with the answer on reddit please say so.

A: If $p$ is the chance that a single person gets 2000-3000 of either heads or tails, then the answer is $p^{5000000}$. So it remains to compute focus on a single person and compute $p$.

The number of heads in 5000 flips is a $\text{Binomial}(5000, 1/2)$ random variable. If you use a computer to compute the probability by summing the probability of having 2000 heads, 2001 heads, 2002 heads, etc. up to 3000 heads, you will find that the probability is incredibly close to $1$.
Another way to see this is that the distribution of the number of heads in 5000 flips is very close to a normal distribution with mean $2500$ and standard deviation $\sqrt{5000 /4} \approx 35.36$. So having 2000-3000 heads is asking for the number of heads to be within $500 / \sqrt{5000/4} \approx 14$ standard deviations of the mean $2500$ which is extremely likely (99.7% of the mass of the normal distribution already lies within $3$ standard deviations of the mean).

Since you really want $p^{5000000}$, the precision of $p$ (how close $p$ is to $1$) will matter (since even $0.999^{5000000} \approx 0$). However, as you see in the WolframAlpha output above, $1-p \approx 10^{-45}$, so $$p^{5000000} = (1-(1-p))^{5000000} \approx 1 - 5000000 \cdot 10^{-45}$$
which is still incredibly close to $1$.


text:
Q: Need to Pull result from last year into inventory usage report I have an inventory usage report that pulls in transactions from the previous year. Right now I have results for the current year. What is the correct date syntax for me to use?
Below is what I have currently for this year I am using the get date function for this year and need it to calculate the same information, but break it down monthly for last year.
SELECT OITM.ItemCode, OITM.ItemName AS 'Description', OITM.CardCode AS
'Vendor',
SUM(OITW.OnHand) AS 'On Hand', SUM(OITW.OnOrder) AS 'On Order',
SUM(OITW.IsCommited) AS 'Committed',

(SUM(OITW.OnHand)+SUM(OITW.OnOrder)-SUM(OITW.IsCommited)) AS 'Available',
OITM.AvgPrice AS 'Unit Cost',(SUM(OITW.OnHand)*OITM.AvgPrice) AS 'Value $',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
YEAR(OINM.DocDate)=((year, -1, GETDATE()) AND OINM.ItemCode = OITM.ItemCode
GROUP BY

OINM.ItemCode) AS 'Prev. Year',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='1' AND YEAR(OINM.DocDate)=(year, -1, GETDATE()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JAN',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='2' AND YEAR(OINM.DocDate)=(year, -1, GETDATE()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'FEB',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='3' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'MAR',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='4' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'APR',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='5' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'MAY',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='6' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JUN',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='7' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JUL',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='8' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'AUG',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='9' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'SEP',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='10' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'OCT',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='11' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'NOV',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='12' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =

OITM.ItemCode GROUP BY OINM.ItemCode) AS 'DEC'
FROM OITM, OITW
WHERE OITM.ItemCode=OITW.ItemCode

A: My suggestion is to shorten the original query a bit. If I'm not completely wrong, it can be written as follows:
WITH
  OINM_Base (ItemCode, [Month], OutQty) AS (
    SELECT
      ItemCode,
      CASE GROUPING(MONTH(DocDate))
        WHEN 1 THEN 0 ELSE MONTH(DocDate)
      END,
      SUM(OutQty)
    FROM OINM
    WHERE TransType <> '67' AND YEAR(DocDate) = YEAR(GETDATE()) -- change this for the previous year
    GROUP BY ItemCode, ROLLUP(MONTH(DocDate))
  ),
  OINM_Data (ItemCode, [Year], JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, [DEC]) AS (
    SELECT ItemCode, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
    FROM OINM_Base
    PIVOT (SUM(OutQty) FOR [Month] IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) pvt
  ),
  OITW_Data (ItemCode, [On Hand], [On Order], [Committed]) AS (
    SELECT ItemCode, SUM(OnHand), SUM(OnOrder), SUM(IsCommited)
    FROM OITW
    GROUP BY ItemCode
  )
SELECT
  tm.ItemCode,
  tm.ItemName AS [Description],
  tm.CardCode AS Vendor,
  tw.[On Hand], tw.[On Order], tw.[Committed],
  tw.[On Hand] + tw.[On Order] - tw.[Committed] AS Available,
  tm.AvgPrice AS [Unit Cost],
  tw.[On Hand] * tm.AvgPrice AS [Value $],
  nm.[Year], nm.JAN, nm.FEB, nm.MAR, nm.APR, nm.MAY, nm.JUN, nm.JUL, nm.AUG, nm.SEP, nm.OCT, nm.NOV, nm.[DEC]
FROM OITM tm
  INNER JOIN OITW_Data tw ON tm.ItemCode = tw.ItemCode
  LEFT OUTER JOIN OINM_Data nm ON tm.ItemCode = nm.ItemCode;

This works as follows:
The data in OINM is restricted to the year in question, summing the OutQty values per month and creating a total for the year which is labelled as month number 0 (CTE OINM_Base). Using a PIVOT query, the sums appearing on different rows are turned into columns (CTE OINM_Data). The aggregation for the OITW data is also done saparately (CTE OITW_Data).
Both OINM_Data and OITW_Data are finally joined with the data building the main rows from OITM. Here, the final calculations are done (Available and Value $).
Now, to change the query to return the previous year, only one thing has to be changed (see my comment "change this for the previous year"), namely :
YEAR(GETDATE()) has to be replaced by YEAR(GETDATE()) - 1.


text:
Q: Error:(15, 32) error: cannot find symbol variable webview cannot find symbol webview
import android.webkit.WebView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview); //get the error here
        WebView webview = (WebView) findViewById(R.id.miWebView);
        webview.loadUrl("http://www.android.com");

    }

In my activity_main.xml
    <WebView
        android:id="@+id/miWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</linearLayout>

I don´t know where is the error.

A: change
 setContentView(R.layout.webview);

to
 setContentView(R.layout.activity_main);

You must set activity_main.xml layout at setContentView(...)

A: use
setContentView(R.layout.activity_main);

to set layout of Activity because activity_main.xml is layout name instead of webview.xml.


text:
Q: Using Pandas to do SIMPLE Backtesting: using until I have a panda df with a date time index from 1990-2015.
It has columns with an adj close of the S&P 500, a FOR (Financial Obligation Ratio), a PE ratio, and so on and so forth. I've created graphs to look at relationships between the different ratios and market. I'm now trying to backtest an investment strategy. I've done some of this in Quantopian but never on my own and am a newbie to pandas.
The first two columns of my table look like this:

I've messed around with some of the code but don't know how to do it. The idea is the following: Invest a starting portfolio of $1,000,000 the first month the FOR drops below 16.5. Ride the S&P until the FOR hits 16.5, sell. Buy back when it drops back below again. I think that I would need to use a while statement
for idx in df.index:
    if df['Financial Obligation Ratio'].loc[idx]<16.5:

       print idx, df['Adj Close'].loc[idx]

This prints all time periods that I would want the $$ invested. Is there a way to use "while" along with "next idx" to make this program successful

A: You don't need to iterate:
In [21]: df
Out[21]:
            Adj Close    FOR
date
1990-01-09     329.07  16.23
1990-01-08     329.07  16.92

In [22]: df[df['FOR'] < 16.5]
Out[22]:
            Adj Close    FOR
date
1990-01-09     329.07  16.23

In [23]:


text:
Q: Library reference missing for WindowsInstaller C# Console Application New to C# and VS
All I am trying is to get details/properties of an msi file programmatically (eg. "Comments" in the details tab when you get file properties)
I am using the following code (using someone's code of internet) , VS is complaining about missing reference for below and also suggesting not to use "using"
using WindowsInstaller;//msi.dll
ERROR
The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)
And also within the function it cannot resolve any reference for the following
WindowsInstaller.Installer installer = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);
Here is the code:
using System.Configuration.Install;//System.Configuration.Install.dll
using WindowsInstaller;//msi.dll

static void get_msi_details(string path)
{

// Get the type of the Windows Installer object
Type installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");

// Create the Windows Installer object
WindowsInstaller.Installer installer = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);

// Open the MSI database in the input file
Database database = installer.OpenDatabase(path, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);

// Open a view on the Property table for the version property
View view = database.OpenView("SELECT * FROM Property WHERE Property = 'Comments'");

// Execute the view query
view.Execute(null);

// Get the record from the view
Record record = view.Fetch();

// Get the version from the data
string version = record.get_StringData(2);
}

VS studio isnt offering anything in "Potential Fixes" to resolve the reference.

A: In Visual Studio go to References > Add Reference... > COM > Browse... > %WINDIR%\system32\msi.dll.


text:
Q: sencha app - ios home screen icon turns black I'm developing a sencha touch 2 app and I've set an icon for ios when it's needed to add to Home Screen. It works perfectly when you save it, but once you click it for the first time, the icon turns black completely, and it keeps like that forever, not being able to see my customized icon ever again. Text keeps perfectly fine.
Do you have any idea about this? Any suggestion?
Thanks in advance.


text:
Q: Assign coordinates of an image to variables on a mouse click The following code gives me the x and y coordinates of an image on a mouse click event.  I want to assign the x and y coordinates to global variables x and y instead of printing them and then close the image.  How do I do this please?
%matplotlib tk
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

fig = plt.figure(figsize=(20,30))

img=mpimg.imread(workingimage)

def onclick(event):
    ix, iy = event.xdata, event.ydata
    print(ix, iy)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

imgplot = plt.imshow(img)
plt.show()

A: You could assign the values to 2 global variables and call plt.close():
%matplotlib tk
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

fig = plt.figure(figsize=(20,30))

img = mpimg.imread(workingimage)

def onclick(event):
    global clicked_on_x, clicked_on_y
    clicked_on_x, clicked_on_y = event.xdata, event.ydata
    plt.close()

cid = fig.canvas.mpl_connect('button_press_event', onclick)

imgplot = plt.imshow(img)
plt.show()
print("clicked on position", clicked_on_x, clicked_on_y)

# rest of code

A: So I modified your code so that it works:
#%matplotlib tk
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import time

fig = plt.figure(figsize=(20,30))

img=mpimg.imread(working_image)

def onclick(event):
    ix, iy = event.xdata, event.ydata
    #global x,y
    #x,y = ix,iy
    #print(ix, iy)
    plt.close() #closing the figure
    get_x(ix,iy)

def get_x(pX,pY):
    print("X-Coordinate: " + str(pX))
    print("Y-Coordinate: " + str(pY))

cid = fig.canvas.mpl_connect('button_press_event', onclick)

imgplot = plt.imshow(img)
plt.show()

The changes:
Handing ix,iy to the next Funktion that needs them as parameters. You could assign them as global, then you don't need the parameters, but global variables should be avoided
the line plt.close(fig) closes the figure named fig
So I hope that answers all your questions


text:
Q: How do I get my coordinate points to be in my spatial dataframe so it puts the points in the right place when I upload it to ArcGIS as a shapefile? I'm trying to upload some of my analysis from R into ArcGIS but there isn't any coordinate points when I upload it. In my original CSV file I had coordinate points but lose them when I create a spatial dataframe???
#read csv file into r and then omit all the NAs
all_baboon <- read.csv(file = 'All_GPS_Collar_Data.csv')
baboon_GPS <- na.omit(all_baboon)

#create spatial dataframe by first creating new table with just individuals and x y coordinates
baboon.sp <- baboon_GPS[, c("Baboon", "X","Y")]

#create spatial points data frame
coordinates(baboon.sp) <- c("X", "Y")
str(baboon.sp)

#set coordinate referene system
proj4string(baboon.sp) <- CRS( "+proj=utm + zone=37 + datum=WGS84 +units=m +no_defs")

#calculate MCPs for each social group, 100% of points used in this scenario
baboon.mcp <- mcp(baboon.sp, percent=100)

baboon.mcp

I followed a tutorial for using adehabitat to find the home range of baboons. I can plot the home ranges in R, but haven't put a map down as the background because I want to import it as a shapefile into arcGIS. However, when I created a shapefile, theres no coordinates so the points and polygons don't get placed on the map.
shapefile(x = baboon.mcp, file = ".../baboonmcp.shp")

writeOGR(baboon.mcp, dsn = "...file_location", layer = "baboon.mcp", driver = "ESRI Shapefile")

I've tried it using shapefile and writeOGR but still have nothing. How can I add back the coordinates from the original csv file so it can be plotted in arcGIS?