text:
Q: Beginner Graphics2D Java : repaint() I am trying to change the color of my Red Cirlces in the Action handler then repaint() and I couldn't figure out why it is not working.
Imports here
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

My class here:
public class CirclePanel extends JPanel implements ActionListener  {
    static JFrame f;
    static JButton run1, run2, reset, quit;
    static JPanel btnPanel;
    static CirclePanel circlePanel;
    static final int NUM = 5;
    static Color c;
    static Graphics2D g2;
    static Graphics2D g3;

    public CirclePanel(){

        f = new JFrame();

        f.setTitle("Dining Philosophers");
        f.setDefaultCloseOperation(EXIT_ON_CLOSE);
        f.setSize(1000,1000);
        f.setLayout(new BorderLayout());

        btnPanel = new JPanel();
        btnPanel.setPreferredSize(new Dimension(250, 100));
        btnPanel.add(run1 = new JButton("Run 1"));
        btnPanel.add(run2 = new JButton("Run 2"));
        btnPanel.add(reset = new JButton("Reset"));
        btnPanel.add(quit = new JButton("Quit"));

        run1.setPreferredSize(new Dimension(180, 50));
        run2.setPreferredSize(new Dimension(180, 50));
        reset.setPreferredSize(new Dimension(180, 50));
        quit.setPreferredSize(new Dimension(180, 50));

        run1.addActionListener(this);

        f.add(btnPanel, BorderLayout.SOUTH);

        f.add(this, BorderLayout.CENTER);

        f.setVisible(true);
    }

    @Override
    public void paintComponent(Graphics g){

        super.paintComponent(g);
        g2 = (Graphics2D) g;
        g3 = (Graphics2D) g;
        g2.translate(470, 400);

        c = Color.red;

        for(int i = 0; i <  NUM; ++i){
            c = Color.red;

            g2.setColor( c);

            g2.fillOval(150, 0, 100, 100);

            g3.setColor(Color.BLACK);
            g3.fillOval(90, 0, 30, 30);

            g2.rotate(2*Math.PI/ NUM);
        }
    }

As you can see when I push the button Run1 it does go into the action handler and executes the repaint method, but nothing changes.
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == run1) {
            System.out.println("Entered Action Handler");

            g2.setColor(Color.green);

            repaint();

        }
    }

Here is my main:
    public  static void main(String[] args) {

         new CirclePanel();
    }

}

A: The Graphics objects are not long-lived, not stable, and you shouldn't be using them in this way. Instead of setting g2 or any other Graphics field, create a Color field, say called Color circleColor = ...;, and change this. Within the protected void paintComponent(Graphics g) method, call g.setColor(circleColor);, and this should work.
Delete these fields as they are dangerous:
// static Graphics2D g2;
// static Graphics2D g3;

Also your code shows gross over-use of the static modifier, and I would venture to recommend that none of your fields should be static except for the constant:
static final int NUM

A: The repaint() method will ultimately invoke the paintComponent() method of your panel. Swing will pass in the Graphics object to be used in the painting.
In the painting code you always hardcode the Color to be RED. Don't do this.
Instead you need to define a variable in your panel class. Lets say "circleColor" (ie, "circleColor" replaces your "c" variable because variable names should be more descriptive, not just a single character).
Then in your ActionListener code you do:
//g2.setColor(Color.green);
circleColor = Color.green;

This in the paintCompnent() method you do:
//c = Color.red;
g.setColor(circleColor);

Also:
static Graphics2D g2;
static Graphics2D g3;

There is no need for any of those variable. You always use the Graphics object that is passed to the painting method.
Read the section from the Swing tutorial on Custom Painting for more information and for better examples on how to structure your code. For example you should NOT be using static variables.

A: What's happening is:

*

*You are changing g2 color in the action listener.

*Then you call repaint(); so paintComponent(Graphics g) is called.

*In the paintComponent(Graphics g) method you are setting the g2 color to c so you are overriding the changes you made in the action listener.

That's why the circles are not changing color in the end.
You should set c = Color.RED; in the constructor instead of in the for loop, then you can just change the value of c in the action listener c = Color.GREEN;.
Also you're setting c = Color.RED; both in the for loop and before it which is useless.
EDIT:
As suggested by @camickr your code is also badly structured.

*

*You don't need g2 and g3 because you can draw multiple shapes
using the same Graphics g object.

*In your case you don't even need to call g outside of the paintComponent method because you can simply change the Color c variable as i said above.

*You also don't need all of those static variables. Just make them private and if you need to access them from outside the class you should create some getters and setters.

Here you'll find more on static variables and some examples.
Here you'll find more about getters, setters and encapsulation.
Example of how you could change your code:
public class CirclePanel extends JPanel implements ActionListener  {

    private JFrame f;
    private JButton run1, run2, reset, quit;
    private JPanel btnPanel;
    private int NUM;
    private Color c;

    public CirclePanel(){

        color1 = Color.red;
        color2 = Color.black;

        NUM = 5;

        // Setup JFrame and stuff as you were doing.

    }

    @Override
    public void paintComponent(Graphics g){

        super.paintComponent(g);

        g.translate(470, 400);

        for(int i = 0; i < NUM; i++){

            g.setColor(color1);
            g.fillOval(150, 0, 100, 100);

            g.setColor(color2);
            g.fillOval(90, 0, 30, 30);

            g.rotate(2*Math.PI/ NUM);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == run1) {
            System.out.println("Entered Action Handler");

            color1 = Color.green;

            repaint();
        }
    }

    // GETTERS and SETTERS if needed
}


text:
Q: Finding a CDF given a PDF using summations I am in a prob and stats class and we have just begun our discussion on discrete random variables.  I am given a pdf of
$$
f(x) = \left\{\begin{aligned}
&x/10 &&: x = 1,2,\ldots,4\\
&0 &&: \text{otherwise}
\end{aligned}
\right.$$
I need to find an expression for the cumulative distributive function.  I have done some research and I see that you can do this with derivatives and anti-derivatives.. however, that is not how the examples my professor has done are shown so I am looking for help with that.  I have the following definition:
$$F(x) = \sum_{x_i \le x} f(x_i)$$ where the summation is taken over indices $i$ such that $ x_i \le x$.  I have the list of properties of CDF I am just not sure how to apply it.  For my particular problem I think I need to do
$$F(X) = \sum_{k=1}^x \frac k {10}$$ which would be $$ \frac 1 {10} \sum_{k=1}^x  k$$

A: Yes you are correct. For discrete random variables, you should sum the lesser values as you have defined.
Derivatives and anti-derivatives are used for continuous random variables. You'll probably cover this topic in your class soon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve file names from a specific directory using JavaScript or jQuery? I want to make a code using only JavaScript or/and jQuery to access a static directory and retrieve the names of some icons i saved there (SVG icons) and display the names to the user. i couldn't do that with the file api and i have no idea where to start.

A: I'm going to assume from your mention of jQuery and the File API that you're trying to do this within a browser.
You can't. It just isn't allowed, there is no mechanism to provide it.
If you're in control of the machine where you want this information to be accessed, you can run a server process on it that can do that; code in the browser can then make a request to the server code to request the information. But there's no browser-only way to do it.


text:
Q: Evaluating Cauchy's integral $ \int _{|z+1|=1}\frac{1}{(z+1)\sin(z^{2}+z+1)}dz$ I have to solve the following Cauchy's integral   $$ \int _{|z+1|=1}\frac{1}{(z+1)\sin(z^{2}+z+1)}dz$$
$|z+1|=1 \Rightarrow |x+1+iy|=1\Rightarrow\sqrt{(x+1)^{2}+(iy)^{2}}=1 \Rightarrow(x+1)^{2}+(iy)^{2}=1^{2}
$
on the other hand
$(z+1)sin(z^{2}+z+1)= 0 \Rightarrow  (z+1)=0 \rightarrow z=-1$ or $sin(z^{2}+z+1)= 0$ but $sin=0  $ only $sin(0)$ and $(z^{2}+z+1)>0$
How do I find the $Z_{0}$ to use the formula $\oint \frac{f(z)}{(z-z_{0})}= 2\pi if(z_{0})$
Even getting $z_{0}$ and evaluating it at f (z) would still be 1, right?


text:
Q: Unit Testing AKKA actors I am doing a web application with Scala and Akka actors and I'm having some troubles with the tests.
In my case I need to taste an actor who talks with the Database. To do the unit testing I would like to use a Fake Database but I can't replace the new with my desired fake object.
Let's see some code:
Class MyActor extends Actor {
    val database = new Database()

    def receive = { ... }
}

And in the tests I would like to inject a FakeDatabase object instead Database. I've been looking in Internet but the best that I found is:

*

*Add a parameter to the constructor.

*Convert the val database to a var so in the test I could access the attribute by the underlying and replace it.

Both solutions solve the problem but are very dirty.
Isn't a better way to solve the problem?
Thanks!

A: The two primary options for this scenario are:

*

*Dependency Injection Use a DI framework to inject a real or mock service as needed. In Akka: http://letitcrash.com/post/55958814293/akka-dependency-injection

*Cake Pattern This is a Scala-specific way of achieving something akin to dependency injection without actually relying on injection.  See: Akka and cake pattern

A: Echoing the advice here, I wouldn't call injecting the database in the constructor dirty. It might have plenty of benefits, including decoupling actor behaviour from the particular database instance.
However if you know there is only ONE database you will be always using in your production code, then think about defining a package level accessible constructor and a companion object returning a Props object without parameters by default.
Example below:
object MyActor {

    def props() : Props = Props(new MyActor(new Database()))

}

class MyActor private[package](database : IDatabase) extends Actor {

    def receive = { ... }
}

In this case you will still be able to inject the test database in your tests case (given the same package structure), but prevent users of your code from instantiating MyActor with unexpected database instance.


text:
Q: How to provide password when prompted in shell script I am writing the shell script to automate few tasks. I am logging into the remote server and installing a few packages.
But to install I need to get the root access.
I am able to login using my credentials with ssh keys.
Once I login I need to switch to root, and then it asks for the password. I tried using echo it still asks for the password.
SCRIPT="pwd; ls; echo 'rootpass' | su -; cd ~; pwd; yum -y install <package>"

How can I pass the password on prompt.
I need to maintain the same session, so not sure spawn/expect/send is gonna work.
UPDATE:
I tried using printf 'rootpass' | ./script.sh, but it is not working.

A: As commented, and illustrated here, expect is a better option.
pw="Password1234"

expect -f - <<-EOF
  set timeout 10

  spawn sudo yum -y install <package>
  expect "*?assword*"
  send -- "$pw\r"
  expect eof
EOF

However, It is best for any script to not include the password itself directly, but rather to fetch that password from an external source, preferable a vault.
Typically, such a script would be run by a tool like Ansible, using ansible-community/ansible-vault. Only Ansible would have the Vault password, Valut which in turn would have the sudo password.


text:
Q: Convexity under diffeomorphisms Let $K \subset \mathbb{R}^n$ be a compact convex subset with non-empty interior, and $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$ a diffeomorphism. Then is it true that $f[K]$ is convex?

A: I'm afraid that in general it's not true. In $\mathbb{R}^2$ you can construct a diffeomorphism $(x, y) \mapsto (x + hy^2, y), \; h > 0$ and apply it to unit square (or unit circle). The "top part" of this figure will be stretched much stronger than parts are near to the $Ox$ axis, which will lead to fail of convexity.
ADDITION: this is an illustration of what happens with rectangle under the action of this map (sorry for the quality, my usual drawing tool is on vacation :) )


