text:
Q: Loading a custom json file - highcharts.js I have a problem with loading the .json file:
[
    [
        [
            "2014-11-19 06:00:00",
            "1.1"
        ],
        [
            "2014-11-19 14:00:00",
            "4.9"
        ],
        [
            "2014-11-19 15:00:00",
            "4.9"
        ],
        [
            "2014-11-19 16:00:00",
            "4.9"
        ],
        [
            "2014-11-19 17:00:00",
            "4.9"
        ],
        [
            "2014-11-19 18:00:00",
            "4.9"
        ]
    ],
    [
        [
            "2014-11-13 23:00:00",
            "194"
        ],
        [
            "2014-11-14 00:00:00",
            "195"
        ],
        [
            "2014-11-14 01:00:00",
            "187"
        ],
        [
            "2014-11-14 02:00:00",
            "191"
        ],
        [
            "2014-11-14 03:00:00",
            "218"
        ],
        [
            "2014-11-14 04:00:00",
            "170"
        ]
    ]
]

values:
[[data, valueTemperature],[data,WindMax]]

I tried in this way, but does not work:
$(document).ready(function () {
 var options = {
    chart: {
        renderTo: 'container',
        type: 'spline',
        zoomType: 'xy'
    },

    title: {
        text: 'Temperatura'
    },

    subtitle: {
        text: '5 dni'
    },

    xAxis: {
        type: 'datetime',

    },

    yAxis: [{ // Primary yAxis
        labels: {
            format: '{value}°C',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        },
        title: {
            text: 'Temperature',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        },

        min: -25,
        max: 25,
    }, { // Secondary yAxis
        title: {
            text: 'Prędkość wiatru',
            style: {
                color: Highcharts.getOptions().colors[0]
            }
        },
        labels: {
            format: '{value} m/s',
            style: {
                color: Highcharts.getOptions().colors[0]
            }
        },
        min: 0,
        max: 15,
        opposite: true
    }],

    tooltip: {
        shared: true
    },

    series: [{}]
};

var chart;

$.getJSON('test.json', function (data) {
    options.series[0].data = data;
    chart = new Highcharts.Chart(options);

});

});

How to correctly write it for a data type?

A: There are a few issues:

*

*You've stored numeric data as strings. While trying to find a solution, I had to strip the "'s off the temperature and wind speed values or I'd get Highcharts Error #14

*You have two data series, yet you are only creating one object in options.series. You should be creating two series objects and adding them to the options.series array.

*For the second series, you must specify which y axis to use. In this case yAxis == 1.

*The max value for your second y axis is too low to display the data.

Here's an example to showcase the above: http://jsfiddle.net/6yvdkp20/1/
$(function () {
    var options = {
        chart: {
            renderTo: 'container',
            type: 'spline',
            zoomType: 'xy'
        },
        title: {
            text: 'Temperatura'
        },
        subtitle: {
            text: '5 dni'
        },
        xAxis: {
            type: 'datetime',
        },
        yAxis: [
            { // Primary yAxis
                labels: {
                    format: '{value}°C',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                },
                title: {
                    text: 'Temperature',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                },

                min: -25,
                max: 25,
            }, { // Secondary yAxis
                title: {
                    text: 'Prędkość wiatru',
                    style: {
                        color: Highcharts.getOptions().colors[0]
                    }
                },
                labels: {
                    format: '{value} m/s',
                    style: {
                        color: Highcharts.getOptions().colors[0]
                    }
                },
                min: 0,
                max: 200,
                opposite: true
            }
        ],
        tooltip: {
            shared: true
        },
        series: [
            {
                data: [
                    [
                        "2014-11-19 06:00:00",
                        1.1
                    ],
                    [
                        "2014-11-19 14:00:00",
                        4.9
                    ],
                    [
                        "2014-11-19 15:00:00",
                        4.9
                    ],
                    [
                        "2014-11-19 16:00:00",
                        4.9
                    ],
                    [
                        "2014-11-19 17:00:00",
                        4.9
                    ],
                    [
                        "2014-11-19 18:00:00",
                        4.9
                    ]
                ]
            },{
                yAxis: 1, // This means the second yAxis will be used to plot this series
                data:[
                    [
                        "2014-11-13 23:00:00",
                        194
                    ],
                    [
                        "2014-11-14 00:00:00",
                        195
                    ],
                    [
                        "2014-11-14 01:00:00",
                        187
                    ],
                    [
                        "2014-11-14 02:00:00",
                        191
                    ],
                    [
                        "2014-11-14 03:00:00",
                        218
                    ],
                    [
                        "2014-11-14 04:00:00",
                        170
                    ]
                ]
            }
        ]
    };

    $('#container').highcharts(options);
});

Since you mentioned in the comments that you cannot change the format of the data you are fetching, you will need to correct the format after receiving the data. The following function should correctly do that (though I make no guarantees):
function fixFormat(data) {
    for(var i = 0; i < dataSeries[0].length; ++i) {
        dataSeries[0][i][1] = parseFloat(dataSeries[0][i][1]);
    }

    for(var i = 0; i < dataSeries[1].length; ++i) {
        dataSeries[1][i][1] = parseInt(dataSeries[1][i][1]);
    }
}

Usage:
$.getJSON('http://kamery.topr.pl/meteo/charts/moko.php', function (data) {
    // Correct the formatting
    fixFormat(data);

    // Put the data in the right place
    options.series[0].data = data[0];
    options.series[1].data = data[1];
});


text:
Q: save images into database i want to retrieve contacts and images and show them into list view and save images and contacts into database, in another activity i want to retrieve contacts from database with images and show them into list view i m able retrieve contacts but how to save images into database and after that how to retrieve images from database
i using this method to save data into database
public void addBlockedNumberWithImage(String number, String name,
        byte[] image) {

    // Add a new blocked number
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(BLOCKLIST_NUMBER, number);
    values.put(BLOCKLIST_NAME, name);
    values.put(CONTACT_IMAGE, image);

    /* Inserting the entry */
    db.insert(TABLE_BLOCKLISTWITHIMAGE, null, values);
    db.close(); // close the database connection
}

DbHelper db = new DbHelper(this);
db.addBlockedNumberWithImage(phoneNumber, name, image);

A: Instead of saving the images into a database, I'd instead save the images to somewhere on the device (preferably the SD card), and in the database save the location of each image
Then when you want to display them, you can simply retrieve the path to the image from the database, and load it up :)

A: In my application i am uploading an image from gallery and the image which i uploaded want to store in database.But how to store bitmap in database i am converting bitmap to string and saving in database.
Imageupload.class:
public class Imageupload12 extends Activity {
Button buttonLoadImage;
ImageView targetImage;
int i=0;
Database database=new Database(this);
String i1;
String img;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
buttonLoadImage = (Button)findViewById(R.id.loadimage);
targetImage = (ImageView)findViewById(R.id.targetimage);

Bundle b=getIntent().getExtras();
if(b!=null)
{
img=b.getString("image");
targetImage2.setImageURI("image");
//i am getting error as i cant assign string to imageview.

}

buttonLoadImage.setOnClickListener(new Button.OnClickListener(){

public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Log.i("photo",""+intent);
startActivityForResult(intent, i);
i=i+1;
}});

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {

case 0:
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
// textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);

i1=bitmap.toString();
Log.i("firstimage........",""+i1);
targetImage.setVisibility(0);

SQLiteDatabase db=database.getWritableDatabase();
db.execSQL("INSERT INTO UPLOAD VALUES('"+i1+"');");

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;

}

}
}

Image.class:
public class Image extends Activity {
Database database=new Database(this);
static EfficientAdapter adapter, adapter1;
static ListView lv1;

static SQLiteDatabase db;
static EfficientAdapter adp;
static Cursor c1;

static Vector<String>IMAGE=new Vector<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

db=database.getReadableDatabase();
c1=db.rawQuery("select * from UPLOAD;", null);

if (c1.moveToFirst()) {

do {
IMAGE.add(c1.getString(0).toString());

} while (c1.moveToNext());

c1.close();
}

lv1=(ListView)findViewById(R.id.List);

adapter=new EfficientAdapter(this);

lv1.setAdapter(adapter);

ImageView add=(ImageView)findViewById(R.id.imv1a);

add.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
IMAGE.clear();

Intent i=new Intent(Image.this,Imageupload12.class);
startActivity(i);

}
});

}

private static class EfficientAdapter extends BaseAdapter{

// protected final Context Context = null;
protected LayoutInflater mLayoutInflater;
AlertDialog.Builder aBuilder;
public EfficientAdapter(Context context) {
// TODO Auto-generated constructor stub
mLayoutInflater=LayoutInflater.from(context);
}

@Override
public int getCount() {
// TODO Auto-generated method stub

return IMAGE.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

final ViewHolder mVHolder;
if(convertView == null){
convertView=mLayoutInflater.inflate(R.layout.pjtlistdetails, parent, false);

mVHolder=new ViewHolder();

mVHolder.t1=(TextView)convertView.findViewById(R.id.pjtdetails);
mVHolder.time=(TextView)convertView.findViewById(R.id.name);

mVHolder.imv=(ImageButton)convertView.findViewById(R.id.editic);
mVHolder.imvd=(ImageView)convertView.findViewById(R.id.delete);
mVHolder.imvf=(ImageView)convertView.findViewById(R.id.fwd);

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

String img=IMAGE.elementAt(position);
Log.i("image...",""+img);

Context ctx=v.getContext();
Intent myIntent = new Intent();
ctx = v.getContext();
myIntent.setClass(ctx, Imageupload12.class);
myIntent.putExtra("image", img);

ctx.startActivity(myIntent);

IMAGE.clear();

}
});
static class ViewHolder{

ImageButton imv;
ImageView imvd,imvf;
}

to retrieve a image from db
public Bitmap getImage(int i){

String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);

if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}

return null ;
}

Its a very old code check if it works :)

A: Using the Base64 class, you can encode a bitmap into string and then store it to database.
The following sample code could be used:
Bitmap bitmapOrg =get bitmap from image;

ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

byte[] ba = bao.toByteArray();

String ba1 = Base64.encodeBytes(ba);

Now decode this string to use image.

