text:
Q: CoreData - could not locate an NSManagedObjectModel I'm getting the error below, I don't know what I'm doing wrong.
I guess there is the managedobject which cannot be located, but... arf !
 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Boxes''

here is my .m ( only the two main functions )
    - (void)loadCoreData
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Test" object:self];
    context = [app managedObjectContext];
    NSError *err;

    // GET THE JSON
    NSString *urlString = [NSString stringWithFormat:@"http://localhost:8888/json.txt"];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
    // FILL THE ENTITY
    for (int i = 0; i != 7; i++)
    {
        Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:@"Boxes" inManagedObjectContext:context];

        boxes.name =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"name"] ;
        boxes.sexe =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"sexe"] ;
        boxes.topic =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"topic"] ;
        boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"number"] intValue]];
    }
    request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Boxes" inManagedObjectContext:context];
    [request setEntity:entity];
    arrayForPredicate = [context executeFetchRequest:request error:&err];
}

- (void) fillSexArray:(NSString *)sexe
{

    // PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
    NSPredicate *sex;

    if ([sexe isEqualToString:@"both"])
    {
        sex = [NSPredicate predicateWithFormat:@"sexe = %@ OR sexe = %@", @"female", @"male"];
    }
    else
    {
        sex = [NSPredicate predicateWithFormat:@"sexe = %@", sexe];
    }
    NSArray  *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
    NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
    //  NSLog(@"%@", [[mutableArray objectAtIndex:1] valueForKey:@"name"]);
  //  NSUInteger numObjects = [mutableArray count];

}

my .h :
@interface AddViewController : UIViewController

{
IBOutlet UIButton *male;
IBOutlet UIButton *female;
IBOutlet UIButton *couple;
UIButton *maleBtn;
BOOL flag;
NSArray *arrayForPredicate;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *context;
NSFetchRequest *request;

}
@property (nonatomic, retain) WonderAppDelegate *app;
- (void) fillSexArray:(NSString *)sexe;
- (NSMutableArray *)createMutableArray:(NSArray *)array;
- (void)loadCoreData;
- (void)sexeButtonPressed;
- (void)sexeArray;
@end

EDIT creating the managedObject :
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
    Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:@"Boxes"
                                             inManagedObjectContext:managedObjectContext];

    boxes.name    = [dict objectForKey:@"name"];
    boxes.sexe    = [dict objectForKey:@"sexe"];
    boxes.topic    = [dict objectForKey:@"topic"];
    boxes.number   = [dict objectForKey:@"number"];

    return boxes;
}

This is my .m and it is working like that but i don't want the code of the function Add there i want it on loadCoreData.
//
//  AddViewController.m
//  CoreDataTuto
//
//  Created by Clement Yerochewski on 30/04/12.
//  Copyright (c) 2012 Weblib. All rights reserved.
//

#import "AddViewController.h"
#import "Boxes.h"

@implementation AddViewController
@synthesize app, context;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
        UINavigationItem *navItem = [[UINavigationItem alloc]  initWithTitle:@"Add Detail"];
        [navBar pushNavigationItem:navItem animated:NO];
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
        UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStyleBordered target:self action:@selector(add)];

        navItem.leftBarButtonItem = cancelButton;
        navItem.rightBarButtonItem = addButton;

        [self.view addSubview:navBar];
        app = [[UIApplication sharedApplication] delegate];
    }
    return self;
}

- (void) add{

    [self dismissModalViewControllerAnimated:YES];

    //    PREDICATE TO GET AN ARRAY OF PRODUCT WITH A LENGTH NAME <= 5
    //    NSPredicate *length;
    //    length = [NSPredicate predicateWithFormat:@"name.length <= 5"];
    //    NSArray  *BoxWithCheapPrice = [array filteredArrayUsingPredicate:length];
    //    NSLog(@"Box %@", BoxWithCheapPrice);

    // PREDICATE TO GET AN ARRAY OF PRODUCT WITH PRICE BETWEEN $MIN AND $MAX
    //    NSNumber *min = [NSNumber numberWithInteger:30];
    //    NSNumber *max = [NSNumber numberWithInteger:100];
    //    NSPredicate *between;
    //    between = [NSPredicate predicateWithFormat:@"number BETWEEN %@", [NSArray arrayWithObjects:min, max, nil]];
    //    NSArray  *BoxWithPriceBetween = [array filteredArrayUsingPredicate:between];
    //    NSLog(@"Box %@", BoxWithPriceBetween);
    //    NSLog(@"%@", [BoxWithPriceBetween valueForKey:@"name"]);

  }

- (NSMutableArray *)createMutableArray:(NSArray *)array
{
    return [NSMutableArray arrayWithArray:array];
}

- (IBAction) sexeChoosen: (id) sender
{
    switch ( ((UIButton*)sender).tag ){
        case 0:
            [self fillSexArray:@"male"];
            break;
        case 1:
            [self fillSexArray:@"female"];
            break;
        default:
            [self fillSexArray:@"both"];
    }
    [self sexeButtonPressed];

}

- (void)sexeButtonPressed
{
    if (flag)
    {
        UIImage * maleImg2 = [UIImage imageNamed:@"pressed.png"];
        [maleBtn setImage:maleImg2 forState:UIControlStateNormal];
        flag = NO;
        [self sexeArray];
    }
    else
    {
        UIImage * maleImg1 = [UIImage imageNamed:@"unpressed.png"];
        [maleBtn setImage:maleImg1 forState:UIControlStateNormal];
        flag = YES;
        [self sexeArray];
    }
}

- (void)sexeArray
{

}

- (void)loadCoreData
{

}

- (void) fillSexArray:(NSString *)sexe
{

    context = [app managedObjectContext];

    // GET THE JSON
    NSString *urlString = [NSString stringWithFormat:@"http://localhost:8888/json.txt"];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSError *err;
    NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];

    // FILL THE ENTITY
    for (int i = 0; i != 7; i++)
    {
        Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:@"Boxes" inManagedObjectContext:context];

        boxes.name =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"name"] ;
        boxes.sexe =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"sexe"] ;
        boxes.topic =   [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"topic"] ;
        boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"number"] intValue]];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Boxes" inManagedObjectContext:context];
    [request setEntity:entity];
    arrayForPredicate = [context executeFetchRequest:request error:&err];

    NSPredicate *sex;
    // PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO

    if ([sexe isEqualToString:@"both"])
    {
        sex = [NSPredicate predicateWithFormat:@"sexe = %@ OR sexe = %@", @"female", @"male"];
    }
    else
    {
        sex = [NSPredicate predicateWithFormat:@"sexe = %@", sexe];
    }
    NSArray  *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
    NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
    NSLog(@"SEXE CHOOSEN %@", mutableArray);

    //  NSLog(@"%@", [[mutableArray objectAtIndex:1] valueForKey:@"name"]);
    NSUInteger numObjects = [mutableArray count];

    NSLog(@"%d", numObjects);
}