text:
Q: can't seem to locate the struct I am trying to fetch values from a struct once its been updated however the problem am facing is an undeclared error as it cannot seem to see it.
sonicNav.h file
#include<stdio.h>
#include<stdlib.h>
#include"sonicThread.h"

extern void calcSonicS();

sonicThread.c file.
    int funcLock = 0;

    void calcSonicS() {
       struct results *rData = results;
       rData = malloc(sizeof(struct results));

       int newVal1 = rData->sens1;
       int newVal2 = rData->sens2;
       int newVal3 = rData->sens3;
       int newVal4 = rData->sens4;

       if(funcLock == 0){
       funcLock = threadFunc();//returns INT value of 1.

     }
      printf("value 1: %d value 2: %d value 3: %d value 4 %d\n", newVal1, newVal2, newVal3, newVal4);
}

sonicThread.h file
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<string.h>
#include<errno.h>
#include<pthread.h>
#include<sys/time.h>
#include<wiringPi.h>

//GPIO PINS stored within structs, for each sonic range finder.
typedef struct sonicPins{
//pins and id.
int trig;
int echo;
int id;
}args;

typedef struct results{
//all pins
int sens1;
int sens2;
int sens3;
int sens4;

}rData;

sonicThread.c file
void* setup(void  *pinsPtr);
extern int threadFunc();

pthread_t pt[4];

int threadFunc()
{
  struct  sonicPins pinsArray[4] = { { 21, 20, 1 }, { 16, 12, 2 }, { 26, 19, 3 }, { 13, 6, 4 } };
  for(int i =0; i <4; i++){
  pthread_create(&pt[i], NULL, setup, &pinsArray[i] );
   }
return 1;
}

void* setup(void *pinsPtr)
{
   struct sonicPins *ptr = pinsPtr;
   int trig = 0, Echo = 0, id;
   trig = ptr->trig;
   Echo = ptr->echo;
   id = ptr->id;
   struct  results *storePtr;
}

The snippet above does update the struct "results", all threads does work concurrently each sensor giving out is own result.
Main.c
int main(){
//void(*foo1)(int, int, int);
//foo1 = &calcSonicS;

printf("In operation\n");
int operational = 1;

while(operational ==1)
{
//sonic range finders.
  calcSonicS();
//gyroscope and acceometer.
}
return 0;
}

Error output:
sonicNav.c: In function 'calcSonicS':
sonicNav.c:5:28: error: 'results' undeclared (first use in this function)
sonicNav.c:5:28: note: each undeclared identifier is reported only once for each function it appears in

A: struct results *rData = results;

error: 'results' undeclared (first use in this function)

The above line tries to declare and define a local variable named rData, which has type struct results *, and initialise it with the value of the variable (local or global) results. The error message is telling you that there is no such variable.
What you're probably mixing up is C++ (old, bad) style initialisation:
MyClass variable = MyClass();

Since the next thing you do with rData is assigning it ...
rData = malloc(sizeof(struct results));

... the solution to your issue is to just remove that "wrong initialisation" from the preceeding line altogether. You could also pack it into a single line:
struct results *rData = malloc(sizeof(struct results));

Looking at ...
typedef struct results{
  // ...
} rData;

... I'd guess that you have a serious misunderstanding of the relationship of structure (type) names, type names and variable names. The above definition gives you:

*

*The name results as structure (type) name, so it can be used after struct to name the defined structure type.

*The name rData as type name, referring to the same (structure) type as struct results.

When you then declare a variable struct results *rData you have additionally rData as name for a variable. This is possible, but far from good style.
If you remove the typedef, then things would change drastically: You'd then have a global variable named rData of type struct results.


text:
Q: How to calculate definite intergrals with respect to positive parts? Now I'm facing with a problem when calculating following definite intergrals:
\begin{eqnarray}
\int_0^1(x-u)_{+}(y-u)_{+}du=(x\wedge y)^2(3(x\vee y)-(x\wedge y))/6
\end{eqnarray}
I don't know how to calculate this kind of integral and obtain the right part. Anyone knows? Thank you so much!

A: Without loss of generality you can suppose that $0 \leq x \leq y \leq 1$.
Then your integral is:
$$I(x,y)=\int_0^1 (x-u)_+ (y-u)_+ du =\int_0^x (x-u)_+ (y-u)_+ du +\int_x^y (x-u)_+ (y-u)_+ du+\int_y^1 (x-u)_+ (y-u)_+ du$$

*

*If $u \in (0,x)$ then  $(x-u)_+ (y-u)_+=(x-u)(y_u)$

*If $u \in (x,y)$ then  $(x-u)_+ (y-u)_+=0 \times (y-u)=0$

*If $u \in (y,1)$ then  $(x-u)_+ (y-u)_+=0 \times 0=0$

Remark: in fact you only have to decompose as $\int_0^1=\int_0^x+\int_x^1$ but in all generality with arbitrary function of $(x-u)_+$ and (y-u)_+ the decomposition $\int_0^1=\int_0^x+\int_x^y+\int_y^1$ is the one to consider
so:
$$I(x,y)=\int_0^x (x-u)(y-u) du=\frac{1}{6} x^2(x-3y)$$
which is the result you want.


text:
Q: Help with grub-update? Good Morning.
Sorry, bit of a newbie question.
I have added a second hard disk to my Ubuntu system with a separate bootable Mint partition.
When I run update-grub as sudo to include new partition/OS I get:
screenshot

A: sudo -H gedit /etc/default/grub # edit this file
You should see both of these lines near the top of this file. Figure out which one is partially missing text, and correct it.
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

Save the file and quit gedit.
sudo update-grub # update grub


text:
Q: Calculation of a delivery date I would like to calculate the date of a delivery according to several parameters:
We are for example the Monday 28th of January. My carrier has a minimum date of 3 days and 5 days maximum so my delivery should be between Thursday 31 January and 4 February because the additional constraint is that this carrier does not deliver Saturday and Sunday. I am looking to do a php function that calculates this date, however i have carriers that book on saturday so if the carrier delivers on saturday the delivery will be between january 31st and february 2nd. Here are some variables that I have:
$minDays = (int)$carrierDefault->delay_min;
    $maxDays = (int)$carrierDefault->delay_max;
    $saturdayDelivery = $carrierDefault->delivered_saturday;

Thank you for help.

A: May this help you:
    <?php
       function isWeekend($date , $ignore_saturday=false) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || ($weekDay == 6 && !$ignore_saturday) ) ;
}

function selectDeliveryinterval($startDate, $min_delivery = 3, $max_delivery = 5 , $ignore_saturday=false) {
    $isfull = true;
    $counter = 0;
    $dates = array();

    while($isfull) {
        $startDate->modify('+1 day');
        if(!isWeekend($startDate->format('Y-m-d'),$ignore_saturday)) {
            $dates[] = clone $startDate;
            $counter++;
        }

        if($counter == $max_delivery) {
            $isfull = false;
        }
    }

    // the array contain the dates in the delivery interval
    return [$dates[$min_delivery - 1], $dates[$max_delivery - 1]];
}

$date = new DateTime('2019-01-28');
$res = selectDeliveryinterval($date,3,5,true);

echo 'your delivery date min is '.$res[0]->format('Y-m-d');

echo 'your delivery date max is '.$res[1]->format('Y-m-d');

Output:

your delivery date min is 2019-02-20
your delivery date max is 2019-02-22

In case the carriers work on saturday :

your delivery date min is 2019-01-31
your delivery date max is 2019-02-02


text:
Q: Creating a Legend Based on Marker Size with Geopandas I'm having trouble creating a legend for the marker size of the map plot I've created.  The marker size is based on the number of electric buses used at each location.  I am trying to create a legend that has 3 entries for 1, 10, and 50 buses.
I have tried doing plt.legend(df.column_name, loc='lower left', scatterpoints=3). I expected this to make a legend with three examples from the column I specified.  Instead I got 3 points that were overlayed on top of eachother.   Below is the code I used and the result.
base = usa.plot(figsize=(20,20), edgecolor='white', linewidth=1)
points = busgp_data['geometry'].plot(ax=base,
                                     color='gold',
                                     marker='o',
                                     markersize=12 * busgp_data['num_of_ESBs'],
                                     edgecolor='black',
                                     alpha=0.7)
plt.legend(busgp_data['num_of_ESBs'], loc='lower left', scatterpoints=3)
plt.title('Location of Electric School Buses in the US', fontdict={'fontsize':20})
plt.tick_params(
    axis='both',
    which='both',
    bottom=False,
    left=False,
    labelleft=False,
    labelbottom=False)

Electric Buses in US Map


text:
Q: Limit of the supremum of a continuous function over a varying set On a book I'm reading the author asserts that
$$\lim_{\epsilon \to 0} \max_{{\bar{Q}}_{T-\epsilon}} u = \max_{{\bar{Q}}_T} u$$
where ${\bar{Q}}_{T-\epsilon}$ is the closure of a varying spatial-temporal cylinder
$${Q}_{T-\epsilon} = \Omega \times (0, T-\epsilon)$$
$\Omega \subset \mathbb{R}^n$ is a domain and $u$ is a continuos function over the closure ${\bar{Q}}_{T}$.
Is this obvious? How to formally prove this?

