text:
Q: OOP How do I add defeated enemy's money to main character's bag? I'm almost done with this java game project. I just have to add a defeated enemy's money to the main character's bag. I also have to add weapons and armor if they are better than the main character's weapons and armor. How do I add the enemy's money to the main character's money? In my mind, main_ch.getBag().getMoney() = main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney(); should work, but it doesn't.
Here is my main class:
import java.util.Scanner;

import Character.Character;

import java.util.Random;
public class Main {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("> Welcome to The Game Project <");
    System.out.println("\n >> Input Main Character Name: ");
    String main_name = scanner.nextLine();
    System.out.println(">> Input Main Character Power: ");
    int main_power=scanner.nextInt();
    System.out.println(">> Input Main Character Hp: ");
    int main_hp=scanner.nextInt();
    System.out.println("----------------------------------------------------");

    Character main_ch=new Character (main_hp,main_power,main_name);
    show_status(main_ch);
    check_bag(main_ch);

    Character enemies[]=new Character [10];
    enemies[0]= new Character("Werewolf");
    enemies[1]= new Character("Vampire");
    enemies[2]= new Character("Alien");
    enemies[3]= new Character("Witch");
    enemies[4]= new Character("Ghost");
    enemies[5]= new Character("Skeleton");
    enemies[6]= new Character("Zombie");
    enemies[7]= new Character("Demon");
    enemies[8]= new Character("Mummy");
    enemies[9]= new Character("Dragon");

    boolean check = false;

    int dead_count=0;
    while(true) {

        Random rnd=new Random();
        int selected = rnd.nextInt(enemies.length); //random enemy selected

        System.out.println();
        System.out.println(">>>>> An enemy has appeared! <<<<<");
            while(enemies[selected].getHp()>0) {
                System.out.println();
                System.out.println(">>>>> "+enemies[selected].getName()+" wants to fight!");
                show_status(enemies[selected]);
                check_bag(enemies[selected]);
                System.out.println();
                System.out.println(">> What do you want to do?");
                System.out.println("\t1. Fight!");
                System.out.println("\t2. Use skill.");
                System.out.println("\t3. Check your stats.");
                int input = scanner.nextInt();

                    if(input==1) {

                            int damageToEnemy = main_ch.hit_point();
                            int damageTaken = enemies[selected].hit_point();
                            enemies[selected].hp -= damageToEnemy;
                            main_ch.hp -= damageTaken;
                            if(enemies[selected].hp <= 0) {
                                enemies[selected].hp=0;
                                   dead_count=dead_count+1;
                                main_ch.level=main_ch.level+1; //gain one level after enemy defeated
                                System.out.println(">> You defeated the enemy and gained a level!");

// The below code also doesn't work.
                                int pickUpMoney = main_ch.getBag().getMoney();
                                pickUpMoney=main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney();
                                System.out.println();
                                System.out.println("You found "+enemies[selected].getBag().getMoney()+" dollars. You now have "+main_ch.getBag().getMoney()+" dollars in your bag."); //take defeated enemy's money

                                for(int i = 0; i<4; i++) {
                                    if(enemies[selected].getWeapon().getPower() > main_ch.getWeapon().getPower()) {
                                        main_ch.getBag().getWeaponArray()[i]=enemies[selected].getBag().getWeaponArray()[i];
                                        System.out.println("You found better weapons! They have been added to your bag.");
                                    }
                                }
                                for(int i = 0; i<4; i++) {
                                    if(enemies[selected].getArmor().getDefense()>main_ch.getArmor().getDefense()) {

                                        main_ch.getBag().getArmorArray()[i]=enemies[selected].getBag().getArmorArray()[i];
                                        System.out.println("You found better armor! They have been added to your bag.");
                                    }

                                }
                                break;

                            }
                            System.out.println("\n>> You caused "+ damageToEnemy +" damage to the enemy! Their hp is now "+ enemies[selected].hp+".");
                            System.out.println(">> You received "+ damageTaken +" damage from the enemy! Your hp is now "+main_ch.hp+".");

                            if(main_ch.hp <=0) {
                                System.out.println();
                                System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
                                System.out.println();
                            break;
                            }

                        }

                    else if(input==2) {
                        if(main_ch.getSkill()>0 && main_ch.getMp()>0) {
                            main_ch.useSkill();
                            System.out.println("\t>> You used a skill. Your hit point increased to "+main_ch.hit_point()+". Your MP decreased to "+main_ch.getMp()+".");
                        }
                        else {
                            if(main_ch.getSkill()<=0) {
                                System.out.println("You have no skill points left.");
                            }
                            else{
                            System.out.println("\t>> Your MP is too low to use skill.");
                        }
                    }
                    }
                    else if(input==3) {
                        System.out.println();
                        show_status(main_ch);
                        check_bag(main_ch);
                        }
                    else {
                        System.out.println(">> You have entered an invalid key.");

                    }
                    }

            if(dead_count==enemies.length) {
                check=true;
            }
            if(check) {
                System.out.println();
                System.out.println(">>>>>>>>>> You won! Congratulations, you defeated all of your enemies! <<<<<<<<<");
                break;
           }
            if(main_ch.hp <=0) {
                System.out.println();
                System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
                System.out.println();
                break;
            }

            }
        }
public static void show_status(Character character) {
    System.out.println("----------------- Character Status -----------------");
    System.out.println("\tCharacter Name:\t\t"+character.getName());
    System.out.println("\tCharacter HP:\t\t"+character.getHp());
    System.out.println("\tCharacter Power:\t"+character.getPower());
    System.out.println("\tCharacter Defense:\t"+character.getDefense());
    System.out.println("\tCharacter MP:\t\t"+character.getMp());
    System.out.println("\tCharacter Level:\t"+character.getLevel());
    System.out.println("\tCharacter Hit Point:\t"+character.hit_point());
    System.out.println("\tCharacter Skill:\t"+character.getSkill());
    System.out.println("\tWeapon Name:\t\t"+character.getWeapon().getName());
    System.out.println("\tWeapon Power:\t\t"+character.getWeapon().getPower());
    System.out.println("\tArmor Name:\t\t"+character.getArmor().getName());
    System.out.println("\tArmor Defense:\t\t"+character.getArmor().getDefense());
    System.out.println("----------------------------------------------------");
}
public static void check_bag(Character character) {
    System.out.println("-------------------- Bag Status --------------------");
    System.out.println("\tMoney:\t\t\t$"+ character.getBag().getMoney());
    for(int i = 0; i<4; i++) {
        System.out.println("\tWeapon Name/Power:\t"+ character.getBag().getWeaponArray()[i].getName()+" // "+character.getBag().getWeaponArray()[i].getPower());
    }
    for(int i = 0; i<4; i++) {
        System.out.println("\tArmor  Name/Defense:\t"+ character.getBag().getArmorArray()[i].getName()+" // "+character.getBag().getArmorArray()[i].getDefense());
    }
    System.out.println("----------------------------------------------------");
}

}

Here is my Character class:
package Character;
import java.util.Random;
import Equipment.*;

public class Character {
    private Armor armor = new Armor();
    private Weapon weapon = new Weapon();
    private Bag bag = new Bag();

    public static String server_name = "CS172";
    public int hp, power, defense, mp, level, skill;
    private String name;
    Random rnd=new Random();

    public Character(String name) {
        this.name=name;
        Random rnd=new Random();
        this.hp=rnd.nextInt(500)+1;
        this.power=rnd.nextInt(100)+1;
        this.defense=rnd.nextInt(100)+1;
        this.mp=rnd.nextInt(50)+1;
        this.level=1;
        this.skill=5;
}
    public Character(int hp, int power, String name) {
        this.hp=hp;
        this.power=power;
        this.name=name;
        this.defense=rnd.nextInt(100)+1;
        this.mp=rnd.nextInt(50)+1;
        this.level=1;
        this.skill=5;
}
    public int getHp() {
        return hp;
}
    public void setHp(int hp) {
        this.hp = hp;
}
    public int getPower() {
        return power;
}
    public void setPower(int power) {
        this.power = power;
}
    public int getDefense() {
        return defense;
}
    public void setDefense(int defense) {
        this.defense = defense;
}
    public int getMp() {
        return mp;
}
    public void setMp(int mp) {
        this.mp = mp;
}
    public int getLevel() {
        return level;
}
    public void setLevel(int level) {
        this.level = level;
    }

    public String getName() {
        return name;
}
    public int damage(int enemy_power) {
        int damage = enemy_power - this.defense;
        if(damage<0){ //avoid healing by damage
            damage=0;
}
        this.hp=this.hp - damage;
        if(this.hp<0) { //avoid negative hp
            this.hp = 0;
}
        return damage;
}

    public Armor getArmor() {
    return armor;
}
    public void setArmor(Armor armor) {
        this.armor = armor;
}
    public Weapon getWeapon() {
        return weapon;
}
    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
}
    public int hit_point() {
        int total_power = this.power + this.weapon.getPower();
        return total_power;
    }
    //------------------------------------------------------why isn't this increasing the hit point at all?
    public int useSkill() {
        this.mp=this.mp-1;
        this.skill--;
        return this.hit_point()+30;
    }
    public int getSkill() {
        return skill;
    }

    public Bag getBag() {
        return bag;
    }
    public void setBag(Bag bag) {
        this.bag = bag;
    }

    public class Bag{
        Weapon weaponArray[] = new Weapon[4];
        Armor armorArray[] = new Armor[4];
        int money = 150;
        public Bag(){
            for(int i=0; i<weaponArray.length; i++) {
                weaponArray[i] = new Weapon();
                armorArray[i] = new Armor();
            }
        }
        public Weapon[] getWeaponArray() {
            return weaponArray;
        }
        public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
            this.weaponArray[yourWeaponIndex] = enemyWeapon;
        }
        public Armor[] getArmorArray() {
            return armorArray;
        }
        public void setArmorArray(Armor[] armorArray) {
            this.armorArray = armorArray;
        }
        public int getMoney() {
            return money;
        }
        public void setMoney(int money) {
            this.money = money;
        }

    }
}

A: You are calling an accessor method like it will also set, which it doesn't.  Try something like this:
main_ch.getBag().setMoney(main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney());


text:
Q: How to use existing database in android I have database called test.sqlite and i have copied the database file in to data/data/packagename/databases folder using DDMS.
When i am trying read the database i am getting the error as table does not exist
What is the solution to access the table.
Below is my code to access database.
SQLiteDatabase myDB = this.openOrCreateDatabase("test.sqlite",
              SQLiteDatabase.OPEN_READWRITE, null);
Cursor c = myDB.rawQuery("select a, b from abc", null);

A: Why you want to put the database file direct into the data/data folder? For testing purposes? Don't make sense to me, I would choose one of the options below:

*

*Load data from the server and insert it into the database.