- (void) cancel{
    [self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    flag = YES;

    maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    maleBtn.frame = CGRectMake(40, 47, 107, 75);
    [maleBtn setTitle:@"male" forState:UIControlStateNormal];
    UIImage * maleImg1 = [UIImage imageNamed:@"unpressed.png"];
    [maleBtn setImage:maleImg1 forState:UIControlStateNormal];
    [maleBtn addTarget:self action:@selector(sexeChoosen:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:maleBtn];
    [self loadCoreData];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

A: Have you updated your model after creating the persistent store? Try to delete your app from the simulator (or the database file) and run it again..


text:
Q: Vertices of a cyclic polygon have integer coordinates and sides. If odd $n$ divides the squares of the sides, it divides twice the area. IMO 2016 Problem 3:

Let $P = A_1 A_2 \cdots A_k$ be a convex polygon in the plane. The vertices $A_1, A_2, \ldots, A_k$ have integral coordinates and lie on a circle. Let $S$ be the area of $P$. An odd positive integer $n$ is given such that the squares of the side lengths of $P$ are integers divisible by $n$. Prove that $2S$ is an integer divisible by $n$.

I tried using the formula for area of a polygon in cartesian plane, after assuming coordinates, but to no avail.

A: Incomplete proof
Since $P$ is convex, we can uniquely truncate $P$ with right-angled triangles with hypotenuses equal to the side lengths of $P$ and the remaining rectilinears inside.
Let reducible triangle be a right-angled triangle with Pythagorean triple $(a,b,c)$ where both $a$,$b$ and $c$ are divisible by $n$.
If all triangles above truncating $P$ is reducible triangles, area of each triangle and rectilinear is divisible by $n^2$. Thus, $2S$ must be divisible by $n$.
Please figure out the case with $P$ truncated by some non-reducible triangles.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas to datetime check format I have several csv files which all have a column with a date which is either in DD/MM/YYYY format or MM/DD/YYYY format.
At the moment I manually check the file and convert it the column to pandas datetime using the code below.
df["date"] = pd.to_datetime(df["date"], dayfirst=True, errors='coerce')

In cases of different date format I change dayfirst=True/False.
I have to coerce errors as some rows contain dirty data.
I would like to automate this process so that I only upload the file and pandas will automatically decide if the column is in MM/DD or DD/MM format.
Any tips and suggestions are appreciated.

A: Okay, I have found something that is working:
for df in df_list:
    df_test=df["Date"].str.split("/", expand=True)
    df_test[0] = pd.to_numeric(df_test[0], errors="coerce")
    df_test[1] = pd.to_numeric(df_test[1], errors="coerce")
    a=df_test[0].max()
    b=df_test[1].max()
    if b > a:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=False, errors='coerce')
    elif a > b:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=True, errors='coerce')


text:
Q: Error on npm start using Angular 2 RC version I changed Angular2 beta 15 version to RC version and I got some errors when running application.
typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'.
typings/browser/ambient/es6-shim/index.d.ts(11,5): error TS2300: Duplicate identifier 'done'.
typings/browser/ambient/es6-shim/index.d.ts(12,5): error TS2300: Duplicate identifier 'value'.
typings/browser/ambient/es6-shim/index.d.ts(250,5): error TS2300: Duplicate identifier 'EPSILON'.
typings/browser/ambient/es6-shim/index.d.ts(285,5): error TS2300: Duplicate identifier 'MAX_SAFE_INTEGER'.
typings/browser/ambient/es6-shim/index.d.ts(292,5): error TS2300: Duplicate identifier 'MIN_SAFE_INTEGER'.
typings/browser/ambient/es6-shim/index.d.ts(348,5): error TS2300: Duplicate identifier 'flags'.
typings/browser/ambient/es6-shim/index.d.ts(500,5): error TS2300: Duplicate identifier 'prototype'.
typings/browser/ambient/es6-shim/index.d.ts(563,5): error TS2300: Duplicate identifier 'size'.
typings/browser/ambient/es6-shim/index.d.ts(572,5): error TS2300: Duplicate identifier 'prototype'.
typings/browser/ambient/es6-shim/index.d.ts(583,5): error TS2300: Duplicate identifier 'size'.
typings/browser/ambient/es6-shim/index.d.ts(592,5): error TS2300: Duplicate identifier 'prototype'.
typings/browser/ambient/es6-shim/index.d.ts(607,5): error TS2300: Duplicate identifier 'prototype'.
typings/browser/ambient/es6-shim/index.d.ts(621,5): error TS2300: Duplicate identifier 'prototype'.
typings/globals/core-js/index.d.ts(3,14): error TS2300: Duplicate identifier 'PropertyKey'.
typings/globals/core-js/index.d.ts(217,5): error TS2300: Duplicate identifier 'flags'.
typings/globals/core-js/index.d.ts(231,5): error TS2300: Duplicate identifier 'EPSILON'.
typings/globals/core-js/index.d.ts(266,5): error TS2300: Duplicate identifier 'MAX_SAFE_INTEGER'.
typings/globals/core-js/index.d.ts(273,5): error TS2300: Duplicate identifier 'MIN_SAFE_INTEGER'.
typings/globals/core-js/index.d.ts(583,5): error TS2300: Duplicate identifier 'size'.
typings/globals/core-js/index.d.ts(589,5): error TS2300: Duplicate identifier 'prototype'.
typings/globals/core-js/index.d.ts(600,5): error TS2300: Duplicate identifier 'size'.
typings/globals/core-js/index.d.ts(606,5): error TS2300: Duplicate identifier 'prototype'.
typings/globals/core-js/index.d.ts(621,5): error TS2300: Duplicate identifier 'prototype'.
typings/globals/core-js/index.d.ts(635,5): error TS2300: Duplicate identifier 'prototype'.
typings/globals/core-js/index.d.ts(646,5): error TS2300: Duplicate identifier 'done'.
typings/globals/core-js/index.d.ts(647,5): error TS2300: Duplicate identifier 'value'.
typings/globals/core-js/index.d.ts(759,5): error TS2300: Duplicate identifier 'prototype'.

Can you help me finding how to fix this problem? I am a noob in Angular2.
My json file typings.json looks like this:
{
    "ambientDependencies": {
        "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
    }
}

A: Your typings.json file is using a deprecated syntax: it's using ambientDependencies instead of globalDependencies. Also, the Angular RC doesn't use the es6-shim anymore.
Remove your typings folder, update your typings.json file and install again.
Update you typings.json as follows:
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

A: In typings.json Rename:
ambientDevDependencies to globalDevDependencies
ambientDependencies to globalDependencies
Then, at the console:
$ typings install
├── es6-shim (global)
├── angular-protractor (global dev)
├── jasmine (global dev)
└── selenium-webdriver (global dev)


text:
Q: java drawing on JPanel with timer/delay I'm trying to make a small Mosaic programm, that draws squares randomly all over the JPanel. I want to make it so, that it draws every 0,2 sec 1 square (not all at once), but so far i can make only it to draw all at once with a while loop. I have tried with ActionListener and Timer, but i found out, that i cant pass the same Graphics g to ActionListener. Then i tried with Thread.Sleep(200) but then the app froze. Now i have tried with System.currentTimeMillis(); but its same as with Threads... Searched all over the internet but didnt find anything that works.
Main:
import javax.swing.JApplet;

public class Main extends JApplet{
public void init(){
    setSize(500, 300);
    Mosaic mosaic = new Mosaic();

    setContentPane(mosaic);

}
}

App:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;

public class Mosaic extends JPanel{

private int width, height;
private int ruut; // square
private int w = width / 2, h = height / 2; // middle of the app

Random rand = new Random();
Color color;

public Mosaic(){
    this(500, 300, 10);
}

public Mosaic(int width, int height, int ruut){
    this.width = width;
    this.height = height;
    this.ruut = ruut;
    setBackground(Color.BLACK);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    //draws random squares
    while (true) {
        moveNext(g);
        wait(200);
    }
}

//delay n millisec
public void wait(int n){
    long t0, t1;
    t0 = System.currentTimeMillis();

    do {
        t1 = System.currentTimeMillis();
    } while ((t1 - t0) < n);
}

//next square
public void moveNext(Graphics g){

    int r = rand.nextInt(4);

    switch (r) {
    case 1:
        h += ruut;
        wallTest();
        break;
    case 2:
        h -= ruut;
        wallTest();
        break;
    case 3:
        w -= ruut;
        wallTest();
        break;
    case 4:
        w -= ruut;
        wallTest();
        break;
    }

    color = new Color(0, rand.nextInt(255-50)+50, 0);
    g.setColor(color);
    g.fillRect(w, h, ruut, ruut);
}

public void wallTest(){
    if (h > height){
        h = 0;
    }
    if (h < 0){
        h = height;
    }
    if (w > width){
        w = 0;
    }
    if (w < 0){
        w = width;
    }
}

}

A: Use the javax.swing.Timer class in conjunction with overriding the paintComponent method. You do not want to execute long-running tasks in the EDT since this will cause the GUI to freeze.
Example -
new javax.swing.Timer(DELAY_IN_MILLIS, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        // do stuff
        repaint();
    }
});

A:
I have tried with ActionListener and Timer, but i found out, that i cant pass the same Graphics g to ActionListener.

Of course not, the Graphics object is transitory.  Instead either do either of:

*

*Add a rectangle to an expandable list and call repaint() (in a loop), drawing every object in the list at once.

*Put a BufferedImage in a JLabel and add a 'rectangle at a time' to the BufferedImage.

A: You need to maintain an off-screen buffer, and draw tiles into that buffer under control of timer events.
Then paintComponent simply copies that buffer to the screen.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Mosaic extends JPanel{

    private int width, height;
    private int ruut; // square
    private int w = width / 2, h = height / 2; // middle of the app
    private BufferedImage buffer;

    Random rand = new Random();
    Color color;

    public Mosaic(){
        this(500, 300, 10);
    }

    public Mosaic(int width, int height, int ruut){
        this.width = width;
        this.height = height;
        this.ruut = ruut;
        this.buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(width, height));
        setDoubleBuffered(false);
        new Timer(200, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                moveNext(buffer.getGraphics());
            }
        }).start();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(buffer, 0, 0, this);
    }

    //next square
    public void moveNext(Graphics g){

        int r = rand.nextInt(4);

        switch (r) {
        case 1:
            h += ruut;
            wallTest();
            break;
        case 2:
            h -= ruut;
            wallTest();
            break;
        case 3:
            w -= ruut;
            wallTest();
            break;
        case 4:
            w -= ruut;
            wallTest();
            break;
        }

        color = new Color(0, rand.nextInt(255-50)+50, 0);
        g.setColor(color);
        g.fillRect(w, h, ruut, ruut);
        repaint();
    }

    public void wallTest(){
        if (h > height){
            h = 0;
        }
        if (h < 0){
            h = height;
        }
        if (w > width){
            w = 0;
        }
        if (w < 0){
            w = width;
        }
    }
}

A: You can use the timer approach as that is only way to not freeze the app. You can call repaint or some equivalent method when timer fires and then in the paint method draw as per requirements.


text:
Q: UIScrollView with active and inactive areas I have a UIScrollView that takes up my whole screen with a vertical toolbar on one side, and I need to constrain the scrolling behavior such that the user can only scroll by dragging the toolbar.  If they try to drag from anywhere else on the screen no scrolling should take place.
I've tried overriding touchesBegan, touchesShouldCancelInContentView, and touchesShouldBegin so that if the touch doesn't originate in the toolbar I call setScrollEnabled:NO and if it does I call setScrollEnabled:YES, but it seems like once scrolling is disabled the methods no longer fire and I'm deadlocked.  Also tried setting up the toolbar as a button and enabling scrolling on touchDown and disabling on touchUpInside and touchUpOutside.  This also doesn't work.  Anyone have any ideas?

A: Use a second scrollview to control the main scroll view. I added a gradient to be able to see the scrolling.
#import <QuartzCore/QuartzCore.h>

@implementation ScrollViewController {
    UIScrollView *mainScrollView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect mainScrollViewRect = CGRectMake(0, 0, self.view.bounds.size.width - 100, self.view.bounds.size.height);
    mainScrollView = [[UIScrollView alloc] initWithFrame:mainScrollViewRect];
    mainScrollView.scrollEnabled = NO;
    mainScrollView.contentSize = CGSizeMake(self.view.bounds.size.width - 100, 1000);
    [self.view addSubview:mainScrollView];

    CAGradientLayer* gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    gradientLayer.frame = CGRectMake(0, 0, mainScrollView.contentSize.width, mainScrollView.contentSize.height);
    gradientLayer.colors = @[(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor]];
    [mainScrollView.layer insertSublayer:gradientLayer atIndex:0];

    CGRect toolbarRect = CGRectMake(self.view.bounds.size.width - 100, 0, 100, self.view.bounds.size.height);
    UIScrollView *toolbarScrollView = [[UIScrollView alloc] initWithFrame:toolbarRect];
    toolbarScrollView.delegate = self;
    toolbarScrollView.contentSize = CGSizeMake(0, 1000);
    toolbarScrollView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:toolbarScrollView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    mainScrollView.contentOffset = scrollView.contentOffset;
}

@end


text:
Q: A proof involving linear ordering concept

"Let $(P, <)$ and $(Q, \prec)$ be linearly ordered sets, and let $h$ be a one-to-one function with domain $P$ and range $Q$ such that $h(p_1)\prec h(p_2)$ whenever $p_1<p_2$. Then $h$ is an isomorphism between $(P,<)$ and $(Q,\prec )$.
Proof. We have to verify that if $p_1, p_2 \in P$ are such that $h(p_1)\prec h(p_2)$, then $p_1<p_2$. But if $p_1$ is not less than $p_2$, then, because < is a linear ordering of $P$, either $p_1=p_2$ or $p_2<p_1$. If $p_1=p_2$, then $h(p_1)=h(p_2)$, and if $p_2<p_1$, then $h(p_2)\prec h(p_1)$, by the assumption. Either case contradicts $h(p_1)\prec h(p_2)$."

Since $<$ is a linear ordering, for all $p_1, p_2\in P$, either $p_1<p_2$ or $p_2<p_1$.
Why is $p_1=p_2$ treated as a separate case?

A: The author is using linear ordering to mean what I would call a strict linear order(ing). A binary relation $<$ on a set $A$ is a strict linear order if it is transitive and has the trichotomy property: for any $a,b\in A$, exactly one of $a<b$, $a=b$, and $b<a$ holds. The usual notions $<$ and $>$ in $\Bbb R$ are strict linear orders, while $\le$ and $\ge$ are what I would call simply linear orders.
Thus, the case $p_1=p_2$ really is a separate case.