A: Sample code to store and retrieve image from database using SQLiteOpenHelper class
package com.aliahmad.store_retrive_image;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataManager extends SQLiteOpenHelper
{
    public final static String tab="image";
    public final static String col1="iname";
    public final static String col2="id";
    public DataManager(Context context)
    {
        super(context, "MyData", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("create table image (iname text,id blob)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w(DataManager.class.getName(), "Upgrading database from version "+oldVersion+" to"+newVersion+", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS "+tab);
        onCreate(db);
    }

}

when store button clicked call this function
public void onStore(View v)
{
    try
    {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        //image is object of Bitmap that you want to store
        image.compress(CompressFormat.PNG, 100, baos);
        byte[] data=baos.toByteArray();
        SQLiteDatabase db=new DataManager(this).getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(DataManager.col1, et.getText().toString());
        cv.put(DataManager.col2, data);
        db.insert(DataManager.tab, null, cv);
    }
    catch (Exception e) {
        Toast.makeText(this, "Errro - "+e,1 ).show();
    }
}

to retrieve the image call this function
public void onRet(View v)
{
    SQLiteDatabase db=new DataManager(this).getReadableDatabase();
    Cursor cr=db.query(DataManager.tab, new String[]{DataManager.col2}, DataManager.col1+"= ?", new String[]{str[which]}, null, null, null);
    if(cr.moveToFirst())
    {
        byte [] b=cr.getBlob(4);
        ByteArrayInputStream imageStream = new ByteArrayInputStream(b);
        image= BitmapFactory.decodeStream(imageStream);
        iv.setImageBitmap(image);
    }
    else
    {
        Toast.makeText(this, "not found", 1).show();
    }
    db.close();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot use pyinstaller I am running windows and trying to use the pyinstaller module. When I run pyinstaller filename.py in cmd, the following error occurs:
Fatal error: PyInstaller does not include a pre-compiled bootloader for your
platform. For more details and instructions how to build the bootloader see
<https://pyinstaller.readthedocs.io/en/stable/bootloader-building.html>

So I tried building the bootloader using the link that was provided. There is a step that says to run the command python ./waf all. When I ran that, I got the following error:
python: can't open file './waf': [Errno 2] No such file or directory

I tried installing the waftools module to see if it would remedy this. It requires that I run the following two commands:
pip install -I waftools
wafinstall

When I run the first command, it works fine, but when I run the second command, I get a long traceback (found here), ending with this error:
FileNotFoundError: [Errno 2] No such file or directory: '.\\waf-waf-1.8.19\\waf'

This is where I get stuck, and I do not even know for sure if this would fix my original issue if I get it working correctly. What should I do?


text:
Q: Normal-gamma distribution in Python Is there an implementation of the Normal-Gamma distribution for Python? I have looked over the internet, including scipy, and could not find it.

A: I am not aware of any package which implements it.
But since its building blocks are the Gamma Distribution and the Normal Distribution you may use them from SciPy.
For instance, in order to generate samples you may do (From Wikipedia - Normal Gamma Distribution):

*

*Sample τ (\tau)  from a gamma distribution with parameters α (\alpha) and β (\beta).

*Sample x from a normal distribution with mean μ (\mu) and variance 1 / λ τ (1 / (\lambda \tau)).


text:
Q: BST List from a sorted Array This is a question from my lab and I am stumped. We basically get an array that is already sorted, and we have to use this array to create a BST in list format. (How does this even look like)? Here is the code that I have thus far, however it doesn't work at all and I don't know how to fix it:
    private static void buildBalancedRec(Integer [] tempArr, int start, int end,
        BinarySearchTreeList<Integer> bstList)
{
    if (bstList.size()<tempArr.length){
        Integer middle  = tempArr[(start+end)/2];
        bstList.add(middle);
        buildBalancedRec(tempArr, start , middle-1 , bstList);
        buildBalancedRec(tempArr, middle+1, end, bstList);
}

Assuming that the array we get is {1,2,3,4,5,6,7}. Start would be 1, and end would be 7. I am assuming the BST list is supposed to look like: {4, 2, 6, 1, 3, 5, 7}, is that correct? The BST would look like:
        4
       / \
      2   6
     /\   /\
    1 3   5 7

So I assumed what the list would look like from that.
How do I get there? And can I have two lines back-to-back for recursion as I have in my current code?
I tried many ways, however I can never get it to print {4, 2, 6, 1, 3, 5, 7}.
Any guidance would be greatly appreciated!
Note: the method needs to use recursion

A: Try with:
private static void buildBalancedRec(int[] tempArr, int start, int end, BinarySearchTreeList<Integer> list) {
    if (start < end) {
        int middle = (start + end) / 2;
        list.add(tempArr[middle]);
        buildBalancedRec(tempArr, start, middle, list);
        buildBalancedRec(tempArr, middle + 1, end, list);
    }
}

EDIT:
Full example:
private static void buildBalancedRec(int[] tempArr, int start, int end, List<Integer> list) {
    if (start < end) {
        int middle = (start + end) / 2;
        list.add(tempArr[middle]);
        buildBalancedRec(tempArr, start, middle, list);
        buildBalancedRec(tempArr, middle + 1, end, list);
    }
}

public static void main(String[] args) {
    int[] tempArr = {1, 2, 3, 4, 5, 6, 7};
    List<Integer> list =new ArrayList<>(tempArr.length);
    buildBalancedRec(tempArr, 0, tempArr.length, list);
    System.out.println(list);
}

It prints:
[4, 2, 1, 3, 6, 5, 7]

A: You could use something similar to the Day Stout Warren method, which converts a tree into a "vine" (like a linked list), then creates a balanced tree from the "vine', only in this case, the first step would be to convert the sorted array into a "vine".
https://en.wikipedia.org/wiki/Day%E2%80%93Stout%E2%80%93Warren_algorithm
Example code to rebalance a BST. In this case, code is needed to convert a sorted array into a "vine", then call the function vine_to_tree(). Don't forget the dummy node that starts the "vine".
//      rebalance binary search tree

#include <iostream>
#include <iomanip>

struct node {
    size_t value;
    node *p_left;
    node *p_right;
};

node *insert (node *p_tree, size_t value)
{
    if (p_tree == NULL) {
        p_tree = new node;
        p_tree->p_left = NULL;
        p_tree->p_right = NULL;
        p_tree->value = value;
    } else if (value < p_tree->value) {
        p_tree->p_left = insert(p_tree->p_left, value);
    } else {
        p_tree->p_right = insert(p_tree->p_right, value);
    }
    return p_tree;
}

node *delete_tree (node *p_tree)
{
node *p_node;
    while(p_tree != NULL){
        if(p_tree->p_left != NULL) {
            p_node = p_tree->p_left;
            p_tree->p_left = p_node->p_right;
            p_node->p_right = p_tree;
            p_tree = p_node;
        } else {
            p_node = p_tree;
            p_tree = p_tree->p_right;
            std::cout << "deleting " << std::setw(2) << p_node->value << std::endl;
            delete p_node;
        }
    }
    return NULL;
}

//  convert tree to vine (list) of p_rights
node * tree_to_vine(node *p_root, size_t *p_size)
{
node * p_vine_tail;
node * p_remainder;
node * p_temp;
size_t size;

    p_vine_tail = p_root;
    p_remainder = p_vine_tail->p_right;
    size = 0;
    while(p_remainder != NULL){
        if(p_remainder->p_left == NULL){    // if left == null, follow right path
            p_vine_tail = p_remainder;
            p_remainder = p_remainder->p_right;
            size = size + 1;
        } else {                            // else rotate right
            p_temp  = p_remainder->p_left;
            p_remainder->p_left = p_temp->p_right;
            p_temp->p_right = p_remainder;
            p_remainder = p_temp;
            p_vine_tail->p_right = p_temp;
        }
    }
    *p_size = size;
    return p_root;
}

size_t floor_power_of_two(size_t size)
{
size_t n = 1;
    while(n <= size)
        n = n + n;
    return n/2;
}

size_t ceil_power_of_two(size_t size)
{
size_t n = 1;
    while(n < size)
        n = n + n;
    return n;
}

// split vine nodes, placing all even (0, 2, 4, ...) leaves on left branches
// p_root->p_right->p_left = 0, p_root->p_right->p_right->p_left = 2

node * perfect_leaves(node * p_root, size_t leaf_count, size_t size)
{
node *p_scanner;
node *p_leaf;
size_t i;
size_t hole_count;
size_t next_hole;
size_t hole_index;
size_t leaf_positions;

    if(leaf_count == 0)
        return p_root;
    leaf_positions = ceil_power_of_two(size+1)/2;
    hole_count = leaf_positions - leaf_count;
    hole_index = 1;
    next_hole = leaf_positions / hole_count;
    p_scanner = p_root;
    for(i = 1; i < leaf_positions; i += 1){
        if(i == next_hole){
            p_scanner = p_scanner->p_right;
            hole_index = hole_index + 1;
            next_hole = (hole_index * leaf_positions) / hole_count;
        } else {
            p_leaf = p_scanner->p_right;
            p_scanner->p_right = p_leaf->p_right;
            p_scanner = p_scanner->p_right;
            p_scanner->p_left = p_leaf;
            p_leaf->p_right = NULL;
        }
    }
    return p_root;
}

//  left rotate sub-tree
node * compression(node * p_root, size_t count)
{
node *p_scanner;
node *p_child;
size_t i;
    p_scanner = p_root;
    for(i = 1; i <= count; i += 1){
        p_child = p_scanner->p_right;
        p_scanner->p_right = p_child->p_right;
        p_scanner = p_scanner->p_right;
        p_child->p_right = p_scanner->p_left;
        p_scanner->p_left = p_child;
    }
    return p_root;
}

//  convert vine to perfect balanced tree
node * vine_to_tree(node *p_root, size_t size)
{
size_t leaf_count; // # of leaves if not full tree
    leaf_count = size + 1 - floor_power_of_two(size+1);
    perfect_leaves(p_root, leaf_count, size);
    size = size - leaf_count;
    while(size > 1){
        compression(p_root, size / 2);
        size = size / 2;
    }
    return p_root;
}

//  reblance tree to perfect balanced tree
node * rebalance_tree(node *p_root)
{
node * p_pseudo;
size_t size;
    p_pseudo = new node;
    p_pseudo->value = 0;
    p_pseudo->p_left = NULL;
    p_pseudo->p_right = p_root;
    p_pseudo = tree_to_vine(p_pseudo, &size);
    p_pseudo = vine_to_tree(p_pseudo, size);
    p_root = p_pseudo->p_right;
    delete p_pseudo;
    return p_root;
}

int main()
{
node *p_tree = NULL;
size_t i;
    for(i = 0; i < 14; i++)
        p_tree = insert(p_tree, i);
    p_tree = rebalance_tree(p_tree);
    return 0;
}


text:
Q: Prompt for valid input using a for loop in Python? So basically on my homework I need to use a FOR loop checking if an input is greater than ten but less than 20... I only know basic python, and this is stumping me.
I've used a while loop, I understand how to use that. The for loop is what gets me.
num1 = int(input("Enter a number greater than 10 and less than 20."))
while(num1<=10 and num1>=20):
    print("Invalid. Try again.")
    num1 = int(input("Enter a number greater than 10 and less than 20."))

A: num1 = int(input("Enter a number greater than 10 and less than 20."))
myNumbers=[11,12,13,14,15,16,17,18,19]
for _ in iter(int, 1):
  if num1 not in myNumbers:
    print("Invalid. Try again.")
    num1 = int(input("Enter a number greater than 10 and less than 20."))

A: You are using the correct logic, but not using correct Boolean statements.
num = 0
while ((num >= 10 and num <= 20) == False):
    num = int(input("Enter a Num: "))

print("Num in range")

A: My guess is that maybe you could design a class for it with a for loop trial:
class Homework(object):
    def __init__(self):
        pass
    def range_validator(self, trial = 10):
        num1 = int(input("Enter a number greater than 10 and less than 20:\t"))
        for _ in range(0, trial):
            if num1 >= 10 and num1 <=20:
                print("Valid")
                exit()
            else:
                print("Invalid")
                self.range_validator()
                break

helper = """
Select an option:
    (1) => Enter a new integer
    (2) => Exit the program
"""
print(helper)
option = int(input("What would you like to do?\t"))

s = Homework()

while True:
    if (option == 1):
        s.range_validator()
    elif(option ==2):
        break
    else:
        break


text:
Q: Good LaTeX template for book about maths As I want to write a short "book" about Analysis I would like to work with a template which is good enough for readability, looks good and furthermore can handle dozens of my theorems, axioms, corollaries etc. by layouting them as good as possible. Can anyone suggest or even provide a good template which satisfies my needs?

A: From someone who has learned the hard way, I think it is best to start with the minimum set of packages:
\documentclass{book}
\usepackage{standalone}%
\usepackage{amsmath}%
\begin{document}
...
\end{document}

I would use the standalone package for dividing your chapters into separately compilable files.
Then add packages only as you need them. There are questions that help you decide What packages do people load by default in LaTeX?.
As you go you'll probably need to select a theorem package (amsthm, ntheorem), a list package (enumitem), and something for doing graphs and figures (tikz, pgfplots).  There are plenty of questions here on selecting those, but I included my preferences in parenthesis.

A: i would suggest using the amsbook document class.  it incorporates amsthm and amsmath, and is tuned particularly for use with math-heavy books.  several publishers other than the ams (american math society) base their house packages on amsbook.
for variations in the final appearance (while using exactly the same input), there are several ams "author packages" that format the output in the specified style of the different ams book series.  all are extensions to amsbook, guaranteeing consistency of input handling and the ability to switch smoothly from one style to another if desired.
there are some differences between amsbook and the basic latex book class, principally in the input style of the top matter and in the inclusion of starred chapter and section titles in the table of contents; these are "house style" matters based on traditional ams practices.  these decisions are subjective; your mileage may vary.
amsbook is part of the amscls collection (formerly ams-latex), which is included in the latex "required" components.  all are on ctan and in the tex live distribution.
disclaimer: before my retirement, i was one of the maintainers of the ams-latex collection, and principal support contact when ams authors encountered problems.

A: Here is the free available algebra book from Jim Hefferon: http://joshua.smcvt.edu/linalg.html/  You can download the sources and have a look into the preamble of
the document. You can get some ideas or use it as a skeleton for your book.

A: Your question seems a little fuzzy: Readability? Good looks? That's in the eye of the beholder. Likewise, there usually isn't much to a template. It sets up the basic structure of the files that you will input into it (such as the chapters). Since you indicate your book is in Analysis, you should use the amsbook format.  TUG (TeX User's Group) has a AMS book template that can get you started. The AMS (American Mathematical Society) has more in depth information to help authors prepare there books in the style of the AMS here. The link to author monograph packages might be especially helpful.
You should also be aware that most schools with math programs (at least in the US) have LaTeX templates to fit their style: example. Likewise, many book publishers have their LaTeX templates: Springer.
The AMS book template link I provided is fairly basic, but since you are talking about readability, it sounds like you are looking for more than basic. If that's so, consider a math book you like the typesetting on and check the website for their style files.


text:
Q: If I uninstall an application from one administrator account in Windows 7, does it delete it for everybody? On one of the laptops I use, there are two administrator accounts. I created one for myself and one for a friend of mine.
If I were to uninstall a program, would that also uninstall the program on my friend's account?

A: When you uninstall any program from your hard disk.
It will uninstall both accounts because you have only one hard disk in your computer and 1 Windows (Operating System).
if you want to access only one account you can change the permission of your program or when you install it some application asking for all user or any specific user then you can decide it that time.
I hope It will help you.

A: Mostly Yes, But the preferences of each user is specific to his account. That is, the software personalize to each user of the computer. But if you uninstall the software the software, in most cases, will be removed for all the users.
If the software is annoying you, I am not sure how. I can assure you there are ways to keep it quiet for you.

A: Yes it will remove the program for all accounts.


text:
Q: Is there a function to sort a bar graph by count instead of the default alphabetical in ggplot? I am trying to make a bar graph using ggplot2
the data looks like this (there are about 10000 observations) and i have around 60 different subgroups.
ID        subgroup            patient_group
1866      cancer              1
1877      heart failure       1
1878      cancer              2
1879      infection           1
...       ...

What I would like to do is sort the subgroups by count instead of alphabetically, so the graph is easier to read. this is my code so far.
ggplot(data = data, aes(x = subgroup, fill = patient_group)) +
  geom_bar(position = "dodge") +
  coord_flip() +
  ggtitle("Count of Subgroups of patients") +
  xlab("") +
  ylab("") +
  labs(fill = "Emerge Version")

Is there a way to reorder the bars without having to make a new dataframe for the subgroups?
Thanks!


text:
Q: Scala SBT Version Dependency Binary Compatibility Error scala-xml I have a project that I host on GitHub and I use scala-steward to keep my plugins and dependencies up to date. This worked for a while and now it is turning out to be a nightmare to use such auto updates. Here is the thing. In my plugins.sbt, I have a dependency to scoverage which was updated by scala-steward to version 2.0.6. But the pull request failed to pass through the compile stage and I see the following error:
[error] (update) found version conflict(s) in library dependencies; some are suspected to be binary incompatible:
[error]
[error]     * org.scala-lang.modules:scala-xml_2.12:2.1.0 (early-semver) is selected over {1.3.0, 1.2.0, 1.1.1, 1.0.6}
[error]         +- org.scoverage:scalac-scoverage-reporter_2.12:2.0.7 (depends on 2.1.0)
[error]         +- org.scalariform:scalariform_2.12:0.2.0             (depends on 1.0.6)
[error]         +- org.scala-lang:scala-compiler:2.12.16              (depends on 1.0.6)
[error]         +- com.typesafe.sbt:sbt-native-packager:1.5.2 (scalaVersion=2.12, sbtVersion=1.0) (depends on 1.1.1)
[error]         +- com.typesafe.play:twirl-api_2.12:1.5.1             (depends on 1.2.0)
[error]         +- com.github.sbt:sbt-native-packager:1.9.9 (sbtVersion=1.0, scalaVersion=2.12) (depends on 1.3.0)
[error]

First of all, it is good that such incompatibilities are reported during compile time to avoid any runtime surprises. But, I'm not sure how to get this fixed. Feels like I have hit a roadblock.
EDIT: Here is my actual project: https://github.com/joesan/plant-simulator

A: I had to do the following in my project/plugins.sbt file to get this error fixed:
ThisBuild / libraryDependencySchemes += "org.scala-lang.modules" %% "scala-xml" % VersionScheme.Always

I also added the following to my build.sbt:
ThisBuild / evictionErrorLevel := Level.Info

But I guess I do not need that in my build.sbt. Hope this helps someone! The Scala community at discord helped me to get this fixed. Thanks to them!


text:
Q: Normalise weights to produce midrange function signal I'm making a multilayer perceptron and I need to choose weights for input -> hidden unit. Our lecture said:

Aim is to select weight values which produce midrange function signals
Select weight values randomly from uniform probability distribution
Normalise weight values so number of weighted connections per unit
    produces midrange function signal

I'm not sure what he means by midrange function signal. So if weights for unit 1 is [0.5 0.9 0.1], do I just take the sum and divide each weight by the sum? Also is it for each input unit or output unit?
Many thanks.

A: Weight initialization
Midrange values
The weights should be initialized within such an interval that a learning algorithm should easily observe the concequences of manipulating a set of weights. By selecting weights from a small interval, the learning algorithm would only have to alter the weights by a small delta to observe a change in the output signal.
Uniform distribution
It is preferred to initialize the weights by selecting random variables from the range [-0.1, 0.1]. By statistical intuition, we may infere that choosing the weights uniformly from an "symmetric" interval around 0 will indeed imply that the average signal would approach the mean value. Eg:
weights = [-0.05, -0.05, 0, 0.1]
signal = 0.7
average(weights * signal)  = 0.7


text:
Q: Accessibility: Shifting focus from button to nested span – good idea? On a responsive website, I have a button for small screens that opens the site's main navigation menu. Inside that button there is a  that displays an icon using CSS.
For design reasons, I hide the text content of the button but keep it accessible for screen-reader users:
<button class="menu-operator button">
    Open menu

</button>

From a design point of view, the button is not visible as a button (no background-color, border or anything). To still support users with a visual clue on focus, I am thinking about making the button non-focusable and shifting focus to the icon span which I then can style with CSS :focus.
So basically this:
<button class="menu-operator button" tabindex="-1">
    Open menu

</button>

Is it advisable to do so? Will I introduce more problems than I solve with this idea?
In the past I've heard bad things about "stealing focus", but while testing my idea with OS X Voice Over I was surprised how good it works, so I am a bit unsure.

A: Your screen reader will read an action "open menu" and you won't be able to click. Strange behavior.
You should use title and aria-label attributes on the button to give the screen reader an alternative, and keep the button focusable.


text:
Q: Java Value of Field Not Used I have the class ModelPlayer, the int fields mainAction and quickAction and the method quickAction(), in the method basically I set the quickAction value and from that it executes one of 4 methods. But I get the warning that I'm not using quickAction and I wanted to know why, because one of the 4 methods can only be executed once I set the value of quickAction, so I don't understand why it says that I'm not using it.

(NOTE: the methods setQuickAction() and getQuickAction() shown in
  the method belong to the class Player, so they're not related)

public class ModelPlayer {
    private int mainAction;
    private int quickAction;

    public void quickAction(Player player,int quickAction){
        this.quickAction=quickAction;
        if (player.getQuickAction()>0){
            switch(quickAction){
            case '1':
                engageAssistant(player);
                player.setQuickAction(0);
            case '2':
                changeBusinessPermitTile(player);
                player.setQuickAction(0);
            case '3':
                electCouncillorWithAssistant(player);
                player.setQuickAction(0);
            case '4':
                mainAction(player,mainAction);
                player.setQuickAction(0);
            }
        }

        }

}

A: You are not using this.quickAction, but the parameter passed in input.
So you just assign a value to this.quickAction but you are not using it.
Try to substitute switch(quickAction) with switch(this.quickAction), the warning should go away.
Also you should use break after any case, see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

A: I believe you get this error because you use the quickAction method parameter
public void quickAction(Player player,int quickAction)

to evaluate the switch statement, and not the private class variable, hence the private class variable
private int quickAction;
...
this.quickAction

is not used anywhere, and therefore the error.

A: The IDE tells give you the warning because the quickActionfield is never actually used.
In public void quickAction(Player player,int quickAction) method, you're never actually using the field quickAction. You're using the quickAction passed in from the method.
There is a Javabean standard that dictates how you should structure your object and fields. You don't need to follow this standard but it is widely used for defining 'properties' in your class.
All you need to know is that for every field you consider a property of the class, you have a 'getter' and a 'setter' for it. Consider the code below
public class ModelPlayer {
    private int mainAction;
    private int quickAction;

    // make getters and setters for the fields
    public int getQuickAction { return quickAction; }
    public void setQuickAction(int quickAction) { this.quickAction = quickAction; }

    public int getMainAction { return mainAction; }
    pulbic void setMainAction(int mainAction) { this.mainAction = mainAction; }

    // remove the quickAction parameter because we can use the field 'quickAction'
    public void quickAction(Player player){
        if (player.getQuickAction()>0){
            switch(quickAction){
            case '1':
                engageAssistant(player);
                player.setQuickAction(0);
            case '2':
                changeBusinessPermitTile(player);
                player.setQuickAction(0);
            case '3':
                electCouncillorWithAssistant(player);
                player.setQuickAction(0);
            case '4':
                mainAction(player,mainAction);
                player.setQuickAction(0);
            }
        }
    }
}

This code will surely not have any errors. Eclipse and other IDEs even give you the option to generate these 'getters' and 'setters' from your fields in the class.


text:
Q: mongodb add an element to array of document by condition My document structure:
 "_id" : ObjectId("55e07b14bd1f3334f4d439ca"),
        "created" : ISODate("2015-08-28T15:15:32.251Z"),
        "userId" : 4790,
        "p2l" : [
            {
                "listId" : 31608,
                "status" : 25,
                "subscriptionDate" : ISODate("2015-09-16T12:33:03.893Z")
            },
            ...
        ]

I need find all documents where p2l.listId==value and then add to the p2l array a new document containing the same p2l.status, but with new listId and subscriptionDate values.
The example for finding this element:

        db.Profiles.find({
            "userId" : 4790,
            "p2l" : { "$elemMatch" : { "listId" : { "$in" : [31617, 31614] } } }
        })

How can I do an update then? I think it should be in the one query.
    I use C# Mongo Driver 2.0.
    For example:
    I have
"_id" : ObjectId("55e07b14bd1f3334f4d439ca"),
            "created" : ISODate("2015-08-28T15:15:32.251Z"),
            "userId" : 4790,
            "p2l" : [
                {
                    "listId" : 31608,
                    "status" : 25,
                    "subscriptionDate" : ISODate("2015-09-16T12:33:03.893Z")
                },
                ...
            ]

I need
     "_id" : ObjectId("55e07b14bd1f3334f4d439ca"),
            "created" : ISODate("2015-08-28T15:15:32.251Z"),
            "userId" : 4790,
            "p2l" : [
                {
                    "listId" : 31608,
                    "status" : 25,
                    "subscriptionDate" : ISODate("2015-09-16T12:33:03.893Z")
                },
                {
                    "listId" : 31615,
                    "status" : 25,
                    "subscriptionDate" : ISODate("2015-09-17T14:35:13.855Z")
                },
                ...
            ]

I find document, where userId=4790 and p2l.listId=31608, and then, add to this p2l new item with new listId = 31615 and subscriptionDate = 'ISODate("2015-09-17T14:35:13.855Z")', but old p2l.status = 25

A: Update it with $push operator
db.Profiles.update({
    "userId" : 4790,
    "p2l" : { "$elemMatch" : { "listId" : { "$in" : [31617, 31614] } } }
    },{'$push:{'p21':{..your new document..}}})


text:
Q: Dataset Query with condition on two subsequent rows The following Dataset
ds = Dataset@*Map[AssociationThread[{"ID", "Date", "Type"} -> #] &]@
{{"C09",SQLDateTime[{2013, 4, 2, 21, 50, 0.}], "D"}, {"C11",
SQLDateTime[{2013, 4, 24, 20, 35, 0.}], "T"}, {"C10",
SQLDateTime[{2013, 3, 21, 20, 0, 0.}], "T"}, {"C09",
SQLDateTime[{2012, 12, 11, 0, 0, 0.}], "V"}, {"C09",
SQLDateTime[{2013, 2, 19, 19, 30, 0.}], "D"}, {"C09",
SQLDateTime[{2013, 3, 8, 19, 40, 0.}], "T"}, {"C10",
SQLDateTime[{2012, 12, 12, 0, 2, 0.}], "V"}, {"C10",
SQLDateTime[{2013, 1, 28, 9, 25, 0.}], "T"}, {"C10",
SQLDateTime[{2013, 5, 24, 19, 45, 0.}], "D"}, {"C10",
SQLDateTime[{2013, 6, 1, 17, 0, 0.}], "T"}, {"C11",
SQLDateTime[{2012, 12, 10, 10, 0, 0.}], "V"}, {"C09",
SQLDateTime[{2013, 1, 22, 0, 0, 0.}], "T"}, {"C11",
SQLDateTime[{2013, 1, 23, 20, 50, 0.}], "T"}, {"C11",
SQLDateTime[{2013, 1, 25, 21, 0, 0.}], "D"}, {"C11",
SQLDateTime[{2013, 5, 4, 22, 0, 0.}], "V"}, {"C11",
SQLDateTime[{2013, 8, 27, 6, 40, 0.}], "T"}}

looks after ds[SortBy[{#"ID" &, #"Date" &}]] like this

My question is now, how can I extract two subsequent lines with the same ID, both having Type T?
As it only occurs in the 2nd and 3rd row of ID C10. All other cases, with a D or V in between are not interesting for me (e.g. last three lines).
I assume one has to use the Query functionality, but since I'm still at the beginning of my Mathematica studies, I don't know how.

A: ds[SortBy[{#"ID" &, #"Date" &}]][SplitBy[#, {#ID, #Type} &] &][Select[Length[#] == 2 &]]

{{<|"ID" -> "C10", "Date" -> SQLDateTime[{2013, 1, 28, 9, 25, 0.}], "Type" -> "T"|>,
 <|"ID" -> "C10", "Date" -> SQLDateTime[{2013, 3, 21, 20, 0, 0.}], "Type" -> "T"|>}}

EDIT
Added Select after WReach, though I don't believe it should only return the First instance.


text:
Q: AngularJS, Modal, "Cannot read property 'splice' of undefined" I am trying to make the Bootstrap Modal to work as an alertbox for my setup. When I run the code in JSFiddle and try to delete a note it gives me the error "Cannot read property 'splice' of undefined". When I run the same code in Visual Studios is doesn´t give me the error but it deletes the wrong note. It deletes the first note created.
Please take a look at the fiddle that I created.
'use strict'

var app = angular.module('plunker', ['ui.sortable','ui.bootstrap']);

app.controller('MainCtrl', function ($scope, $modal) {

    var i;
    $scope.itemsList = {
        items1: [],
        items2: []
    };

    for (i = 0; i <= 5; i += 1) {
        $scope.itemsList.items1.push({ 'Id': i, 'Label': 'Item ' + i });
    }
    $scope.sortableOptions = {
        containment: '#sortable-container',
        accept: function (sourceItemHandleScope, destSortableScope) {
            return sourceItemHandleScope.itemScope.sortableScope.$id === destSortableScope.$id;
        }
    };

    $scope.addNote = function() {
    $scope.itemsList.items1.push({"Id" :  $scope.itemsList.items1.length, "Label": "Item " +     $scope.itemsList.items1.length})
    }

    $scope.alert = function () {
        $modal.open({
            templateUrl: 'openAlertBox.html',
            scope: $scope,
            controller: function ($scope) {
                $scope.ok = function (index) {
                    $scope.itemsList.items.splice(index, 1)
                    $scope.$dismiss();
                }
                $scope.cancel = function () {
                    $scope.$dismiss()
                }
            }
        })
    }

});

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

                <form>

                    <button class="btn btn-success" type="button" ng-click="addNote()">
                        Add Note
                    </button>
                </form>

                <input class="category-form textboxid" type="text" name="input" ng-model="item.Label" placeholder="Deltager1">

MOVE ME

DELETE

                <input class="category-form textboxid" style="float:right" type="text" name="input" ng-model="item.Label2" placeholder="Deltager2">

A: You index args in $scope.ok method is undefined. You need pass index of item in params.

A: Its simple, you do not have "items" array :) its called "items1" so you need just to change this
$scope.itemsList.items1.splice(index, 1)

A: You need to pass the index from initial html :

DELETE

And in $scope.alert function, instead of taking index as parameter to 'ok' function, take index as parameter to alert function and use it in 'ok' function.
$scope.alert = function (index) {

}


text:
Q: SSL verification fails for apex domain using route 53 with aws load balancer Secure Connection Failed

An error occurred during a connection to domain.com. PR_END_OF_FILE_ERROR

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    Please contact the web site owners to inform them of this problem.

I am getting this error only for root domain. My subdomains are working well. My ssl certificate is for *.domain.com, I tried using domain.com ssl certificate but this is giving me insecure connection on subdomain as well as root domain.
The website loads on brave and chrome browser after reloading 3 times. Initial 2 hits give the same error. This is giving consistent error on firefox.

A: If you read the documentation for AWS ACM (you are likely using this with your AWS load balancer) you will find the following:

When you request a wild-card certificate, the asterisk (*) must be in the leftmost position of the domain name and can protect only one subdomain level. For example, *.example.com can protect login.example.com, and test.example.com, but it cannot protect test.login.example.com. Also note that *.example.com protects only the subdomains of example.com, it does not protect the bare or apex domain (example.com). To protect both, see the next step.

So in this case, you are able to protect *.domain.com but domain.com is not part of this wildcard, which is why you are seeing the error. To resolve this, you'll want to create a certificate with both *.domain.com and domain.com so that you can serve HTTPS traffic from your subdomains and apex domain.
Further information on how to do this can be found in this document:
https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html
Specifically this section:

*To add another name, choose Add another name to this certificate and type the name in the text box. This is useful for protecting both a bare or apex domain (such as example.com) and its subdomains such as *.example.com).


text:
Q: I need to have all Instagram API endpoints I want to use Instagram API. I'm able to use API using code and token. In my account I just have 2 endpoints. I want to know why ? Why there is not media endpoints for example ?

Upload media with Instagram API

Thanks to this post I saw that It was not possible to add media.
Today is this still the case ?
I want to allow to users of my website to share media like images, so I don't know why there is no media

A: These endpoints is no longer available, Instagram is closing that API in 2020. Please check Instagram Graph API instead.
Go to >> https://developers.facebook.com/docs/instagram-api/getting-started


text:
Q: .xml big file Uploading error - System.OutOfMemoryException in asp.net with C# I am uploading .xml file but getting error 'System.OutOfMemoryException' on ds.GetXml();  in asp.net with C#.
small .xml file is working fine but big file not. i am trying with 60 mb file but it failed and getting memory exception on ds.GetXml() method.
Detail view :
System.OutOfMemoryException: The function evaluation was disabled because of an out of memory exception.
DataSet dsCompendium = General.getDataSet4mXML(strFilePath,strFileName);
// this is custom function to get dataset from XML : getDataSet4mXML(string,string)
DataTable dtCompendium = dsCompendium.Tables[1];
strXML = dsCompendium.GetXml();

<httpRuntime targetFramework="4.5.1" maxRequestLength="1048576" />

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="1073741824" />
  </requestFiltering>
</security>

help me out

A: See the values for maxRequestLength value of httpRunTime in web.config. Try changing it to a bigger number.

A: It seems like HTTP web request size is exceeding in your case.
The 4MB default is set in machine.config, but you can override it in you web.config. For instance, to expand the upload limit to 20MB, you'd do this:
<system.web>
  <httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>

Edit
For IIS7 and above, you also need to add the lines below:
 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Note: maxAllowedContentLength is measured in bytes

A: Try to use DataSet ReadXml(XmlReader) method.
To create XmlReader
FileStream st = File.Open(@"filepath", FileMode.Open);
XmlReader reader = XmlReader.Create(st);
DataSet ds = new DataSet();
ds.ReadXml(reader);


text:
Q: Mapped keys do not work in some applications I have an Apple keyboard where the right command key (Super_R) is mapped to the right Alt key (ISO_Level3_Shift) with xmodmap:
$ cat ~/.Xmodmap
clear mod4
keysym Super_R = ISO_Level3_Shift

In some applications though, like Firefox and Thunderbird, the right Command and Alt keys are disabled altogether. Is my .Xmodmap invalid?
I have also tried redefining keycodes in section xkb_keycodes of a dump from xkbcomp and then loading the keymap with xkbcomp but still no luck with Firefox and Thunderbird. Any clues?

A: This neat command solves the problem:
setxkbmap -option lv3:rwin_switch


text:
Q: apache RewriteRule question I want to test for test.com and serve a particular file if I find it anywhere in the request, and if I don't find it move on to the rest of the rules.  I can't get it to consistently do this.
RewriteRule ^/test.com /var/www/html/index.html [NC,L]

A: The ^ means start of line/string, so requests to http://example.com/test.com and https://www.example.com/test.com_with_more should match, but http://example.com/in_front_test.com would not match. Try removing the ^ and prefix the . with a \ so that it matches a . and not any char use
RewriteRule test\.com /var/www/html/index.html [NC,L]

http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule was used as a reference.


text:
Q: AngularJS Chrome App - Select a local folder - not being displayed I am developing an AngularJS Chrome app, and using the chrome.fileSystem.chooseEntry API, a user can choose a directory. I want to show the user the selected directory, also save the details into local storage to use it everytime the app load.
The former part - show the selected directory to the user does not seem to work.
Here's my template:

    <form role="form">

            Add a New Company

            Enter Company Name
            <input id="companyName" type="text" class="form-control" ng-model="newCompany.companyName" style="width:80%"/>

            Select Company Folder Location
            <button id="location" ng-click="getUserSelectedFolder()">Choose Company Folder</button>
            {{newCompany.location}}

    </form>

My Controller:
app.controller('SelectCompanyController',['$scope','ReadLocalDBDataService',
    function($scope, ReadLocalDBDataService){
        $scope.newCompany={};
        getUserSelectedFolder=function(){
            ReadLocalDBDataService.getUserSelectedFolder().then(function(fileEntry){
                chrome.fileSystem.getDisplayPath(fileEntry, function(displayPath){
                    console.log(displayPath);
                    $scope.newCompany.location=displayPath;
                    console.log($scope.newCompany);
                });
            });
        };
        $scope.getUserSelectedFolder=getUserSelectedFolder;
}]);

My service
app.factory('ReadLocalDBDataService',['$q', function($q){
    var getUserSelectedFolder=function(){
        var deferred=$q.defer();
        chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(fileEntry){
            if(!fileEntry) deferred.reject("Please select the folder where the Companys' files are present");
            else{
                var error = chrome.runtime.lastError;
                if(error) deferred.reject("An error occurred while selecting the folder. Details: "+error);
                else{
                    deferred.resolve(fileEntry);
                }
            }
        })
        return deferred.promise;
    };

    return {
        getUserSelectedFolder: getUserSelectedFolder
    };
}]);

In my controller, I have got logs showing that that folder has been set to something like ~/Dropbox/folder... Why is this not showing up on the screen?
Edit:
I just realised that, after I select the folder once, nothing happens, but if I select the folder again, then it shows up. Why is not showing up the first time?

A: Here's a response from a developer of the chrome.fileSystem APIs when I asked him to look at your question.
"This question might be written in such a way as to be to be easier to answer. (Its a lot easier when the user can reduce their problem down to a simple example.) I can't immediately find anything wrong with it, but it sounds like the Chrome API part is working fine, but the display isn't updating for some reason ("In my controller, I have got logs showing that that folder has been set to something like ~/Dropbox/folder... Why is this not showing up on the screen?"). I don't know Angular so I can't help with that."
It sounds like his suggestion is to
1.) Reduce the example down to something as simple as possible.
2.) Investigate why the display might not be updating the first time.


text:
Q: Xcode raising Log tcp_input [C109:3]/tcp_input [C107:3] I found when making requests the log pops a lot logs like or similar to the following:
2020-03-27 14:06:10.966089+0800
ProjectC[20844:8100184] [] tcp_input [C23:3] flags=[R] seq=3301246612, ack=0, win=0 state=LAST_ACK rcv_nxt=3301246612, snd_una=3639195287

However I don`t understand what these things mean, could anyone explain a little bit?


text:
Q: Postgresql + PostGIS: find record by geometry column I have a table:
CREATE TABLE main.address_list
(
  id serial NOT NULL,
  address_string text NOT NULL,
  address_position geometry(Point,4326)
  CONSTRAINT pk_address_list PRIMARY KEY (id)
)

I want to find some record in this table using the address_position column:
select *
       , public.ST_Y(al.address_position) latitude
       , public.ST_X(al.address_position) longitude
from address_list al
where al.address_position = public.ST_SetSRID(public.ST_MakePoint(56.187339 --longitude$n
                                                                  , 57.964295 --latitude$n
                                                                  ), 4326)

But I got the following error:
ERROR:  operator is not unique: public.geometry = public.geometry
LINE 5: where al.address_position = public.ST_SetSRID(public.ST_Make...
                                  ^
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.

How can I get explicit type cast?

A: You are trying to compare two geometries with the equals-to = operator. That is not supported; instead you should use some spatial relationship function. Probably the best thing is to use a minimal distance:
select *
       , public.ST_Y(al.address_position) latitude
       , public.ST_X(al.address_position) longitude
from address_list al
where public.ST_DWithin(al.address_position::geography
                      , public.ST_SetSRID(public.ST_MakePoint(56.187339 --longitude$n
                                                            , 57.964295 --latitude$n
                                         ), 4326)::geography
                      , 1.); -- maximum separation of 1m

Alternatively, you can compare the latitude and longitude values for equality:
select *
       , public.ST_Y(al.address_position) latitude
       , public.ST_X(al.address_position) longitude
from address_list al
where public.ST_X(al.address_position) = 56.187339  --longitude$n
  and public.ST_Y(al.address_position) = 57.964295; --latitude$n

But you should keep in mind that comparing floating point values for equality is usually not a safe option due to the representation in binary form.

A: I've converted geometry column to WKT (Well Known Text) and compare that values.
select *
       , public.ST_Y(al.address_position) latitude
       , public.ST_X(al.address_position) longitude
       , public.ST_AsText(al.address_position)
from address_list al
where public.ST_AsText(al.address_position) = public.ST_AsText(public.ST_SetSRID(public.ST_MakePoint(56.187339 --longitude$n
                                                                                , 57.964295 --latitude$n
                                                                                ), 4326)
                                                               )

And added function index on column address_position
CREATE INDEX i_address_position_as_text
  ON address_list
  USING btree
  (public.ST_AsText(address_position));


text:
Q: String.replaceFirst different behaviour The following routine behaves differently on WIN XP x32, JAVA Version 7 Update 9 and on WIN7 x64, JAVA version 6 Update 32.
private int getNrOfMatches(String temp, String regex) {
            String prev;
            int nrOfIterations = -1;
            do {
                nrOfIterations++;
                prev = temp;
                temp = temp.replaceFirst(regex, " ");
            } while (temp != prev);
            return nrOfIterations;
        }

replaceFirst() returns the same object if it didn't modify anything and the loop ends on WIN XP. On Win7 it goes on an endless loop as != will always return false because the routine returns a new object even if it didn't change anything.
  Using .equals() instead of != solves this issue but my question is can anyone explain this behaviour?

A: Never compare Strings with == or !=
Use (str1.equals(str2)) or (!str1.equals(str2))
== and != compare object references for non primitive types.
equals() compares the content of objects when the class overrides this method it inherits from Object.

A: So to take a stab at answering the part of the question of why it is working some of the time.  The JVM has some cleaver optimizations that try and reuse references of the same string instead of creating new references with the same content.  It is possible that while running on Win XP your JVM has these optimizations while your Win 7 does not (are they the same version?)
This SO Question covers this topic fairly well and the accepted answer talks about ways to actually add strings to a constant pool (calling .intern()).  In terms of determining equality, this is not a stable solution because the JVM will always take priority over any memory management choices you make in your Java code.
Also digging into the JVM options I did find this interesting option (-XX:+UseStringCache) and this SO question that talks about what it does.  Maybe your Win XP JVM has the -server optimizations while your Win 7 does not?


text:
Q: Condition for equal or lower I've got this:
    {if $next_bid_amount > $bid}

                    The lowest possible next bid is {$meta.currency_sign}{$next_bid_amount|number_format}. Please bid this amount or higher.

            {/if}

But it only works when I place a bid that is higher than the current value, how can I add the condition that it will allow me to place a bid equal OR higher than the current value?

A: it's written this way:  >= ..

A: Just add the >= instead of =
{if $next_bid_amount >= $bid}

 The lowest possible next bid is {$meta.currency_sign}{$next_bid_amount|number_format}. Please bid this amount or higher.

 {/if}

A: Do it like this,
$next_bid_amount >= $bid


text:
Q: How to search dynamic columns in Datatable in asp.net core? Following the example, on https://www.datatables.net/release-datatables/examples/api/regex.html I want to filer the table by columns, The global search us working fine but search the columns is showing an error that.
Uncaught TypeError: $(...).DataTable(...).column(...).search(...).draw is not a function
    at filterColumn (Index:667)
    at HTMLInputElement.<anonymous> (Index:637)
    at HTMLInputElement.dispatch (jquery.min.js:2)
    at HTMLInputElement.v.handle (jquery.min.js:2)

This is my code

@section Styles {

    <link rel="stylesheet" href="~/libs/datatables/css/dataTables.bootstrap.min.css">
    <link href="~/css/listedviews.css" rel="stylesheet" />

}

@section Scripts {

}

Search Panel

                                Employee Name
                                <input type="text" class="global_filter" id="global_filter">
                                <input type="text" class="column_filter" id="col0_filter">

A: Actually you were pretty close.
You forgot to include your second filter on its own row and include the data-column attribute on its tr tag. This is your original code:

    Employee Name
    <input type="text" class="global_filter" id="global_filter">
    <input type="text" class="column_filter" id="col0_filter">

And this is how you should do it:

    Employee Name
    <input type="text" class="global_filter" id="global_filter">

    Another Filter
    <input type="text" class="column_filter" id="col0_filter">

Look at my example:

var jsonData = [
  {
     "loanAccountNo": "500507082020",
     "amountWrittenOff": "$320,800"
  },
  {
     "loanAccountNo": "308205105020",
     "amountWrittenOff": "$170,750"
  },
  {
     "loanAccountNo": "120205205070",
     "amountWrittenOff": "$186,800"
  }
];

$(document).ready(function () {
  $('#dailyload').DataTable({
    pageLength: 10,
    /*ajax: {
      url: '/MonthlyInterest/MonthlyDetails',
      dataSrc: ''
    },*/
    data: jsonData,
    columns: [
      {title: 'Account No', data: 'loanAccountNo'},
      {title: 'Amount Written off',data: 'amountWrittenOff'}
    ]
  });

  $('input.global_filter').on('keyup click', function () {
    filterGlobal();
  });

  $('input.column_filter').on('keyup click', function () {
    filterColumn($(this).parents('tr').attr('data-column'));
  });
});

function filterGlobal() {
  $('#dailyload').DataTable().search(
    $('#global_filter').val(),
  ).draw();
}

function filterColumn(i) {
  $('#dailyload').DataTable().column(i).search(
    $('#col' + i + '_filter').val()
  ).draw();
}

/*function filterColumn2(i) {
  $('#dailyload').DataTable().columns(i).search(
    $('#col' + i + '_filter').val()
  ).draw();
}*/
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>

Search Panel

              Employee Name
              <input type="text" class="global_filter" id="global_filter">

              Another Filter
              <input type="text" class="column_filter" id="col0_filter">

By the way, in my first attempt I was having the same issue (same error message), and I changed this line:
 $('#dailyload').DataTable().column(i).search(

For this:
 $('#dailyload').DataTable().columns(i).search(

And finally it was working as expected. Notice the extra s in columns.
But then I tried again removing the s (with column), and suddenly, to my surprise, it was working. Strange glitch, maybe?


text:
Q: How to find the source of "Denying load of chrome-extension://" My Chrome debug console tends to be full of lines like this:
Denying load of chrome-extension://ganlifbpkcplnldliibcbegplfmcfigp/scripts/vendor/jquery/jquery.min.map. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

How can I find the source of the complaint?
EDIT For clarity: I don't know what extension is causing this. I have dozens installed. The log is not very helpful.

A: As said by Rob Wu, this is a chrome bug, and it has been reported by him HERE.

By the way, as long as the bug isn't solved, if you are experiencing this issue you'll only need to add the resources that are causing it to your "web_accessible_resources" field in your manifest.
Plus, if you don't know the extension that is causing this, you can find its ID in the console error log, contained in the URL of the resource:
chrome-extension://<extension-id>/path/to/some_file.js

To identify the extension you can then copy the extension ID and go to the extension page chrome://extensions, then enable developer mode checking the box on the top right part of the page and find the ID of the extension either memorizing part of it or pasting it into the search field hitting CTRL+F.

A: Avast Bank Mode can stop viewing mp4 and .H264 files. Works in normal Chrome Browser, and not in the Bank Mode.


text:
Q: Optimizing performance of for-loops in R I have a character vector and want to create a matrix with distance metrices for each pair of vector values (using the stringdist package). Currently, I have an implementation with nested for-loops:
library(stringdist)

strings <- c("Hello", "Helo", "Hole", "Apple", "Ape", "New", "Old", "System", "Systemic")
m <- matrix(nrow = length(strings), ncol = length(strings))
colnames(m) <- strings
rownames(m) <- strings

for (i in 1:nrow(m)) {
  for (j in 1:ncol(m)) {
    m[i,j] <- stringdist::stringdist(tolower(rownames(m)[i]), tolower(colnames(m)[j]), method = "lv")
  }
}

which results in following matrix:
> m
         Hello Helo Hole Apple Ape New Old System Systemic
Hello        0    1    3     4   5   4   4      6        7
Helo         1    0    2     4   4   3   3      6        7
Hole         3    2    0     3   3   4   2      5        7
Apple        4    4    3     0   2   5   4      5        7
Ape          5    4    3     2   0   3   3      5        7
New          4    3    4     5   3   0   3      5        7
Old          4    3    2     4   3   3   0      6        8
System       6    6    5     5   5   5   6      0        2
Systemic     7    7    7     7   7   7   8      2        0

However, if I have - for instance - a vector of lenght 1000 with many non-unique values, this matrix is quite large (let's say, 800 rows by 800 columns) and the loops are very slow. I like to optimize the performace, e.g. by using apply functions, but I don't know how to translate the above code into an apply syntax. Can anyone help?

A: When using nested loops, it's always interesting to check whether outer() doesn't do the job for you. outer() is a vectorized solution for nested loops; it applies a vectorized function to every possible combination of the elements in the first two arguments. as stringdist() works on vectors, you can simply do:
library(stringdist)
strings <- c("Hello", "Helo", "Hole", "Apple", "Ape", "New",
             "Old", "System", "Systemic")

outer(strings,strings,
      function(i,j){
        stringdist(tolower(i),tolower(j))
      })

gives you the desired result.

A: Bioconductor has a stringDist function that can do this for you:
source("http://bioconductor.org/biocLite.R")
biocLite("Biostrings")

library(Biostrings)

stringDist(c("Hello", "Helo", "Hole", "Apple", "Ape", "New", "Old", "System", "Systemic"), upper=TRUE)

##   1 2 3 4 5 6 7 8 9
## 1   1 3 4 5 4 4 6 7
## 2 1   2 4 4 3 3 6 7
## 3 3 2   3 3 4 3 5 7
## 4 4 4 3   2 5 4 5 7
## 5 5 4 3 2   3 3 5 7
## 6 4 3 4 5 3   3 5 7
## 7 4 3 3 4 3 3   6 8
## 8 6 6 5 5 5 5 6   2
## 9 7 7 7 7 7 7 8 2

A: Thanks to the hint of @hrbrmstr I found out that the stringdist package itself provides a function called stringdistmatrix, which does what I was asking for (see here).
The function call is simply: stringdistmatrix(strings, strings)

A: Here's an easy one to start with: the matrix is symmetric, so there's no need to calculate the entries below the diagonal. m[j][i] = m[i][j]. And obviously the diagonal elements are all zero, so there's no need to bother with those.
Like this:
for (i in 1:nrow(m)) {
  m[i][i] <- 0
  for (j in (i+1):ncol(m)) {
    m[i,j] <- stringdist::stringdist(tolower(rownames(m)[i]), tolower(colnames(m)[j]), method = "lv")
    m[j,i] <- m[i,j]
  }
}


text:
Q: Reference a class library only if it exists - .NET Core I have an API that has it's controllers in a separate class library. Currently this library is referenced as a project from the main\core API project. This API is deployed to the customers site, so each customer has their own setup. Sometimes we are required to add an API call that is specific to one company. I do not want to put it in the main controller library, because it is really important that only the one company can see the specific calls we created for them.
My question is: is it possible to create another controllers library and load it if it exists, but otherwise do not error out if it doesn't exist. That way, if a company needs their own special calls, i would setup the API like normal, but then also just copy their special controllers.dll into the setup also. A setup might look like this.

COMPANY 1
  core-api-logic.exe
  shared-controllers.dll
comp1-controllers.dll
COMPANY 2
  core-api-logic.exe
  shared-controllers.dll
comp2-subdivision1-controllers.dll
comp2-subdivision2-controllers.dll

Note: The controller libraries are never manually called from the core logic, they simply exist to house the controllers.


text:
Q: When to build a router? I have some questions regarding building your own router.

*

*When should one build their own router?

*What are some of the advantages/disadvantages in building your own?

*What are some of the knowledges you need to have before building it.

*What is your insight in building a router?

*Should one who is very interested in building their own web server look into building their own router?

A:
When should one build their own router?

*

*When you want to learn networking.

*You need to do obscure and unusual things that standard distributions do not make easy.  Linux offers some extremely advanced routing/networking functionality, that can be used and abused in very weird and obscure ways.

*You are a control freak and don't want to be limited by any web interfaces, guis, scripts, or so on.  You want to dig into the guts and really understand.

What are some of the advantages/disadvantages in building your own?

*

*You have to learn networking

*You have to maintain the system

Should one who is very interested in building their own web server look into building their own router?

To build a router from a general purpose OS you will have to learn and understand networking.  That may help in setting up a web server, and may help you understand some complex problems, but many people run web servers with out that level of understanding.

A:
When should one build their own router?

*

*When you want to learn networking as @Zoredache says

*When you want to use any of Linux's advanced networking features on your own traffic in addition to routing/packet filtering/NAT, such as transparent bridging, Layer 2 filtering/frame mangling, QoS, SCTP, MPLS, Netflow, etc.

*If you want to host VPNs on your network such as OpenVPN or pptp, doing that on the router makes things easy, especially if you want to bridge into your physical network.

What are some of the advantages/disadvantages in building your own?

*

*Advantages: you probably won't have a higher level of control over the traffic and what you can do with it without buying expensive networking equipment.

*Disadvantages: This is a critical machine that's the gateway to your network.  So you need to invest in ways to keep it up constantly such as RAID, UPS, etc.  It's also the same with anything that gives you more control, you have more responsibility - it's up to you to configure everything properly where you are secure, etc.

What are some of the knowledges you need to have before building it.

Basic knowledge of how TCP/IP works and how TCP/IP routing works, including the OSI model, and subnets.  Know the format and meaning of each field in the IP header.  Study the ip command's syntax and capabilities.  Tools like iptables and tc are complex and will take you a long time to learn.
You'll likely be dealing with getting an IP from your ISP via DHCP, as well as handing them out to hosts on the rest of your network via DHCP, so knowing about Linux DHCP client and server tools is as must.  You'll probably want to eventually do your own DNS so be prepared to get into that. Knowledge of routing protocols such as RIP, OSPF, BGP isn't needed unless you want to do multi-site setups with multiple routers in your LAN (really complex stuff).

What is your insight in building a router?

Never going back to a plastic router if I can help it.  I have learned a lot and like the level of control I have.

Should one who is very interested in building their own web server look into building their own router?

Not unless you really want to get into lower-level stuff about how the Internet and TCP/IP works.  It's convenient to run your webserver on your router but sort of bad from a security perspective.


text:
Q: How to use Time format for hour greater than 24? I need the format hh:mm:ss into my cell, so I use : Cells(i, j).NumberFormat = "hh:mm:ss".
This is working fine when number of hours is lower than 24.
But for some cells, values are 35:58:00 or 46:12:00. So, Excel replaced 35:58:00 by 01/01/1900  11:58:00 and 46:12:00 by 01/01/1900  22:12:00.
There is a way to bypass this ? I try to use the format "hh:mm:ss" to do time calculations.
Thanks for help.


text:
Q: Deploying Flask Application to Azure App Servce (Linux) I was deploying a flask applications to Azure App Services with the following (example) file structure.
flask-app
├── application.py
└── web
    └── __init__.py

Inside __init__.py I declared app = Flask(__name__) (and of course do other things such as setup the configuration and add the controllers). Then, inside application.py, I just did from web import app.
When attempting to deploying this to Azure App Services, I would receive the following error when App Services would try to start the application: "Failed to find attribute 'app' in 'application'".

A: In order to fix this, I modified application.py to do the following:
from web import app
app = app

And then the app was able to be deployed. Of course, I'm somewhat skeptical that this is a proper fix or if what was happening was a bug, but I thought I would share this in case it helped others in the future.


text:
Q: Control collapse/expand status upon rebuild of xxforms:tree I have a tree view based on xxforms:tree. On the form I edit properties that influence the status of that tree. After saving my properties, the tree gets rebuilt (not by my choosing, but apparently as part of default behavior) but without retaining the collapse/expand status of the items in that tree. In my case that leads to full expansion.
We use a dated version of Orbeon (v3.9) but I'm not seeing anything in newer version with regards to this. Is there any way to influence that?

A: There is a comment in Tree.js which says "Expand nodes corresponding to values that were previously expanded". But if it doesn't work out of the box for you, it might be a bug, or it might not be designed to take place in certain kind of updates, who knows. There doesn't seem to be a specific way to keep nodes expanded.
I fear that xxforms:tree hasn't been maintained since 3.9 at all. So using a newer version wouldn't help.
For reference here is the documentation.


text:
Q: What is the difference between yarn.lock and npm's shrinkwrap? Recently I tried installing my Node packages with Yarn. It works great and it's a lot faster than NPM. Yarn automatically generates yarn.lock. We already have NPM shrinkwrap (npm-shrinkwrap.json).
Is there any difference between them?
Does yarn.lock has any advantage over npm-shrinkwrap.json?

A: The yarn.lock file is quite similar to other package managers' lock files, especially Rust's Cargo package manager, which has Cargo.lock. The idea of these lock files is to represent a consistent set of packages that should always work.
npm stores dependency ranges in the package.json file, which means that when someone installs your package, they might get a different set of dependencies to you, since you might be running outdated packages (although they still satisfy the dependency range you specified). Take, for example, someone who has specified the dependency "foo": "^1.0.0". They might have actually installed foo v1.0.1, because that was the latest when they ran npm install, but later on, someone installs your package and gets the dependency foo v1.1.0. This might break something unexpectedly, which can be avoided if you have a yarn.lock file which guarantees consistent package resolution.
As for comparison with npm shrinkwrap, the documentation explains it very clearly:

It's similar to npm's npm-shrinkwrap.json, however it's not lossy and it creates reproducible results.

The documentation also advises committing yarn.lock to your repositories, if you're not already doing this, so you can reap the benefits of consistent and reproducible package resolution. This question also explains further why you should do this.
The lossy behaviour of npm shrinkwrap is due to the non-deterministic algorithms used by npm itself; as stated in the comments of another answer, npm shrinkwrap > npm install > npm shrinkwrap is not guaranteed to produce the same output as just shrinkwrapping once, whereas Yarn explicitly uses "an install algorithm that is deterministic and reliable".

A:
Is there any difference between them

Yarn follows a more deterministic algorithm, compared to npm shrinkwrap. If you're using Yarn, continuing to use shrinkwrap would be counter-intuitive
You can find this in the documentation for yarn.lock:

It's similar to npm's npm-shrinkwrap.json, however it's not lossy and it creates reproducible results

However, the question still remains whether yarn is production ready. There are still a bunch of glaring bugs open on the GitHub repo, so I would wait it out for a month or so.


text:
Q: is the fish pond not producing at a steady rate normal? I have had void salmon and sturgeon both going but the void salmon got two days in a Rowe and the sturgeon I got nothing, both after 10 in-game days. I was wondering if this is normal.

A: On the wiki, there's a section that tells you what any given fish produces:
Fish Pond: Produce
What you might've missed is the percent chance that anything will be produced:

The chance that a Fish Pond will produce an item starts with the equation (0.15 + 0.08 * population of pond).

In other words, as the population of a pond ranges from 1 to 10 fish, the chance of producing anything ranges from 23% to 95%.  There's always a 5% or greater chance the fish pond won't produce anything.
I'm not sure how many Sturgeon you have in your pond, but if you have fewer than 10, the chance of getting Sturgeon Roe is significantly lower.  For example:
10 Sturgeon -> 95% chance of anything -> 25% chance of 2 Roe; 100% chance of 1 Roe
9 Sturgeon -> 87% chance of anything -> 80% chance of 1 Roe
8 Sturgeon -> 79% chance of anything -> 60% chance of 1 Roe
7 Sturgeon -> 72% chance of anything -> 60% chance of 1 Roe
etc.
These are just the initial checks.  The game proceeds through several levels of checking to produce an item, but the chances get lower at each level.  We can sum up all the levels to calculate the full chance that 9 Sturgeon will produce a Sturgeon Roe.  (Notice how each level starts with the % that the previous level didn't produce.)
13% nothing
87% * 80% = 69.6% 1 Roe
87% * 20% * 60% = 10.44% 1 Roe
87% * 20% * 40% * 40% = 2.784% 1 Roe
87% * 20% * 40% * 60% * 20% = 0.8352% 1 Roe

69.6 + 10.44 + 2.784 + 0.8352 = 83.6592% chance of 1 Roe with 9 Sturgeon
Similar math can be done for other numbers of Sturgeon.
Now if you only have, say, one Sturgeon, then the math is:
0.23 * 0.2 = 0.046
That is, 23% chance of anything * 20% chance of 1 Roe = 4.6% chance of 1 Roe
So chances are you'd get 1 Sturgeon Roe in 22 days.
Now of course over time your Sturgeon will grow, as long as you keep fulfilling their requests, so the chance will increase.  But the chance is a lot lower than you might think from the "20%" given on the wiki page, due to the initial chance that the Fish Pond will produce nothing at all at any level of fish.


text:
Q: Reflexivity of finite dimensional space I was given the statement in exam(for which I was supposed to mark it as correct or incorrect):
Every Finite dimensional space is reflexive. (I marked it as incorrect).
My attempt: I learnt the following theorem which says: Every finite dimensional normed space is reflexive. But since there was no use of word "normed", I thought it may happen that the definition of reflexivity may also be applicable to some other spaces where I could find a counterexample and so I marked it as incorrect.
My professor said, it is correct. So my question is : Is there any finite dimensional space which is not reflexive? Please throw some light.

A: Hints: (Prove them as easy exercises, if you haven't already)

*

*Any finite dimensional vector space can be given a norm.

*On a finite dimensional normed space, any two norms are equivalent.
Bingo!


text:
Q: VBA create new excel if cell value changed and it's unique value in range I have a master sheet where I enter name in column "B" from cell "B4:B50000" and in column "E" from cell "E4:50000" now when cell value change in this range than first check whether it's unique value or not, if it's unique value than create new sheet in same workbook with that unique name
I also want to have drop down list where all unique value from range B4:B50000 and E4:E50000 auto suggest matching name
e.g. In cell B4 name written is salman now i am typing name in cell B5 and after writing sal,it should be suggesting unique names starting from sal
I have tried following code from my side but as I am beginner in VBA I got partial success only, kindly help to fix it up
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, sh As Worksheet
With ActiveSheet
For Each c In .Range("B3:B50000", .Cells(Rows.Count, 1).End(xlUp))
    Set sh = Sheets.Add(After:=Sheets(Sheets.Count))
    sh.Name = c.Value
    Set sh = Nothing
  Next
 End With

End Sub

Any help ll be appriciated, thx in advance.

A: Add a new worksheet for Unique values entered into Column B

*

*Make sure the change event is only activated when change occurs in your target column (B) using Interest

*Loop for each new value added to target column vs every item (what you are doing)

*Use CountIf to isolate unique values

*Check to make sure the sheet being added does not already exist (UDF from Tim Williams)

Private Sub Worksheet_Change(ByVal Target As Range)

Dim x As Range, ws As Worksheet

If Not Intersect(Target, Range("B:B")) Is Nothing Then
    For Each x In Target

        If Application.WorksheetFunction.CountIf(Range("B:B"), x) = 1 Then
            If Not WorksheetExists(x.Value, ThisWorkbook) Then
                Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
                ws.Name = x.Value
                Set ws = Nothing
            Else
                MsgBox "Worksheet Already Exists With Name '" & x.Value & "'", vbCritical
            End If
        End If

    Next x
End If

End Sub

Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean

    Dim sht As Worksheet

    If wb Is Nothing Then Set wb = ThisWorkbook
        On Error Resume Next
            Set sht = wb.Sheets(shtName)
        On Error GoTo 0
    WorksheetExists = Not sht Is Nothing

End Function


text:
Q: iOS - Some tiles not rendered in a custom MKTileOverlay I have a custom MKTileOverlay in my iOS project using MapKit, it works fine most of the time. However, after zooming in/out a few times and panning the map some of the tiles are not being drawn.
At first I thought it was a simple case of tiles not being loaded so I subclassed the MKTileOverlay and added logging in the console. It showed that all tiles were loaded perfectly fine and delivered to the result block.
As I was running out of ideas I created a local tile generator that just returns images with their path x/y/z and frame drawn to see what tiles are missing.
Missing tile example image
Unfortunately the problem persists even with locally generated tiles so it has nothing to do with Internet connectivity. Another weird behaviour is that if I have two custom overlays on top of one another, it will be exactly the same tiles that are not being rendered on both overlays.
The only solution I can think of right now is subclassing the tile renderer and making sure that everything is displayed as there is no way to know that the tile is not rendered. This, however, sounds like a lot of work and a "reinventing the wheel" kinda task...

A: We were also experiencing this problem of missing tiles - trying to draw map tiles around New Zealand. The MKOverlayRenderer was not even requesting the tiles. We went down a rabbit hole thinking it must be because New Zealand is near the 180/0 latitude boundary. Nope. It was because the sub-classed method:-
- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData * __nullable data, NSError * __nullable error))result;

Must always call the result method even if there is no data to return! To give credit where credit is due this was the source of the solution for us:-
MKTileOverlay not drawing every tile?


text:
Q: 'class' type redefinition rejection Having some issues with my two classes and having issues with my account files. I'm not fully sure how to go about fixing it with the classes I think being defined twice. I looked through other suggestions on how to fix it and I'm not exactly sure where to go with it. All the error says is 'Account:' 'class' type redefinitions
Account.h
#include <string>
class Account
{
private:
    unsigned int accountNumber;
    std::string firstName, lastName;
    double balance;
    static unsigned int count;

public:
    Account();
    void setFirstName(std::string fName);
    void setLastName(std::string lName);
    void setBalance(double inBalance);
    void display();
};

this would be the main file
Account.cpp
#include "Account.h"
#include <iostream>
using namespace std;

//Initializes the static counter set equal to 0
unsigned int Account::count = 0;

//Sets up a default constructor
Account::Account()
{
    count++;
    //Set accountNumber to count
    accountNumber = count;
}

//Sets up the first name
void Account::setFirstName(std::string fName)
{
    firstName = fName;
}

//Sets up the last name
void Account::setLastName(std::string lName)
{
    lastName = lName;
}

//Sets up the balance
void Account::setBalance(double inBalance)
{
    balance = inBalance;
}

//Displays the details of the Account
void Account::display()
{
    cout << fixed;
    cout.precision(2);
    cout << "Balance: " << balance << endl;
    cout << "Account: " << accountNumber << endl;
    cout << "First Name: " << firstName << endl;
    cout << "Last Name: " << lastName << endl;
}

A: You need include guards in your header file
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
#include <string>
class Account
{
private:
    unsigned int accountNumber;
    std::string firstName, lastName;
    double balance;
    static unsigned int count;

public:
    Account();
    void setFirstName(std::string fName);
    void setLastName(std::string lName);
    void setBalance(double inBalance);
    void display();
};
#endif

this prevents the header being included twice in one file


text:
Q: Partial view with Javascript I have a drop down list (telerik dropdownlist) and for every option i call a different partial view from my controller.
onChange = function (e)
{
    var product = e.value;
    if (product)
    {
        $.post( myUrl,
            { CodigoProduto : product }, // passing the product to my controller
            function (retorno) {
               // insert the partial view in a div
               $('#AreaGenerica').html(retorno);
            }
        );
    }
}

the first option returns a partial view that contains a javascript code

Option A

and the second option returns a partial view without any javascript code.
In my view i call the function inside the partial view
ViewFunction = function () {
        // check if the function 'PartialViewFunction' exists.
        if (typeof PartialViewFunction === "function")
        {
            PartialViewFunction();
        }
    };

My problem is that if i choose the first option and then the second the 'PartialViewFunction' is still being called but it shouldn't because it doesn't exists inside the second partial view.
I tried to remove the div containing my partial view following this answer but it didn't work.
Thanks in advance and i hope you can understand my english.
EDIT:
 @(Html.Telerik().DropDownList()
        .Name("grpAutorizacaoPublicacao")
        .SelectedIndex(0)
        .Effects(e => e.Opacity())
        .ClientEvents(e =>
            {
                e.OnChange("onChange");
            })
        .DataBinding(db => db.Ajax().Select("_ListaGrupoAutorizacao", "Publicador")))

A: As a general rule I would avoid including JavaScript in partial views.  You can search for advice about that.  This might mean refactoring your JS to be generic and always included from the view proper.  Such a design pattern would, I think, solve your problem, or at least make it easier to understand and fix.
Alternatively, it seems like you may need to limit onChange function to just the first select element.  The code you have shown does not make it clear what calls the onChange event.  You could include the html of the select element before and after the first selection is made.


text:
Q: For any query on a django model, performing query only on elements that have active set as true Due to lack of planning I found myself in a situation where I had to introduce a Boolean field called "Active" at later stage in model.The idea is to return only elements that have active as true for any query on Db. One way possible would be to edit all my queries on model to add something like
Q(active==true)

which would require a lot of change. Is it possible that using "class meta" I can set ordering so that any query on Db is only performed on elements that have active set as true.
class Db(models.Model):
   url = models.TextField()
   description = models.TextField(blank=True, null=True)
   active = models.BooleanField()(initial=True)

   class Meta:
       ordering = ['-id']

A: You can implement custom default object manager and filter out depending upon your criteria.
Refer Custom managers , however keep in mind for this Do not filter away any results in this type of manager subclass as django warns for overriding default object manager.

A: i think you can add new QuerySet methods for your model as this snippet.
from django.db import models

class QuerySetManager(models.Manager):
    def get_query_set(self):
        return self.model.QuerySet(self.model)

# Using it in a model:

from django.db.models.query import QuerySet

class Entry(models.Model):
   ...
   objects = QuerySetManager()
   ...
   class QuerySet(QuerySet):
        def chckactive(self):
            return self.filter(active=True)

#   Entry.objects.all().chckactive()


text:
Q: Automatically render HTML to Image I know it's possible to render HTML code as an image. However, I would like to make the image update every 30 seconds, 1 minute etc. etc.
I am attempting to display the price of various assets on sites that don't allow JavaScript. So, in order to do this, I will host the script on my own domain that should then render an image and most importantly, update that image as often as possible, while still keeping it in the same location on my site.
Is there any way to do that?

A: if the website is php,asp,etc that's allow to make changes to a folder of images and inside a database text,prices,...etc and you can't want to use javascript for any reasons.. eg:the parser 's method you choose OR eg: in apk i put my browser that render only html ,not javascript, then you can use in your html output   this will refresh your page after 30 secconds so if in this time you modify the image at the same location =same name other content of the same image you will have a "new" page with modifies done.


text:
Q: Не работает функция отсчета таймера Мне нужно в 2 lebl'а парсить минуты и секунды соответсвенно. Вот функция которую я сделал:
 public void StartTimer()//Функция запуска отсчета таймера
    {
        if(timer1.Enabled)
        {
            if (minutes <= 59&&minutes>=0)
            {
                minutes--;
                if (minutes < 10)
                    timeMinutes.Text = "0" + minutes.ToString();
                else
                    timeMinutes.Text = minutes.ToString();
            }
            else
            {
                timeMinutes.Text = "00";
            }
            if (seconds <= 59 && seconds>=0)
            {
                seconds--;
                if (seconds < 10)
                    timeSeconds.Text = "0" + seconds.ToString();
                else
                    timeSeconds.Text = seconds.ToString();
            }
            else
            {
                timeSeconds.Text = "00";
            }
        }

    }

Эту функцию я вызываю в событии
private void timer1_Tick(object sender, EventArgs e)
        {
            StartTimer();
        }
Для справки заношу 30 минут и 00 секунд. Labl'ы имеют вид: 29:0-1. Да и ход вычитания не показывается

A: Предлагаю такой вариант кода:
    private int seconds;
    private int minutes;
    private TimeSpan time1;

    private void button1_Click(object sender, EventArgs e)
    {
        minutes = 30;
        seconds = 0;
        time1 = TimeSpan.FromMinutes(30);
        timer2.Enabled = true;
        timer2.Start();
    }

    public  void StartTimer()//Функция запуска отсчета таймера
    {

        if (timer2.Enabled)
        {

            if (time1.TotalSeconds > 0)
            {
                time1 = time1.Subtract(TimeSpan.FromSeconds(1));
            }
            timeMinutes.Text = time1.Minutes.ToString("##");
            timeSeconds.Text = time1.Seconds.ToString("##");
        }

    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        StartTimer();
    }

Кстати вот пара ссылок которые могут быть Вам полезны.
1.Работа с датой и временем
2.Форматирование строк


text:
Q: html5 canvas and emberjs view I'd like to add some drawing functionality in my ember based application. I plan to use the html5 canvas element. Basically, in my DOM I have
<canvas id="my-canvas">

And I need to get my canvas context when the DOM is loaded with
var c = document.getElementById('my-canvas')
// ... do something with c

If the canvas is represented with an Ember.View :
App.Canvas = Em.View.extend({
 tagName: 'canvas'
})

What is the equivalent of document.getElementById?

A: var view = App.Canvas.create().append();
var viewContext = Ember.get(view, 'element');

viewContext will hold what you need.

A: From the canvas context, you could use the $() method:
this.$('#id')

which provides a JQuery-flavored way to access elements.