A: I'll state this in greater generality, which I think makes the statement more transparent.
Claim
Let $A$ be a subset of topological space $X$, and let $f:A\to\mathbb R$ be a continuous function. If $A_1\subset A_2\subset $ is a sequence of subsets of $A$ such that $$A\subset \overline{\bigcup_n A_n}\tag{1} $$
then $$\sup_A f = \lim_{n\to\infty}\sup_{A_n} f$$
(The supremum on the left may be infinite, in which case the limit is understood in the extended sense.)
Proof
Since the sequence $\sup_{A_n} f$ is increasing, we have
$$\lim_{n\to\infty}\sup_{A_n} f=\sup_n \sup_{A_n} f \tag{2}$$
Since $A_n\subset A$ for every $n$, it follows that  $$\sup_A f \ge  \sup_n \sup_{A_n} f $$
To prove the reverse inequality, pick a sequence $x_n\in A$ such that $f(x_n)\to \sup_A f$. For each $n$ there is $r_n>0$ such that $f>f(x_n)-1/n$ in $r_n$-neighborhood of $x_n$. By assumption (1) this neighborhood contains a point $y_n$ in some set $A_{k_n}$. Since $f(y_n)\to \sup_A f$, it follows that
$$\sup_A f \le  \sup_n \sup_{A_n} f $$


text:
Q: Objective-C - Accessing class methods inside Initializer method I have a class called SqliteImageAccess that is going to have various methods that provide support for some sqlite functionality. I have a local class variable of type sqlite3 and a class method called opendb. This class method should do one thing and one thing only. Open the database.
The only sticky point here is that my sqlite3 object is going to be an instance variable and Objective-C, for whatever weird reason, doesn't let you access instance variables inside of class methods. Obviously, in other languages, when you instantiate a class, the constructor of that class might call a private method to initialize some local class variables(local private variable perhaps). I want to do the same thing with my sqlite3 object through the equivalent of an Objective-C class constructor method. Perhaps someone can help because I am stuck on this one.
Obviously in another class I can instantiate the SqliteImageAccess class and then call the opendb method. That works fine. I don't want to have to do that. When i instantiate the class the goal is so that the class will handle the opening of the database automatically.
Lastly, with the other methods that are going to be available to do other sqlite work(inserts, etc), i am going to need full access to the db object. thanks in advance for any help.
//SqliteImageAccess.h
@interface SqliteImageAccess : NSObject {

}

+(void)opendb; //class method

@end

//SqliteImageAccess.m
#import "SqliteImageAccess.h"

@implementation SqliteImageAccess

static sqlite3 *db;

+(void)initialize{
    [self opendb];
}

+(void)opendb{
int open = sqlite3_open("/Users/csmith/RPG/cws.sqlite3", &db);
if(open == SQLITE_OK){
    NSLog(@"Database was opened successfully");
}
else {
    NSLog(@"open result = %d", open);
}

}

@end

A: In the interface you declare opendb as a class methode (+) but your are using - in the implementation. Normaly you should get a warning, that your class implementation isn't complete. Change the - to + to implement opendb as a class method and call it via
[self opendb];

Further, + (void)initilaize is only called once during program life cycle, in think you would like to go with
-(id) init;

Seeing one more thing, your sqlite3 property is declared as an instance variable, so you can't call it from a class method! You have to move the sqlite3 *db from the .h to the .m file as
static sqlite3 *db;

after @implementation.

A: observation :
you have declared opendb in .h as class method.
But in .m class , you are using it as instance method.
+(void)opendb{
int open = sqlite3_open("/Users/csmith/RPG/cws.sqlite3", &db);
if(open == SQLITE_OK){
    NSLog(@"Database was opened successfully");
}
else {
    NSLog(@"open result = %d", open);
}

}

Suggest you to have bind both with your instance (class object), and send message to opendb explicitly from outside of your class, whenever you create the instance of your database access class.

- (void) init {
    if (self = [super init]) {

       //initialize all your class member here,

    }
}

And your opendb instance method function
 - (void)opendb{
    int open = sqlite3_open("/Users/csmith/RPG/cws.sqlite3", &db);
    if(open == SQLITE_OK){
        NSLog(@"Database was opened successfully");
    }
    else {
        NSLog(@"open result = %d", open);
    }

    }

Now lets create the instance of sqllite3 access class.
SqliteImageAccess*  smySqliteImageAccess = [SqliteImageAccess  alloc] init];
[smySqliteImageAccess opendb];

A: If all instances of SqliteImageAccess are going to share the same db instance (sqlite3 *), then you can declare it globally instead of declaring it as an instance variable:
//SqliteImageAccess.m
@implementation SqliteImageAccess

// 'db' will be shared by all instances of SqliteImageAccess
static sqlite3 *db;

+ (void)initialize {
    if (self == [SqliteImageAccess class]) {
        opendb(&db); // assumes opendb is a function, not a method
    }
}

If you create all instance methods of SqliteImageAccess in this file, db will be visible to them.
EDIT: if you don't want to share one db instance among all instances of SqliteImageAccess, then you should change -opendb to an instance method, and call it in your class's designated initializer (like -init). In this case, of course, -opendb will have access to the instance variable db.


text:
Q: Can't do an in-place Update of an Azure cloud service (extended support) after a VIP swap - Public IP is in use (error) I have successfully performed a VIP swap on a pair of Azure cloud services (extended support) that had Reserved IP addresses (static, although I don't think it matters).
Now I can Update (by uploading a new package) neither of them, although it had worked like a charm before the swap. In fact, I can't even complete the deployment (update) configuration form because of an error displayed for the Public IP address field.
It says: "The public IP address is currently in use by another resource. Choose a different resource group or create a new resource group". (The message part about the "group" feels hardly related.)
Note that I have corrected the cloud service configuration file so it referenced the IP Address that was assigned to the cloud service as a result of the swap.
E.g., the services are called cs1 and cs2, while the public addresses they used to use before the swap are ip1 and ip2. After the swap, cs1 is using the address ip2, which is clearly indicated by the cloud service current properties and configuration that can be seen via the portal.
So, I am updating cs1 having specified ip2 as its Reserved address:
      <ReservedIPs>
        <ReservedIP name="ip2"/>
      </ReservedIPs>
    </AddressAssignments>
  </NetworkConfiguration>
</ServiceConfiguration>

Still, I am getting the error.
(I've tried to specify the "old" address, ip1, but it has correctly failed with "address cannot be changed". I've also tried to delete the second service, cs2, but it has not fixed the problem with the first one, cs1.)
(Another thing worth mentioning is that the config XML that can be exported from the cloud service page on the portal specifies the ReservedIP name attribute value as "Group MyServiceResourceGroupName ip2" - the classic way. I tried specifying it this way in my config, but the update failed saying config XML was malformed or something like that. Indeed, it has been working with just the resource name specified, no group spec, for all of the preceding deployments.)
Frankly, the problem looks like a bug, but how can I be sure?
Dear experts, would you please help?
Perhaps a workaround, if no solution. Otherwise, the VIP swap feature is hardly usable for the cloud services (extended support). It makes us choose: whether to update our services only by VIP swap, or only by Update with the service occasional complete recreation. Not quite convenient. We've been using a mix with the cloud services (classic).
I would greatly appreciate your help!
Thank you!
Vasily


text:
Q: How to found center of an image? I have faced trouble how to find center of an image and write it to different image.
Situation is that I have image (for e.g. 800X500) and I need to crop exactly (50X50 or 70X70) center of it with img.getSubimage(x, y, w, h).
Sizes will be different every time for new image.
How could I calculate X and Y to get 50X50 subImage from the image center?
Thanks in advance.
img.getSubimage(x, y, w, h) - X and Y are not coordinates of center.
     * @param x the X coordinate of the upper-left corner of the
     *          specified rectangular region
     * @param y the Y coordinate of the upper-left corner of the
     *          specified rectangular region

A: int bigwidth = 800;
int bigheight = 500;
int cropwidth = 70;
int cropheight = 70;
img.getSubimage((bigwidth - cropwidth) / 2, (bigheight - cropheight) / 2, cropwidth, cropheight);


text:
Q: $\sigma$ is a permutation of $\mathbb{N}$,then the sum $\sum\sigma(n)/n^2$ ,$NThe options are :
(a)$\sigma$ is only an injective function then also the sum is convergent
(b) the sum is bounded above
(c) the sum is bounded below
(d) has 0.125 as a lower bound
Now I think options (c) is correct as it will be bounded by 0.Next I think is that the (d) is not true because if I take $N=10,00,000$ then the sum has to be very large to get to $0.125$.Since the sum is finite I think (b) is true.This  has been my attempt.
Also what I wanted to ask is there a general way to find all the permutations on $\mathbb{N}$


text:
Q: Problema com input e autofocus Estou tendo um probleminha com inputs... eu tenho dois inputs: o primeiro tem autofocus e o outro não.
Porém, sempre que eu digito no segundo input, ele perde o foco e o foco volta pro primeiro input.
Eu li que React vai renderizar novamente o component sempre que digito algo. Eu tentei colocar keys e etc, mas nada funcionou
No meu form (component chamado Signup), eu tenho o seguinte:
import React from 'react'
import Input from '../../components/Input'
import styles from './styles.scss'

class Signup extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      name: '',
      email: '',
    }
  }

  onSignup (e, userData) {
    e.preventDefault()
    this.props.onSignup(userData)
  }

  render () {
    return (

CADASTRAR

          <Input
            id="name"
            label="Nome"
            onChange={e => this.setState({ name: e.target.value })}
            autofocus={true}
          />
          <Input
            id="email"
            label="E-mail"
            onChange={e => this.setState({ email: e.target.value })}
          />

    )
  }
}

Signup.propTypes = {
  onSignup: React.PropTypes.func.isRequired
}

export default Signup

Já meu component Input é o seguinte:
import React, { PropTypes } from 'react'
import MaskedInput from 'react-maskedinput'
import styles from './styles.scss'

function Input (props) {
  let iconComp

  if (props.icon) {
    iconComp = ()
  }

  let input = ''

  if (props.type === 'date') {
    input = (
      <MaskedInput
        ref={inp => inp && props.autofocus && inp.focus()}
        onChange={props.onChange}
        mask="11/11/1111"
        placeholder={props.placeholder}
        className={styles.input}
      />
    )
  } else {
    input = (
      <input
        ref={inp => inp && props.autofocus && inp.focus()}
        onChange={props.onChange}
        id={props.id}
        placeholder={props.placeholder}
        type={props.type}
        className={styles.input}
      />
    )
  }

  return (

      {props.label}

      {input}
      {props.error &&

          {props.errorMessage}

      }
      {iconComp}

  )
}