*Put the database file in the assets folder, and then copy the bytes to create the app database (you can't move the database file).

Example (as requested):
First you need to put your database file inside the assets/database folder. If your database is bigger than 1mb you need to split it. (i.e. database1, database2, database3...)
You probably have a class to do all database tasks, here I have a class called DatabaseHelper (extends SQLiteOpenHelper). Don't forget to set you database path and name.
private static String DB_PATH = "/data/data/com.example/databases/";
private static String DB_NAME = "mydb.sqlite";

If you had to split your database, declare the pieces into a variable too.
private static String[] sFiles = {'database1','database2','database3'};

You can create/open your database quickly using the getReadableDatabase() method.
Then, create an implementation like this:
private void copyDatabase() throws IOException {
    // Path to the empty database.
    String outFilename = DB_PATH + DB_NAME;
    // Open the empty database as the output stream.
    OutputStream outputDatabase = new FileOutputStream(outFilename);
    // Transfer bytes from the input file to the output file.
    byte[] buffer = new byte[1024];

    for (int i = 0; i < sFiles.length; ++i) {
        // Open the local database as the input stream.
        InputStream is = mContext.getAssets().open("database/" + sFiles[i]);

        int length;
        while ((length = is.read(buffer)) > 0) {
            outputDatabase.write(buffer, 0, length);
        }
        // Closing stream.
        is.close();
    }

    // Closing the streams.
    outputDatabase.flush();
    outputDatabase.close();
    // Closing database.
    close();
}

A: Copy your sqlite database file in data/data/<package_name>/databases directory.
Then be sure you are opening the copied sqlite database file..
Also to check whether you are opening a correct database and which table in this, look at this query,
SELECT * FROM sqlite_master where type='table' and name='my_table_name'

A: Thanks for the replies finally it is working. i did a mistake actually i copied the database file in data/data/packagename so it is caused the error.
What i did was again copied the database in data/data/packagename/databases folder.
SQLiteDatabase myDB = this.openOrCreateDatabase("test.sqlite",
              SQLiteDatabase.OPEN_READWRITE, null);
Cursor c = myDB.rawQuery("select a, b from abc", null);

This is working fine for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Onchange Handler not response for this.setState({userName:event.target.value}) Username:Undefined , Password:Undefined After Pressing SignIn button, Alert should appear as Username: "Entered Value" and Password: "Enter Value".But now it shows Username: Undefined, Password: Undefined.
How Can I fix this.
export default class Login extends Component{

    state={userName:"",password:""}

    setUName=(event)=>{
        this.setState({userName:event.target.value})
    }

    setPW=(event)=>{
        this.setState({password:event.target.value})
    }

    onSubmit=(event)=>{
        event.preventDefault()
        const {userName,password}=this.state;
        alert(`Username:${userName},Password:${password}`);
    }
    render(){

        return (
            <ImageBackground source={require('../../src/login.png')} style={styles.container}>
                <View style={styles.logoContainer}>
                    <Text style={styles.header}>
                        Welcome
                    </Text>
                </View>

                <View>
                    <View style={styles.inputContainer}>
                        <TextInput style={styles.txtInput}
                            placeholder='Username'
                            returnKeyType='next'
                            onChange={this.setUName}
                        />

                        <TextInput style={styles.txtInput}
                            placeholder='Password'
                            returnKeyType='next'
                            secureTextEntry
                            onChange={this.setPW}
                        />

                    </View>

A: In react-native, you can get value from onChangeText prop from TextInput component.
Try this
      setUName=(value)=>{
        this.setState({userName:value})
    }

<TextInput style={styles.txtInput}
                            placeholder='Username'
                            returnKeyType='next'
                            onChangeText={this.setUName}
      />

A: No need to pass function on OnChange replace your onchange property with
  <TextInput style={styles.txtInput}
   placeholder='Username'
   returnKeyType='next'
   onChangeText={userName=> this.setState({ userName})}
   />

A: Seems like you are using TextInput, this may be custom created or from some styling library. You should log the argument once and check, where exactly the value is coming, so try the below code and check in console and you will know what to do next.
setUName=()=>{
    console.log(arguments)
}

Its always the best debugging practice to console.log(arguments) as in some library, these events are customEvents and values are in 2nd or 3rd argument.


text:
Q: Vue.js - Event does not trigger child component to show requested data in table I am using vue-jd-table, trying to make simple app with pre-set data object (no need to make API requests). Following official Usage guide, I managed to initialize and configure the app, but can't make it load data.
main.js
import Vue from 'vue'
import JDTable from 'vue-jd-table';
import App from './App.vue'

import "@fortawesome/fontawesome-free/css/all.min.css";
import 'vue-jd-table/dist/jd-table.min.css';

Vue.config.productionTip = false
Vue.component( 'jdtable',JDTable );
new Vue
({
  render: h => h(App),
}).$mount( '#app' );

App.vue
<template>

Click me

    <HelloWorld></HelloWorld>

</template>

/components/HelloWorld.vue
<template>

        <JDTable
            :option                 = "tableOptions"
            :loader                 = "tableLoader"
            :event-from-app         = "eventFromApp"
            :event-from-app-trigger = "eventFromAppTrigger"
            @event-from-jd-table    = "processEventFromApp( $event )"
        />

</template>

Program compiles successfully, makes table without data, and to mimic API request, I want to fill it with data on click at "Click me". Unfortunately, clicking it does nothing.
What am I missing?

A: This looks like a scope issue. this.eventFromApp doesn't exist in App.vue. Move everything form HelloWorld.vue into App.vue and it should work. As it is right now, your methods in App.vue have no way of communicating with the JD-Table component.
If you want to separate your button to JD-Table component then you need to have the click pass the data via a prop to the HelloWorld.vue component which would then send it to JD-Table.


text:
Q: card game can't put empty space between cards I am building a simple card game, and I have a line in the bottom of the cards like this:

when I click on the card and it matches the number the card disappears and it is the expected behaviour. The issue is that when it disappears it doesn't leave an empty space, it just occupy the empty space with the next card, as this:

** I am doing the component this way:**
<template>

    <tri-pack :deckCards="deckCards" />

</template>

I know that it doesn't work, because when I remove a card the index change and when it multiplies it gives the same position to occupy the empty space, but how can I solve this problem?
Any help?


text:
Q: Naming convention in sharepoint, file with comma in name is giving error I am facing issue with file name in document library which contain "," comma in its naming convention like abc,xyz.doc
Error comes while opening or exporting file.
I saw that comma is not recommended by microsoft but we have 80% file with comma naming convention. Is their any workaround for this?
Thanks :)

A: There are certain characters that you cannot use in files in SharePoint. You will have to adhere to these instructions otherwise you will not be allowed to upload files with such names to SharePoint.
If you want to upload such files then either you will have to write a utility which removes special characters from file name.
below is the link with some more details:
[Click here]http://support.microsoft.com/kb/905231

A: SharePoint will not allow you to upload files with commas, my suggestion would be to rename files, a few ways to do this, either use Windows explorer, power shell, command prompt (ren)
http://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/
Third Part tools: http://www.bulkrenameutility.co.uk/Download.php
Or using powershell: http://blogs.technet.com/b/heyscriptingguy/archive/2013/11/22/use-powershell-to-rename-files-in-bulk.aspx


text:
Q: on long click listener delete item in list dialog I am using a dialog which is show the item of list of string my code is
 final CharSequence[] items = {"1", "2", "3"};

            AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                }

            }).show();

now my question is how to implement onLongClicklistener method to delete a selected item my dialog is looking like shown in image

A: You need to implement onItemLongClick method as follows:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
        // TODO: Get the position of the item clicked.
        //       Delete it from your collection eg.ArrayList.
        //       Call notifydatasetChanged so that it will refresh
        //       the views displaying updated list.
        return true;
    }
});

A: 1) Set an ItemLongClickListener on your listview
2) remove the long pressed item from your array, which populates your list adapter
3) Refresh your adapter
public ListView listView;
public ArrayList<String> items;
public ArrayAdapter adapter;

listView.setOnItemLongClickListener(new OnItemLongClickListener(){
    @Override
    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
    String selectedItem = items.get(pos);
    items.remove(selectedItem);
    adapter.notifyDataSetChanged();
    return true;
    }
});


text:
Q: How to add a caption to an image in Pages How does one create a caption for an image in Pages? In Word it is easy, you simply right click on the image and "Insert Caption…", but I cannot find any way to do it at all in Pages?
You can set a 'Description' on an image, however that only affects voiceover, which I do appreciate! But I also want the ability to move the image and it's caption together.
I am using Pages 5.5.2, I understand that this is easier in Pages '09, but I don't have that version anymore…
Edit: The only method that I have found that vaguely works is to create a new text box, manually make the text box the same size as the image, and text, set the paragraph style to caption, and, finally, group the image and the text box together so that they are treated as a unit. I hope that there is a simpler way that I have just missed somehow!

A: There's no automatic way of adding a caption.

*

*If your image is inline, add the text below using the Caption text style.

*If your image is floating, you'll need to add a text box below the image. You can group these if you wish.

A: I found a way to add Table Label in the Inspector for others who might be looking at how to add a caption. Click on Table in Inspector, and in the section with Header Footer select Table Label.

A: I often make a table that has two rows. Paste your image into the top cell, put your caption in the cell below, and remove the borders. The figure scales with the size of the cell and the caption moves with the text. However, I can't do this on pages in iCloud, so if you are going back and forth with iCloud editing, grouping of objects seems more robust.