text:
Q: Log Fractional optimization problem Let $\mathbf{x}$ be a vector of $N$ variables. Then, how can I solve the following optimization problem?
\begin{align}
\max_\mathbf{x}&\quad \sum_{n} \log(1+\frac{x_n}{\alpha+\sum_{m}\beta_m^{(n)}x_m})\\
\text{subject to}&\quad\mathbf{A}\mathbf{x}\leq \mathbf{p}.
\end{align}
Constraints are linear. How about objective function? Is it quasiconcave?

A: Here is an attempt for a special case. Let me write your problem as the following:
$$
\begin{align}
\max_\mathbf{x}&\quad \sum_{n} \log\left(1+\frac{x_n}{f_n(x)}\right)\\
\text{subject to}&\quad\mathbf{A}\mathbf{x}\leq \mathbf{p}.
\end{align}.
$$
Assume the following: (i) $x> 0$, (ii)the coefficients of $f_n(x)$ are all positive $\forall ~n$, and (iii) all elements of $A$ and $p$ are positive.
Firstly, using AM-GM inequality:
$$
1+\frac{x_n}{f_n(x)} \geq 2\sqrt{\frac{x_n}{f_n(x)}}.
$$
This leads to the relaxed problem (barring constants added/multiplied):
$$
\begin{align}
\max_\mathbf{x}&\quad \sum_{n} \log\left(\frac{x_n}{f_n(x)}\right)\\
\text{subject to}&\quad\mathbf{A}\mathbf{x}\leq \mathbf{p}, ~\mathbf{x}>0.
\end{align}.
$$
Now, introduce variables $t_n> 0, \forall n$, such that:
$$
\frac{x_n}{f_n(x)} \geq \frac{1}{t_n} \Rightarrow x^{-1}_nt_n^{-1}f_n(x) \leq 1.
$$
And then the relaxed problem is equivalent to (removing $\log$ as its a monotonic):
$$
\begin{align}
\min_\mathbf{x}&\quad \prod_{n} t_n\\
\text{subject to}&\quad\mathbf{A}\mathbf{x}\leq \mathbf{p},~\mathbf{x}> 0\\
&~~~~~\mathbf{t}>0,~x^{-1}_nt_n^{-1}f_n(x) \leq 1~ \forall n.
\end{align}.
$$
Note that the cost function and constraints are all posynomials, with the assumptions made. Thus, this is in the form of a Geometric Program (see https://en.wikipedia.org/wiki/Geometric_programming), which can be converted to a convex program. In fact, softwares like CVXPY will readily solve a problem in this form.
As far as relaxation gap is concerned, that still needs some thought. Anyway, hope this helps.


text:
Q: Python: Removing elements from a list inside an iterator? I am trying to remove elements from a list in Python. Most answers seem to suggest that using a list iterator is best, but I don't think it's possible (or at least elegant) for my problem.
I want to iterate over the test_data list and delete any items that meet the following two conditions: (1) have an attribute total:sum (2) have an attribute (pagePath) that starts with, but is not equal to, any element in the list mystrings.
Here is my list of strings, and my test data:
    mystrings = [u'/calculate-state-pension', u'/check-uk-visa']
    test_data = [
        {
            "pagePath": "/check-uk-visa",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa/y",
            "total:sum": 3.0
        },
        {
            "pagePath": "/check-uk-visa/n",
            "total:sum": 4.0
        },
        {
            "pagePath": "/bank-holidays",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa",
            "searchUniques:sum": 2.0
        }
    ]

So I would like to end up with this list:
    results = [
        {
            "pagePath": "/check-uk-visa",
            "total:sum": 2.0
        },
        {
            "pagePath": "/bank-holidays",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa",
            "searchUniques:sum": 2.0
        }
    ]

This is my code:
    results = test_data[:]
    for r in results_copy:
        for s in mystrings:
            if 'total:sum' in r and r['pagePath'].startswith(s) \
                 and r['pagePath'] != s:
                results.remove(r)
    return results

But this doesn't seem to work. It removes the element with /check-uk-visa/y but not the one with /check-uk-visa/n.
What am I doing wrong? I think it's something to do with the deleting and the iterator - it looks like it's skipping elements.

A: You want any combination where "pagePath" value startswith a string in your string list but is not equal to the string.
for dic in test_data[:]:
    s = dic.get("pagePath","")
    if "total:sum" in dic and any(s.startswith(y) and s != y  for y in mystrings):
        test_data.remove(dic)

[{'total:sum': 2.0, 'pagePath': '/check-uk-visa'}, {'total:sum': 2.0, 'pagePath': '/bank-holidays'}, {'searchUniques:sum': 2.0, 'pagePath': '/check-uk-visa'}]

One caveat is if you have similar  strings in your mystrings list where one might start with the same letters and not be equal but may be equal to another so in that case we can use a set for 0(1) lookups and use in.
mystrings = {u'/calculate-state-pension', u'/check-uk-visa'}

for dic in test_data[:]:
    s = dic.get("pagePath","")
    if "total:sum" in dic and any(s.startswith(y) for y in mystrings)and s not in mystrings:
        test_data.remove(dic)
print(test_data)

A: The easiest way to filter something like this is usually to use the filter function.
results_copy = filter(lambda r: ('total:sum' in r
                                 and any([r['pagePath'].startswith(s)
                                                             for s in mystrings])
                                 and r['pagePath'] not in mystrings),
                      results)

Alternatively, you could use a list comprehension. Sometimes it is easier to read when you want to do some processing in addition to filtering:
results_copy = [r for r in results if ('total:sum' in r
                                       and any([r['pagePath'].startswith(s)
                                                             for s in mystrings])
                                       and r['pagePath'] not in mystrings)]


text:
Q: 1 time run activity when app is installed i want privacy policy , disclaimer statement and a color picker as 1 time run activity when the app is installed . So how can i use persistent storage so that when we install and run the app for the first time privacy policy runs then clicking on  button(next) goes to disclaimer activity then to color picker and finally to main activity. And when second time app is run it directly goes to main activity.
 MAIN ACTIVITY:

public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't   change this after it's saved something

//public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
      boolean firstRun = settings.getBoolean("firstRun", false); // Is it first run? If not specified, use "true"

        if (firstRun == false) {
            Log.w("activity", "first time");
            setContentView(R.layout.activity_gasfurnancediagnostics);

            SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
            editor.putBoolean("firstRun", false); // It is no longer the first run
            editor.apply(); // Save all changed settings
            return;
        }  else {
            Log.w("activity", "second time");
            checkColor();
            setContentView(R.layout.activity_theme);
            return;
        }
       // setContentView(R.layout.activity_main);

        //*** CHECKING COLOR IF IT WAS SET PREVIOUSLY ***/

}

    public void checkColor()
    {
        // INITIALIZING THE SHARED PREFRENECES
        SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);

        // CHECK IF WE HAVE COLOR_SET VALIRABLE IF NOT DEFAULT WILL BE 0
        int color_set = pref.getInt("color_set", 0);

        if(color_set==0){
              Intent e = new Intent(getApplicationContext(), ThemeActivity.class);
                startActivity(e);
                return;

        }
        if(color_set==1)
        { // IF IT IS ALREADY SET IN THE PREVIOUS THAN THIS CAN BE USED FOR REDIRECTING TO OTHER CONTROLLER AND THE BELOW FUNCTIONS CAN BE USED IN THAT CONTROLLER FOR COLOR MODIFICATIUON

            String color = pref.getString("color", null);  // COLOR CODE

            ActionBar mActionBar = getActionBar(); // GETTING ACTIONBAR
            //final Button testbutn = (Button) findViewById(R.id.testbtn);  // GETTING BUTTON

            if (color.equals("red")) {
                mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFBA1E1E));  // CHANGES ACTION BAR COLOR
               // testbutn.setBackgroundColor(0xFFFF6666);
                // CHANGES BUTTON COLOR

            } else if (color.equals("blue")) {
                mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF21a4dd));  // CHANGES ACTION BAR COLOR
              //  testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR

            }

            else if (color.equals("yellow")) {
                mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFF6D72B));  // CHANGES ACTION BAR COLOR
              //  testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR

            }

                mActionBar.setDisplayShowTitleEnabled(false); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR
                mActionBar.setDisplayShowTitleEnabled(true); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR

     }

    GAS FURNANCE ACTIVITY

       Button btnnext = (Button)findViewById(R.id.nextbtn);
       btnnext.setOnClickListener((OnClickListener) this);
       }

        public void onClick(View v) {
            // TODO Auto-generated method stub
            //Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
            //Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
            switch(v.getId())
            {
            case R.id.nextbtn:

                 Intent a = new Intent(getApplicationContext(), MainActivity.class);
                 startActivity(a);
                 break;

                default:

            }

        }

 package com.example.gasfurnancediagnostics;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ThemeActivity extends Activity implements  ColorPicker.OnColorChangedListener {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_theme);
 Button blueBtn = (Button) findViewById(R.id.bluebtn);

blueBtn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    //***** PERSISTANCE STORAGE INITIALIZATION****/
      SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors",  0);

      // **** PERSISTANCE STORAGE EDITOR *** /
      SharedPreferences.Editor editor = pref.edit();

      editor.putString("color", "blue");

      //**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
      editor.putInt("color_set", 1);

      //*** COMMITING ALL THE DETAILS TO THE STORAGE...
      //** NOTE WITHOUT THIS THE DATA WONT BE SAVED
      editor.commit();
      Intent e = new Intent(getApplicationContext(), MainActivity.class);
      startActivity(e);

  }
 });

 Button redBtn = (Button) findViewById(R.id.redbtn);

 redBtn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {

    //***** PERSISTANCE STORAGE INITIALIZATION****/
      SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);

      // **** PERSISTANCE STORAGE EDITOR *** /
      SharedPreferences.Editor editor = pref.edit();

      editor.putString("color", "red");

      //**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
      editor.putInt("color_set", 1);

      //*** COMMITING ALL THE DETAILS TO THE STORAGE...
      //** NOTE WITHOUT THIS THE DATA WONT BE SAVED
      editor.commit();
      Intent e = new Intent(getApplicationContext(), MainActivity.class);
      startActivity(e);

  }
 });

 Button yellowBtn = (Button) findViewById(R.id.yellowbtn);

yellowBtn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    //***** PERSISTANCE STORAGE INITIALIZATION****/
      SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);

      // **** PERSISTANCE STORAGE EDITOR *** /
      SharedPreferences.Editor editor = pref.edit();

      editor.putString("color", "yellow");

      //**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
      editor.putInt("color_set", 1);

      //*** COMMITING ALL THE DETAILS TO THE STORAGE...
      //** NOTE WITHOUT THIS THE DATA WONT BE SAVED
      editor.commit();
      Intent e = new Intent(getApplicationContext(), MainActivity.class);
      startActivity(e);

  }
 });

}

@Override
public void colorChanged(String key, int color) {
// TODO Auto-generated method stub

}

}

A: SharedPreferences is what you are looking for,add this piece of code in your very first activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
  Boolean firstRun = preferences.getString("FirstRun",true);

  if(true)
  {
    /*Open your activity here which you want to open for only once*/
     SharedPreferences.Editor editor = preferences.edit();
     editor.putBoolean("FirstRun",false);
     editor.apply();
  }
  else
  {
   /*Open your activity which you want to open later,generally*/
   }