Input.propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  icon: PropTypes.string,
  placeholder: PropTypes.string,
  type: PropTypes.string,
  autofocus: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  error: PropTypes.bool,
  errorMessage: PropTypes.string
}

Input.defaultProps = {
  icon: '',
  placeholder: '',
  type: 'text',
  autofocus: false,
  error: false,
  errorMessage: ''
}

export default Input

Como resolver esse problema?


text:
Q: Extract count of a string in log file using grep I want to get a count of exceptions in error log file of current date. below is log snippet
10.01.2017 14:03:15.517 *Error* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NumberFormatException: For input string: "true"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:441)
    at java.lang.Long.parseLong(Long.java:483)

10.01.2017 14:03:15.516 *INFO* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NumberFormatException: For input string: "true"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:441)
    at java.lang.Long.parseLong(Long.java:483)

09.01.2017 14:03:15.514 *INFO* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message  at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException: For input string: "true"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:441)
    at java.lang.Long.parseLong(Long.java:483)

If i run the following grep command it gives me the result
$ grep -c $(date +"%d.%m.%Y") error.log

But when i'm trying to search it further using 'Exception' keyword it doesn't work. Below is the command
$ grep -c $(date +"%d.%m.%Y") error.log | grep 'Exception'

secondly another thing is i want to get the count of same exception line for this i'm using this command
$ grep  $(date +"%d.%m.%Y") error.log | sort | uniq -c | sort -r

But in excepted out i'm getting "1" "1" count for both line of 10 jan date because the millisecond(14:03:15.517 , 14:03:15.516) value is different. Is there any way through which i can skip this second value and find the line count
output:-
 1 10.01.2017 14:03:15.517 *Error* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
      1 10.01.2017 14:03:15.516 *Error* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)

Expected output :-
2 10.01.2017 14:03:15 *Error* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)

A: If you are using GNU grep use the the -A flag to show lines matching after the given pattern, i.e.
grep -A 2 "$(date +"%d.%m.%Y")" file
10.01.2017 14:03:15.517 *Error* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NumberFormatException: For input string: "true"
--
10.01.2017 14:03:15.516 *INFO* [10.207.11.183 [1481704390201] POST /bin/flipkart/cart.GetCart.json HTTP/1.1] org.apache.cxf.services.StockServiceService.StockServicePort.StockService Inbound Message at com.day.j2ee.servletengine.HttpListener$Worker.run(HttpListener.java:644)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NumberFormatException: For input string: "true"

The above command shows only the next two lines following the date, now to get the count, use
grep -A 2 "$(date +"%d.%m.%Y")" file | grep -c "Exception"
2

Using a combination of two awk
awk -v dateToSearch="$(gdate +"%d.%m.%Y")" '$0 ~ dateToSearch{line[NR+2]}NR in line' file | awk -F'[:.]' '{unique[$4]++}END{for (i in unique) print i, unique[i]}'
NumberFormatException 2

I will break-down the logic used in Awk for a better understanding.

*

*The input lines are parsed one line at a time in awk, to search on today's date, am using a variable with the -v flag (awk specific), and setting it to today's date.

*The body of the command $0 ~ dateToSearch{line[NR+2]}NR in line does the following; the $0 represents the entire line and a regEx pattern match is done with the ~ operator to match the lines containing the today's date. Once matched the commands within {} are executed. Which simply mean, print the 2nd line after the pattern match (similar to grep -A 2 ..). NR is a special variable in awk which keep tracks of the record number (line number) as and when the file is processed. So when a pattern is matched, NR is set to that line and hence NR+2 prints the 2nd line after match.

*The pipelined awk, i.e. after | awk .. could be avoided and clubbed to make a single awk which could make the command complex. So what basically the second part does is, -F'[:.]' sets the input field separator to either the occurrence of a : or ., so that the fields/columns can be accessed via individual numbers (e.g. like $1, $2, etc).

*So to track the unique count of exceptions, am creating a hash-table using an array with the exception name ($4 in the line) as the index and incrementing the occurrence of the exception, as it is seen. So once all the lines are processed, the array contains all exception types with their counts.

*The END{} clause in awk gets to run after all the lines are processed, so using it to print the count and the unique exception identifier.

A: The right way to do what you're trying to do is with awk in paragraph mode (i.e. blank-line separated chunks of text courtesy of RS=<null>):
$ awk -v date="$(date +"%d.%m.%Y")" -v RS= '$1==date && /Exception/{c++} END{print c+0}' file
2

Note that there is no chance of false matches on the date with this approach since we're using an exact match and a string comparison on the first field.


text:
Q: Inline CSS transitions/animation I have a project where users can enter custom css that becomes an inline style on a div. I tried putting in a transition: all 2s linear and a transform: rotate(180deg), but there was no animation, it just started rotated 180deg.
Is there a way to do any sort of css animation but only with inline styles on the element?


text:
Q: solve$\,\ \;\cos\left(\,2\arctan\left(1/2\right)\,\right)\,$ How would I go on about solving:
$\,\quad\cos\Big(\,2\cdot \arctan\big(\frac{1}{2}\big)\Big)$ ?
My attempt was to find $\,v\,$ in $\,\frac{\sin\left(v\right)}{\cos\left(v\right)} = \frac{1}{2}\,$ and substitute that with $\,\arctan\left(\frac{1}{2}\right),\,$ but I end up with $\,\sin\left(v\right) = \sqrt{\frac{1}{5}}\,$ which I cant solve.
Is there any other way to approach the problem?

A: HINT: Recall the tangent half-angle formula
$$
\cos 2\alpha = \dfrac{1 - \tan^2 \alpha}{1 + \tan^2 \alpha}
$$

A: So you have $\sin(v) = \sqrt{\frac{1}{5}}$, then $\cos^2(v) = \frac{4}{5}$. Now you just need to calculate $\cos(2v) = 2\cos^2(v) - 1 = \frac{3}{5}$


text:
Q: End-to-end encryption with ECS and ALB I have three applications deployed in an ECS cluster with an EC2 instance.
Each application has its frontend and its backend.

*

*App1 frontend serving port 80 backend serving port 3001

*App2 frontend serving port 8080 backend serving port 3000

*App1 frontend serving port 8880 backend serving port 8000

I am using a single task to deploy all the containers.
In front of the ECS cluster I have an ALB with host-based rules so I can redirect the traffic to the appropriate container depending on the address the ALB receives (I have three target groups to target the appropriate port), i.e.

*

*site1.example.com sent to the target group for port 80

*site2.example.com sent to the target group for port 8080

*site3.example.com sent to the target group for port 8880

Now I want to enable encryption in transit from the client to the final container. I tried to do this by requesting a public certificate and modify the listener to use https with this certificate, but this only encrypts the traffic from the client to the ALB.
I read some solutions involving Envoy with sidecar containers, but It seems a bit overcomplicated, also I considered to use Network Load Balancer, but I believe this will not allow me to do the host-based redirection, and I don't want to use addresses like  example.com:8080 to reach a website.
Is it possible to achieve this in other ways?
Hope the question make sense.
Thanks in advance!

A: You will need to add SSL certificates to your containers, and configure your containers to use them and listen for HTTPS traffic instead of HTTP traffic, and modify the ports in the target group accordingly.
The ALB will not verify the certificates, so the certificates you use on the containers can be self-signed certificates.


text:
Q: Select one per unique ID with newest timestamp I have a table in Big Query with unique IDs , timestamps and distances and would like to select one record by ID with the newest timestamp.
E.g. the table looks like
ID|timestamp|distance
A|100|2
A|90|3
B|110|5
D|100|4
A|80|2
B|10|2

The query should return something like:
A|100|2
B|110|5
D|100|4

A working query in PostgreSQL looks like this, but there is no "distinct ON" in bigquery?
SELECT * FROM (
SELECT DISTINCT ON (ID)
id, timestamp, distance
FROM ranking
ORDER BY ID, timestamp DESC
) AS latest_dtg
ORDER BY distance

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT row.* FROM (
  SELECT ARRAY_AGG(r ORDER BY timestamp DESC LIMIT 1)[OFFSET(0)] AS row
  FROM ranking AS r
  GROUP BY id
)

You can play/test with below dummy data from your question
#standardSQL
WITH ranking AS (
  SELECT 'A' AS id, 100 AS timestamp, 2 AS distance UNION ALL
  SELECT 'A', 90, 3 UNION ALL
  SELECT 'B', 110, 5 UNION ALL
  SELECT 'D', 100, 4 UNION ALL
  SELECT 'B', 10, 2 UNION ALL
  SELECT 'A', 80, 2
)
SELECT row.* FROM (
  SELECT ARRAY_AGG(r ORDER BY timestamp DESC LIMIT 1)[OFFSET(0)] AS row
  FROM ranking AS r
  GROUP BY id
)

A: Here is one idea:
#standardSQL
WITH ranking AS
(SELECT 'A' id, 100 ts, 2 distance UNION ALL
SELECT 'A', 90, 3 UNION ALL
SELECT 'B', 110, 5 UNION ALL
SELECT 'D', 100, 4 UNION ALL
SELECT 'B', 10, 2 UNION ALL
SELECT 'A', 80, 2)
SELECT id, ARRAY_AGG(STRUCT(ts, distance) ORDER BY ts DESC LIMIT 1)[SAFE_OFFSET(0)]
FROM ranking
GROUP BY id

A: What about this one?
SELECT a.*
FROM yourtable AS a
INNER JOIN (
SELECT id, MAX(timestamp) AS newesttimestamp
FROM yourtable
GROUP BY id
) AS b
ON a.id = b.id AND a.timestamp = b.newesttimestamp
ORDER BY a.id