text:
Q: In what way does wait(NULL) work exactly in C? If I use wait(null), and I know (for sure) that the child will finish (exit) before we reach to wait(null) in the parent process, does the wait(null) block the parent process?
I mean, the wait() won't get any signal, right?
int main() {
    int pipe_descs[2];
    int i, n, p;

    srand(time(NULL(;
    pipe(pipe_descs);

    for (i = 0; i < 2; i++) {
        pid_t status = fork();

        if (status == 0) {
            n = rand() % 100;
            p = (int) getpid();

            write(pipe_descs[1], &n, sizeof(int));
            write(pipe_descs[1], &p, sizeof(int));
            exit(0);
        }
        else {
            read(pipe_descs[0],  &n,  sizeof(int));
            read(pipe_descs[0],  &p,  sizeof(int));
            printf(" %d %d\n", n, p);
            wait(NULL); // (1)
        }
    }
    return 0;
}

A: wait(NULL) will block the parent process until any of its children has finished. If the child terminates before the parent process reaches wait(NULL) then the child process turns to a zombie process until its parent waits on it and its released from memory.
If the parent process doesn't wait for its child, and the parent finishes first, then the child process becomes an orphan and is assigned to init as its child. And init will wait and release the process entry in the process table.
In other words: the parent process will be blocked until the child process returns an exit status to the operating system which is then returned to the parent process. If the child finishes before the parent reaches wait(NULL) then it will read the exit status, release the process entry in the process table and continue execution until it finishes as well.


text:
Q: how to have pass-by-reference parameters for behavior methods in cakephp? According to http://book.cakephp.org/2.0/en/models/behaviors.html#creating-behavior-methods,
I can do the following:
public function fly(Model $Model, $from, $to) {
    // Do some flying.
}

I want to have a passed-by-reference parameter in the behavior method.
This is my method:
public function extractByFields(Model $model, $data, $options = array(), Array $missingFields) {

the parameter I want to be passed by reference is $missingFields.
Reason is because I want to return my $foundFields but in case there are any other missing fields, I also want to expose them to the method caller.
If CakePHP cannot allow me to return passed-by-reference parameters in my behavior methods, I would like some advice on how best to have a workaround?
My version is CakePHP2.4

A: With behavior methods you cannot use pass-by-reference parameters. call_user_func_array() is used to call the methods and the arguments are not passed by reference.
Possible workaround: store missing fields in the Behavior class as an attribute and have a method to retrieve them.


text:
Q: XBOX One gamepad detected in slot 0 but no input detected in Game Maker Studio 2 I am following along this udemy course and in the section where we implement a very simplistic gamepad support, I am unable to make my XBOX One controller work as demonstrated in the lecture. Here is the get_input() script with both keyboard support (which works fine when there is no controller connected) and gamepad support.
//keyboard input
left = keyboard_check(vk_left);
right = keyboard_check(vk_right);
up = keyboard_check(vk_up);
down = keyboard_check(vk_down);
attack = keyboard_check_pressed(vk_shift);
jump = keyboard_check_pressed(vk_space);
jump_held = keyboard_check(vk_space);
block = keyboard_check(ord("Z"));

//controller input
var _dev = 0;
if gamepad_is_connected(_dev) {
    var _deadzone = 0.3;
    left = gamepad_axis_value(_dev, gp_axislh) < -_deadzone;
    right = gamepad_axis_value(_dev, gp_axislh) > _deadzone;
    up = gamepad_axis_value(_dev, gp_axislv) < -_deadzone;
    down = gamepad_axis_value(_dev, gp_axislv) > _deadzone;
    attack = gamepad_button_check_pressed(_dev, gp_face2);
    jump = gamepad_button_check_pressed(_dev, gp_face1);
    jump_held = gamepad_button_check(_dev, gp_face1);
    block = gamepad_button_check(_dev, gp_shoulderr);
}

I know that my gamepad is detected because when I run this code:
var numPads= gamepad_get_device_count();
for(var i = 0; i < numPads; i++;)
{
    if(gamepad_is_connected(i)) show_message(string(i) + ": " + gamepad_get_description(i));
}

I get a message saying "0: XInput STANDARD GAMEPAD". However, when I launch the game and try to use the buttons or the joystick, nothing happens. I tried using two different XBOX One controller but I have the same problem. When I try with my gamecube controller connected using a Mayflash GC Controller Adapter on slot 4, it works. Am I missing something specific about XBOX One controllers? I think that in the course the teacher uses an XBOX 360 controller, which I don't have.
Please send help!

A: I've last month tried to implement Controller support using an XBox One Controller, and I got it working just fine. Also with using gamepad_button_check() and gamepad_axis_value() and the other variables I've used from this link: https://docs2.yoyogames.com/source/_build/3_scripting/4_gml_reference/controls/gamepad%20input/index.html
I use both gamepad_is_supported and gamepad_is_connected in the gamepad code to make sure it has found a gamepad.
It should be possible to work with an XBox One Controller.
So maybe the problem is something out of the box. (e.g. Have you checked the Controller is installed on your PC? Or is the connection only in the Create Event, and that it doesn't update when your controller is plugged in?)


text:
Q: Summarise all values for a particular key in JSON in Ruby I have the following json stored in a column in my database. I'm using this JSON to populate a table in one of my views which works great. What I'm now trying to do is calculate a sum of all of the values for a particular key --> sum of every ("ownership_percentage") for each "shareholder".
{
   "captable":{
      "id":28,
      "version":1,
      "name":"CapTable",
      "company_id":22,
      "created_at":"2018-10-31T18:56:03.965Z",
      "updated_at":"2018-10-31T18:57:30.626Z",
      "total_stocks_in_company":"400.0"
   },
   "event":{
      "status_locked":null,
      "id":51,
      "price_per_share":"1000.0",
      "total_company_stocks_after_event":"400.0",
      "name":"2nd event ",
      "date":"2018-10-31",
      "currency":"SEK",
      "valuation":"400000.0",
      "created_at":"2018-10-31T18:57:17.282Z",
      "updated_at":"2018-10-31T18:57:30.676Z",
      "captable_id":28,
      "company_id":22,
      "snapshot":"{\"captable\":{\"id\":28,\"total_stocks_in_company\":\"400.0\",\"version\":1,\"name\":\"CapTable\",\"company_id\":22,\"created_at\":\"2018-10-31T18:56:03.965Z\",\"updated_at\":\"2018-10-31T18:57:30.626Z\"},\"event\":{\"status_locked\":null,\"id\":51,\"price_per_share\":\"1000.0\",\"total_company_stocks_after_event\":\"400.0\",\"name\":\"2nd event \",\"date\":\"2018-10-31\",\"currency\":\"SEK\",\"valuation\":\"400000.0\",\"created_at\":\"2018-10-31T18:57:17.282Z\",\"updated_at\":\"2018-10-31T18:57:30.665Z\",\"captable_id\":28,\"company_id\":22,\"snapshot\":null},\"shareholders\":[{\"id\":52,\"shareholder\":\"Peter\",\"name\":\"Peter\",\"number_of_stocks\":\"100.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:42.730Z\",\"updated_at\":\"2018-10-31T18:57:30.637Z\",\"ownership_percentage\":\"0.25\",\"email\":\"\",\"telephone\":\"\"},{\"id\":53,\"shareholder\":\"Jane\",\"name\":\"Jane\",\"number_of_stocks\":\"100.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:49.490Z\",\"updated_at\":\"2018-10-31T18:57:30.644Z\",\"ownership_percentage\":\"0.25\",\"email\":\"\",\"telephone\":\"\"},{\"id\":54,\"shareholder\":\"Sally\",\"name\":\"Sally \",\"number_of_stocks\":\"200.0\",\"company_id\":22,\"created_at\":\"2018-10-31T18:55:56.192Z\",\"updated_at\":\"2018-10-31T18:57:30.651Z\",\"ownership_percentage\":\"0.5\",\"email\":\"\",\"telephone\":\"\"}]}"
   },
   "shareholders":[
      {
         "id":52,
         "shareholder":"Peter",
         "name":"Peter",
         "number_of_stocks":"50.0",
         "company_id":22,
         "created_at":"2018-10-31T18:55:42.730Z",
         "updated_at":"2018-10-31T18:58:31.406Z",
         "ownership_percentage":"0.125",
         "email":"",
         "telephone":""
      },
      {
         "id":53,
         "shareholder":"Jane",
         "name":"Jane",
         "number_of_stocks":"150.0",
         "company_id":22,
         "created_at":"2018-10-31T18:55:49.490Z",
         "updated_at":"2018-10-31T18:58:31.410Z",
         "ownership_percentage":"0.375",
         "email":"",
         "telephone":""
      },
      {
         "id":54,
         "shareholder":"Sally",
         "name":"Sally ",
         "number_of_stocks":"200.0",
         "company_id":22,
         "created_at":"2018-10-31T18:55:56.192Z",
         "updated_at":"2018-10-31T18:57:30.651Z",
         "ownership_percentage":"0.5",
         "email":"",
         "telephone":""
      }
   ]
}

Just to add another layer - the ownership_percentage is a string, so that need to be converted into either a decimal/float before performing the sum so that one liner is getting a bit long :)
What I'd like to achieve is the following (pseudocode) but I'm having trouble finding a one liner that works well for me. Would love a push in the right direction here!
<td> <%= snapshot_json["shareholders"]["ownership_percentage"].to_f.sum %> </td>

Note: The ownership_percentage in this example should summarise up to 1.0 (i.e. 100%).

A: You'll have to pass a block to Array#sum on your shareholders array
snapshot_json["shareholders"].sum { |x| x["ownership_percentage"].to_f }


text:
Q: How to find out whole statistics about age of users which use my app? So in Google Play I have the next target audience for my app:

But when I go to Firebase Analytics or Google Analytics website and check statistics for this app it doesn't allow me to see age below 18:

How am I supposed to know which full audience use my app? It can show only statistics about adults..


text:
Q: Lottie animation not showing at all My import:
implementation "com.airbnb.android:lottie:3.2.2"

In my splash_layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splash"/>

<com.airbnb.lottie.LottieAnimationView
    android:id="@+id/animation_view"
    android:layout_width="100dp"
    android:layout_height="100dp"
    app:lottie_fileName="logo_android.json"
    app:lottie_loop="true"
    app:lottie_autoPlay="true"
    app:lottie_imageAssetsFolder="demo"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"/>

In SplashActivity:
private LottieAnimationView animationView;
(...)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_layout);
    animationView=findViewById(R.id.animation_view);
    animationView.playAnimation();
(...)
}

My image folder is in src/main/res/assets/demo. The logo_android.json file is in src/main/assets
This way, the animation does not show at all. Not a single image is displayed. How can I get the animation working?
In case it matters, the JSON file looks something like this:
{"v":"5.5.8","fr":25,"ip":0,"op":400,"w":800,"h":400,"nm":"logo_android","ddd":0,"assets":[{"id":"image_0","w":396,"h":51,"u":"images/","p":"img_0.png","e":0},{"id":"image_1","w":122,"h":215,"u":"images/","p":"img_1.png","e":0},(...)

A: Solved it.
In case it can help someone, you have to put the images in src/main/assets/images

A: For anyone using Expo SDK V44 (React Native V0.64.3), lottie-react-native V5.0.1 and lottie-ios V3.2.3. What I have found that works is to call the .play() method on the ref from the LottieView, on mount of the component. I referenced this from the official Expo Lottie documentation: https://docs.expo.dev/versions/latest/sdk/lottie/.
const animationRef = useRef<LottieView | null>(); // The <> is for TypeScript, but can be removed for JavaScript

  useEffect(() => {
    animationRef.current?.play();
  }, []);

  return (
    <LottieView
      ref={(animation) => {
        animationRef.current = animation;
      }}
      source={require("../path_to_animation_folder)}
      autoPlay
      loop
      style={{ width, height }}
    />
  );

Hope I managed to help someone!

A: managed to get it working by this:
if(lottieTest.getFrame() == lottieTest.getMaxFrame()) {
   lottieTest.setFrame(1);
}

please refer to this.


text:
Q: Analytic geometry reference request? Do you know any rigorous introduction to analytic geometry?
I'm looking for a reference which defines vectors as equivalence classes of oriented segments.
Thanks.

A: See "free vectors" in E. Swokowski's Calculus with analytic geometry.


text:
Q: Vapor Mysql not building Getting build error when I run:
vapor build --mysql
Not much documentation on how to install any dependencies for this project in their [website][1]. From the stack trace, it seems im missing 'lmysqlclient' which im not sure if im supposed to add to the linker flags or is this something that needs to be added to the vapor config (im pretty new to vapor).
Here is the stack trace:
computer:Server user$ swift build -Xswiftc -I/usr/local/mysql/include -Xlinker -L/usr/local/mysql/lib -Xswiftc -DNOJSON
Linking CLibreSSL
Compile Swift Module 'TurnstileCrypto' (3 sources)
Compile Swift Module 'Jay' (21 sources)
Compile Swift Module 'SocksCore' (14 sources)
Compile Swift Module 'Polymorphic' (2 sources)
Compile Swift Module 'PathIndexable' (2 sources)
Compile Swift Module 'libc' (1 sources)
Compile Swift Module 'Core' (28 sources)
ld: warning: directory not found for option '-L/usr/local/mysql/lib'
Compile Swift Module 'Node' (22 sources)
Compile Swift Module 'Socks' (5 sources)
Compile Swift Module 'Fluent' (35 sources)
Compile Swift Module 'Essentials' (2 sources)
Compile Swift Module 'TLS' (7 sources)
Compile Swift Module 'Console' (34 sources)
Compile Swift Module 'Leaf' (34 sources)
Compile Swift Module 'JSON' (8 sources)
Compile Swift Module 'Turnstile' (13 sources)
Compile Swift Module 'Random' (3 sources)
Compile Swift Module 'Cipher' (2 sources)
Compile Swift Module 'MySQL' (10 sources)
Compile Swift Module 'TurnstileWeb' (8 sources)
Compile Swift Module 'BCrypt' (1 sources)
Compile Swift Module 'Hash' (3 sources)
Compile Swift Module 'HMAC' (2 sources)
Compile Swift Module 'FluentMySQL' (2 sources)
Compile Swift Module 'URI' (10 sources)
Compile Swift Module 'Transport' (8 sources)
Compile Swift Module 'HTTP' (33 sources)
Compile Swift Module 'SMTP' (21 sources)
Compile Swift Module 'WebSockets' (14 sources)
Compile Swift Module 'Settings' (10 sources)
Compile Swift Module 'Cookies' (11 sources)
Compile Swift Module 'Cache' (3 sources)
Compile Swift Module 'Routing' (9 sources)
Compile Swift Module 'HTTPRouting' (5 sources)
Compile Swift Module 'Sessions' (6 sources)
Compile Swift Module 'Auth' (14 sources)
Compile Swift Module 'TypeSafeRouting' (3 sources)
Compile Swift Module 'Vapor' (86 sources)
Compile Swift Module 'VaporMySQL' (1 sources)
Compile Swift Module 'App' (3 sources)
Linking ./.build/debug/App
ld: warning: directory not found for option '-L/usr/local/mysql/lib'
ld: library not found for -lmysqlclient for architecture x86_64
<unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode/10.0/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/user/test/Server/.build/debug.yaml

A: ld: warning: directory not found for option '-L/usr/local/mysql/lib'
You don't appear to have the mysql headers installed at that directory. Did you install mysql? Are you sure that's where they are located?

A: For anyone using Xcode to build this and assuming mysql is installed properly on your machine (I used homebrew) you need to pass in the -DNOJSON flag in the Xcode project under project > Build Settings > Other Swift Flags.
After running vapor xcode and assuming your mysql package provider is all set up open up the project and add in the flag.
Clean the project (⌘K) and you should be good to go.
That is what worked for me


text:
Q: Having trouble including ant jsch library I'm an ant newbie and I'm trying to run an ant build from Cruise Control that utilizes the SCP and SSHEXEC tasks. When I try to run the script I get this error:

Problem: failed to create task or type sshexec Cause: the class
  org.apache.tools.ant.taskdefs.optional.ssh.SSHExec was not found. This
  looks like one of Ant's optional components. Action: Check that the
  appropriate optional JAR exists in -/app/cruisecontrol-bin-2.8.4/lib

I ran ant -diagnostics and it says ant-jsch.jar (40200 bytes) is included in my ANT_HOME/lib, and I see the jar in cruisecontrol-bin-2.8.4/lib as well, though this one is ~30,122 bytes.
However, the diagnostic says:
sshexec : Missing dependency com.jcraft.jsch.Logger
scp : Missing dependency com.jcraft.jsch.Logger

I dropped the version from ANT_HOME/lib into the cruise control lib and it didn't make a difference (I'm not sure if I have to reload the class path or something, or even how to do that).
Any advice or suggestions would be greatly appreciated, I really have no idea how to remedy this. I was trying taskdefs last night as well but that wasn't working either.

A: You made a step in the right direction by ensuring you have the Ant-side of this in place.
The problem is that you're missing the external JSch class com.jcraft.jsch.Logger.
To fix this problem you need to satisfy the external dependency (as listed in the Ant docs) by downloading and installing jsch.jar from JCraft.  You can put the jar in your Ant lib directory if that suits.
When you get 'dangling' external dependencies that you don't recognise, googling is often the quickest way to find the source: in this case JCraft shows up about fourth in the search at the moment.  JarFinder is third, and it maps the class name to the jar that contains it.


text:
Q: Filtering data out of an api in python? I try to filter out some specific data out of the list I get from an api request of a crypto price ticker.
This prints all the data:
import requests, json
r = requests.get('https://api.bitvavo.com/v2/ticker/price')
data = r.json()
print (data)

But I only need the prices of this markets "BTC-EUR" and "ETH-EUR".
This is the data what comes from the API:
[{"market":"AAVE-EUR","price":"258.99"},{"market":"ADA-BTC","price":"0.000021401"},{"market":"ADA-EUR","price":"1.0998"},{"market":"AE-BTC","price":"0.0000031334"},{"market":"AE-EUR","price":"0.064378"},{"market":"AION-BTC","price":"0.000004433"},{"market":"AION-EUR","price":"0.10173"},{"market":"ANT-BTC","price":"0.00011591"},{"market":"ANT-EUR","price":"3.1229"},{"market":"ARK-BTC","price":"0.000024647"},{"market":"ARK-EUR","price":"0.945"},{"market":"BAL-EUR","price":"17.716"},{"market":"BAND-EUR","price":"5.4089"},{"market":"BAT-BTC","price":"0.000020403"},{"market":"BAT-EUR","price":"0.53508"},{"market":"BCH-BTC","price":"0.0091659"},{"market":"BCH-EUR","price":"448.27"},{"market":"BSV-BTC","price":"0.0036256"},{"market":"BSV-EUR","price":"116.89"},{"market":"BTC-EUR","price":"32574"},{"market":"CHZ-EUR","price":"0.2181"},{"market":"CMT-BTC","price":"0.000000095639"},{"market":"CMT-EUR","price":"0.027029"},{"market":"COMP-EUR","price":"333.45"},{"market":"DAI-EUR","price":"0.8424"},{"market":"DCR-BTC","price":"0.002769"},{"market":"DCR-EUR","price":"110.82"},{"market":"DGB-BTC","price":"0.0000012116"},{"market":"DGB-EUR","price":"0.041454"},{"market":"DOT-EUR","price":"14.545"},{"market":"ELF-BTC","price":"0.0000060815"},{"market":"ELF-EUR","price":"0.21208"},{"market":"ENJ-BTC","price":"0.000044049"},{"market":"ENJ-EUR","price":"1.1605"},{"market":"EOS-BTC","price":"0.000072182"},{"market":"EOS-EUR","price":"3.3319"},{"market":"ETC-BTC","price":"0.0002102"},{"market":"ETC-EUR","price":"42.069"},{"market":"ETH-BTC","price":"0.030931"},{"market":"ETH-EUR","price":"2113.9"},{"market":"FET-EUR","price":"0.332"},{"market":"GAS-BTC","price":"0.00020596"},{"market":"GAS-EUR","price":"6.6111"},{"market":"GLM-EUR","price":"0.30293"},{"market":"GNO-EUR","price":"160.32"},{"market":"GNT-BTC","price":"0.000005145"},{"market":"GNT-EUR","price":"0.09968"},{"market":"HOT-BTC","price":"0.00000013588"},{"market":"HOT-EUR","price":"0.0051574"},{"market":"ICX-BTC","price":"0.000033193"},{"market":"ICX-EUR","price":"0.82902"},{"market":"IOST-BTC","price":"0.00000083881"},{"market":"IOST-EUR","price":"0.020588"},{"market":"KMD-BTC","price":"0.000030016"},{"market":"KMD-EUR","price":"0.686"},{"market":"KNC-EUR","price":"1.3403"},{"market":"LINK-BTC","price":"0.00051778"},{"market":"LINK-EUR","price":"19.137"},{"market":"LOOM-EUR","price":"0.06653"},{"market":"LRC-BTC","price":"0.00001021"},{"market":"LRC-EUR","price":"0.20504"},{"market":"LSK-BTC","price":"0.000064109"},{"market":"LSK-EUR","price":"2.6978"},{"market":"LTC-BTC","price":"0.0034759"},{"market":"LTC-EUR","price":"116.79"},{"market":"MANA-EUR","price":"0.58193"},{"market":"MIOTA-BTC","price":"0.000022837"},{"market":"MIOTA-EUR","price":"0.73894"},{"market":"MKR-EUR","price":"2366.8"},{"market":"NANO-BTC","price":"0.000088476"},{"market":"NANO-EUR","price":"3.6449"},{"market":"NAS-BTC","price":"0.000015282"},{"market":"NAS-EUR","price":"0.28762"},{"market":"NEO-BTC","price":"0.00076305"},{"market":"NEO-EUR","price":"35.342"},{"market":"NMR-EUR","price":"37.275"},{"market":"NPXS-BTC","price":"0.000000080918"},{"market":"NPXS-EUR","price":"0.0063093"},{"market":"NULS-BTC","price":"0.00001495"},{"market":"NULS-EUR","price":"0.33311"},{"market":"OGN-EUR","price":"0.65464"},{"market":"OMG-BTC","price":"0.00010162"},{"market":"OMG-EUR","price":"3.5235"},{"market":"ONG-BTC","price":"0.000013713"},{"market":"ONG-EUR","price":"0.64352"},{"market":"ONT-BTC","price":"0.00002071"},{"market":"ONT-EUR","price":"0.66787"},{"market":"OXT-EUR","price":"0.23841"},{"market":"POWR-BTC","price":"0.0000063743"},{"market":"POWR-EUR","price":"0.22833"},{"market":"PUNDIX-EUR","price":"1.3019"},{"market":"QTUM-BTC","price":"0.00011871"},{"market":"QTUM-EUR","price":"6.554"},{"market":"RDD-BTC","price":"0.00000006"},{"market":"RDD-EUR","price":"0.0029025"},{"market":"REN-EUR","price":"0.35152"},{"market":"REP-EUR","price":"20.646"},{"market":"REQ-BTC","price":"0.0000027979"},{"market":"REQ-EUR","price":"0.049529"},{"market":"RLC-EUR","price":"2.7609"},{"market":"RSR-EUR","price":"0.029507"},{"market":"RVN-BTC","price":"0.000003409"},{"market":"RVN-EUR","price":"0.055052"},{"market":"SNT-BTC","price":"0.0000017591"},{"market":"SNT-EUR","price":"0.066089"},{"market":"SNX-EUR","price":"7.672"},{"market":"STEEM-BTC","price":"0.0000092917"},{"market":"STEEM-EUR","price":"0.4"},{"market":"STMX-BTC","price":"0.00000083031"},{"market":"STMX-EUR","price":"0.017834"},{"market":"STORJ-EUR","price":"0.84081"},{"market":"STORM-BTC","price":"0.00000032019"},{"market":"STORM-EUR","price":"0.0028761"},{"market":"STRAT-BTC","price":"0.000038581"},{"market":"STRAT-EUR","price":"0.41621"},{"market":"STRAX-EUR","price":"1.59"},{"market":"SUSHI-EUR","price":"6.8024"},{"market":"SXP-EUR","price":"1.8182"},{"market":"TRB-EUR","price":"32.783"},{"market":"TRX-BTC","price":"0.00000093686"},{"market":"TRX-EUR","price":"0.05386"},{"market":"UMA-EUR","price":"7.2881"},{"market":"UNI-EUR","price":"17.943"},{"market":"USDC-EUR","price":"0.84219"},{"market":"USDT-EUR","price":"0.8388"},{"market":"UTK-EUR","price":"0.19191"},{"market":"VET-BTC","price":"0.0000014302"},{"market":"VET-EUR","price":"0.070825"},{"market":"VTC-BTC","price":"0.000010824"},{"market":"VTC-EUR","price":"0.42721"},{"market":"VTHO-BTC","price":"0.0000001866"},{"market":"VTHO-EUR","price":"0.005126"},{"market":"WAVES-BTC","price":"0.00017881"},{"market":"WAVES-EUR","price":"13.344"},{"market":"WTC-BTC","price":"0.000028721"},{"market":"WTC-EUR","price":"0.46438"},{"market":"XEM-BTC","price":"0.0000063552"},{"market":"XEM-EUR","price":"0.13628"},{"market":"XLM-BTC","price":"0.0000068038"},{"market":"XLM-EUR","price":"0.22757"},{"market":"XRP-BTC","price":"0.0000080191"},{"market":"XRP-EUR","price":"0.60536"},{"market":"XTZ-BTC","price":"0.000072727"},{"market":"XTZ-EUR","price":"2.5732"},{"market":"XVG-BTC","price":"0.00000055161"},{"market":"XVG-EUR","price":"0.019311"},{"market":"YFI-EUR","price":"26489"},{"market":"YFII-EUR","price":"3468.8"},{"market":"ZIL-BTC","price":"0.0000031492"},{"market":"ZIL-EUR","price":"0.066433"},{"market":"ZRX-BTC","price":"0.00002664"},{"market":"ZRX-EUR","price":"0.6746"},{"market":"SOL-EUR","price":null}]

I have tried many options. But I haven't found the solution yet.
Looking forward to your answers.

A: The data variable is a list with dictionaries and the dictionaries have the values you want.So, you just need to dig in a bit deeper for the data you want.
Steps:

*

*Firstly, access each dictionary in the list using a for loop

*Check if the "market" value for the current dictionary is among ["BTC-EUR","ETH_EUR"] or not

*If it is, print the price for those values

Try:
import requests
r = requests.get('https://api.bitvavo.com/v2/ticker/price')
data = r.json()
for item in data:
    if(item['market'] in ['BTC-EUR','ETH-EUR']):
        print(item['market'] + ' : ' + item['price'])    # you could use a f-string if you know about it like print(f{item['market']} : {item['price']}")

Output:
BTC-EUR : 32427
ETH-EUR : 2119

A: you could also use the Native python client.
https://github.com/bitvavo/python-bitvavo-api#get-price-ticker

pip install python-bitvavo-api
from python_bitvavo_api.bitvavo import Bitvavo
bitvavo = Bitvavo({
    'RESTURL': 'https://api.bitvavo.com/v2',
    'ACCESSWINDOW': 10000,
    'DEBUGGING': False
})
print(bitvavo.tickerPrice({"market": "BTC-EUR"}))
print(bitvavo.tickerPrice({"market": "ETH-EUR"}))

produces:
{'market': 'BTC-EUR', 'price': '32434'}
{'market': 'ETH-EUR', 'price': '2120.7'}

A: This code works:
import pandas as pd
import requests, json
r = requests.get('https://api.bitvavo.com/v2/ticker/price')
data = r.json()
dataframe = pd.DataFrame.from_dict(data)    #transform data to pandas dataframe
newdf = dataframe.query('market == "BTC-EUR" | market == "ETH-EUR"')
#filter dataframe based on the conditions


text:
Q: Rigid regression - show $||w||_2$ is $O(\lambda ^ -1)$ Relevant question: Ridge regression formulation as constrained versus penalized: How are they equivalent?
I've got an assignment to show that in rigid regression the coefficients vector $L_2 $ norm, $||w||_2$,  is bounded by $O(\lambda ^ {-1})$. We haven't seen Lagrange Multipliers or KKT so I am assuming it's something a lot simpler (basic calculus and linear algebra).
We can assume X,Y are constants.
I've shown this bound, which isn't enough:

Setting $w$ to $0$ we get from the Rigid Regression objective $RSS+\lambda ||w||^2$ = $\sum_{i=1}^n y(x_i)^2$.
So for any $w$ chosen, $\sum_{i=1}^{n}(f_{w}(x_{i})-y(x_{i}))^{2}+\lambda||w||^{2}\le c$, then > $\lambda||w||^2 \le c$ , then $||w|| = O(\frac{1}{\sqrt{\lambda}})$.


text:
Q: Passport is not serializing my user in login I am practicing of using passport.js for authentication but there is a problem in login part. I've tried to solve the problem by different way but nothing was successful, the problem is even after changing the passport.serialize to (user, done) the code worked but if I enter any fake password and username, it authenticate me.
How do I solve it?
// npm i passport passport-local passport-local-mongoose express-session

const express = require("express");
const app = express();

const bodyParser = require("body-parser");
app.use(express.urlencoded({ extended: false }));

app.use(express.static("public"));

const session = require("express-session"); // session first
const passport = require("passport");  //then passport
const passportLocalMongoose = require("passport-local-mongoose"); // last passport-local-mongoose
// no need to passport-local

app.use(session({  // use the session first and set it up
    secret: "this is our secrete",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize()); // then use passport to initialize
app.use(passport.session()); // then use passport to deal with session

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/authentication", { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.set("useCreateIndex", true); // to prevent the deprecation message
const authSchema = new mongoose.Schema({
    email: String,
    password: String
})

authSchema.plugin(passportLocalMongoose); //plug passportLocalMongoose in the schema

const Auth = new mongoose.model("Auth", authSchema);

passport.use(Auth.createStrategy());

passport.serializeUser(Auth.serializeUser()); // put a message in a cookie
passport.deserializeUser(Auth.deserializeUser()); // destroy the cookie and reveal the message

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
})
app.get("/register", (req, res) => {
    res.sendFile(__dirname + "/register.html");
})
app.get("/login", (req, res) => {
    res.sendFile(__dirname + "/login.html");
})
app.get("/success", (req, res) => {
    res.sendFile(__dirname + "/success.html");
})
app.get("/secret", (req, res) => {
    console.log(req.isAuthenticated());
    if (req.isAuthenticated()) {
        res.sendFile(__dirname + "/secret.html")
    } else {
        res.sendFile(__dirname + "/login.html")
    }
})

app.post("/register", (req, res) => {
    var regEmail = req.body.email;
    var regPassword1 = req.body.password1;
    var regPassword2 = req.body.password2;
    if (regPassword1 === regPassword2) {
        Auth.register({ username: regEmail }, regPassword1, (err, user) => {
            if (err) throw err;
            passport.authenticate('local')
            res.redirect("/success")
        })
    }
})

app.post("/login", (req, res) => {
    const user = new Auth({
        email: req.body.email,
        password: req.body.password
    });
    req.login(user, (err) => {
        if (err) throw err;
        passport.authenticate("local")
        res.redirect("/secret")
        })
    })

var port = 3000;
app.listen(port, () => {
    console.log(`listening to ${port}`);
})

A: Currently the /login route is creating a new user by calling new Auth() and logging in with it regardless of if the password does not match the one being stored.
You should be able to use the passport.authenticate method on your route to verify that the user is registered in your Mongo database. This method also automatically calls req.login.
app.post("/login", passport.authenticate("local",{
    successRedirect: "/secret",
    failureRedirect: "/login"
}));

Here is a fully example that uses passport-local-mongoose for reference: https://gist.github.com/yukeehan/23fbbe53f1ca94be440161c1562b489a


text:
Q: Uploading data in Blackberry using POST method in HTTPS I am trying to figure out how to upload a data using HTTPS POST method in Blackberry. The following code worked well when i tried it on HTTP. I just want to know what did i miss here
            String _postData = "LATITUDE="+lat+"&LONGITUDE="+lng+"&"+"NAME="+name+"&NRIC="+ICNo+"&PLATENO="+VehicleNo+"&CONTACTNO="+ContactNo+"&LOCATION="+ADDRESS;
            OutputStream os;

            //the preferred network is already arranged here
            int[] preferredTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_TCP_CELLULAR};
            ConnectionFactory factory = new ConnectionFactory();
            factory.setPreferredTransportTypes(preferredTransportTypes);

            ConnectionDescriptor connDescriptor = factory.getConnection("https://example.com");
            if(connDescriptor==null){
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        Dialog.alert("Invalid Network. Please check your network set up.");

                    }
                });
            }else{

                final HttpsConnection https = (HttpsConnection) connDescriptor.getConnection();

                https.setRequestMethod(HttpsConnection.POST);
                byte [] postDataBytes = _postData.getBytes("UTF8");
                `enter code here`https.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
                https.setRequestProperty("Content-Language", "en-US");
                https.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                os = https.openOutputStream();
                os.write(postDataBytes);
                os.flush();
                os.close();
                int state= https.getResponseCode();

                if(state==HttpsConnection.HTTP_OK){
                    UiApplication.getUiApplication().invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            Dialog.alert("SOS sent. Our customer care personnel will contact you shortly.");

                        }
                    });
                } else {
                    UiApplication.getUiApplication().invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            Dialog.alert("Failed to send SOS .");
                        }
                    });
                }
            }
        } catch(Exception e) {}