See this for detailed explaination and this


text:
Q: Best way to read and process a large data files >0.5GB in C I need to write code in C which could read large csv files containing large matrix of data with double values. I have to read column by column and I have no prior information about the number of rows and columns in the file.
What is the most efficient way to process it in C language - in terms of both time and memory? I basically need to process each column separately but can do with reading row wise if it is more efficient to read.
Please direct me to the answer if it has been asked before.
Thanks

A: A csv file is a text file. Usually, each row is separated by end-of-line characters and commas separate the columns. You have to scan each line to identify columns.
There are lots of ways to solve this. Your solution really depends on the routines you are comfortable using.
I would allocate as big a buffer as you can afford using malloc(), read the csv file in in chunks using fread(), and scan through it to find and process the columns.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>

// JFL 11 Feb 15
int main(int argc,char *argv[])
{
   int r;
   int allocsize,filesize,len;
   char *fname;
   char *alloc=0;
   FILE *fh=0;

   if(argc<2)
      goto BAIL;
   fname=argv[1];

   // open file, find size
   if(!(fh=fopen(fname,"rb")))
      goto BAIL;
   fseek(fh,0,SEEK_END); // seek to end
   if((filesize=ftell(fh))<0)
      goto BAIL;
   fseek(fh,0,SEEK_SET);

   // alloc buffer
   allocsize=16*1024; // max buffer size
   if(allocsize>filesize)
      allocsize=filesize; // limit to filesize

   // 'search' for the largest buffer we can use temporarily
   for(;allocsize>1024;allocsize-=1024)
   {
      if((alloc=malloc(allocsize)))
         break; // allocated
   } // for

   if(!alloc)
   { // try once more, small buffer
      allocsize=1024;
      if(!(alloc=malloc(allocsize)))
         goto BAIL;
   }

   // read the file
   for(;filesize;)
   {
      len=filesize; // remaining size
      if(len>allocsize)
         len=allocsize; // limit to buffer size
      if(len!=fread(alloc,1,len,fh)) // read
         goto BAIL;
      filesize-=len; // adjust remaining size

      // process len bytes
   } // for

   r=ftell(fh);

   printf("success, read %d bytes\n",r);
BAIL: // common exit point
   if(fh)
      fclose(fh); // close if opened
   if(alloc)
      free(alloc); // free if allocated
   return 0;
} // main()