text:
Q: Can you convert String version of R.id to int? As an exercise, I am building a calendar. Below is a small segment of my code. I have a class MyCalendar that extends Activity.
This Activity will be linked to an XML file whose layout includes seven TextViews with ids R.id.day0 thru R.id.day6.
If converted from String to int, will the Activity's findViewById() method recognize the int version of these ids?
        String Days [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        TextView dayViews [];

        private void populateViews (){

            for (int counter = 0; counter < Days.length; counter++){
                int ID = Integer.parseInt("R.id.day"+counter);
                dayViews [counter] = (TextView) findViewById(ID);
                dayViews[counter].setText(Days[counter]);
            }

A: I have not tried it myself. but this answer https://stackoverflow.com/a/11595723/1514861 suggest you can do it like this:
private String getStringResourceByName(String aString) {
  String packageName = getPackageName();
  int resId = getResources().getIdentifier(aString, "string", packageName);
  return getString(resId);
}

EDIT: I think you would also need to replace "string" with "id"

A: Definitely not.
R class from Java are ids generated at compilation.
I would do:
final int[] days = { R.id.day0, R.id.day1, ... };
for (int day : days) {
    // ...
}

A: NO, int ID = Integer.parseInt("R.id.day"+counter);, what you did in there is making a representation of String to Integer, not an actual mapping from R class to xml resource.

A: I know that's an old question, but it might help more people. What you can do is to call getIdentifier(), like our friends said. For that, you'll need to call it inside a loop, inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:
Your resources file:
R.string.string0
R.string.string1
R.string.string2
...
R.string.string9

In java:
for (i=0;i<10;i++){
    int resourceId = getResources().getIdentifier("string"+i, "string", this.getPackageName())
    println(getResources().getString(resourceId));
}

Then, in your rescourceId variable, you'll have an equivalent to: R.string.string0 to R.string.string9. And, in println, you'll have the value correspondent of your resources string.
In Kotlin:
for (i in 0..10){
    val resourceId = this.resources.getIdentifier("string"+i, "string", this.packageName)
    println(resources.getString(resourceId))
}

With the same explanation that I said before.


text:
Q: Any way to get all rows of a table where the foreign key matches the primary key using only models rather than accessing the database directly? I have two models: User and Lesson.  Lessons are tied to users through a user_id foreign key in Lessons.  I want to say "give me all lessons for user 8", but the only way I've been able to accomplish that is by going through the DB class
$lessons = DB::table('lessons')->where('user_id','=',8)->get();

Is there a way to do something like this?
$lessons = Lesson::all()->where('user_id','=',8);

or (even better)
$lessons = User::find(8)->lessons();

Just wondering because the latter two ways make more sense.  Just wondering!

A: You may try something like this:
$lessons = Lesson::where('user_id', 8)->get(); // '=' is optional

Or user with lessons:
$userWithLessons = User::with('lessons')->find(8);

Also User::find(8)->lessons; will work but eager loading (with('lessons')) is better.
Another way depending on id in users table:
// pass the id in $id
$lessons = Lesson::with('user')->whereHas('user', function($q) use ($id){
    $q->where('id', $id);
})->get();

Update: You may try this
// pass the id in $id
$id = 8; // user id
$lesson71 = Lesson::with('users')->whereHas('users', function($q) use ($id){
    $q->where('id', $id);
})->find(71);


text:
Q: Calculate the time remaining until a subscription I have a subscription that can be subscribed to every month, every two months or every 3 months. That's represented as a subscription_frequency of 1, 2 or 3.
I then have a month_joined property (1 through 12).
But I'm trying to work out, when someone should receive their subscription. So far I know I want to work out when the user will next receive a subscription.
So I'm adding 12 to the current month, then subtracting the month_joined number, and then finding the remainder of their subscription_frequency, to add on to the current month to tell them when their next box is due.
public function nextsub()
{
    $remainder = ($current_month + 12 - $this->month_joined) % $this->subscription_frequency;
    return $current_month + remainder;
}

But all my number are coming out screwy. Here is dump of users:
[
{
current_month: 3,
month_joined: 1,
subscription_frequency: 1,
next_box: 3
},
{
current_month: 3,
month_joined: 3,
subscription_frequency: 3,
next_box: 3
},
{
current_month: 3,
month_joined: 11,
subscription_frequency: 3,
next_box: 4<----------------- this is incorrect
},
{
current_month: 3,
month_joined: 12,
subscription_frequency: 3,
next_box: 3<----------------- this is incorrect
},
{
current_month: 3,
month_joined: 8,
subscription_frequency: 2,
next_box: 4
},
{
current_month: 3,
month_joined: 1,
subscription_frequency: 1,
next_box: 3
},
{
current_month: 3,
month_joined: 3,
subscription_frequency: 2,
next_box: 3
},
{
current_month: 3,
month_joined: 2,
subscription_frequency: 3,
next_box: 4 <----------------- this is incorrect
},
{
current_month: 3,
month_joined: 2,
subscription_frequency: 1,
next_box: 3
}
]

What's the matter with my maths?

A: IMHO you could check if the current month is a month you should be sending the subscription (this doesn't check if you sent the subscription for the current month, this should be a separate functionality)
If you deliver in the month of subscription
enter code here
$shouldSubscriptionBeSent = ($currentMonth - $monthJoined) % $subscriptionFrequency === 0

If you deliver the next month after subscription
$shouldSubscriptionBeSent = ($currentMonth - $monthJoined - 1) % $subscriptionFrequency === 0

I think you should keep an array with the months you delivered, and the subscription month in fact should be a date, and afterwards you could find the subscription dates by adding the frequency months to the subscription date.

A: This is hardly efficient but it should give you the next subscription month
  public function nextsub()
{
    $arrayofpossiblesubscriptionmonths=array();

    for($i=1;$i<=12;$i++){
        $submonth=$month_joined+($i*$this->subscription_frequency);
        if($submonth>12){
            $submonth=$submonth-12;
        }
        //this will create some duplicate months
        $arrayofpossiblesubscriptionmonths[]=$submonth;
    }
    //cleanup duplicates
    $uniquesubmonths=array_unique($arrayofpossiblesubscriptionmonths);

    //fix the order
    sort($uniquesubmonths);

    //since they are in order.  find the first one bigger than our current month
    foreach($uniquesubmonths as $onesub){
        if($onesub>$current_month){
            return $onesub;
        }
    }
}

Here is a CodeViper in action with a slightly altered function so I could pass the variables in easier
http://codepad.viper-7.com/9Er2pi
      function nextsub($current_month,$month_joined,$subscription_frequency)
{

    $arrayofpossiblesubscriptionmonths=array();

    for($i=1;$i<=12;$i++){
        $submonth=$month_joined+($i*$subscription_frequency);
        if($submonth>12){
            $submonth=$submonth-12;
        }
        //this will create some duplicate months
        $arrayofpossiblesubscriptionmonths[]=$submonth;
    }
    //cleanup duplicates
    $uniquesubmonths=array_unique($arrayofpossiblesubscriptionmonths);

    //fix the order
    sort($uniquesubmonths);

    //since they are in order.  find the first one bigger than our current month
    foreach($uniquesubmonths as $onesub){
        if($onesub>$current_month){
            return $onesub;
        }
    }
}
$curmonth=3;
$monthjoined=1;
$sub_freq=1;
echo '
Current month: '.$curmonth;
echo '
Month Joined: '.$monthjoined;
echo '
Subscription Frequency: '.$sub_freq;
echo '
Next Subscription Month: '.nextsub($curmonth,$monthjoined,$sub_freq);

echo'
';
$curmonth=3;
$monthjoined=11;
$sub_freq=3;
echo '
Current month: '.$curmonth;
echo '
Month Joined: '.$monthjoined;
echo '
Subscription Frequency: '.$sub_freq;
echo '
Next Subscription Month: '.nextsub($curmonth,$monthjoined,$sub_freq);

echo'
';
$curmonth=3;
$monthjoined=8;
$sub_freq=2;
echo '
Current month: '.$curmonth;
echo '
Month Joined: '.$monthjoined;
echo '
Subscription Frequency: '.$sub_freq;
echo '
Next Subscription Month: '.nextsub($curmonth,$monthjoined,$sub_freq);

Output
Current month: 3
Month Joined: 1
Subscription Frequency: 1
Next Subscription Month: 4

Current month: 3
Month Joined: 11
Subscription Frequency: 3
Next Subscription Month: 5

Current month: 3
Month Joined: 8
Subscription Frequency: 2
Next Subscription Month: 4


text:
Q: Is it ever a good idea to give "partial credit" (continuous outcome) in training a logistic regression? I am training a logistic regression to predict which runners are most likely to finish a grueling endurance race.
Very few runners complete this race, so I have severe class imbalance and a small sample of successes (maybe a few dozen). I feel like I could get some good "signal" from the dozens of runners who almost made it.  (My training data has not only completion, but also how far the ones that didn't finish actually made it.)  So I am wondering whether it is a terrible idea or not to include some "partial credit."  I came up with a couple functions for partial credit, the ramp and the logistic curve, which could be given various parameters.

The only difference with the regression would be that I would use training data to predict the modified, continuous outcome instead of a binary outcome.  Comparing their predictions on a test set (using the binary response) I had fairly inconclusive results -- the logistic partial credit seemed to marginally improve R-squared, AUC, P/R, but this was just one attempt on one use case using a small sample.
I do not care about the predictions being uniformly biased toward completion -- what I care about is correctly ranking contestants on their likelihood to finish, or maybe even estimating their relative likelihood of finishing.
I understand that logistic regression assumes a linear relationship between predictors and the log of the odds ratio, and obviously this ratio has no real interpretation if I start messing with the outcomes.  I'm sure this is not smart from a theoretical viewpoint, but it might help get some additional signal and prevent overfitting. (I have almost as many predictors as successes, so it may be helpful to use relationships with partial completion as a check on relationships with full completion).
Is this approach ever used in responsible practice?
Either way, are there other types of models out there (maybe something that explicitly models the hazard rate, applied over distance instead of time) that may be better suited for this type of analysis?

A: This seems like a job for survival analysis, like Cox proportional hazards analysis or possibly some parametric survival model.
Think about this problem in reverse from the way you're explaining it: what are the predictor variables associated with earlier distances to quitting?
Quitting is the event. The distance covered might be considered equivalent to time-to-event in standard survival analysis. You then have a number of events equal to the number of individuals who quit, so your problem with limited numbers of predictors will diminish. All those who quit provide information.
A Cox model, if it works on your data, will provide a linear predictor based on all the predictor variable values, ranking contestants in order of predicted distances to quitting.


text:
Q: can we implement table splitting in grails/using Hibernate based on month in a date field I have a huge transaction table which I need to split. Right now  am thinking on monthly basis. But I want this to be handled automatically by grails or by hibernate. It is similar to Sharding where a new table would be created  and data belonging to a month will be inserted in that months table. whenever I give a select query with a date range, the appropriate months are queried and data is retrieved.
It would differ from the classical Sharding in that there is no limit on the data in each table and separation is based only on the month index.
I saw that there is a  grails Sharding plugin, but it looks like it is used for something different?
Right now I have created this structure of 12 tables manually and for every select I get the date range and get a list of month domains to query on and retrieve individually and then again combine this data..
I want to know if I am not using something out of the box instead of doing the whole implementation manually
Thanks in advance
Priyank

A: You don't mention which database you're using.
Sounds like a lot like table partitioning, supported by databases like Oracle and Postgres.
This kind of feature is best implemented within the database and hidden from the application. For example test systems rarely need partitioned tables.
Update:
Googling also found a sharding plugin for grails, with article describing its use.


text:
Q: Javascript run function on  click Is there a way to execute a javascript function when the user clicks on a certain <option> within a <select> drop down menu?

A: <select> elements support the onchange event.
http://w3schools.com/jsref/event_onchange.asp

A: You HTML would look like this:
<select onchange="functionName(this.value)">
    <option value="1"> 1 </option>
    <option value="2"> 2 </option>
    <option value="3"> 3 </option>
</select>

In your JavaScript, you would have a function ( ex: functionName() )
and you would use that function to test for each case.

A: Here:
elem.onclick = function ( e ) {
    if ( e.target.tagName.toLowerCase() === 'option' ) {
        // an <option> element was clicked
        // do your thing
    }
};

where elem is your SELECT element.
Live demo: http://jsfiddle.net/vBB7a/

A: You can use the change event to check which option the user clicked on and then execute your desired code.
In Jquery:
$('#yourSelect').change(function(){
    var item = $(this).val();

    if (item === "Specified Choice")
    {
        //do your stuff here
    }
});

A: You need to hook the onchange event of the <select> element, and check the value. Have you tried that?

A: Inside your <option> you could use the onclick event to specify a javascript function to be executed.
E.g.
<option onclick="yourFunction()">

A: Use Jquery in your Project..
HTML Code:
<select id="myselect">
    <option value="">Select</option>
    <option value="1">StactOverFlow</option>
    <option value="2">SuperUser</option>
    <option value="3">Another 1</option>
    <option value="4">Another 2</option>
    <option value="5">Another 3</option>
</select>

JQuery Code:
$("#myselect").bind('change', function(){
    switch($(this).val()){
        case "1":
            click_action_1();
            break;

        case "2":
            click_action_2();
            break;

        case "3":
            click_action_3();
            break;
    }
});

function click_action_1(){
    alert('Hi 1');
}

function click_action_2(){
    alert('Hi 2');
}

function click_action_3(){
    alert('Hi 3');
}

You can even execute a new javascript function with a <option>
Watch in Action: http://jsfiddle.net/extremerose71/PnfCk/8/
Enjoy!...


text:
Q: How to play background music with MPMusicPlayerController's applicationMusicPlayer in iOS? Hello i am trying to play background music with MPMusicPlayerController's applicationMusicPlayer in iOS.
I have also added Required background modes in Plist.
But it doesn't play background music.
How can i play background music with MPMusicPlayerController?
Thanks for your reading. :)

A: The applicationMusicPlayer does not support background music. Use MPMusicPlayerController's iPodMusicPlayer instead. It shares the state with the built-in iPod player and music will continue to play when your app enters the background.

A: Bryan is right about applicationMusicPlayer not playing music in background, but there is another solution:
You can use AVAudioPlayer to play either streamed or local(bundle) audio. It even allows you to play multiple audio file at the same time having an AVAudioPlayer instance for each.
Here's the documentation:
http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html


text:
Q: Issue with program in Scilab for calculating the cumulative distribution function of a geometric discrete random variable I wrote a program that shows the graph of cumulative distribution function and PMF of a random discrete variable with geometric distribution. But I've encountered a problem: The sum of all the probabilities of PMF is not 1, but something very close to 1.When I saw this, I switched to Matlab, where I used the function: geocdf. Thus, I observed that the first value of CDF, taking p 0.6 and n = 10, is 0.84 and not 0.6 as expected. Can you, please, help me find out what's wrong with my program ? Here's my script written in Scilab:
   n = input('n = ');
tab = zeros(2, n);
p = input('p = ');//probability
q = 1 - p;

for k = 1:n
    tab(1,k) = k;
    tab(2,k) = (q^(k - 1))*p;
end

subplot(1,2,1);
plot(tab(1,:), tab(2,:), "-");

F = cumsum(tab(2, :));//cumulative distribution
subplot(1,2,2);
plot2d2(tab(1,:), F);

disp([tab' F']);
Mean = 1/p;
Variance = q/(p^2);

mprintf('\nMedia = %g, Dispersia = %g', Mean, Variance);

A:
The sum of all the probabilities of PMF is not 1

You could not possibly add all the probabilities, because the geometric distribution assigns nonzero probabilities to all positive integers. If you run the sum up to n=10, the sum of probabilities is appreciably less than 1. If you run it up to 20, the cumulative is getting rounded to 1 in the output:
1.     0.6          0.6
2.     0.24         0.84
3.     0.096        0.936
4.     0.0384       0.9744
5.     0.01536      0.98976
6.     0.006144     0.995904
7.     0.0024576    0.9983616
8.     0.0009830    0.9993446
9.     0.0003932    0.9997379
10.    0.0001573    0.9998951
11.    0.0000629    0.9999581
12.    0.0000252    0.9999832
13.    0.0000101    0.9999933
14.    0.0000040    0.9999973
15.    0.0000016    0.9999989
16.    0.0000006    0.9999996
17.    0.0000003    0.9999998
18.    0.0000001    0.9999999
19.    4.123D-08    1.0000000
20.    1.649D-08    1.0000000

the first value of CDF, taking p 0.6 and n = 10, 0.84 and not 0.6 as expected

There are two versions of geometric distribution, as Wikipedia explains at the very beginning of the article. Your code follows the first convention, with PMF supported on the set 1,2,3,.... Matlab's geocdf uses the second convention, with PMF supported on 0,1,2,3... The output of geocdf(1,0.6) is 0.84, representing the sum of probabilities of 0 and 1. The output of geocdf(0,0.6) is 0.6.


text:
Q: Linear voltage regulator input voltage drop error. What's the problem? I am doing a homework project, making an AC to DC converter using a rectifier circuit and regulator.
The homework conditions are:
We must use an AC input voltage with Vpp = 20V and frequency = 1kHz.
We must get an output DC constant positive +9V or above.
My thought (diagram) is
Input AC signal -> voltage doubler -> peak rectifier -> regulator
That is:

I measured the above voltage.  This is the result:

Good result. Right? So I connected an LM7812CT to node C2. Like this:

The problem is here. The measured voltage graph looks like this:

What? The input voltage to the voltage regulator drops a lot. I can't get the result what I want. I found that Rsig (power supplier resistance) has much voltage so the input voltage to voltage regulator is very low.
Why does this happen? I think that the input voltage regulator is very small so voltage dividing makes this situation, but it's not clear.
I want to know the reason for the voltage drop.

A: Like suggested in the comments, this will work much better:
build a boring bridge rectifier, capacitor, 9V voltage regulator, done

simulate this circuit – Schematic created using CircuitLab
This is a "classic" linear power supply circuit.

A: Welcome to EE stack exchange!
The circuit should work, but the numbers are against you.
There's no perfect voltage regulator; the LM7812, for instance, draws approximately 8 mA of current for its  internal amplifiers and voltage
reference, so the 1 k ohm resistor will lose about 8V.   The
fact that your rectifier is a doubler, makes that 16V, and the capacitors
are not zero impedance (22 uF at 1 kHz is about 7 ohms), so you can
expect about another 20 ohms in two capacitors and two diodes.
Lower that resistance, use bigger capacitors, and... it should work.
Of course, there's also usually going to be a load on the output, using that regulated power that your circuit provides.   You want to simulate
that, too.


text:
Q: Sqlite EF Core 5 won't let me do case insensitive searches So I've tried doing a linq query with ef-core to do a where search, but no matter what I've tried I can't get it to do a case insensitive search.
As in, if I search for "tuesday" it won't fetch any data since everything in the database is saved as "Tuesday".
After searching I've found that you have to tell sqlite through ef core migrations that you want it to be case insensitive with the following code, for each property.
b.Property<string>("DayOfWeek")
    .HasColumnType("TEXT COLLATE NOCASE");

That info is in the ContextModelSnapshot.cs file.
So I did that, deleted the database and did an "Update-Database", a new database was created but nothing changed.
Now I could of course use the .ToLower() in every search, but that will just make a performance hit and increase the possibility for failure if I forget to add that to every where clause.
I'm using the following packages for databas creation, migration and access.
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1">

What am I missing or did I missunderstand the whole concept of case insensitive queries for sqlite?

A: Unfortunately the provided answer didn't work for me. Here is how to iterate over all of the string properties of all of the exposed models to EF-Core and set their default collation to nocase:
public static void SetCaseInsensitiveSearchesForSQLite(this ModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException(nameof(modelBuilder));
    }

    modelBuilder.UseCollation("NOCASE");

    foreach (var property in modelBuilder.Model.GetEntityTypes()
                                            .SelectMany(t => t.GetProperties())
                                            .Where(p => p.ClrType == typeof(string)))
    {
        property.SetCollation("NOCASE");
    }
}

And then call it this way:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException(nameof(modelBuilder));
    }

    modelBuilder.SetCaseInsensitiveSearchesForSQLite();
}