When the above code was executed, the application received HttpsConnection.HTTP_OK and show the dialog that the SOS was sent. But the data is not uploaded in the server.


text:
Q: What does IE use //@ in javascript for? So, a bug in a piece of javascript revolved around code similar to :
<script>
    (function() {
        if (true) {
            //@todo: do we need to set total or -- ?
            alert('hello?');
        }
    })();
</script>

In the larger system IE complained "Expected ';' ".  In the small scale example IE simply caused a warning about blocking ActiveX controls.
Obviously, "//@" has some context to activeX controls in IE.  I was unable to find this as searching for the symbols was useless, and any search about special comments in IE result in the conditional html comments.  I am just curious how the //@ are supposed to be used in IE.

A: The IE JScript engine supports conditional comments which turn comments written in a particular way into code (partially). However, you are not using those.
In your case it seems to be a way to tell e.g. an IDE that there is a TODO item. The error you got is most likely unrelated.

A: Unless there's some quirk about IE that I don't know, the //@todo is just commenting fluff that some programmers use when they are too lazy/don't know how to implement something.


text:
Q: Unity Addressables: RemoteProviderException : TextDataProvider : unable to load from url /base.apk!/assets/aa/settings.json I have followed closely the samples for using the play asset delivery in my project as it is from here:
https://github.com/Unity-Technologies/Addressables-Sample
I have prepared a single addressable package with a few scenes in it and marked it On-Demand. When I test in the editor (via Addressables.InitializeAsync() and Addressables.DownloadDependenciesAsync) all works fine. The pack is loaded and scene displayed. When I upload the instant app to the play console (internal testing) and run it on device, I get the following error 404 and other errors after that (see below). It seems looking for the settings.json in the base apk, but that file is in the bundle. How can I fix this? Tried with two devices and got the same error.