A: As csv is row-based (line-based) and you need to process columns, the best way would be to take the whole file in memory: ask the filesize and allocagte that chunk of memory with malloc. Read the first line and determine the number of columns, 'numcols'. Now reprocess the file and allocate for each line an array with 'numcols' entries that will point to the start of the column in the line (as each number can have a different number of digits, you may not assume all columns start at the same offset in the line). Now you are ready to process your columns.
If the file does not fit in memory, you can open 'numcols' additional output files into which you write the columns from the lines of the input (e.g. you write doubles in binary format to the files), then rewind them and process each file, which holds a column. If these output files fit in memory, you can read them in into an array. (I didn't say this is efficient.)


text:
Q: How do I get configuration parameters in Chi middleware? I have a middleware in my web app written with Chi in Golang.
I am creating a cookie with user ID and encrypt it using an app secret (that is not the exact process, the thing that I want to point out is that the middleware uses an App secret that is set in the app config via env variables).
How do I access that app config vars in the middleware?


text:
Q: If $\sum a_n$ converges and $b_n=\sum\limits_{k=n}^{\infty}a_k $, prove that $\sum \frac{a_n}{b_n}$ diverges
Let $\displaystyle \sum a_n$ be  convergent series of positive terms and set  $\displaystyle b_n=\sum_{k=n}^{\infty}a_k$ , then prove that $\displaystyle\sum \frac{a_n}{b_n}$ diverges.

I could see that $\{b_n\}$ is monotonically decreasing sequence converging to $0$ and I can write $\displaystyle\sum \frac{a_n}{b_n}=\sum\frac{b_n-b_{n+1}}{b_n}$, how shall I proceed further?

A: Assuming $\sum a_n=L$, for any $n$ big enough we must have:
$$a_n \geq \frac{1}{n}\sum_{m>n}a_m,\tag{1}$$
otherwise, assuming that $N$ is the greatest integer for which $(1)$ holds, we have:
$$L< a_N+\frac{1}{N}(L-a_n)+\frac{N-1}{(N+1)N}(L-a_n)+\ldots = L,\tag{2}$$
contradiction. This implies that for any $n\geq M$
$$\left(1+\frac{1}{n}\right)a_n\geq\frac{1}{n}b_n\tag{3}$$
holds, hence:
$$\sum_{n\geq M}\frac{a_n}{b_n}\geq\sum_{n\geq M}\frac{1}{n+1},\tag{4}$$
but the RHS of $(4)$ diverges.

A: First note that $\{b_n\}_{n\in\mathbb N}$ is a decreasing sequence of positive numbers, which tends to zero.
We have that, for $n> m$
$$
\frac{a_m}{b_m}+\cdots+\frac{a_n}{b_n}\ge
\frac{a_m}{b_m}+\cdots+\frac{a_n}{b_m}=\frac{1}{b_m}(a_m+\cdots+a_n)=\frac{b_n-b_m}{b_m}=1-\frac{b_n}{b_m}.
$$
Next, as $b_n\searrow 0$, choose $m_1,m_2,\ldots,m_k,\ldots$, so that
$$
\frac{b_{m_{i+1}}}{b_{m_i}}<1/2.
$$
Then we have that
$$
\sum_{n=1}^{m_k}\frac{a_n}{b_n}\ge\sum_{i=1}^{k-1}\sum_{n=m_i+1}^{m_{i+1}}\frac{a_n}{b_n}\ge
\sum_{i=1}^{k-1}\left(1-\frac{b_{m_i}}{b_{m_{i+1}}}\right)\ge\frac{k-1}{2},
$$
and hence $\displaystyle\sum_{n=1}^{\infty}\frac{a_n}{b_n}=\infty$.

A: For $m>n$ one has
$$\begin{aligned}\frac{a_n}{b_n}+\cdots\frac{a_m}{b_m}&\ge \frac{a_n}{b_n}+\cdots +\frac{a_m}{b_n}\\
&=\frac{b_n-b_{m+1}}{b_n} = 1-\frac{b_{m+1}}{b_n}.
\end{aligned}$$
Can you continue from here?

A: For a sum $\sum_{k=0}^{\infty}c_k$ to converge its tail must converge to 0.
$$
\lim_{n \to \infty} \sum_{k=n}^{\infty}c_k = 0
$$
i.e. for every $\epsilon$ there exist a $n_0$ such that for all $n > n_0$
$$
\left| \sum_{k=n}^{\infty}c_k \right| < \epsilon
$$
We can prove that there exists a $\epsilon$ such that for all $n$ the sum is bigger than $\epsilon$ and thus the sum diverges.
$$
\sum_{k=n}^{\infty}\frac{a_k}{b_k} \geq \frac{1}{b_n}\sum_{k=n}^{\infty}a_k = 1 = \epsilon
$$

A: First answer was wrong. Here is my new try :
If $\underset{n\to+\infty}{\lim} \frac{a_n}{b_n}$ is not $ 0 $ or does not exist,  $\sum \frac{a_n}{b_n}$ is directly divergent.
Otherwise we have $\underset{n\to+\infty}{\lim} \frac{a_n}{b_n} = 0 $ so $b_{n+1} \sim b_n $ . It implies   $\sum \frac{a_n}{b_n} = \sum  \frac{b_n-b_{n+1}}{b_n}$ and  $\sum  \frac{b_n-b_{n+1}}{b_{n+1}}$  have the same behavior thanks to limit comparison test.
Now, since $b_n$ is decreasing and tends to $0$ as $n\to+\infty$, we can use an integral comparison :
$$ \sum_{n=1}^N \frac{b_n-b_{n+1}}{b_{n+1}} \ge \sum_{n=1}^N \int_{b_{n+1}}^{b_n} \frac{dx}{x} = \int_{b_{N+1}}^{b_1} \frac{dx}{x} = \ln \left(\frac{b_1}{b_{N+1}}\right) \underset{N\to+\infty}{\longrightarrow}+\infty $$

A: Sorry, my previous answer was not correct. A new tentative:
$$\frac{b_{k+1}}{b_{k}}=1-\frac{a_k}{b_k}$$
 Hence
 $$\frac{b_{N+1}}{b_1}=\prod_{k=1}^N{(1-\frac{a_k}{b_k}})$$ and
$$\log b_{N+1}-\log b_1=\sum_{k=1}^N \log(1-\frac{a_k}{b_k})$$
Now if the series $a_k/b_k$ is convergent, we have $a_k/b_k \to 0$, and as $\log(1-x)\sim -x$ and the series have constant sign, this imply that the series $\displaystyle \log (1-\frac{a_k}{b_k})$ is convergent, a contradiction as $\log (b_{N+1}) \to -\infty$.

A: Preliminary
For $x\ge0$,
$$
\log\left(\frac1{1-x}\right)=\int_0^x\frac{\mathrm{d}t}{1-t}\le\frac{x}{1-x}\tag1
$$
therefore,
$$
\frac{\mathrm{d}}{\mathrm{d}x}\frac{\log\left(\frac1{1-x}\right)}x=\frac{\frac{x}{1-x}-\log\left(\frac1{1-x}\right)}{x^2}\ge0\tag2
$$
thus, $\frac{\log\left(\frac1{1-x}\right)}{x}$ is increasing on $(0,1)$. Thus, for $0\lt x\le\frac12$,
$$
\frac{\log\left(\frac1{1-x}\right)}{x}\le2\log(2)\tag3
$$

Application
Let $u_k=\frac{a_k}{b_k}$ and note that $\frac1{1-u_k}=\frac{b_k}{b_{k+1}}$. Assume the sum converges. Then for $k\ge m$, $u_k\le\frac12$, and then
$$
\begin{align}
\sum_{k=m}^n\frac{a_k}{b_k}
&=\sum_{k=m}^nu_k\\
&\ge\frac1{2\log(2)}\sum_{k=m}^n\log\left(\frac1{1-u_k}\right)\\
&=\frac1{2\log(2)}\sum_{k=m}^n\log\left(\frac{b_k}{b_{k+1}}\right)\\
&=\frac1{2\log(2)}\frac{b_m}{b_{n+1}}\tag4
\end{align}
$$
but the right side diverges since $\lim\limits_{n\to\infty}b_{n+1}=0$. Therefore, $\sum\limits_{k=1}^\infty\frac{a_k}{b_k}$ diverges.


text:
Q: ReactJs state inside of nested function is not being updated, but it is updated outside(in fucntional component) I'm trying to send get requests at certain interval using setInterval. So my script looks like that:
const [package_id, setPackageId] = useState({id: 1, result: NaN})

async function get_images(detail_id){
    axios.get('http://127.0.0.1:8000/get_images', {params: {detail_id}, headers:{
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': '0',
      }}).then((res) =>{

        ... // some processing

        setPackageId(prevstate => {return {...prevstate, id :prevstate.id + 1}})

    }
    ).catch(errs => {
        console.log(errs)
    })
}
useEffect(() => {
    const request_interval = setInterval(get_images, 2000, package_id.id)
    return () => clearInterval(request_interval);
}, [])

Even though state package_id.id is being updated(I checked using useEffect). In get_images function, it's value is always the same. How can I use updated value of state?
PS: I also tried to access state inside of function(without passing argument (detail_id)), but it didn't work either.
Any help would be appreciated.

A: I think you want to pass package_id.id through setInterval
But you didn't add package_id.id as a dependency in the useEffect
so you're passing the same id every time
because the effect here doesn't listen to the id updates
But if you add package_id.id as a dependency
the effect will keep listening for id updates and the effect will keep getting triggered
So you can try this
I hope this will help you
const [package_id, setPackageId] = useState({id: 1, result: NaN})

const get_images = useCallback(async () =>{
    axios.get('http://127.0.0.1:8000/get_images', {params: {package_id.id}, headers:{
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': '0',
    }}).then((res) =>{
        ... // some processing
        setPackageId(prevstate => ({...prevstate, id :prevstate.id + 1}))

    }).catch(errs => {
        console.log(errs)
    })
}, [package_id])
useEffect(() => {
    const request_interval = setInterval(get_images, 2000)
    return () => clearInterval(request_interval);
}, [get_images])


text:
Q: Does Samba 4 actually respect Unix file acls? After researching the subject on the internet I drew a conclusion that Samba should take into account Unix file acls. During my tests I found the opposite. Only Unix file mode bits are respected, and file acls are ignored. If my initial assumption is correct and Samba do respect Unix file acls, then I am doing something wrong. Please see the setup below and point to what I am doing wrong.
Distribution and Samba version in use: Centos Linux 7; Samba 4.1.1
##### Server

# Create Linux users
useradd alice
useradd bob

# Create a directory to be shared; set ro permissions for alice using \
# file mode bits and rw permissions for bob using file acls
mkdir /home/smbshare
chown alice:alice /home/smbshare
chmod 0500 /home/smbshare
setfacl -m u:bob:rwx /home/smbshare
setfacl -m m:rwx /home/smbshare

# Create a file for testing purposes
echo 'Hello world!' > /home/smbshare/test.txt

# Add users to Samba database
pdbedit -a -u alice
pdbedit -a -u bob

# Define share in smb.conf and restart the smb daemon
vim /etc/samba/smb.conf
    comment = smbshare for alice(ro) and bob(rw)
    path = /home/smbshare
    browseable = yes
    writeable = yes
    valid users = alice bob

systemctl reload smb

# Set the SELinux permissions and open samba on firewall
chcon -R -t samba_share_t /home/smbshare

firewall-cmd --add-service=samba --permanent
firewall-cmd --reload

##### Client

# Create Linux users
useradd alice
useradd bob

# Mount the remote Samba share
mkdir /mnt/smbshare
mount -t cifs -o username=alice,password=pass //192.168.1.112/smbshare /mnt/smbshare

# Now test the permissions
su - alice
cd /mnt/smbshare
cat test.txt        # shows the contents of test.txt, as expected
echo 'I am alice' > test2.txt   # permission denied, as expected
exit

su - bob
cd /mnt/smbshare    # permission denied -- ???? NOT AS EXPECTED
exit

# I think it doesn't matter under which user to mount, but just to be sure \
# I tried to mount using bob's credentials
umount /mnt/smbshare
mount -t cifs -o username=bob,password=pass //192.168.1.112/smbshare /mnt/smbshare

# After checking file permissions I got the same results as above: \
# alice have read-only permissions (as expected), bob have no access (NOT as expected)


text:
Q: How to make scrollable UIView without using UIScrollView? Is there any way to make a normal UIView scrollable without using UIScrollView?

A: You could, by overriding -touchesBegan:withEvent: and associate methods, but you'd have to implement an equivalent to contentOffset, contentSize, and probably have some sort of contentView which moves within your own scroll view. You'd also have to implement all of the momentum physics, which would potentially be very time consuming. Then you've got all of the interaction between gestures and scrolling (e.g. some touch events are "cancelled" if you hold your finger down then start scrolling, this is all handled for you automatically by the built-in UIKit classes).
It's certainly possible, but it'd be a hell of a lot of work, so unless you had a really, really good reason to build your own there's no point.

A: It might help to state what you're trying to achieve, because probably you can do it with UIScrollView and also implementing the UIScrollViewDelegate. I have done some very fancy things with scroll views quite easily just by implementing the delegate and putting my additional code in there.


text:
Q: What harm can DBO do to a server? Aside from executing XP_CmdShell, which I have disabled in my SQL 2005 installation, what could a malicious user who gains DBO rights to my database do:

*

*To my database,

*To my server?

I'm assessing the worst-case security risk of someone obtaining DBO to justify running a "least-privileged" user account in an application. Some allege that since we're not working with "confidential data" that the impact of someone gaining DBO is minimal.

A: he can run any XP_ sproc so it can mess up the registry and mess up your whole server for one thing.
drop/change tables, etc...

A: dbo is Database Owner - which may or may not be sa. As dbo, you basically have free reign over the owned database - obviously, this could lead to changed permissions, dropped tables, etc.
As sa, you have free reign over the server. This includes installing new extended procedures (or .NET assemblies if you have CLR enabled), as well as everything dbo can do (for all databases). And, you can also enable xp_cmdshell again.

A: Lots of info online about SQL injection. Limiting the privs of the user you connect to SQL with is one very important defesse.
http://en.wikipedia.org/wiki/SQL_injection
Here's a simple, frightening example I ran into a couple of years ago. Website generates SQL stateemnts on the fly using URLs and runs them. I was able to guess that URLs like
www.blah.com/.../load.aspx?itemid=1
produced SQL like this
SELECT * FROM items where id=1
so I sent this url:
www.blah.com/.../load.aspx?itemid=1;drop table items
bang.
At the very least, if the DB connection was not dbo this would have failed.

A: To put it bluntly, if he owns your database, he pwns your database. That is to say, you can kiss your data good-bye.

A:
That is to say, you can kiss your data good-bye.

But you have backups on disk and on tape, so you are golden!

A: Yeah. The typical defense is "well, at least he can't mess up anything outside of his database" (xp_CmdShell is not enabled). Me, I'm not comfortable having a mad-dog rapist in a locked closet in my house. But that analogy isn't a great sell to management.


text:
Q: I'm getting a Server Error Error: Element type is invalid I am getting this message on my localhost Error:
Element type is invalid: expected a string (for built-in components) or
a class/function (for composite components) but got: object. You likely
forgot to export your component from the file it's defined in, or you
might have mixed up default and named imports. '

I have cancelled out all my pages on my VS Code and just have index.js and _app.js active. When I delete the components on my index.js file I still get the same message, can anyone help on how to troubleshoot this error?
Troubleshooting my error message on localhost:
import Footer from "../components/footer";
import Image from "next/image";
import lightningbolt from "../public/lightningbolt.svg";
import lowcost from "../public/lowcost.svg";
import globe from "../public/globe.svg";
import peoplePic from "../public/people.svg";
import peopleMobPic from "../public/peopleMobile.svg";
import Tooltip from "../components/Tooltip";
import pipesMob from "../public/pipesMob.svg";
import pipes from "../public/pipes.svg";
import Link from "next/link";

export default function Home() {
  return (

            <Navbar />

                          Connecting the world through{" "}

                            <Image
                              class=" lg:h-14  max-md:w-auto "
                              src={lightningbolt}
                              alt=""
                            />{" "}
                            instant
                            <Image
                              className="relative lg:h-14  max-md:w-auto "
                              src={lowcost}
                              alt=""
                            />
                            low cost{" "}

                            <Image
                              className="relative lg:h-14 max-md:w-auto"
                              src={globe}
                              alt=""
                            />

                          <Image
                            class="lg:absolute top-40  right-0 max-md:hidden max-lg:hidden  md:w-5/12 lg:w-5/12 xl:w-6+/12"
                            src={peoplePic}
                            alt=""
                          />
                          <Image
                            class="max-md:block max-md:mx-auto max-2xl:hidden 2xl:hidden xl:hidden lg:hidden md:hidden"
                            src={peopleMobPic}
                            alt=""
                          />

                            {" "}
                            {" "}
                            <Tooltip description="">
                              Lightning Network,
                            </Tooltip>

                            {" "}
                            {" "}
                            <Tooltip description="">

                            </Tooltip>

                        <Image className="absolute " src={pipesMob} alt="" />

Wallet Users

                            <Link href="/about">Learn more</Link>

Businesses

Contact Us

Lightning Node Operators

                            {" "}

Node Questions

                        <Image
                          className="absolute left-0 w-full max-w-full h-auto max-md:hidden max-lg:hidden"
                          src={pipes}
                          alt=""
                        />

  );
}

import "../styles/global.css";
import Head from "next/head";
import Layout from "../components/layout";

  <meta charset="UTF-8" />
  <meta name="keywords" content="titla, meta, nextjs" />
  <meta name="author" content="Syamlal CM" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
;

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}
```

A: As stated in my comment, putting the Head component in the correct position should fix the issue.
import "../styles/global.css";
import Head from "next/head";
import Layout from "../components/layout";

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>

        <meta charset="UTF-8" />
        <meta name="keywords" content="titla, meta, nextjs" />
        <meta name="author" content="Syamlal CM" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      <Component {...pageProps} />
    </Layout>
  );
}


text:
Q: Can't access css files in my public folder - laravel 6.2 I know this question has been asked many times but unfortunately i can't seem to get this working. I have my assets in public/vendor/ and public/css/ . When i upload files on my live server, it works perfectly. All assets in the public folders are accessed but not on localhost , i keep getting 404 errors (file not found)
Login.blade.php
  <link rel="stylesheet" href="<?php echo asset('public/vendor/bootstrap/css/bootstrap.min.css') ?>" type="text/css">
<link rel="stylesheet" href="<?php echo asset('public/vendor/bootstrap/css/bootstrap-datepicker.min.css') ?>" type="text/css">
<link rel="stylesheet" href="<?php echo asset('public/vendor/bootstrap/css/bootstrap-select.min.css') ?>" type="text/css">

I have my index.php in my public folder
index.php
require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

htaccess
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ ^$1 [N]

    RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
    RewriteRule ^(.*)$ public/$1

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ server.php

</IfModule>

A: remove public from here asset() function directly target public dir
<link rel="stylesheet" href="<?php echo asset('vendor/bootstrap/css/bootstrap.min.css') ?>" type="text/css">
<link rel="stylesheet" href="<?php echo asset('vendor/bootstrap/css/bootstrap-datepicker.min.css') ?>" type="text/css">
<link rel="stylesheet" href="<?php echo asset('vendor/bootstrap/css/bootstrap-select.min.css') ?>" type="text/css">

and as your using laravel don't use <?php echo ?> it is in {{ }} in laravel
<link rel="stylesheet" href="{{ asset('vendor/bootstrap/css/bootstrap.min.css') }}" type="text/css">
<link rel="stylesheet" href="{{ asset('vendor/bootstrap/css/bootstrap-datepicker.min.css') }}" type="text/css">
<link rel="stylesheet" href="{{ asset('vendor/bootstrap/css/bootstrap-select.min.css') }}" type="text/css">

ref link https://laravel.com/docs/8.x/helpers#method-asset


text:
Q: important files are not in list , all some files go in untract files list? I am using a Git Repository to manage my project,
Now when i try to commit i see there are some impoertant file like content/image , scripts , etc files in untrack files
Why?
Is there any way to resolve this?
Regards,
vinit

A: If your Git repo has been initialized on GitHub (and then cloned), it is likely to come with a .gitignore (as well as a README.md, and even a LICENSE file).
Check if those files aren't ignored by the rules in the .gitignore.
You can do that with:
git check-ignore -v scripts

You can edit that file to remove the rules you don't want, then a git add . will add:

*

*the modified .gitignore files

*the files that were previously ignored.

A: You have to use "git add [wildcard or directory or file(s)]" first to add your files to the versioning system GIT. Manual page is here: https://www.kernel.org/pub/software/scm/git/docs/git-add.html
And the git book is worth a read.
Also I liked gitready very much.
Happy coding


text:
Q: CSS background image in flex container I need to put a background image to a text. I suspect it could be because we nested too many classes in "div" but still can't figure it out.
CSS:
.box {
  display: flex;
  top: 80px;
  position: relative;
  padding-top: 30px;
  border-top: thin solid black;
  border-bottom: thin solid black;
  border-right: thin solid black;
  border-left: thin solid black;
}

.box1 {
  padding-left: 300px;
  padding-right: 30px;
  width: 630px;
  flex-direction: column;
  align-self: flex-start;
}

.smalltitle2 {
  border-bottom: medium solid black;
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/freelance-1/unit-4/img-news-bite.png");
  background-repeat: no-repeat;
}

HTML:

Mother of Three Buys Tuna Steak at Phish Concert. Leaves, "Feeling Funny."

A: You can either try background-size: contain; or background-size: cover; etc.
There is no problem with the CSS, it's just missing a rule to define the size of your background image.
See demo here : https://jsfiddle.net/v8eLsef4/1/

A: Add a width and height to your smalltitle2 container and you can tweak around how you want to make it look whether it should be part of the image, or do you want the entire image inside the container (make use of background-size).

.box {
  display: flex;
  top: 80px;
  position: relative;
  padding-top: 30px;
  border-top: thin solid black;
  border-bottom: thin solid black;
  border-right: thin solid black;
  border-left: thin solid black;
}

.box1 {
  padding-left: 300px;
  padding-right: 30px;
  width: 630px;
  flex-direction: column;
  align-self: flex-start;
}

.smalltitle2 {
  border-bottom: medium solid black;
  background:url(https://s3.amazonaws.com/codecademy-content/courses/freelance-1/unit-4/img-news-bite.png);
  background-repeat: no-repeat;
  background-size: contain;
  width:100%;
  height:100px;
}

Mother of Three Buys Tuna Steak at Phish Concert. Leaves, "Feeling Funny."


text:
Q: H2 Database issue : Column interpretation with CSVREAD and convert function I am currently using h2 version 1.4.196. I have a CSV file as follows,
Status,message,code
1,hello,13
2,world,14
3,ciao,26

Following query works as expected & returns proper Status values.
select "Status" from  CSVREAD('myfile.csv',
'Status,message,code', null) ;

Following query produces an exception. It seems like the literal string "Status" is being passed to convert instead of the values returned by the
execution of the query. I am not sure if my understanding of convert is
correct. Please help me with fixing this query to return the desired result. Thanks in advance.
select convert("Status", int) from  CSVREAD('myfile.csv', 'Status,message,code', null) ;

Caused by: java.lang.NumberFormatException: For input string: "Status"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at org.h2.value.Value.convertTo(Value.java:940)

----------------------Detailed Exception------------------------------
select convert("Status", int) from  CSVREAD('myfile.csv',
'Status,message,code', null) ;
Data conversion error converting "Status"; SQL statement:
select convert("Status", int) from  CSVREAD('myfile.csv',
'Status,message,code', null) [22018-196] 22018/22018 (Help)
org.h2.jdbc.JdbcSQLException: Data conversion error converting "Status"; SQL statement:
select convert("Status", int) from  CSVREAD('myfile.csv',
'Status,message,code', null) [22018-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:168)
    at org.h2.value.Value.convertTo(Value.java:996)
    at org.h2.expression.Function.getSimpleValue(Function.java:945)
    at org.h2.expression.Function.getValueWithArgs(Function.java:1196)
    at org.h2.expression.Function.getValue(Function.java:591)
    at org.h2.command.dml.Select$LazyResultQueryFlat.fetchNextRow(Select.java:1459)
    at org.h2.result.LazyResult.hasNext(LazyResult.java:79)
    at org.h2.result.LazyResult.next(LazyResult.java:59)
    at org.h2.command.dml.Select.queryFlat(Select.java:519)
    at org.h2.command.dml.Select.queryWithoutCache(Select.java:625)
    at org.h2.command.dml.Query.queryWithoutCacheLazyCheck(Query.java:114)
    at org.h2.command.dml.Query.query(Query.java:371)
    at org.h2.command.dml.Query.query(Query.java:333)
    at org.h2.command.CommandContainer.query(CommandContainer.java:113)
    at org.h2.command.Command.executeQuery(Command.java:201)
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:186)
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:164)
    at org.h2.server.web.WebApp.getResult(WebApp.java:1380)
    at org.h2.server.web.WebApp.query(WebApp.java:1053)
    at org.h2.server.web.WebApp$1.next(WebApp.java:1015)
    at org.h2.server.web.WebApp$1.next(WebApp.java:1002)
    at org.h2.server.web.WebThread.process(WebThread.java:164)
    at org.h2.server.web.WebThread.run(WebThread.java:89)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NumberFormatException: For input string: "Status"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at org.h2.value.Value.convertTo(Value.java:940)
    ... 22 more

A: The way you're using it you're defining the columns and reading all the rows from the csv, so you're getting the first row with Status as well. Then you try to convert the string Status to an integer which obviously results in exeption.
Instead you shouldn't define the columns but let h2 get them from the first row of the csv:
select convert(status,int) from CSVREAD('myfile.csv');


text:
Q: Why Won't Exported Blog From One Site Import Into New Site? I have an old RHEL Workstation site, running the latest wordpress version 3.5.1.
I have a newer CentOS 6.4 site, running the latest wordpess version 3.5.1.
I have added the Wordpress import plugin tool into the new site successfully.
I have exported the entire blog from the older wordpress site successfully.
I have attempted to import the resulting xml file, but it appears not to succeed, but without any errors or explanation.
The import appears to start successfully after pressing the button for uploading and importing, after the .xml file is selected, and I see some activity. However, the Import page goes blank, and there are no errors or any other kind of message.
The blog is still usable; that is nothing has frozen.
What do I need to do to import properly?

A: A lot of people (including myself) have experienced random issues like you describe with this latest version of the WordPress Importer plugin.
I recommend using WP Migrate DB.  This plugin will not only migrate your content, but allow you to optionally find/replace any serialized URLs (in the event you're migrating to a different domain as well).

A: Here is what I did to fix the problem.
I looked at an export of the old blog after wordpress, php, and apache had all been upgraded.
I looked at an export of the mostly blank new blog (on the recently installed CentOS 6.4 system).
I made the title and other fields look the same for the first few lines in the xml file to be imported from the older blog.
Most of the XML required no editing.
Everything updated just fine after that.

A: The same problem was here with me on my website i tried lot a lot of plugings but but at the end i used Jetpact Sitemap. This is working great and also supports the Google News as well sitemap.xml file.


text:
Q: Combining JSON_SEARCH and JSON_EXTRACT get me: "Invalid JSON path expression." I have a table names "campaigns". One of the columns is named "filter_apps" and his type is JSON
I have file rows and they just contain array of tokens like so:
["be3beb1fe916ee653ab825fd8fe022", "c130b917983c719495042e31306ffb"]
["4fef3f1999c78cf987960492da4d2a"]
["106c274e319bdeae8bcf8daf515b1f"]
["2521f0df6cffb7487d527319674cf3"]
["c130b917983c719495042e31306ffb"]

Examples:
SELECT JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb') FROM campaigns;

Result:
"$[1]"
null
null
null
"$[0]"

Right now everything is correct, the matched columns come back. If I make a test I can prove it:
SELECT JSON_EXTRACT(filter_apps, '$[1]') FROM campaigns;

Result
"c130b917983c719495042e31306ffb"
null
null
null
null

So at this point I think I can extract the values using JSON_EXTRACT, my query:
SELECT JSON_EXTRACT(filter_apps, JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb')) FROM campaigns;

That leads me to an error:
"[42000][3143] Invalid JSON path expression. The error is around character position 1."

A:
SOLUTION

Simple as that:
SELECT JSON_EXTRACT(filter_apps, JSON_UNQUOTE(JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb'))) FROM campaigns;

Problem resolved! I wrap JSON_SEARCH in a JSON_UNQUOTE method!
A little tip, I found the solution here: https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

A: It took me hours, as my JSON object is way more complex, but I found the solution for the 'all' option.
SELECT *,
    REPLACE(REPLACE(LTRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(filter_apps, ',', n), ',', -1)), '[', ''), ']', '') AS all_json
FROM (
    SELECT *, JSON_EXTRACT(filter_apps, JSON_UNQUOTE(JSON_SEARCH(filter_apps, 'all', 'c130b917983c719495042e31306ffb'))) AS hit
    FROM campaigns
) AS t
JOIN (SELECT  @N := @N +1 AS n FROM campaigns, (SELECT @N:=0) dum LIMIT 10) numbers
      ON CHAR_LENGTH(filter_apps) - CHAR_LENGTH(REPLACE(filter_apps, ',', '')) >= n - 1
WHERE hit IS NOT NULL;

# for the "JOIN-FROM" use a table that has more or equal entries than the length of your longest JSON array
# make sure the "JOIN-LIMIT" is higher or equal than the length of your longest JSON array

Query Explanation:

*

*Inner SELECT:
Main Select as asked in question with JSON_SEARCH Option 'all'

*JOIN:
a) SELECT table 'numbers':
create a table which contains the numbers from 1 to user defined LIMIT.
compare SQL SELECT to get the first N positive integers
b) JOIN ON combined with Outer SELECT SUBSTRING_INDEX:
splits the defined array column 'filter_apps' to the number of element of the array. Note user defined limit of 2)a) must be equal or greater than the longest array to split. compare SQL split values to multiple rows

*REPLACE and LTRIM of Outer SELECT:
used to remove remaining brackets and spaces of previous array

*WHERE clause:
to show only matching results of Inner SELECT


text:
Q: How should I create objecs inside a loop whithout wasting memory? I have done a test Java program to see how Java behave when "new" is used inside a loop, and my results are really bad. This is the program:
package test;

public class Test {
    static int objectCount = 0;

    public static int getObjectCount() {
        return objectCount;
    }

    public Test() {
        objectCount++;
    }

    public void finalize() {
        objectCount--;
    }

    public static void main(String[] args) {
        int maxObjects = 0;
        long maxMemory = 0;
        long maxUsedMemory = 0;
        long maxFreeMemory = 0;
        long memory = 0;
        long usedMemory = 0;
        long freeMemory = 0;

        final long t0 = System.currentTimeMillis();
        Test test = null;
        for (int i=0; i<10000000; i++) {
            System.gc();
            test = new Test();

            memory = Runtime.getRuntime().totalMemory();
            freeMemory = Runtime.getRuntime().freeMemory();
            usedMemory = memory - freeMemory;

            if (maxMemory < memory) maxMemory = memory;
            if (maxFreeMemory < freeMemory) maxFreeMemory = freeMemory;
            if (maxUsedMemory < usedMemory) maxUsedMemory = usedMemory;

            if (maxObjects < getObjectCount()) maxObjects = getObjectCount();
        }
        final long t1 = System.currentTimeMillis();

        System.out.println(
            "Maximum number of objects simultaneously allocated: "+ maxObjects);
        System.out.println("Max memory: " + maxMemory/1024/1024 + "MB");
        System.out.println("Max used memory: " + maxUsedMemory/1024/1024 +"MB");
        System.out.println("Max free memory: " + maxFreeMemory/1024/1024 +"MB");
        System.out.println("Total Time: " + (t1 - t0)/60 + " secconds");
    }
}

Test 1: "System.gc(); and test = new Test();" commented:
Maximum number of objects simultaneously allocated: 0
Max memory: 123MB
Max used memory: 0MB
Max free memory: 122MB
Total Time: 17 secconds

Test 2: "System.gc();" commented:
Maximum number of objects simultaneously allocated: 8196834
Max memory: 696MB
Max used memory: 485MB
Max free memory: 343MB
Total Time: 163 secconds

Test 3: nothing commented, total iterations lowered to 10000 (from 10000000):
Maximum number of objects simultaneously allocated: 6
Max memory: 123MB
Max used memory: 0MB
Max free memory: 122MB
Total Time: 974 secconds

I believe this is awfull, so, how this should be addresed? Is there any way to prevent this?
UPDATE:
Test 2 whith -Xmx64M:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at test.Test.main(test.java:31)

Same result with 128MB.
Test 2 whith -Xmx256M:
(working...) (More than 21 minutes...)

A: If you create an Object, then some space is allocated.
If you create 1000 Objects, then 1000 * x space is allocated.
There is no way to minimize the space of an Object, the solution is to create less Objects or wait for the Garbage Collection.

A: EDIT Taking out all the code which just makes the JITs job harder and running with verbose:gc -Xmx8m the following program
public class Test {
    public static void main(String[] args) {
        final long t0 = System.currentTimeMillis();
        for (int i = 0; i < 100 * 10000000; i++) {
            Test test = new Test();
        }
        final long t1 = System.currentTimeMillis();
        System.out.println("Total Time: " + (t1 - t0) / 1000.0 + " secconds");
    }
}

prints
[GC (Allocation Failure)  1535K->424K(7680K), 0.0013697 secs]
[GC (Allocation Failure)  1960K->384K(7680K), 0.0013561 secs]
Total Time: 0.008 secconds

Note: this is 100x the iteration count.

How should I create objecs inside a loop whithout wasting memory?

You are not just wasting memory you are wasting work.  Note: System.gc() is many orders of magnitude more expensive than creating an object.
If you want to optimise you loop, create the object outside the loop.  However, 99% of cases, you don't need to do this and in fact the JIT has Escape Analysis which places the fields of the object on the stack and eliminates the object entirely.
Try running this with -verbose:gc -Xmx32m it creates enough objects to fill the whole heap 1000x and yet
public class EscapeAnalysisMain {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 2_000_000_000; i++) {
            Integer x = i;
            if (x.hashCode() < 0)
                throw new AssertionError();
        }
        System.out.println(i);
    }
}

prints
2000000000

i.e. 2 billion Integer object but not enough garbage to trip even one collection.  How is that possible? The Integer objects were all placed on the stack instead of the heap once the code warmed up so there was no garbage after this (except the last line)


text:
Q: Printing contents of an array in a non-sequential order using threads Having trouble printing the contents of my array in a non synchronized way. I am looking to iterate through and output the letters "A" , "B" , "C" in a non sequential manner from a static array of strings using Threads to print the loop.
Here is my code:
public class ThreadWithExtends extends Thread {

    public ThreadWithExtends() {
        super();
    }

    public void run() {
        String[] arr = { "A", "B", "C" };
        int num = 10;
        try {
            for (int j = 0; j < num; j++) {
                for (int i = 0; i < arr.length; i++) {
                    sleep((int) (Math.random() * 1000));
                    System.out.print(arr[i] + " ");
                }
            }

        } catch (InterruptedException e) {
            System.out.println("Finished");
        }
    }
}

My TestThread class:
public class TestThread {

    public static void main(String args[]) {
        new ThreadWithExtends().start();
    }

}

My Output : A B C A B C A B C A B C A B C A B C A B C A B C A B C A B C
My Desired Output : C A B A B C B A C .. etc , not sequential like above.

A: Actually you aren't executing any code in parallel. You only created one thread that prints some statements sequentially. You need to create three threads that print stuff on their own, like so:
public class Printer extends Thread {
    private String mText;

    public Printer(String text) {
        mText = text;
    }

    @Override
    public void run() {
        int num = 1_000;
        for (int i = 0; i < num; i++) {
            System.out.print(mText + " ");
        }
    }
}

and then
public static void main(String args[]) {
    new Printer("A").start();
    new Printer("B").start();
    new Printer("C").start();
}

Now you have three threads that run in parallel. Prints should be mixed now.

Note that in general you shouldn't care about how the scheduler schedules the threads. It tries to optimize and it works well. It probably has its reasons why it scheduled this or that way. You can assign priorities to threads if you want to tell the scheduler your preferences.


text:
Q: Setting MatrixWorld of camera in threeJS I'm trying to sync the camera orientation of one threejs scene with another by passing the world matrix of the first scene's camera to the second and then using
         camera.matrix.fromArray(cam1array); //cam1array is the flattened worldmatrix of the 1st scene
         camera.updateMatrixWorld( true );

However, when I print camera.matrixWorld for the second scene, it would appear that there has been no update (matrixWorld is the same as before the previous commands). The second scene does use OrbitControls so maybe they are overriding my commands, but I wondered if anyone could advise me on how to achieve the same world matrix for the second scene as the first?
I should also clarify that part of the issue is that it would appear that setting
camera.matrixAutoUpdate = false;
in order to prevent overriding seems to prevent OrbitControls from functioning corrrectly.


text:
Q: Can not obtain a specific td from td_list through find_element_by_class_name or find_element_by_css_selector When obtaining a specific td which is existed from td_list, I can not find it through class_name, and for the td, it only has a class_name and a title.
enter image description here
Here is my code:
td_list = self.driver.find_elements_by_xpath(".//tbody/tr/td")
for td in td_list:

print("what we got")
print(td.find_elements_by_css_selector("[class='day.disabled.offday']"))

    if td.find_elements_by_css_selector("[class='day.disabled.offday']") == []:

    self.driver.refresh()
    break

    else:
    click_date = self.driver.find_elements_by_class_name("day.disabled.offday")
    break

and it keeps refreshing and outputting with:
what we got
[]
what we got
[]
...

How should I change it to obtain the specific td( class name ="day disabled offday")
Great thanks!

A: Did you try the same with this //*[@class='day disabled offday'] XPath ?
td_list = self.driver.find_elements_by_xpath(".//tbody/tr/td")
for td in td_list:

  print("what we got")
  offday_list = td.find_elements_by_xpath(".//*[@class='day disabled offday']")
  print(len(offday_list))


text:
Q: Easiest way to combine date and time strings to single datetime object using Python I have a web form which has 2 input fields, "StartDate" and "StartTime".  I convert the StartDate field's string into a Python datetime object, no problem.  The StartTime field is passed in as a string in the form "0130" for 1:30am.  What is the best way to convert the StartTime string and combine it with the StartDate datetime object so that both are stored as a single datetime?

A: Use datetime.combine:
import datetime as dt
mytime = dt.datetime.strptime('0130','%H%M').time()
mydatetime = dt.datetime.combine(dt.date.today(), mytime)

A: import datetime
def time_tango(date, time):
    return datetime.datetime.combine(date, time)

A: If you can load the time into a datetime.time, you can use the following code
import datetime

dt = datetime.datetime(2012, 2, 12)
tm = datetime.time(1, 30)

combined = dt.combine(dt, tm)

print(combined)

Output
2012-02-12 01:30:00

A: Just a short version:
from datetime import datetime
print datetime.combine(datetime.strptime("5 Mar 12", "%d %b %y"), datetime.strptime("0130","%H%M").time())

Output
2012-03-05 01:30:00


text:
Q: How to make a JAR file that includes DLL files? I bought a third-party Java library which includes a JAR file and two DLL files. I wrote my own Java program which invoke the third-party JAR file. Now my question is how can I package all my code into a single JAR file which include all my code and the third-party JAR and DLLs?
I know SWT is such a case. The swt.jar includes dll files, but I don't know how to do this and how to make it work properly.

A: Just package it anywhere in the jar. One thing you have to keep in mind though - before you can use the DLLs you need to actually extract these from the JAR and dump these on the hard disk somewhere otherwise you won't be able to load these
So basically - I did JNI project for the client where I will use such jar packaged within the war. However - before running any native methods I would get the DLL as a resource and write it to the disc into temp directory. Then I would run regular initialization code where my DLL is set to the same location I just wrote DLL to
Oh, and just in case: there's nothing special about packaging dll or any other file into jar. It's just like packaging stuff into zip
Here's some code I just digged out
public class Foo {
private static final String LIB_BIN = "/lib-bin/";
private final static Log logger = LogFactory.getLog(ACWrapper.class);
private final static String ACWRAPPER = "acwrapper";
private final static String AAMAPI = "aamapi51";
private final static String LIBEAU = "libeay32";

static {
    logger.info("Loading DLL");
    try {
        System.loadLibrary(ACWRAPPER);
        logger.info("DLL is loaded from memory");
    } catch (UnsatisfiedLinkError e) {
        loadFromJar();
    }
}

/**
 * When packaged into JAR extracts DLLs, places these into
 */
private static void loadFromJar() {
    // we need to put both DLLs to temp dir
    String path = "AC_" + new Date().getTime();
    loadLib(path, ACWRAPPER);
    loadLib(path, AAMAPI);
    loadLib(path, LIBEAU);
}

/**
 * Puts library to temp dir and loads to memory
 */
private static void loadLib(String path, String name) {
    name = name + ".dll";
    try {
        // have to use a stream
        InputStream in = ACWrapper.class.getResourceAsStream(LIB_BIN + name);
        // always write to different location
        File fileOut = new File(System.getProperty("java.io.tmpdir") + "/" + path + LIB_BIN + name);
        logger.info("Writing dll to: " + fileOut.getAbsolutePath());
        OutputStream out = FileUtils.openOutputStream(fileOut);
        IOUtils.copy(in, out);
        in.close();
        out.close();
        System.load(fileOut.toString());
    } catch (Exception e) {
        throw new ACCoreException("Failed to load required DLL", e);
    }
}
    // blah-blah - more stuff
}

A: Use http://www.jdotsoft.com/JarClassLoader.php which could load DLLs and JARs from another JAR with unlimited nesting. For example, DLL could be in JAR which is in another root JAR. All DLLs and JARs are loaded like they are in a classpath or library path.


text:
Q: How to download a file from a node server, using a react client, but hiding the filename and the path I have a client/server architecture:
the client is running a reactjs & javascript application;
the server is running a nodejs application with a redis database.

*

*The application start with the client asking the user for his/her email

*then pass the email to the server which activates a two factor authentication sending a code to the user's phone.

*the server send the user's phone a random code

*the user insert the received code into the client and send back to the server

*the server check the code and, if correct, send to the client a list of the user's owned files.

*The client display a list of files (any kind, any extension), each with a connected button.

*when the user push the button, I would like to send to the server just the user's email and the selected file name.

*The server must then build the real path and is then able to retrieve the file and return it to the server which should store it as in any normal download (maybe asking the user in which location it want to store the file)
I'm using Axios on the client and express on the server.
I'm not able to realize this architecture:
If I use an 'a' tag, as suggested in several sites, it seems that the entire download is managed by the client, so I have to put the entire path of the file to download, and I don't want to show it.
Have someone an idea on how to approach and solve the problem?
Thank you
Paolo


text:
Q: Lottie Animation Drawable Renders Incorrectly Inside a Floating Action Button on Android 5 I'm trying to set an LottieDrawable as image drawable for a FloatingActionButton. The problem comes when I try to run the code on an Android 5 device: the animation is not centered within the button as it is in Android >= 6.
Anyone has an answer for this problem or maybe an workaround?
val lottieDrawable = LottieDrawable()

LottieCompositionFactory.fromRawRes(context, R.raw.loading_anim).addListener { lottieComposition ->
     lottieDrawable.composition = lottieComposition
     lottieDrawable.scale = 0.5F
     lottieDrawable.repeatCount = LottieDrawable.INFINITE
     lottieDrawable.playAnimation()
}

floatingActionButton.setImageDrawable(lottieDrawable)

Expected result (Android 6,7,8,9,Q):

Actual Result (Android 5)


text:
Q: Session variable: save an auto increment from a sql field next a insertion I want to save in a session variable on php  an auto increment value field from one SQL table, just next to do the insert on that table. Why it appears empty? What should I do?
Because I check my sql statement on the database and everything is correct, all of that and have values.
$usersetdataregister="INSERT INTO `questionnaire`.`tbluserset`(`UserIDFKPK`, `QuestionSetIDFKPK`) VALUES ('$UserId','0')";

mysql_query($usersetdataregister);

$query_usersetID= "SELECT tbluserset.UserSetIDPK
                   FROM tbluserset
                   INNER JOIN (SELECT US.UserIDFKPK, MAX(US.Timestamp) AS MaxTimestamp
                               FROM tbluserset AS US
                               WHERE US.UserIDFKPK ='$UserId'
                               GROUP BY US.UserIDFKPK) AS USL ON tbluserset.UserIDFKPK = USL.UserIDFKPK AND tbluserset.Timestamp = USL.MaxTimestamp";

 $row_UserSetIDPK = mysql_query($query_usersetID);

 $UserSetID= $row_UserSetIDPK['UserSetIDPK'];
 $_SESSION['UserSetIDPK']= $UserSetID;

Next to do this i want use the value on a query statement and UserSetIDPK appears empty.

A: I think you forgot to start your session.
session_start();
$_SESSIONS['UserSetIDPK'] = $UserSetID;

You should also check what $row_UserSetIDPK is returning. If it's empty then there is something wrong with your query, or he can't find any results in your database.
If it's not empty, you should see if $row_UserSetIDPK['UserSetIDPK'] is the right way to get your value.
to debug try this:
var_dump($row_UserSetIDPK);die();

Hope this helps a bit, 'cause your post is quite a mess! :-)


text:
Q: Copy table and open a new popup window I need some help from the experts here on this site.
What I would like to accomplish is, at the click of a button is to copy the existing table ('data'), open a new popup window and use the document.write to write the table from the previous page onto the new one.
<!DOCTYPE html>

        <meta http-equiv="Content-Language" content="en-ca">

                Fruits
                Vegetables
                Colors
                Quantity
                Price

                Apples
                Carrots
                red
                10
                0.99

                Pears
                Celery
                blue
                24
                1.00

                Mangos
                Broccoli
                green
                12
                1.50

                Oranges
                Cauliflower
                purple
                48
                1.25

        <input type="button" value="test it" />

A: Add onclick function for your button first:
  <input type="button" value="test it" onclick="openWin()" />

In script:
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write(document.getElementById('data').outerHTML);
myWindow.focus();
}
Thats it.
I am not sure outerHTML property compatibility across browsers. Please check once.

A: Here is a working example.
The button needs a click handler:
<input type="button" value="Open popup" onclick="openPopup();" />

The click handler function:
function openPopup() {
  var popup = window.open("", "", "width=640,height=480,resizeable,scrollbars"),
      table = document.getElementById("data");

  popup.document.write(table.outerHTML);
  popup.document.close();
  if (window.focus)
    popup.focus();
}


text:
Q: Every Class extends to class Object but my program gives me error that method print() is not defined for type Object class Aquatic extends Animal {

boolean scale;
Aquatic(long years,float kg, boolean skin){
    super(years,kg);
    scale=skin;
}

public void print() {
    super.print();
    System.out.println(scale);
}

}
public class Animal  {

    long lifespan;
    float weigh;
    Animal(long years,float kg){

        lifespan=years;
        weigh=kg;
    }

    public void print() {
        System.out.println(lifespan);
        System.out.println(weigh);
    }
}

public class AnimalWorld <T extends Animal>{        //scope of Animal and its sub classes

T[] ListOfAnimals;
AnimalWorld(T[] list){
    ListOfAnimals=list;
}

}
public class BoundedWildcardArgumentsDemo {

    static void vitality(AnimalWorld<?> animal) {

            for(Animal a: animal.ListOfAnimals)
                a.print();
            System.out.println();
    }

    static void showSea(AnimalWorld<? super Aquatic> animals) {

        for(Object obj: animals.ListOfAnimals) {
            obj.print(); // This gives error that "method print is undefined for type object
        }
    }

    public static void main(String args[]) {

        Animal unknown=new Animal(40,720);
        Animal u[]= {unknown};

        AnimalWorld<Animal> uList=new AnimalWorld<>(u);
        vitality(uList);
    }

}

Naturally my Animal class should inherit Object class and thus print() should be defined for obj. Even when I added Animal extends Object, I got the same error again.
By my understanding of inheritance obj should be able to acess the print() method. Am I missing something ?

A: You just change the object's type inside the showSea() method of the BoundedWildcardArgumentsDemo class.
You must change the "Object obj" to "Animal obj".
Before:
static void showSea(AnimalWorld<? super Aquatic> animals) {
        for(Object obj: animals.ListOfAnimals) {
            obj.print(); // This gives error that "method print is undefined for type object
        }
}

After:
static void showSea(AnimalWorld<? super Aquatic> animals) {
        for(Animal obj: animals.ListOfAnimals) {
            obj.print(); // This gives error that "method print is undefined for type object
        }
}

The "Object obj" doesn't have the "print" method, so you should have set it as the type of your abstract Parent class, being "Animal".


text:
Q: How to get permission's role with seam I need in my application to get all permissions associated with a specific role with seam ?
I tried with permissionManager.listPermissions but this method gives permissions associated with a specific target and not a specific recipient (role in my case).
Thanks for your help.

A: this is not possible by default in Seam. However, you can extend your permission store to do this. If you are using the JpaPermissionStore (which in most of the cases is true), you can check this link


text:
Q: Specifying preprocessor macros for a cocoapod dependency, without forking it I have an XCode workspace managed by Cocoapod with a few dependencies to external libraries. One of them, MTDates, extends NSDate and NSDateComponents with either prefixed methods, or non-prefixed if a certain preprocessor macro is defined (which is what I want).
There are a few places where I can put the preprocessor macro definition in order to have the compiled library provide the non-prefixed methods, but all seem to be reset as soon as I ask Cocoapod to update the project, which leads me to think that these configs are driven by the pod spec. These include :

*

*The pod's target build settings

*The pod's private .xcconfig file in Cocoapod's Targets Support Files
Changing the pod's spec would require to manage my own version of the library, whereby losing the ability for cocoapods to update it when a new version comes around. So my question is: is there a way to specify a preprocessor macro for a cocoapod dependency, without forking the pod and changing the pod's spec itself?
Edit:
There is an open issue about this, that seem to be just around the corner.

A: as you mentioned 'The pod's private .xcconfig file in Cocoapod's Targets Support Files', i do this resolved my problem.
s.xcconfig = {'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) COCOAPODS=1 IOS=1' }

A: This functionality is now available.  Here is an example of what you could put at the bottom of your Podfile to add a macro based on a specific configuration.
post_install do |installer_representation|
  installer_representation.project.targets.each do |target|
    if target.name == "Pods-TweaksBuildConfigurationsDemo-Tweaks"
      target.build_configurations.each do |config|
        if config.name == 'QA'
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'FB_TWEAK_ENABLED=1']
        end
      end
    end
  end
end

A: Looking at Cocoapods documentation, I don't think this is possible just yet, I think what you can do is to copy the pod spec - make the changes you want (e.g s.prefix_header_contents = #define symbolToDefine) and then add it to your local specs with a different name, and use that in your pod file. When a new version comes out unfortunately, you'd have to go in and change the tag number (and other stuff depending on the changes).

A: Update for Swift preprocessor flags and podspecs:
s.pod_target_xcconfig = {
  'OTHER_SWIFT_FLAGS' => '$(inherited) -D DEFINE_ME'
}