A: You can use the following code to configure your properties to be case-insensitive.
In your context:
 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.UseCollation("BINARY");

        modelBuilder.Entity<Entry>().Property(c => c.DayOfWeek)
            .UseCollation("NOCASE");
    }

With this setting, DayOfWeek will not be case-sensitive, while other columns will still be distinguished.

A: So after a lot of testing I finally found my error.
Turns out all you need is to change the collation in OnModelCreating to NOCASE and suddenly it works like a charm everywhere.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.UseCollation("NOCASE");
}


text:
Q: Nullcheck on nullable Types in Typescript I'm new to typescript, with the following code interface definition.
export Interface Response {
  content?: {
    // ...
  }
}

let response: Response | null = something();

How to access content without doing null checks, which i assume is not at all the best approach.
if (response != null) {
  if (response.content != null) {
    content = (response.content as MyContent);
  }
}

A: content = response?.content == null ? null : response.content as MyContent;

A: I was running version 3.0.x version of typescript, this does not support the Safe Navigation Operator.
Updating typescript made it possible to do something similar to.
response?.content?.something


text:
Q: Running services Is there a way to get precise list of services with "is running"/"is not running" statuses specified.
service --status-all

outputs more than 30 ? services.
Why is that output is so not informative? Is it that difficult to determine if service is running or not? And how to get the exact statuses for all services?
zerkms@ubuntu-server-11:~$ sudo service --status-all 2>&1|grep cron
 [ ? ]  cron