quote RemoteProviderException : TextDataProvider : unable to load from url : jar:file:///data/app/~~ZhQZpprHVhrDt8BlKkhj-Q==/com.xxx.yyy-fghV3Mdrsb3j3mBwDmAVsg==/base.apk!/assets/aa/settings.json
05-02 22:28:26.378 14876 14929 E Unity : UnityWebRequest result : ProtocolError : HTTP/1.1 404 Not Found
05-02 22:28:26.378 14876 14929 E Unity : ResponseCode : 404, Method : GET
05-02 22:28:26.378 14876 14929 E Unity : url : jar:file:///data/app/~~ZhQZpprHVhrDt8BlKkhj-Q==/com.xxx.yyy-fghV3Mdrsb3j3mBwDmAVsg==/base.apk!/assets/aa/settings.json
...
RuntimeData is null. Please ensure you have built the correct Player Content.
...
Addressables - Unable to load runtime data at location UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle1[[UnityEngine.AddressableAssets.Initialization.ResourceManagerRuntimeData, Unity.Addressables, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]. 05-02 22:28:26.380 14876 14929 E Unity : OperationException : Addressables - Unable to load runtime data at location UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle1[[UnityEngine.AddressableAssets.Initialization.ResourceManagerRuntimeData, Unity.Addressables, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].
...
OperationException : ChainOperation failed because dependent operation failed
05-02 22:28:26.417 14876 14929 E Unity : UnityEngine.AddressableAssets.InvalidKeyException: Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown. No Location found for Key=MainMenu

A: I could try to provide some more info hopefully to help someone else who had the same issue.
The "Split Application Binary" (enabled) option in Player Settings is responsible for dividing the aab and adding a part called asset-slices. If the addressables groups and .androidpack folders (I missed that part) are not setup properly, unity will move the settings.json file to the asset-slices folder and this will result to this error, because the json is no longer part of the base apk.
So to fix this, make sure "Split Application Binary" is disabled and the .androidpack folders are into place.


text:
Q: If the input was no number php I made a form where someone could order a product, (they have to order at least 1 product in order to continue) when they click submit they will be taken to a confirmation page with the order and their personal details where they can print or change their order.
But if someone wants to they can change the script within the source code and enter text, images or - numbers using html code or just -10. So they can order -10 of a product.
Now i wanted to make some kind of protection on the confirmation page that if $number is no number or if $number contains something else then numbers it will go echo ""; so it won't show up.
i'm running this array which will place the order in the confirmation page table:
    $total_price = 0;
    $count = 0;
    foreach ($products as $key => $product){
      $number = isset($_POST[$key])?$_POST[$key]:'';
            if (!$number){
            $count++;
            echo "";
            } else {
        echo "
";
            echo "";
                echo $product;
            echo "	";
            echo "";
                echo htmlspecialchars($number);
            echo "	";
            echo "";
                $price = $prices[$count]* $number;
                echo "&#8364 ", number_format($price, 2);
            echo "	";
        echo "
";

        $total_price += $price;
        $count++;
        }
    }

So whenever !$number (the field is empty) it will skip the product. So only products that have something put in the input field it will show on my order. But as i told you before you can enter letters negative numbers whatever you want. Caus it only checks if the field is empty or not.
Any help is greatly appreciated, maybe someone knows a better way of protection, using preferably PHP since it can't be found in the source code.
Thanks in advance!

A: To detect if a string contains a numeric string use is_numeric():
if(is_numeric($input)) {
    echo 'Input is a number';
}

A: You could start with is_numeric , then when you're sure it's a number, test if it's over 0 ...


text:
Q: How to display HTML Page as in gridview c#? Hi I am developing a html tag based user input, like a rich text box, which saves all the data into a database; including all the html tags.
I then am pulling this data using gridview in asp.net c#.
But when the gridview displays my data, it displays incorrectly.
For example: a user enter his name in bold in the rich textbox as such  < b > Superman < /b >, to make it bold. Sadly the gridview displays ecxactly what was entered tags and all without making it bold.
Another example: To enter the name in italics:< i > Superman < /i >, Superman is being display, not in italics.
What I want is for the gridview to display like an HTML PAGE, just like the rich textbox does.
I am using to write question. <-- no idea
Can you help me please?
Thanks

A: when you bring the html(because that is what you are asking them to enter) back to the view, you are either going to need to transform it yourself or eval the html as is mentioned by @MikeB
alternatively if you are not using Razor try this question for some ideas:
Is there a way to insert Html into a gridview row?

A: You need to display the raw html.  Otherwise it is html encoded to prevent people from being able to run scripts against your site.
You need to be extremely careful displaying user inputted raw html.
If you are using razor it will be something like this:
@Html.Raw(ViewBag.HtmlOutput)


text:
Q: PHP Array Contain string i create a method that will read a file with the application/octet type and here are some of the code.
Raw data :
GTHHS;MEKID Interface;5496;2012-07-20;
 NM1;081;IN1;980898989;2001-01-15;Mr;Gaf;Uhkil;Uhkil,Gaf;PRI;Gaf
 $contents = file_get_contents($tmp_filename);
 $stringContents = explode(";", $contents);

Now it gives me this output :
Array
(
    [0] => GTHHS
    [1] => MEKID Interface
    [2] => 5496
    [3] => 2012-07-20
NM1
    [4] => 081
    [5] => IN1
    [6] => 980898989
    [7] => 2001-01-15
    [8] => Mr
    [9] => Gaf
    [10] => Uhkil
    [11] => Uhkil,Gaf
    [12] => PRI
    [13] => Gaf
PR1
    [14] => 081
    [15] => IN1
    [16] => 20730089
    [17] => 7 The Schooner
    [18] => Auhaas
    [19] => Huuula Ave
    [20] =>
    [21] => Kishma
PR2
    [22] => 081
    [23] => IN1
    [24] => 232323233
    [25] => 400006
    [26] => HGD
    [27] => M
    [28] => M
    [29] => 2007-10-16
    [30] => 1976-03-31
);

How can i make the NM1, PR1 as the head of array like this :
Array (
     [NM1] = array(
            [0] => GTHHS
            [1] => MEKID Interface
            [2] => 5496
            [3] => 2012-07-20
            )
);

I am planning also to make the inner array [0]-[3] as json.

A: If you explode the contents by \n you have each line starting with that identifier. If you then just explode by ; in that line and add it as a sub array, you got it like you want.
This actually looks like a plain old CSV file with your ifentifier in line one. If so, try something like this:
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE)
    {
        $key = array_shift($row);
        $data[$key] = $row;
    }
    fclose($handle);
}