zerkms@ubuntu-server-11:~$ sudo service cron status
cron start/running, process 804

A: It seems a bug in the service script. Changing the grep pattern in line 77 with this gives better results:
"\(^\|\W\)status)"

Edit
Found a bug report in Debian on this. A patch is available, functionally equivalent to what I write above: service doesn't correctly parse "cron" init.d. Launchpad do not recognize the project sysvinit-utils.


text:
Q: Auto width for child div within a parent container div I have found the following jsfiddle on this site which 90% answers my query.
JSFiddle
However I want to be able to include margins on the inner divs. I've tried amending the calculationg to account for margins but I can't get it to work without the inner divs going on a new line or overflowing.
jquery code is
var containerW = $('.container').width();
var innerCount = $('.container .inner').length;

$('.inner').css({
    width: containerW / innerCount
})

html is

css
.container {
    width: 100%;
    height: 150px;
    background : #bbb;
}
.inner {
    float:left;
    height:100%;
    min-width:30px;
}

I only want to be able to put left and right margin so the inner divs appear spaced out.
Thanks

A: If you are giving margin to  the .inner class like margin:5px; then try in js like
$('.inner').css({
    width: (containerW / innerCount)-10
})

because if we are giving margin :5px means left-right its 5-5 , so total 10px for one inner div, so we have to minus it from its width;

A: Instead of setting the css width, you can use jquery "outerWidth" function. So, your jquery code should be:
var containerW = $('.container').width();
var innerCount = $('.container .inner').length;
$('.inner').outerWidth(containerW / innerCount, true);

The second argument in outerWidth tells whether to include margin in width computation or not.


text:
Q: Action of a Category over Another? Let $G$ and $H$ be two groups. We say $G$ acts on $H$ if there is a group homomorphism $\rho:G\longrightarrow \textrm{Aut}(H)$, where the $\textrm{Aut}(G)$ is the group of automorphisms of $H$.
We can regard $G$ and $H$ as the sets of morphisms of small categories with only one object. The composition and identities are induced from the group definition. So we can say an action of $G$ on $H$ is an action of the category $G$ on the category $H$.
In general, if $\mathcal{C}$ and $\mathcal{D}$ are categories, is there a notion of an action of $\mathcal{C}$ on $\mathcal{D}$?
Thanks.

A: In Introduction to foliations and Lie groupoids (§5.3), Moerdijk and Mrcun define the action of a groupoid on another groupoid, which is already a generalization of the situation you describe.
A (right) action of a groupoid $G$ on a groupoid $H$ is given by two (right) actions of $G$ on $H_1$ (the set of morphisms of $H$) and on $H_0$ (the set of objects of $H$) such that the groupoid structure maps of $H$ are equivariant.
Moreover, Julia Bergner has developped a notion (a rooted action) of a category acting on another category in her article Reedy categories which encode the notion of category actions.
She defines the action of a small category $\mathcal{C}$ on a set $A$, and then a rooted action of a category $\mathcal{C}$ on a category $\mathcal{D}$ is given by an action of $\mathcal{C}$ on the set of morphisms of $\mathcal{D}$, satisfying two additional axioms.
However, it seems that the latter is not a generalization of the former, since if $\mathcal{D}$ is a discrete category then there is no nontrivial rooted action of $\mathcal{C}$ on $\mathcal{D}$, though there may be nontrivial actions of $\mathcal{C}$ on $\mathcal{D}_0$.


text:
Q: Sybase ODBC driver not working over a VPN I need to run a client's software locally on my machine and have it talk over a VPN link (Team Viewer VPN) to connect to the live database so I can attach a debugger to the client software and figure some issues out that the client is having.
When any of the computers on the client's network connect it works fine. Here is the output from the driver's debug information.
Sun Aug 05 2012 15:06:10
15:06:10 CONN: Application information:
15:06:10 "HOST=WORKSTATION36;OS=Windows XP Build 2600 Service Pack 3;PID=0x11a0;THREAD=0xdcc;EXE=C:\abba\dbisqlc.exe;VERSION=7.0.4.3472;API=DBLIB"
15:06:10 CONN: Attempting to connect using:
UID=abdbo;PWD=*****;DBN=abba;ENG=abba;ASTOP=YES;DBG=YES;LOG=C:\log\odbcLog.txt;DMRF=NO;LINKS=TCPIP{}
15:06:10 Trying to start TCPIP link ...

15:06:10 Loading wsock32.dll
15:06:10 Loading ws2_32.dll
15:06:10 TCP using Winsock version 2.0
15:06:10 My IP address is 192.168.0.111
15:06:10 My IP address is 127.0.0.1
15:06:10     TCPIP link started successfully

15:06:10 Trying 192.168.0.2:2638
15:06:10 Found database server abba on TCPIP link
15:06:10 Client connected
15:06:10 CONN: Connected to the server
15:06:10 [1174510859] CONN: Connected to database successfully
15:06:10 [1174510859] Client disconnected

However if I attempt to connect using my VPN link it does not work.
Sun Aug 05 2012 17:13:26
17:13:26 CONN: Application information:
17:13:26 "HOST=CONVERSIONVM;OS=Windows 2003 Build 3790 Service Pack 2;PID=0x878;THREAD=0x98c;EXE=C:\abba\dbisqlc.exe;VERSION=7.0.4.3472;API=DBLIB"
17:13:26 CONN: Attempting to connect using:
UID=abdbo;PWD=*****;DBN=abba;ENG=abba;ASTOP=YES;DBG=YES;LOG=C:\log\odbcLog.txt;DMRF=NO;LINKS=TCPIP{}
17:13:26 Trying to start TCPIP link ...
17:13:26 Loading wsock32.dll
17:13:26 Loading ws2_32.dll
17:13:26 TCP using Winsock version 2.0
17:13:26 My IP address is 7.192.193.89
17:13:26 My IP address is 10.0.1.106
17:13:26 My IP address is 127.0.0.1
17:13:26     TCPIP link started successfully
17:13:26 Looking for abba
17:13:26 I am in a class A network
17:13:26 Sending broadcast
17:13:26 Using broadcast address of: 7.255.255.255:2638
17:13:26 I am in a class A network
17:13:26 Sending broadcast
17:13:26 Using broadcast address of: 10.255.255.255:2638
17:13:26 I am in a class A network
17:13:26 Sending broadcast
17:13:26 Using broadcast address of: 127.255.255.255:2638
17:13:27     No reply received
17:13:27 Resending
17:13:28     No reply received
17:13:28 Resending
17:13:29     No reply received
17:13:29 Resending
17:13:30     No reply received
17:13:30 Resending
17:13:31     No reply received
17:13:31 CONN: Cannot connect

A few issues I think could be the problem is the fact that Team Viewer wants me to route the traffic through it's special IP and the broadcast is not transmitted through it. I attempted to tell the TCP/IP link to use the server's VPN's IP and port but that did not solve the issue either
Sun Aug 05 2012 17:29:29
17:29:29 CONN: Application information:
17:29:29 "HOST=CONVERSIONVM;OS=Windows 2003 Build 3790 Service Pack 2;PID=0x13c;THREAD=0x810;EXE=C:\abba\dbisqlc.exe;VERSION=7.0.4.3472;API=DBLIB"
17:29:29 CONN: Attempting to connect using:
UID=abdbo;PWD=*****;DBN=abba;ENG=abba;ASTOP=YES;DBG=YES;LOG=C:\log\odbcLog.txt;DMRF=NO;LINKS=TCPIP{IP=7.192.141.131;PORT=2638}
17:29:29 Trying to start TCPIP link ...
17:29:29 Loading wsock32.dll
17:29:29 Loading ws2_32.dll
17:29:29 TCP using Winsock version 2.0
17:29:29 My IP address is 7.192.193.89
17:29:29 My IP address is 10.0.1.106
17:29:29 My IP address is 127.0.0.1
17:29:29     TCPIP link started successfully
17:29:29 Looking for abba
17:29:29 I am in a class A network
17:29:29 Sending broadcast
17:29:29 Using broadcast address of: 7.255.255.255:2638
17:29:29 I am in a class A network
17:29:29 Sending broadcast
17:29:29 Using broadcast address of: 10.255.255.255:2638
17:29:29 I am in a class A network
17:29:29 Sending broadcast
17:29:29 Using broadcast address of: 127.255.255.255:2638
17:29:29 Trying 7.192.141.131
17:29:29 Trying 7.192.141.131
17:29:30     No reply received
17:29:30 Resending
17:29:31     No reply received
17:29:31 Resending
17:29:32     No reply received
17:29:32 Resending
17:29:33     No reply received
17:29:33 Resending
17:29:34     No reply received
17:29:34 CONN: Cannot connect

One thing I did notice is that the port was not listed on the Trying 7.192.141.131 even though I explicitly told it to use that port and the same line in the working log shows the port included as Trying 192.168.0.2:2638.
Firewalls are disabled on both the client and server so the problem is not related to that, I think it is because the port number is not being set but I do not know what I am doing wrong to cause it not to be set.
This is using the Adaptive Server Anywhere 7.0 driver.


text:
Q: Usando duas opções simultaneamente JQueryUI Dialog Widgets Estou tentando implamentar o Widget Dialog do JQuery-UI para que toda a tela (e mais) seja completamente populada por Dialogs de diferentes tamanhos (width) e em diferentes posições (position).
Porém estou enfrentando dois problemas:
1) Não consigo setar as duas opções no JQuery UI. Ou aceita uma ou aceita a outra. O código que estou usando é esse:
  $( function() {
    $( "#lub" ).dialog({
      position: { my: "center top", at: "left top+150", of: window }
      width: 500
   });
} );

Mesmo se eu der uma solução "macarrônica" para o problema ainda tem o outro problema:
2) Não consigo fazer aparecer o Widget Dialog fora da área de visualização da página. Não há numero que eu informe que faça com que a janela apareça aonde eu queo. O código da outra janela ficou assim:
  $( function() {
    $( "#rank" ).dialog({
        position: { my: "left top", at: "left top+1530", of: window }

    });
  } );

A: Já consegui resolver parte do problema. Aprendi como fazer para usar duas opções. Basta usar a vírgula como o exemplo abaixo:
  $( function() {
    $( "#rank" ).dialog({
        width: 500,
        autoOpen: true,
        show: {
            effect: "blind",
            duration: 1000
        },
        position: { my: "left top", at: "left top+1530", of: window }

    });
  } );

Agora só falta descobrir como faz para o "position" funcionar em qualquer lugar da página.


text:
Q: How to get String Name in VCF Format String Android via CamCard So I use CamCard API to get the VCard Format String, and this string appears from BEGIN:VCARD to END:VCARD

From BEGIN:VCARD and END:VCARD, how do I get the name, phone number, e-mail in String separately? Any reference that what should I do?

A:     @Override
    public void onQRCodeRead(final String text, PointF[] points) {
        pointsOverlayView.setPoints(points);

        if (text.length() > 0 && !text.isEmpty()) {
            resultTextView.setText(text);
            qrCodeReaderView.stopCamera();
            btnSaveToContact.setVisibility(View.VISIBLE);

            btnSaveToContact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (checkandRequestPermission()) {

                        VCard vCard = Ezvcard.parse(text).first();

                        File vcfFile = new File(getActivity().getExternalFilesDir(null), "generated.vcf");

                        VCardWriter writer = null;
                        try {
                            writer = new VCardWriter(vcfFile, vCard.getVersion());
                            writer.write(vCard);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (writer != null) {
                                try {
                                    writer.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        Intent i = new Intent();
                        i.setAction(android.content.Intent.ACTION_VIEW);
                        i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
                        startActivity(i);
                    }
                }
            });
                model = new Model();
                model.setQrText(resultTextView.getText().toString());
                model.setDate(getDateTime().toString());
                realm.beginTransaction();
                realm.copyToRealm(model);
                realm.commitTransaction();
        }
    }

here "text" is my qr code result. what i m doing is to making one .vcf file and storing my qrcode result in it. and after that VCardWriter will do its work.. it will seprate your result text regarding Contact application. and its automatically store in Contact application.
or if you want each separate result as a string. this is how you can get it.
 String name = vCard.getFormattedName().getValue();
 String email = vCard.getEmails().get(0).getValue();
 String address = vCard.getAddresses().get(0).getStreetAddress() + vCard.getAddresses().get(0).getCountry();
 String birthday = vCard.getBirthday().getText().toString();
 String telephone = vCard.getTelephoneNumbers().toString();

you need to add this dependency first:
compile 'com.googlecode.ez-vcard:ez-vcard:0.10.0'


text:
Q: how exclude the end character in regex expression I have this problem: from list of this  tag:
address.info
address1.com
address2.de
address3.co.uk

I want select with regex expression only http://address.info or address1.com or address2.de ecc. I have written this regex: http:.{1,}?" but there is " at end. I can select all without "

A: You can try this:
http:[^"]+
[^"] will match any char but ".


text:
Q: Essa é uma boa maneira de manter minha API segura? Minha aplicação consiste de uma API nodejs no backend mas também estou criando a implementação de referência de um cliente JavaScript, que é uma SPAen feita com Backbone.
Primeiramente: a API aceita apenas requisições HTTPS, no caso de um request HTTP chegar no servidor ele o ignora completamente e opcionalment pode invalidar a senha utilizada naquele request não seguro.
Meu servidor não guarda estado (sem sessão/cookies) e eu uso apenas autenticação HTTP básicaen, onde forneço duas maneiras de se autenticar um request:
1- Enviar as credenciais no header: Authentication: base64('Basic ' + nomeDeUsuario:senha)
2- Enviar um request autenticado com o método 1 para GET /usuarios/atual que retorna um token, que é uma string criptografada* contendo: nomeDeUsuario + '|' + dataDeExpiracaoDoToken. O cliente daí então passa a enviar o header Authentication: 'Token ' + base64(nomeDeUsuario:token).
*Criptografia feita com algoritmo aes-256-ctr do OpenSSL. A chave privada é o hash da senha do usuário.
O método 1 pode ser utilizado para comunicação servidor-servidor, portanto não é adequado ao cliente JavaScript, pois para todos os requests o usuário teria que inserir suas credenciais, a menos que tais credenciais fossem armazenadas na memória do browser, o que eu não sei se é seguro o suficiente. Além do mais, armazenar as credencias no local storage manteria o usuário logado indefinidamente.
Pelo método 2 o cliente JavaScript envia apenas um request autenticado com autenticação básica e imediatamente descarta essas informações sensíveis de login, armazenando apenas o token no local storage. Após um determinado tempo este token irá expirar e será necessário uma revalidação, quase que emulando uma sessão no servidor.
Do lado do servidor eu verifico a autenticidade de um request feito com o método 2 simplesmente obtendo o hash da senha do usuario e tentando descriptografar o token, então eu verifico tokenDescriptografado.split('|')[0] === username.
Esta á uma abordagem segura? Existe algum ponto que não estou levando em consideração? Dada esta abordagem, quais tipo de ataques eu estaria sujeito?
*Este é um crosspost de uma pergunta que fiz no Information Security

A: Há um problema em seu método 2: suponha que um atacante obtenha uma cópia do seu BD. Normalmente isso não seria uma catástrofe, pois as senhas dos usuários estão hasehadas, mas pelo método 2 o atacante poderia se autenticar somente com o hash:

*

*Crie um novo token nomeDeUsuario + '|' + dataDeExpiracaoDoToken, com uma data de expiração recente;

*Use o hash desse usuário para criptografar o token, e envie-o. O servidor aceitará a autenticação!

Um método mais seguro de gerar tokens no servidor sem guardar estado é através de uma assinatura (ou melhor dizendo, um HMAC): guarde da maneira mais segura que puder (ex.: um arquivo de configurações com acesso restrito, ou um módulo de hardware) uma chave secreta conhecida somente pelo servidor. Não coloque essa chave no BD. Quando um usuário acessar /usuarios/atual, crie um token tal como estava fazendo (nome de usuário e data de expiração), mas em vez de criptografá-lo com o hash da senha do usuário, assine-o usando esse segredo:
HMAC(segredo, token)

E envie ambos ao usuário (o token em texto plano, e a assinatura do token). Quando o usuário repassar esses dados ao servidor, verifique se a assinatura está intacta (o usuário poderia alterar o nome de usuário ou a data de expiração no token em texto plano, mas ele não poderia falsificar a assinatura sem o segredo do servidor). Dessa forma, um atacante com acesso somente ao hash da senha do usuário não poderia se autenticar usando o método 1, nem forjar um token para ser usado no método 2.
Isso deixaria seu sistema mais seguro num cenário como este, em que o atacante tem uma cópia do seu BD mas não do seu sistema como um todo (ex.: numa vazamento via Injeção de SQL, obtém-se uma cópia do banco, mas os arquivos de configuração/módulo de hardware continuam intactos). E se esses tokens tem curta duração, pode ser interessante nem usar um segredo persistente, mas sim gerar uma chave aleatória em memória, válida somente até o servidor ser reiniciado (se há múltiplos servidores, com balanceamento de carga por exemplo, isso pode ser menos viável).


text:
Q: How to know spin out of wave function? I do not clearly understand some concepts, so maybe someone will clarify this for me.
Imagine we have a random wavefunction for an electron, it could be anything.
How can I with known wave function calculate the value of spin of electron? I mean I know that we cannot exactly know with 100% would it be spin up or spin down, but which steps should be made to calculate the probabilities?
Or maybe I am misunderstanding, and that the wavefunction of an electron must always be in the form of $|\psi\rangle=c_1|\psi_{1_{spin up}}\rangle + c_2|\psi_{2_{spin down}}\rangle$? If yes, I know that probabilities of spin up and down is just ${c_1}^2$ and ${c_2}^2$ respectively.
But what if wave function would be different (not necessarily identical to the following equation, but of a different form)? For example, the normalized wavefunction of a particle in an infinite square well.
$$\psi_n\left(z\right) = \sqrt{\frac{2}{L_z}}\sin{\frac{n\pi z}{L_z}}$$

A: The wavefunction you are giving is the one of a particle (with no spin) in an infinite potential well, this is described as a state living on a certain Hilbert space. To include the spin of a particle you must force it as a tensor product of the system you are considering times the two-level system from the spin (if you want to consider the potential well $\otimes$ spin). So you are right, to have a spin system, your wavefunction (a qubit) will only have two degrees of freedom represented in the Bloch sphere or as you put it $|{\psi}\rangle = c_1 |{up}\rangle + c_2 |{down}\rangle$ where $|c_1|^2 + |c_2|^2 = 1$.
Thus, if you are describing the state as energy levels of the potential and a spin configuration, you may have a superposition of states living in this space. If you want the information of a certain value (such as the spin or the energy of the harmonic oscillator) you can project to that space on the basis you prefer. For example, if you want to project on either up or down spin component you can act with $\langle up|$ or $\langle down|$ to your state $|\psi\rangle$. Whether you get 0 or 1 from one of these projections you may conclude if your spin is up or down, also, you could project the state you have to a particular space of energy levels (since each $\psi_n$ you mentioned are orthogonal).
This post might be helpful as well.


text:
Q: JQuery: How to do validation on blur of a text box? I have a textbox with ID "name", I want to do validation when the text box get onblur function. The below code doesn't work. What's wrong with me?
  $(function() {
    $('name').validate({
      rules:{ "name": {required: true, minlength: 5 } }
    });
    $('name').blur(function(){
      $('name').validate()
    });
  };

A: Working Demo http://jsfiddle.net/qC2Ya/ or this one is way more shorter and cooler http://jsfiddle.net/XdAkv/
All you need to do is add an element validation on blur event and that will work like a rocket.
See validation element api : http://docs.jquery.com/Plugins/Validation/Validator/element#element
Hope this helps :)
code
var v = $("form").validate({
    submitHandler: function() {
        console.log('successful submit');
        return false;
    }
});

$('#firstName').blur(function(){
   v.element('#firstName');
});

$('#lastName').blur(function(){
   v.element('#lastName');
});

OR from second demo
$("form").validate({
    submitHandler: function() {
        console.log('successful submit');
        return false;
    }
});

$('#firstName,#lastName').blur(function(){
    $("form").validate().element($(this))
});

A: There is onfocusout option, set to false will validate elements (except checkboxes/radio buttons) on blur. The doc.
$('form').validate({
  onfocusout: false,
  rules:{ "name": {required: true, minlength: 5 } }
});