echo json_encode($data);

http://php.net/manual/en/function.str-getcsv.php


text:
Q: Type initializer threw Exception using MVVM in uwp? Below the code for developing a simple UWP project using the MVVM concept. I'm struggling to solve a System.TypeInitializationException thrown on the AddEngineerviewmodel static property in the Locator class.
Inner exception pointing to the DataContext line in View.xaml:

Cannot find a Resource with the Name/Key primary [Line: 10 Position: 5]"} ..

Model:
public class AddEngineerModel : BindableBase
{

    private string _engrName;
    public string EngrName
    {
        get { return _engrName; }
        set
        {
            _engrName = value;
            RaisePropertyChanged("EngrName");
        }
    }

    private string _phoneNo;
    public string PhoneNo
    {
        get { return _phoneNo; }
        set
        {
            _phoneNo = value;
            RaisePropertyChanged("PhoneNo");
        }
    }

    private string _email;
    public string Email
    {
        get { return _email; }
        set
        {
            _email = value;
            RaisePropertyChanged("Email");
        }
    }

    private string _address;
    public string Address
    {
        get { return _address; }
        set
        {
            _address = value;
            RaisePropertyChanged("Address");
        }
    }

    private int _salary;
    public int Salary
    {
        get { return _salary; }
        set
        {
            _salary = value;
            RaisePropertyChanged("Salary");
        }
    }
}

ViewModel:
public class AddEngineerViewModel:BindableBase
{

    #region Constructor

    public AddEngineerViewModel(IAddEngineerDataService _engineerDataService, IDialogServices _dialog)
    {
        _engineerDataService = new AddEngineerDataServices(new AddEngineerData());
        _dialog = new DialogServices();
        LoadCommand();
    }

    #endregion

    #region Fields

    private static IAddEngineerDataService _engineerDataService;
    private static IDialogServices _dialog;

    private string _engrName;
    public string EngrName
    {
        get { return _engrName; }
        set
        {
            _engrName = value;
            RaisePropertyChanged("EngrName");
        }
    }

    private string _phoneNo;
    public string PhoneNo
    {
        get { return _phoneNo; }
        set
        {
            _phoneNo = value;
            RaisePropertyChanged("PhoneNo");
        }
    }

    private string _email;
    public string Email
    {
        get { return _email; }
        set
        {
            _email = value;
            RaisePropertyChanged("Email");
        }
    }

    private string _address;
    public string Address
    {
        get { return _address; }
        set
        {
            _address = value;
            RaisePropertyChanged("Address");
        }
    }

    private int _salary;
    public int Salary
    {
        get { return _salary; }
        set
        {
            _salary = value;
            RaisePropertyChanged("Salary");
        }
    }

    #endregion

    #region Methods

    #region Command

    public ICommand AddEngineerCommand { get; set; }
    public ICommand ViewEmployeeCommand { get; set; }

    private void LoadCommand()
    {
        AddEngineerCommand = new CustomCommand(Add, CanAdd);
        ViewEmployeeCommand = new CustomCommand(Views, CanView);
    }

    private void Views(object obj)
    {
        _dialog.ShowDialog();
    }

    private bool CanView(object obj)
    {
        return true;
    }

    private bool CanAdd(object obj)
    {
        return true;
    }

    private void Add(object obj)
    {
        _engineerDataService.Add_Engineer_Details(new AddEngineerModel { EngrName=_engrName,Email=_email,PhoneNo=_phoneNo,Address=_address,Salary=_salary });
    }

    #endregion

    #endregion
}

Locator:
public class Locator
{

    private static IDialogServices Dialog = new DialogServices();
    private static IAddEngineerDataService EngineerService = new AddEngineerDataServices(new AddEngineerData());
    private static ISupervisorDataServices SupervisorService = new SupervisorDataServices(new SupervisorData());

    private static AddEngineerViewModel _engineerViewModel = new AddEngineerViewModel(EngineerService, Dialog);

    public static AddEngineerViewModel EngineerViewModel
    {
        get { return _engineerViewModel; }
    }
}

app.xaml
  <Application.Resources>
    <locator:Locator x:Key="loc"/>
  </Application.Resources>

View.xaml
<Page
 Datacontext={Binding Source={StaticResources loc},Path=EngineerViewModel}/>

A: what about changing
<Page>
 Datacontext={Binding Source={StaticResources loc},Path=EngineerViewModel}
</Page>

to
<Page Datacontext={Binding Source={StaticResource loc},Path=EngineerViewModel}>
</Page>


text:
Q: How do I get a list of allowed values for an option? When using Mathematica how can I get a list of the allowed values of an option? As an example I can use the Options command as follows -
Options[Manipulate]

which gives me a list of available options
(* {Alignment->Automatic,AppearanceElements->Automatic,AutoAction->\
False,AutorunSequencing->Automatic,BaselinePosition->Automatic,\
BaseStyle->{},Bookmarks->{},ContentSize->Automatic,ContinuousAction->\
Automatic,ControlAlignment->Automatic,ControllerLinking->Automatic,\
ControllerMethod->Automatic,ControllerPath->Automatic,\
ControlPlacement->Automatic,ControlType->Automatic,DefaultBaseStyle->\
"Manipulate",DefaultLabelStyle->"ManipulateLabel",Deinitialization:>\
None,Deployed->False,Evaluator->Automatic,Frame->False,FrameLabel->\
None,FrameMargins->Automatic,ImageMargins->0,Initialization:>None,\
InterpolationOrder->Automatic,LabelStyle->{},LocalizeVariables->True,\
Method->{},Paneled->True,PreserveImageOptions->True,RotateLabel->\
False,SaveDefinitions->False,ShrinkingDelay->0,\
SynchronousInitialization->True,SynchronousUpdating->Automatic,\
TouchscreenAutoZoom->False,TouchscreenControlPlacement->Automatic,\
TrackedSymbols->Full,UnsavedVariables:>None,UntrackedVariables:>None} \
*)

I can use Options for a specific parameter, i.e.,
Options[Manipulate,ControlType]
(* {ControlType->Automatic} *)

But this doesn't tell me what the possible allowed values are for this option. Checkbox, Setter etc. Is there a command I can use to find the allowed values of an option?

A: What follows is merely @halirutan's answer expressed in Wolfram Language:
Fetch symbol names and options:
symbolNamesWithOption@opt_ :=
Quiet @
Cases[
  {#1, Options/@Unevaluated/@#2}& @@@
  ({#, ToExpression[#, InputForm, HoldComplete]}&/@Names@"*") // ReleaseHold
, {symbolName_, {___, (opt -> _) | (opt :> _), ___}} :> symbolName]

Assemble names of files to search in:
notebooksToSearchInForInfoOnOption@opt_ :=
FileNameJoin @
{ $InstallationDirectory
, "Documentation", "English"
, "System", "ReferencePages", "Symbols"
, # <> ".nb"}& /@
Prepend[symbolNamesWithOption@opt, ToString@opt]

(could probably be done smarter with a proper use of `Documentation``)
With a basic formatting…
justSomeGrid@optString_String :=
Grid[
  Prepend[#, Style[#, Bold]& /@
  {"Reference notebook", "Values for "<> optString}]
, Alignment -> Left]&

…show the results:
tableOfExamplesForOption@opt_ :=
With[{optString = ToString@opt}
, { Button[FileBaseName@#1, SystemOpen@#1
    , Appearance -> "Palette", ImageSize -> Automatic]
  , Row[#, ","]& @
    Cases[#2
    , RowBox[{optString, "\[Rule]", val_}] |
      RowBox[{optString, " ", "\[Rule]", " ", val_}] :>
      DisplayForm@val
    , \[Infinity]]}& @@@
  DeleteCases[
    {#, Quiet@Import[#, "NB"]}& /@
    notebooksToSearchInForInfoOnOption@opt
  , {_, $Failed}] // justSomeGrid@optString ]

An example:
tableOfExamplesForOption@Extension

Notes:

*

*please check symbolNamesWithOption@Method with Quiet omitted from its definition before trying the whole thing. There could be side-effects, and they may be version-dependent. From my experience, it's safe to run on 8.0 but I had to add an use at ou own risk warning

*pattern for search could be improved

*some searches are very slow in this implementation (try tableOfExamplesForOption@Method — I personally haven't yet had enough patience to wait for its result)

*reference notebooks called with buttons will stay at (and thus, may mess with) your recent files history

*using special contexts in Names one could search in definitions for examples values not covered in documentation

*symbolNamesWithOption@_String comes as a nice bonus

Still, I hope it adds something to the description in natural language.
Ideas on improvements are very welcome.

A: Unfortunately, there is no command which tells you that. There are several reasons for that. First, the possible option values are context dependent. This means, e.g. the option Method can be set to different values depending on whether you use it in NDSolve, FindRoot, etc..
Second, as you see with "Elements" or "ImageList" options of Export, options are not always symbols, but usage messages cannot be applied to strings and documentation to string options rarely exists as separate page.
Therefore, the only way you find out about possible option values is the documentation. Note, that you often have two places to look

*

*You want to know what the special option ControlType of Manipulate does, then you first check out the help page of Manipulate

*For general information about the option, if it is a symbol, you check out the help page of the symbol itself.


text:
Q: How to disable password encoding in grails 3.x.x I am facing issue while creating/updating password in grails 3.x.x Application. Whenever i try to enter any special case lets say "@" it encodes only this special character in password field.
Password value is coming from request body.
Example:
Real password : abc@555
Auto Encoded password : abc%40555

A: Grails by default uses a plugin that uses bcrypt algorithm to hash passwords for security.There are some configurable password hashing attributes. You can customize the password plugin with the grails.plugin.springsecurity.password.algorithm attribute.


text:
Q: OpenCV 3.0 Segmentation Fault (Bag of visual words) I am trying to set up a bag of visual words using openCV 3.0. I have looked a bit everywhere and all I seem to be able to find is code that is only compatible with versions in the 2.x domain. As of now this is what I have:
#include <opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

int main(int argc, const char** argv) {

    Ptr<FeatureDetector> features;
    Ptr<DescriptorExtractor> descriptors;
    Ptr<DescriptorMatcher> matcher;

    int MAX_ITER = 100;
    int EPS = 2;

    TermCriteria tc(MAX_ITER + EPS,1,0.001);

    int dictSize = 1000;
    int retries = 1;
    int flags = KMEANS_PP_CENTERS;
    BOWKMeansTrainer bowTrainer(dictSize,tc,retries,flags);

    BOWImgDescriptorExtractor bowDE(descriptors,matcher);

    Mat img1 = imread("/Users/Lucas/Desktop/pic2.jpg");
    Mat img2 = imread("/Users/Lucas/Desktop/2.jpg");

    vector<KeyPoint> keypoints,keypoints2;
    features->detect(img1, keypoints);
    features->detect(img2, keypoints2);

    Mat myFeatures;
    Mat myFeatures2;

    descriptors->compute(img1, keypoints, myFeatures);
    descriptors->compute(img2, keypoints2, myFeatures2);
    bowTrainer.add(myFeatures);
    bowTrainer.add(myFeatures2);

    Mat dictionary = bowTrainer.cluster();
    bowDE.setVocabulary(dictionary);

    cout << dictionary << endl;

    return 0;
}

I have put this together by using a few tutorials and snippets, but I am running into an issue. When the program gets to
features->detect(img1, keypoints);

it exits with a segmentation fault 11, whatever that means. Could someone help me and point out what it is I am doing wrong?

A: you have to create your FeatureDetector, DescriptorExtractor first. atm, you got null-pointer instances (that's your segfault).
   #include <opencv2/xfeatures2d.hpp>
   ...

   Ptr<FeatureDetector> features = xfeatures2d::SIFT::create();
   Ptr<DescriptorExtractor> descriptors = xfeatures2d::SIFT::create();
   Ptr<DescriptorMatcher> matcher = makePtr<BFMatcher>(NORM_L2);

note, that since you have to use SIFT or SURF, you will need the opencv_contrib repo installed for this


text:
Q: Service Stack 6 UI I recently upgraded to ServiceStack 6 and trying to get the API UI to work. I have 2 issues.
After I authenticate (I have custom CredentialsAuthProviderSync) I still get an error that I need to authenticate (requires Authentication)
I then took out authentication for a service to test without Authentication and I get the below error.
Unexpected token E in JSON at position 0.
The browser log shows: Couldn't find Request DTO for ...


text:
Q: Equivalence of Markov chain definitions I'm studying markovianity of quantum process and the two article that i'm reading right now refers to two different definition of classical markovianity.
The first one is the definition reported also here, and it is also what I studied in class.
The second one is essentially this. Both the article and Wikipedia refer to the same book, but there is no the proof of equivalence of the two definition.
My question is: how can I prove that are equivalent?
It seems reasonable to me that 1 implies 2, but I have no idea how to prove.
Implication 2 $\implies$ 1, I am not even sure is true.

A: Firstly I will prove general fact about Markow Chains and then I'll go to your definitions for the case of homogenous one.
Let $(X_n)$ be a discrete time process. I'll use the following notation:

*

*$\mu$ will be the distribution of $X_0$ that is $\mu(a):= \mu(\{a\}) = \mathbb P(X_0=a)$.

*$A_n(a,b) = \mathbb P( X_n = b | X_{n-1}=a)$ if $\mathbb P(X_{n-1}=a) > 0$ (that is $A_n$ can be interpreted as a matrix with entries - probabilities of certain direction in $n'$th step).
Now our definitions are:
(1) $(X_n)$ is a Markow Chain if $\mathbb P(X_{n+1} = a_{n+1} | X_n = a_n , ... ,X_0 = a_0) = \mathbb P(X_{n+1} = a_{n+1} | X_n = a_n)$ for any $a_0,...,a_{n+1}$ such that it makes sense ( $\mathbb P(X_n = a_n ,... , X_0 = a_0) > 0 $)
(2) $(X_n)$ is a Markow Chain if $\mathbb P(X_0=a_0,...,X_n = a_n) = \mu(a_0)A_1(a_0,a_1)A_2(a_1,a_2)...A_n(a_{n-1},a_n)$ for any $a_0,...,a_n$ such that it makes sense.
Proof:
Direction (1) $\Rightarrow$ (2)
We're work with induction. Note that $\mathbb P(X_0 = a_0) = \mu(a_0)$ by definition of $\mu$, so the induction basis holds. Assume it holds for $n-1$. Then for $n$ we get:
$$ \mathbb P(X_0=a_0,...,X_n=a_n) = \mathbb P(X_{n} = a_{n} | X_{n-1}=a_{n-1},...,X_0=a_0) \mathbb P(X_{n-1} = a_{n-1},...,X_0=a_0)$$
where we used definition $\mathbb P(A \cap B) = \mathbb P(A | B) \mathbb P(B)$. Now for the first term on the right apply definition (1) and for the second term apply induction step, to get:
$$ \mathbb P(X_0=a_0,...,X_n=a_n) = \mathbb P(X_n =a_n | X_{n-1}=a_{n-1})\mathbb P(X_{n-1}=a_{n-1} | X_{n-2} = a_{n-2})... \mathbb P(X_0=a_0)$$ what can be rewritten as $$ \mathbb P(X_0=a_0,...,X_n=a_n) = \mu(a_0)A_1(a_0,a_1)...A_n(a_{n-1},a_n)$$
Direction (2) $\Rightarrow$ (1)
Simplier, just definition of conditional probability (conditioned on event with prob. greater than $0$)
$$ \mathbb P(X_n=a_n | X_{n-1}=a_{n-1},...,X_0=a_0) = \frac{\mathbb P(X_n=a_n,...,X_0=a_0)}{\mathbb P(X_{n-1}=a_{n-1},...,X_0=a_0)}$$ And now use (2) for numerator and denominator to get $$ \mathbb P(X_n=a_n| X_{n-1}=a_{n-1},...,X_0=a_0) = A_n(a_{n-1},a_n) = \mathbb P(X_n = a_n | X_{n-1}=a_{n-1})$$
Homogenous case:
Note that in this case, we just have $A_n(a,b)$ is the same for every $n$, so we can just define $p(b|a) = A_1(a,b) = \mathbb P(X_1 = b | X_0=a)$ and $p(a) = \mathbb P(X_0=a)$ (that is we don't need to care about time when we want to go to different states, only about the states from which and where we go to).
Definition $1$ may be unchanged (or $\mathbb P(X_n = a_n | X_{n-1}=a_{n-1},...,X_0=a_0) = \mathbb P(X_1 = a_n | X_0=a_{n-1})$
Definition $2$ changes to $\mathbb P(X_n=a_n,...,X_0=a_0) = p(a_0)p(a_1|a_0)...p(a_n|a_{n-1})$ which is exactly the notation used in your definition.


text:
Q: Read String without defining length Is it possible to read a string using (call ReadString) without defining the length of the string which will be read? Before I call ReadString I must say how long the string will be:
mov edx, offset StringOffset
mov ecx, maxLenght
call ReadString
mov countOfChars, eax

Is there any way to read a string without defining max length?

A: I never made it with a ReadString call, but you can use the \0 at end of string to have the maxLength or read it mannually ?
    xor     eax, eax
    cmp     edi, 0
    jz      end
deb:
    cmp     BYTE[edi+eax], 0
    jz      end
    inc     eax
    jmp     deb
end:
    ...


text:
Q: ALTER SESSION SET NLS_LANGUAGE MYSQL Through combining v$session of my applications seem to have sessions running the following SQL:
ALTER SESSION SET NLS_LANGUAGE= 'ARABIC' NLS_TERRITORY= 'ARABIC' NLS_CURRENCY= '$' NLS_ISO_CURRENCY= 'ARABIC' NLS_NUMERIC_CHARACTERS= '.,' NLS_CALENDAR= 'ARABIC' NLS_DATE_FORMAT= 'DD-MON-RR' NLS_DATE_LANGUAGE= 'ARABIC' NLS_SORT= 'BINARY'

Any idea why these applications are performing these ALTER SESSION commands in MYSQL?
Guys, I have a few questions in MySQL, could you please help me.

*

*How do I change the NLS_LANGUAGE to ARABIC from the existing one ?

*By changing the NLS_LANGUAGE to ARABIC , would the MySQL data also
get changed to ARABIC ? What does NLS_LANGUAGE control MySQL?


text:
Q: How to read the text in the shape use python-docx How to read the text in the shape use python-docx?
I have tested the inline_shapes, which is an empty array.
The definition of inline_shape has no text either.
https://python-docx.readthedocs.io/en/latest/api/shape.html#docx.shape.InlineShapes
How could I read the name from the following docx?

A: python-docx does not support the arbitrary drawing at this moment.
https://python-docx.readthedocs.io/en/latest/user/shapes.html


text:
Q: SQL 2005 - Search stored procedures for text (Not all text is being searched) The following bits of code do not seem to be searching the entire routine definition.
Code block 1:
select top 50 * from information_schema.routines
where routine_definition like '%09/01/2008%' and specific_Name like '%NET'

Code Block 2:
SELECT ROUTINE_NAME, ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%EffectiveDate%' AND ROUTINE_TYPE='PROCEDURE' and ROUTINE_NAME like '%NET'

I know for a fact that these bits of SQL work under most circumstances. The problem is this: When I run this for "EffectiveDate" which is buried at line ~800 in a few stored procedures, these stored procedures never show up in the results. It's as if "like" only searches so deep.
Any tips on fixing this?
I want to search the ENTIRE stored procedure for the specified text.
Thanks!

A: Just to clarify why the procedure text is truncated:

ROUTINE_DEFINITION  nvarchar(4000)
Returns the first 4000 characters of
  the definition text of the function or
  stored procedure if the function or
  stored procedure is not encrypted.
  Otherwise, returns NULL.
To ensure that you obtain the complete
  definition, query the
  OBJECT_DEFINITION function or the
  definition column in the
  sys.sql_modules catalog view.

A: Here's different approach if you are looking for a search feature against the SQL server databases. Basically the freely available search tool from RedGate.
Free 'Search' from Redgate

A: select *
FROM   INFORMATION_SCHEMA.ROUTINES
WHERE  OBJECTPROPERTY(OBJECT_ID(SPECIFIC_NAME),'IsMSShipped') =0
       and OBJECT_DEFINITION(OBJECT_ID(SPECIFIC_NAME)) like '%EffectiveDate%'
       AND ROUTINE_TYPE='PROCEDURE'
       AND ROUTINE_NAME like '%NET'

Use the object definition instead.

A: very fast,live and handy
Direct link
http://www.red-gate.com/products/SQL_Search/index.htm


text:
Q: Drupal 6: sort display of node references I have a content type that references multiple nodes, and I need a way to sort the display of those referenced nodes.
Any ideas?
--- EDIT ---
Clarification:
I'm not using views, but rather am using my own queries.
I have a bunch of teachers (teacher content-type), and some conferences (conference content-type).
Within the conference content-type I want a node-reference field set to handle multiple teacher selections.  But I need to be able to manually order them independently. What that means is that each individual conference needs to be able to sort the order of the particular teachers selected.
That's the ideal situation, but not the way I'm actually doing it.
What I'm ACTUALLY doing to jury-rig this thing is to have separate node-reference fields (teacher 1, teacher 2, teacher 3 etc.).  Each node-reference field independent of the others.
It makes for a mess when it comes to creating views or composing db queries.
I know what I'm looking for is all but impossible, but I thought I'd run it by the Drupal gurus here anyway...
--- EDIT 2 ---
Further clarification:
Another way to do what I want, but is really impractical, is to create a separate nodequeue for each conference. Then you could select a handful of teachers associated with each conference and order them via the nodequeue. - That should help with visualizing the problem.  But as a solution, it's even more messy (in terms of administration) than the one I'm currently using.
Also: I should mention that we're talking about 40 to 80 conferences, and 100-200 teachers.  Just to get an idea of why I'm looking for a more elegant solution than the two I mentioned above.

A: Node reference with autocomplete widget gives you reordering capabilities when number of values set to 'unlimited'. Maybe not the most comfortable, but works.

A: I'm assuming you're using Views since you mentioned "displays". You can always change the order of the view fields from the Views UI but the order will be static (all items will have the same order).
If you want each item to have a potentially different order for the fields maybe you can set up a parent child relationship where the child item is ordered dynamically.


text:
Q: Where does Mutt save attachment? I use v to open attachment list and select an item and hit s to save it.
Q1. Now where does Mutt save the attachment?
Q2. How to define a directory where I want to save attachments?
Thanks in advance.

A: After you hit s and before you hit Enter, mutt proposes a default file name (which is the original name of the attachment). At this point, you can provide mutt with a new directory (and with a different file name).
So if mutt proposes attach.ment, just fill in the path you need the file saved to, ~/your/desired/folder/attach.ment and hit Enter.
If you want to save attachments always in the same folder, John1024 describes how to do it.

A: There's no config option (AFAIK) but here's a simple work around.
The following alias will save your files into an "attachments" folder in your home directory:
alias mutt='cd $HOME/attachments;/usr/bin/mutt;cd -'
Add it to your .bashrc or .bash_profile.

A: By default, mutt saves attachments to whatever the current directory was when you started mutt.
If you want to save to a particular directory, cd to that directory before starting mutt:
cd mypreferreddirectory
mutt

mutt also allows you to define many powerful macros.  To define a macro "W" for saving to a particular directory, put the following in your ~/.muttrc file:
macro attach W <save-entry><kill-line>/home/gawron/attachments/

For more on this, see the mutt FAQ.

A: This page suggest that procmail determines where the attachments are saved. In that case, check the file .procmailrc in your home directory. It should have a line like SAVE =$MAILDIR/save which specified where attachments are saved, likely defaulting to your mail directory. It should also have a line like MAILDIR =$HOME/Mail which will identify your mail directory.
In your case, it might be /home/shinokada/mail/save/.
Naturally, to specify where attachments are saved, just change the SAVE variable.


text:
Q: Webview screen shows nothing I have a topic.
I have a webview in my ionic app, it works all the pages that use https I understand. But when I use this link: https://portal.argos.com.do/, because the screen goes blank and says nothing else. That happens when I use it as _self. Anyone know why?
Code:
openurl(url: string) {
    const options: InAppBrowserOptions = {
      zoom: 'no'
    };
    const bro = this.browser.create(url, '_self', options);
}

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true"
          android:versionCode="1" android:versionName="0.0.1"
          package="io.ionic.starter"
          xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true"
                      android:largeScreens="true"
                      android:normalScreens="true"
                      android:resizeable="true"
                      android:smallScreens="true"
                      android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
            android:hardwareAccelerated="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:networkSecurityConfig="@xml/network_security_config"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
                  android:label="@string/activity_name"
                  android:launchMode="singleTop" android:name="MainActivity"
                  android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
                  android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

A: What happens is that the page even if it says https is not completely secure, because the server uses a TLS 1.0 and not the updated ones now. You can find some pages that verify your SSL certificate just in case:
https://www.dondomain.com/products/ssl/tools/ssl-checker/
https://www.ssllabs.com/ssltest/analyze.html
Then the solution would be to ignore the SSL of the page.
Also a way to test and know more in depth is (in my case) with android studio see the emulator log of my application and use this code to ignore the SSL and know what is the cause it has here:
https://stackoverflow.com/a/49786820/11150506
So in ionic what should be done is to ignore the SSL and the page will be displayed, but the play store may not allow it, so it should create a way for the user to cancel the action of going to the page Not sure yes or no.
It is the same here:
Webview: Failed to validate the certificate chain (android java)


text:
Q: What is the important dll files to execute any Qt5 application on any platform (Runtime files dll)? I have created a simple application in Qt5 but, when run that application in for example windows 7, tells me the dll file something is missing, and another dll and another dll.
Now I want a package that contain all dll files that any Qt application needed.
Or, What's the Important dll files that needed to work any Qt application ?

A:
Or, What's the Important dll files that needed to work any Qt application ?

In general, the Qt modules that you are using. If you use QtSql, you need to have the corresponding dll, but it goes the same way for any module. As for a simple core application, you would need to have the QtCore dll, respectively. I could continue the enumeration, but I believe you see the pattern how it goes.
Going even a bit further, you would need to specify your dependencies in the LIBS variable if you happen to use qmake. That is also a place where you would already need to be aware of your direct dependencies.
It would be usually the single library name, but in complex cases, you can always read the documentation of the project. The main point is the fact that you need to get aware of this without debugging. The latter would be more like an after-thought.
There are no "hidden dependencies". Since you are coding the project, you know the dependencies that you use. You will need to ship them.
There are some odd and rare cases when issues come that you would not be aware of, like missing dll for a different machine having a distinct VS/MSVC setup. In that case, it is better not to ship all the dlls for each possible end machine, but the end machine is supposed to install redistributable packages.
In rare cases when the above does not suffice, you can check the error message. If that is still unclear, you can use introspection tools for debugging the issue, like dependency walker.
Disclaimer: this answer goes as broad as the question is.


text:
Q: CakePHP: command cake server hangs on xampp I have a basic XAMPP install on windows 10, and I've installed cakePHP, with no errors.
When I run bin/cake server in the xampp terminal, it tells me it's started on localhost:8765, and that I can press CTRL-C to return. It hangs here, shell goes unresponsive, and trying to hit localhost:8765 in the browser hangs indefinitely.
I can view the apache page at localhost:80, with no issue. Any help would be greatly appreciated.

A: Im almost definetly sure, that you have debugging turned on somewhere, and PHP script hangs on first line. Do you have any IDE opened during that procedure? If so, close it, restart php server and try again. It should work now.
I had similar WTFs working with PHPStorm, that unwanted debugging sessions was paused on "script first line" exposing behavior you have described.