text:
Q: How to change the level names of a set of factor? How to change the level names of a set of factor?
Please check the F1 of Example df , F1 is a factor of 6 levels(0~5).
How do I change F1 into 3 levels(1,2,3)?
eg: if F1 == 0 or 1, the new level name is 1, if F1 == 2 or 3, the new level name is 2, if F1 == 4 or 5, the new level name is 3. Like Expected Outcome.
library(plyr)
revalue(df$F1, c("0"="1", "1"="1","2"="2", "3"="2","4"="3", "5"="3"))
# I could do this but if there are tens or hundreds of levels,
# I will need to do this one by one, there must be a more convenient way.

Example df
    Volume Weight F1 F2
 1: 0.5367 0.5367  0  1
 2: 0.8645 0.8508  0  0
 3: 0.8573 0.8585  0  0
 4: 1.1457 1.1413  1  0
 5: 0.8573 0.8568  1  0
 6: 0.5694 0.5633  1  1
 7: 1.2368 1.2343  2  0
 8: 0.9662 0.9593  2  1
 9: 1.4850 1.3412  2  0
10: 1.4850 1.3995  2  0
11: 1.1132 1.1069  3  1
12: 1.4535 1.3923  3  0
13: 1.0437 1.0344  3  1
14: 1.1475 1.1447  4  1
15: 1.1859 1.1748  4  0
16: 1.1859 1.1735  4  0
17: 1.1859 1.1731  4  0
18: 1.1557 1.1552  5  1
19: 1.1749 1.1731  5  0
20: 1.1749 1.1552  5  0

Expected Outcome
   Volume Weight F1 F2
 1: 0.5367 0.5367  1  1
 2: 0.8645 0.8508  1  0
 3: 0.8573 0.8585  1  0
 4: 1.1457 1.1413  1  0
 5: 0.8573 0.8568  1  0
 6: 0.5694 0.5633  1  1
 7: 1.2368 1.2343  2  0
 8: 0.9662 0.9593  2  1
 9: 1.4850 1.3412  2  0
10: 1.4850 1.3995  2  0
11: 1.1132 1.1069  2  1
12: 1.4535 1.3923  2  0
13: 1.0437 1.0344  2  1
14: 1.1475 1.1447  3  1
15: 1.1859 1.1748  3  0
16: 1.1859 1.1735  3  0
17: 1.1859 1.1731  3  0
18: 1.1557 1.1552  3  1
19: 1.1749 1.1731  3  0
20: 1.1749 1.1552  3  0

A: We can use data.table methods as the object is a data.table
library(data.table)
df[, F1 := factor((F1 %/% 2)+1)]


text:
Q: Better way of handling multiple environment variable in AWS Codebuild I have a AWS Codebuild project connected to my Github account. Within my github I have separate branches for each environment.
I have in total 4 environments (and by that relationship, 4 github branches) currently: dev, qa, customer1-poc, customer2-prod.
Now I use multitude of environment variables within my project and initially I was setting up these env vars within the Codebuild project under Environment > Environment variables section. So ideally per env there are 4 env vars which are distinguished using the env name.
For example if there is an env var called apiKey it is saved in codebuild 4 times by the name
apiKey_dev
apiKey_qa
apiKey_customer1poc
apiKey_customer2prod
You get the idea. Same goes for other env vars which need to be different across all envs.
These env vars are read from the buildspec file and passed on to serverless.yml file.
Now the issue is as I keep creating new environments (like more poc, prod envs) I need to keep replicating the set of env vars for each env and its getting tedious.
Is there some way I can save these env vars outside the Codebuild project which can then be passed on to the Lambda function upon successful builds?

A: CodeBuild has native integration with Parameter store:

*

*https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.parameter-store
In Paramter store, you can keep your variable as a json with name like /config/prod":

... then retrieve it in CodeBuild and parse via 'jq' 2. This way, all the environment specific variables are in one place. If you go this way, make sure to encrypt the Param Store variable with a KMS key if it contains secrets. Also check AWS Secrets Manager.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection string with odbc connector I am getting error
ERROR [08S01] [MySQL][ODBC 5.1 Driver]Lost connection to MySQL server at 'waiting for initial communication packet', system error: 10060.

While using connection string
"DRIVER={mysql odbc 5.1 Driver};SERVER=204.11.58.166;DATABASE=dbname;UID=uid;PASSWORD=uid;OPTION=3;"
So, please guide me how to solve it.
Thanks
Ravi

A: What MySQL version are you using ? ( To see the version you can use 'SELECT VERSION();' )
Is MySQL 64b or 32b  ?
What is your OS ?
Try to update to ODBC 5.2, see on dev.mysql.com -> download -> conectors
Roberto Novakosky

Well I already have this in 3 situations
1) I was using old version of connection on Delphi, and with MySQL installed on Linux. I did update of my components and the connection was OK. (similar message)
2) In a remote application I used 'localhost' inside string connection, when must be the IP of server, on server works OK, but when I use from remote host this problem occurs. resolved with the real IP. (similar message)
3) In my LAN, the port 3306 was redirected to other machine, so when I tried to connect an outside server, the response connection was wrong. the message was exactly as yours. As, we can't to change the port of MySQL of outside server (that was 3306), I changed the port of my local MySQL server to 3307 and removed from my router the redirect over 3306. It was with conflict, see: I need to use 3306 from outside and it need to respond to my machine, the router hindered the connection ...
Good luck

A: Please refer this thread
and this site for detailed explanation


text:
Q: Pandas - Create dynamic column(s) from a single column's values I have JSON data which I am planning after converting it to desired dataframe, will concat with another dataframe.
Participant

**row 1** [{'roles': [{'type': 'director'}, {'type': 'founder'}, {'type': 'owner'}, {'type': 'real_owner'}], 'life': {'name': 'Lichun Du'}}]

**row 2** [{'roles': [{'type': 'board'}], 'life': {'name': 'Erik Mølgaard'}}, {'roles': [{'type': 'director'}, {'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Mikael Bodholdt Linde'}}, {'roles': [{'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Dorte Bøcker Linde'}}]

**row 3** [{'roles': [{'type': 'director'}, {'type': 'real_owner'}], 'life': {'name': 'Kristian Løth Hougaard'}}, {'roles': [{'type': 'owner'}], 'life': {'name': 'WORLD JET HOLDING ApS'}}]

However, I want it like this where dynamically the column will be generated and "N" of Participant#N Role or Participant#N Name should be the maximum number of participant present in the rows of the dataframe overall  :

So far I have tried:
Try 01:
participants = pd.concat([pd.DataFrame(pd.json_normalize(x)) for x in responses['participants']])
print(participants.transpose())

I could not find any relevant post to move forward to the desired dataframe.
Try 02:
responses['Role of Participants'] = [x[0]['roles'] for x in participants['roles']]
responses['Participant Name'] = [x[0]['life'] for x in participants['participants']]

But it just returned only the first type object in role and first name object of life for each data where there can be multiple.

A: Are you looking for something link this?
# Extract the value from the "type" property of each subobject of each row
df['roles'] = df['roles'].apply(lambda x: ', '.join(t['type'] for t in x))

# Extract the value of "name" from the subobject of each row
df['life'] = df['life'].str['name']

# Rename 'life' column to 'name' (optional)
df = df.rename({'life': 'name'}, axis=1)

Output:
>>> df
                         roles                   name
0                        board          Erik Mølgaard
1  director, board, real_owner  Mikael Bodholdt Linde
2            board, real_owner     Dorte Bøcker Linde

Try:
>>> df[df['name'] == 'Mikael Bodholdt Linde']
                         roles                   name
1  director, board, real_owner  Mikael Bodholdt Linde

>>> df[df['name'] == 'Mikael Bodholdt Linde']['roles']
1    director, board, real_owner
Name: roles, dtype: object

>>> df[df['name'] == 'Mikael Bodholdt Linde']['roles'].iloc[0]
'director, board, real_owner'

>>> df[df['name'] == 'Mikael Bodholdt Linde']['roles'].iloc[0].split(', ')
['director', 'board', 'real_owner']

A: You could run one apply() which will use for-loop to convert list to  Series with headers - it can use enumerate to put correct number in headers.
Because some rows have less participants so it puts NaN which you can later fill with empty strings.
And next you can use join() to add all as new columns. Because headers are create in apply() so you don't have to create them in join()
import pandas as pd

data = {'participants':
[
    [{'roles': [{'type': 'director'}, {'type': 'founder'}, {'type': 'owner'}, {'type': 'real_owner'}], 'life': {'name': 'Lichun Du'}}],
    [{'roles': [{'type': 'board'}], 'life': {'name': 'Erik Mølgaard'}}, {'roles': [{'type': 'director'}, {'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Mikael Bodholdt Linde'}}, {'roles': [{'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Dorte Bøcker Linde'}}],
    [{'roles': [{'type': 'director'}, {'type': 'real_owner'}], 'life': {'name': 'Kristian Løth Hougaard'}}, {'roles': [{'type': 'owner'}], 'life': {'name': 'WORLD JET HOLDING ApS'}}],
]
}

df = pd.DataFrame(data)

def get_names(cell):

    all_names = pd.Series(dtype=object)

    for number, item in enumerate(cell, 1):
        name = item['life']['name']
        all_names[f'Participant #{number} Name'] = name

    return all_names

def get_roles(cell):

    all_roles = pd.Series(dtype=object)

    for number, item in enumerate(cell, 1):
        roles = [role['type'] for role in item['roles']]
        all_roles[f'Participant #{number} Role'] = ",".join(roles)

    return all_roles

roles = df['participants'].apply(get_roles)
roles = roles.fillna('')  # put empty string in place of NaN

names = df['participants'].apply(get_names)
names = names.fillna('')  # put empty string in place of NaN

df = df.join(roles)
df = df.join(names)

df = df.drop(columns=['participants'])  # remove old column

pd.options.display.max_colwidth = 100
print(df.to_string())

Result:
                 Participant #1 Role        Participant #2 Role Participant #3 Role     Participant #1 Name    Participant #2 Name Participant #3 Name
0  director,founder,owner,real_owner                                                              Lichun Du
1                              board  director,board,real_owner    board,real_owner           Erik Mølgaard  Mikael Bodholdt Linde  Dorte Bøcker Linde
2                director,real_owner                      owner                      Kristian Løth Hougaard  WORLD JET HOLDING ApS

I used two function to get first only columns with roles and next columns only with names - but if you would need role1, name1, role2, name2, role3, name3 then it could be done with one function.
import pandas as pd

data = {'participants':
[
    [{'roles': [{'type': 'director'}, {'type': 'founder'}, {'type': 'owner'}, {'type': 'real_owner'}], 'life': {'name': 'Lichun Du'}}],
    [{'roles': [{'type': 'board'}], 'life': {'name': 'Erik Mølgaard'}}, {'roles': [{'type': 'director'}, {'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Mikael Bodholdt Linde'}}, {'roles': [{'type': 'board'}, {'type': 'real_owner'}], 'life': {'name': 'Dorte Bøcker Linde'}}],
    [{'roles': [{'type': 'director'}, {'type': 'real_owner'}], 'life': {'name': 'Kristian Løth Hougaard'}}, {'roles': [{'type': 'owner'}], 'life': {'name': 'WORLD JET HOLDING ApS'}}],
]
}

df = pd.DataFrame(data)

def get_columns(cell):

    results = pd.Series(dtype=object)

    for number, item in enumerate(cell, 1):
        name = item['life']['name']
        results[f'Participant #{number} Name'] = name

        roles = [role['type'] for role in item['roles']]
        results[f'Participant #{number} Role'] = ",".join(roles)

    return results

columns = df['participants'].apply(get_columns)
names = columns.fillna('')  # put empty string in place of NaN

df = df.join(columns)
#print(df.columns)

df = df.drop(columns=['participants'])

pd.options.display.max_colwidth = 100
print(df.to_string())

Result:
      Participant #1 Name                Participant #1 Role    Participant #2 Name        Participant #2 Role Participant #3 Name Participant #3 Role
0               Lichun Du  director,founder,owner,real_owner                    NaN                        NaN                 NaN                 NaN
1           Erik Mølgaard                              board  Mikael Bodholdt Linde  director,board,real_owner  Dorte Bøcker Linde    board,real_owner
2  Kristian Løth Hougaard                director,real_owner  WORLD JET HOLDING ApS                      owner                 NaN                 NaN


text:
Q: Is there any possible method to calculate effect size in mixed models? I run MIXED command for mixed model analysis of repeated measured data.
However, there is no option or menu for estimate power(like partial eta in GLM) in mixed analysis.
Is there any method to calculate effect size in mixed model?

A: The estimates are the effect sizes as for simple regression. For example in following output in R:
Linear mixed model fit by REML ['lmerMod']
Formula: Reaction ~ Days + (Days | Subject)
   Data: sleepstudy

REML criterion at convergence: 1743.6

Scaled residuals:
    Min      1Q  Median      3Q     Max
-3.9536 -0.4634  0.0231  0.4634  5.1793

Random effects:
 Groups   Name        Variance Std.Dev. Corr
 Subject  (Intercept) 612.09   24.740
          Days         35.07    5.922   0.07
 Residual             654.94   25.592
Number of obs: 180, groups:  Subject, 18

Fixed effects:
            Estimate Std. Error t value
(Intercept)  251.405      6.825   36.84
Days          10.467      1.546    6.77

Correlation of Fixed Effects:
     (Intr)
Days -0.138

In above output, the effect size for Days can be taken as 10.5. If multiple predictors are present, their estimates will reflect effect sizes for each.

A: I found myself two options.
One is calculation based on correlation, based on the book of Rosenthal, Rosnow, & Rubin.
"Contrasts and Effect Sizes in Behavioral Research A CORRELATIONAL APPROACH"
Another option is use SAS and calculate f squared.


text:
Q: java list iterator I'm writing a code to have 2 lists of integers and iterators for each one.  Second one is constructed as reversed first one.
I have a problem with displaying values of the second one using iterator.  How to fix that (note that I have used simple for iteration and it works, but want to do it with iterator).
import java.util.*;

public class Ch11Ex12 {
      public static void main(String[] args) {

            List<Integer> li = new ArrayList<Integer>();
            li = Arrays.asList(1, 6, 4, 7);
            //List<Integer> li2 = new ArrayList<Integer>();
            int z = li.size();
            List<Integer> li2 = new ArrayList<Integer>();

            /**
            for (int index = 0; index < ints.length; index++)
            {
                li.add(ints[index]);
            }
            **/
            ListIterator<Integer> it = li.listIterator(z);
            ListIterator<Integer> it2 = li2.listIterator();
            while(it.hasPrevious()){
                //System.out.print(it.previous() + " ");
                int k = it.previous();
                System.out.print(k + " ");
                li2.add(k);
            }
            /**
            for (int f = 0; f < li2.size(); f++){
                System.out.println(li2.get(f));
            }
            **/
            while(it2.hasNext()){
                int p = it2.next();
                System.out.print(p + " ");
            }
     }
}

A: Define your second Iterator it2 after having filled li2.
        ListIterator<Integer> it = li.listIterator(z);
        while(it.hasPrevious()){
            //System.out.print(it.previous() + " ");
            int k = it.previous();
            System.out.print(k + " ");
            li2.add(k);
        }

        /**
            Now that I have filled li2, I create my ListIterator it2.
        **/
        ListIterator<Integer> it2 = li2.listIterator();
        while(it2.hasNext()){
            int p = it2.next();
            System.out.print(p + " ");
        }


text:
Q: Modelling changes in a distribution over time ggridges does a nice job of visualizing the change in a distribution over time.
df <- read.csv('https://raw.githubusercontent.com/bdetweiler/bdetweiler.github.io/master/data/sample.csv')
df %>%
  ggplot(aes(x = age, y = year, group = year)) +
    geom_density_ridges()

Clearly the data is becoming less concentrated at 80, and expanding to people in the 50s-70s range.
How would I go about modelling this change over time? Since I am dealing with ages, my data is discrete. I could run a time series for each age, but it seems like I would miss out on the overall trend.
I would be particularly interested in any Bayesian methods that might accomplish this.


text:
Q: Which SQL datatype should I use to store datetime from GPS devices? I'm working on a project where I have to gather data from GPS devices located in different countries (timezones + daylight savings) and display those data to different users also from different countries. I'm thinking about saving the date in UTC format (that is what I receive from the GPS device) but then again I belive I'll have trouble converting that date to the user's local date (I have to display historical data also so I'll have to account for daylight savings for the given date). Maybe the datetimeoffset datatype would be more appropriate but how would I go about converting the received UTC date to the datetimeoffset datatype? What would you suggest? Thanks!

A: As you don't have to store any time zone along with the datetime, you can store them as UTC. That has the advantage of being linear, and easy to document. You don't have to bother with gaps and overlaps at the daylight savings time switches.
Convert the date to the local time zone when you display it to the user. It doesn't make sense to convert it to a local time zone until you know which user will be viewing the data.


text:
Q: Are there any web applications to merge small images into a single one? Is there any application to merge small images into a single one in a web application in order to make less HTTP request and have the page load faster?
GWT does this automatically and makes proper images + CSS styles to show those images. When I have a plain HTML + CSS is there a helper application which given HTML + CSS + a bunch of small images, outputs a proper HTML + CSS + Single Image?
See for example this Google image.

A: The technique you're looking for is called CSS sprites (take note of this name the next time you talk about it).
Although what you're asking for (give them your code, get back same code with sprites applied) is a little too much, some online generators do come close - they will automatically calculate the most optimal image placement and give you the CSS needed for this. Googling for CSS Sprite Generator gets back some very good ones, like http://spritegen.website-performance.org/.
You should note that these generators are not perfect, and for static sites you will need to do this ever ytime you want to tweak the graphics on the site.

A: You could give SpriteMe a try


text:
Q: Lambda function with if else clause with Python I have a dataframe that looks like:
A   B   C   D   SUM
2   5   -4  12  15

I try and run:
df.apply((lambda x: x / x.sum() if x/x.sum() >= 0 else None), axis=1).fillna(0)

to get, if cell is same at total then calculate x/total:
A         B     C   D
2/15    5/15    0   12/15

I get:
'The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can i improve the code.

A: You are mixing up pd.Series.apply and pd.DataFrame.apply. They are different methods: one works on a series and operates on each element; the other operates across the dataframe along an axis. In the latter case, along axis=1 means each row is fed to the function sequentially.
Because these apply methods (both versions) are just thinly veiled loops, the dataframe will change after each columnwise lambda call. Therefore, you will need to work with a copy of the dataframe:
df2 = df.copy()

for col in df.columns[:-1]:
    df2[col] = df.iloc[:, :-1].apply(lambda x: x[col] / x.sum() if x[col]/x.sum() >= 0 \
                                     else None, axis=1).fillna(0)

print(df2)

          A         B  C    D  SUM
0  0.133333  0.333333  0  0.8   15

However, this is all very inefficient. We aren't utiling the underlying NumPy arrays. Instead, you can use vectorised operations:
res = df.iloc[:, :-1].div(df.iloc[:, :-1].sum(1), axis=0)
res.mask(res < 0, 0, inplace=True)

print(res)

          A         B    C    D
0  0.133333  0.333333  0.0  0.8


text:
Q: Meteor collection sort by $size issue This is about likes and dislikes on comments. I'd like to sort comments by likeness, so a comment with more likes will appear first. The issue is that comments with dislikes appear before than comments with no dislikes.
What i want:

*

*Comment A : 1 like 0 dislikes

*Comment B : 0 like 0 dislike

*Comment C : 0 like 1 dislike

What I'm actually getting:

*

*Comment A : 1 like 0 dislikes

*Comment C : 0 like 1 dislike

*Comment B    : 0 like 0 dislike

My mongo query on my meteor helper:
Missatges.find({ topic: 'xxx' }, { sort: { like:{ $size: -1}, dislike:{ $size: 1}, date: -1 } }).fetch();

Note that I use $size because like and dislike are arrays of user _id's.
Here my comment schema:
author: {
    type: String

},
authorId: {
    type: SimpleSchema.RegEx.Id
}
isAnswer: {
    type: Boolean
},
parentId: {
    type: SimpleSchema.RegEx.Id,
    optional: true
},
date: {
    type: Date
},
topic: {
    type: String
},
likes: {
    type: [SimpleSchema.RegEx.Id]
},
dislikes: {
    type: [SimpleSchema.RegEx.Id]
},
answers: {
    type: [SimpleSchema.RegEx.Id],
    optional: true
},
text: {
    type: String,
    max: 900,
}

A: According to the answer to this question you can't use $size to sort in mongo. One solution is to fetch the matching documents and sort them in the helper. Here's an example (note this is untested and may require some tweaking):
Template.something.helpers({
  sortedThings: function () {
    return Missatges
      .find({ topic: 'xxx' })
      .fetch()
      .sort(function (b, a) {
        var al = a.likes.length;
        var ad = a.dislikes.length;
        var bl = a.likes.length;
        var bd = a.dislikes.length;
        var d1 = a.date;
        var d2 = b.date;

        // compare by likes
        if (al > bl) return 1;
        if (al < bl) return -1;

        // compare by dislikes
        if (ad < bd) return 1;
        if (ad > bd) return -1;

        // compare by date
        if (d1 > d2) return 1;
        if (d1 < d2) return -1;

        // they are equal
        return 0;
      });
  },
});


text:
Q: Searching Window Spread in Ubuntu 13.10? The super + w shortcut which "window spreads" will not let me search through windows. I tried messing with ccsm but still cannot figure out what is wrong.
Ubuntu 13.10

A: The filter by window option is available through the plugin "Scale Window Title Filter".
You'll need to install the extra package:
compiz-plugins-extra

Once done you'll be able to filter your windows by typing part of the window title:


text:
Q: Currency is not defined I decided to use this discord.js guide  to create my economy discord bot. Apparently something went wrong as I was about to run the bot. It had this error message and it said :
Reflect.defineProperty(currency, 'add', {
                       ^

ReferenceError: currency is not defined

I have no idea what was wrong with it. Here's my index.js:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();

Reflect.defineProperty(currency, 'add', {
    /* eslint-disable-next-line func-name-matching */
    value: async function add(id, amount) {
        const user = currency.get(id);
        if (user) {
            user.balance += Number(amount);
            return user.save();
        }
        const newUser = await Users.create({ user_id: id, balance: amount });
        currency.set(id, newUser);
        return newUser;
    },
});

Reflect.defineProperty(currency, 'getBalance', {
    /* eslint-disable-next-line func-name-matching */
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.once('ready', () => {
    console.log('Ready!');
});

});

client.on('message', async message => {
    if (message.author.bot) return;
    currency.add(message.author.id, 1);

    if (!message.content.startsWith(PREFIX)) return;
    const input = message.content.slice(PREFIX.length).trim();
    if (!input.length) return;
    const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

    if (command === 'balance') {
        const target = message.mentions.users.first() || message.author;
        return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
    } else if (command === 'inventory') {
        const target = message.mentions.users.first() || message.author;
        const user = await Users.findOne({ where: { user_id: target.id } });
        const items = await user.getItems();

        if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
        return message.channel.send(`${target.tag} currently has ${items.map(t => `${t.amount} ${t.item.name}`).join(', ')}`);
    } else if (command === 'transfer') {
        const currentAmount = currency.getBalance(message.author.id);
        const transferAmount = commandArgs.split(/ +/).find(arg => !/<@!?\d+>/.test(arg));
        const transferTarget = message.mentions.users.first();

        if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount`);
        if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author} you don't have that much.`);
        if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}`);

        currency.add(message.author.id, -transferAmount);
        currency.add(transferTarget.id, transferAmount);

        return message.channel.send(`Successfully transferred ${transferAmount} to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}`);
    } else if (command === 'buy') {
        const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
        if (!item) return message.channel.send('That item doesn\'t exist.');
        if (item.cost > currency.getBalance(message.author.id)) {
            return message.channel.send(`You don't have enough currency, ${message.author}`);
        }

        const user = await Users.findOne({ where: { user_id: message.author.id } });
        currency.add(message.author.id, -item.cost);
        await user.addItem(item);

        message.channel.send(`You've bought a ${item.name}`);
    } else if (command === 'shop') {
        const items = await CurrencyShop.findAll();
        return message.channel.send(items.map(i => `${i.name}: ${i.cost}`).join('\n'), { code: true });
    } else if (command === 'leaderboard') {
        return message.channel.send(
            currency.sort((a, b) => b.balance - a.balance)
                .filter(user => client.users.cache.has(user.user_id))
                .first(10)
                .map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}`)
                .join('\n'),
            { code: true }
        );
    }
});

client.login(`[TOKEN]`);

I presume the only probelm of this code is Reflect.defineProperty(currency, 'add', { as it can't define what is currency. I hope someone can help...

A: You're attempting to use the currency variable but you haven't defined it so JavaScript is rightfully complaining because it doesn't know what currency is.
The following line from the guide is missing from your code:
const currency = new Discord.Collection();

A: You have to define currency.
Basic js-


text:
Q: How can I play a JavaScript audio only getUserMedia stream to the user agent? I can't figure out how to get an audio only stream (from navigator.mediaDevices.getUserMedia) into a real, working audio playback for my users. I would prefer to do everything in native JavaScript (no HTML) but libraries are fine. So, what would I use? Would I just execute
new Audio(stream);

or would that be not what I want? Very confused, seems like I'm making a simple mistake. I know how to do it with video! Again, prefer audio JS or audio elements only, in this use case we can't show a video in a good place. Stream will always come in audio only due to our constraints. Thanks for trying to help!

A: I did some experimenting; here's how you do it.
(async () => {
    let audio = new Audio();
    audio.srcObject = await navigator.mediaDevices.getUserMedia({audio: true, video: false});
    audio.play();
})();

WARNING: Obviously this code would play sound from your own microphone; so use a remote stream to avoid very annoying feedback (trust me, I've heard it).


text:
Q: How to uncheck the CheckBox, when limit exceeds in android? Hello I am New to Android, My requirement is allow the user to check maximum 3 number of checkboxes. when user is trying to check fourth one should populate dailogue.
Iam trying but the problem is fourth one is not unchecking...
can any one help me...
Regards
Shiva.M

A: Just uncheck the checkbox using the following code block:
     final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
     if (checkBox.isChecked()) {
         checkBox.setChecked(false);
     }


text:
Q: Knockout inheritance reusing same instance of base ViewModel? I am using Knockout.js on an MVC application.
I am attempting to use inheritance, but I think may BaseViewModel is being reused, instead of a new one being created for each ViewModel instance.
I have a single BaseViewModel, and multiple ViewModels that extend it. The behavior is the same for all Views\ViewModels - They display a list of items as an html table, and clicking the edit button of a row pops up the selected row in a modal window so that you can edit and save the changes to that row.
These all work just fine on their independent views. However, when I try to display them all on a single view, I am having issues.
The lists for each View are all binding just fine.
Clicking edit on a selected row of the LAST list/table works fine.
But clicking edit on a selected row of the FIRST list/table fails with error.
Uncaught ReferenceError: Unable to process binding "value: function (){return Name }"

"Name" is a property of the model on the the second ViewModel, not the first.
It appears that error is because only one BaseViewModel is getting created, and so properties of that BaseViewModel are being overwritten every time I add a new ViewModel to the View.
Here is a fiddle with Example of the issue.
JSFiddle
Take a look at the editItem function and bring up the console.
Then click on Edit of the second table, you will see it properly prints to console the values passed into the base class, and the Modal window opens fine.
If you then cancel and click edit of the first table, you will see it prints the SAME values that the second ViewModel passed into the BaseVM, and NOT the values that it itself passed in.
Here is my knockout BaseViewModel as well the derived ViewModels.
EnvironmentAssetBaseViewModel = function(modalWindowName, apiResourceName, modelDefinition) {
    var self = this;
    self.modalWindowName = modalWindowName;
    self.apiResourceName = apiResourceName;
    self.modelDefinition = modelDefinition;
    self.itemList = ko.observableArray([]);
    self.selectedRow = ko.observable(modelDefinition);

    function getData() {
        //make ajax API call and store data in itemList
        var data = [];
        if (apiResourceName == 'activityLogs') {
            data = [
                { Id: "1", Action: "a", Details: "d"},
                { Id: "2", Action: "b", Details: "e"},
                { Id: "3", Action: "c", Details: "f"}
            ]
        } else {
            data = [
                { Id: "109", Name: "a", Description: "d" },
                { Id: "209", Name: "b", Description: "e" },
                { Id: "309", Name: "c", Description: "f" }
            ]
        }

        self.itemList(data);
    }

    function editItem(item) {
        console.log(self.modalWindowName);
        console.log(self.apiResourceName);
        console.log(self.modelDefinition);
        self.selectedRow(item);
        $(modalWindowName).modal('show');
    }

    function cancel(item) {
        $(modalWindowName).modal('hide');
    }
    return {
        self: self,
        itemList: self.itemList,
        selectedRow: self.selectedRow,
        getData: getData,
        editItem: editItem,
        cancel: cancel
    }
};

ActivityLogsViewModel = function() {
    var self = this;
    var modalName = "#activityLogModal";
    var apiResourcename = "activityLogs";
    var modelDefinition = { Id: "", Action: "", Details: "" };

    ko.utils.extend(self, new EnvironmentAssetBaseViewModel(modalName, apiResourcename, modelDefinition));
    getData(); //initial data load

    return {
        self: self,
        editItem: editItem,
        cancel: cancel
    }
};
ko.applyBindings(ActivityLogsViewModel, document.getElementById('activityLogsDiv'));

DomainsViewModel = function() {
  var self = this;
  var modalName = "#domainModal";
  var apiResourcename = "domains";
  var modelDefinition = { Id: "", Name: "", Description: "" };

  ko.utils.extend(self, new EnvironmentAssetBaseViewModel(modalName, apiResourcename, modelDefinition));
  getData(); //initial data load

  return {
    self: self,
    editItem: editItem,
    cancel: cancel
  }
};

ko.applyBindings(DomainsViewModel, document.getElementById('domainsDiv'));

A: You're mixing up some methods of creating "instances" of functions.
You've defined constructor functions that "manually" return a plain object. This is perfectly fine, but it means you don't call them with the new keyword.
The new keyword creates a new this context, but since you're not using it, your first line:
var self = this;

will set self to whatever the context of the caller of the factory method is. In this case, window.
This means all your constructor functions/factories are polluting the window namespace, resulting in a weird combination of properties that are missing/overridden.
Try replacing var self = this with var self = {} to create a new object. Make sure you call your functions to create viewmodels: var activityVM = ActivityLogsViewModel().
You'll run in to some other bugs (for example, getData() needs to be self.getData()), but you should be able to figure it out.
Let me know if you need more help.


text:
Q: Аргумент типа char* несовместим с параметром типа tchar* DWORD gamebaseadress1 = GetModuleBaseAddress(_T(gamemmodule1), pID);

ошибка в (_T

A: Давайте посмотрим, а что же делает этот _T(...). Для этого возьмем подчищенный код с библиотеки
#ifdef _UNICODE
 #define _T(c) L##c
 #define TEXT(c) L##c
#else
 #define _T(c) c
 #define TEXT(c) c
#endif

То есть, грубо говоря, если определен макрос _UNICODE, то _T(word) заменяется на Lword. Странно, да? нет, просто в плюсах есть конструкция L"text", для того, что бы подсказать компилятору, что текст в кавычках это не const char*,  const wchar_t*. Что же будет, если туда подсунуть просто какую то переменную типа char*? а ничего хорошего. При компиляции с отключенным _UNICODE, оно будет работать, а с включенным (это 99% современного кода), будет ошибка.
Как исправлять?
если тип у gamemmodule1 wchar_t*, то можно просто написать
DWORD gamebaseadress1 = GetModuleBaseAddress(gamemmodule1, pID);

или даже так (как по мне, то если не нужно заморачиваться на старый код без поддержки юникода, то это самый простой вариант):
DWORD gamebaseadress1 = GetModuleBaseAddressW(gamemmodule1, pID);

Если же тип char*, то можно по быстрому так
DWORD gamebaseadress1 = GetModuleBaseAddressA(gamemmodule1, pID);

Но лучше имя модуля сразу получать в wchar_t*. или преобразовать.
А ещё лучше, хотя это и сложно, поддержать тип TCHAR* - это такой тип, который также зависит от _UNICODE и разворачивается в char* или wchar_t* или заморочится с конвертированием, но это нудно. Проще сразу в юникод стиле делать.
На почитать https://habr.com/ru/post/164193/


text:
Q: Calculating weighted/unweighted GPA by reading text file into string/vector I'm aware that there are many GPA calc questions in existence but I haven't managed to find one involving weighted and unweighted distinction.
I need to read the text file, input lines into a string or vector (not experienced with these), and parse the data (haven't done this before either) to calculate GPA and whether or not the credits are weighted. If the course is AP, the grade is weighted +1.0, if it is Honors, +0.5.
I'm pretty sure what I have so far is very wrong, but I'm trying to hash out the syntax for this type of operation.
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    using namespace std;

    int main(){

        string data;
        vector<string> lines;
        ifstream myfile("Grades.txt");

        //test file open//
        if (!myfile){

            cout << "Error opening file" << endl;
            system("pause");
            return -1;
        }
        //insert file text into vector//
        while (getline(myfile, data)){

            lines.push_back(data);
        }
        for (int i = 0; i < 8; i++){

            if ((strlen(lines[i]) - 1) == 'A'){
                sum =+ 4;
            }
            else if ((strlen(lines[i]) - 1) == 'B'){
                sum =+ 3;
            }
            else if ((strlen(lines[i]) - 1) == 'C'){
                sum =+ 2;
            }
            else if ((strlen(lines[i]) - 1) == 'D'){
                sum =+ 1;
            }
            else {
                sum =+ 0;
            }
        }

    }

This is the text file's contents:
    Math A
    AP History C
    Chemistry B
    Honors Physics C
    Ethics A

A: I don't know an awful lot about C++, but since you tagged this with C and your code contains some C constructs I'm going to pretend that I am qualified to answer it anyway.
Firstly, these lines are rather questionable:
system("pause");
return -1;

If you want to have the program wait (why?) the easiest way would probably be to just prompt for some input with getchar(). Also, don't return negative values from main(). The return should be between 0 and 127.
More importantly though, you're doing a few things that are not going to work at all. strlen() calculates the length of a NUL terminated C string. C++ std::string's are very definitely not NUL terminated strings and the result will be completely undefined. If you want to find the length of an std::string, you must call std::string.length(), which is much preferable anyway since the result doesn't need to be calculated. Also, you cannot use getline with an std::string either.
I actually wrote some code I was going to submit as a possible solution to your problem, but it was C code, and since I see you've removed the C tag from this question I won't include it.
EDIT: Ah, the heck with it, this is how I'd do it in C.
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define FILENAME "Grades.txt"

int main(void)
{
    struct stat st;
    char *tok, *obuf, *buf;
    FILE *fp = fopen(FILENAME, "r");

    if (!fp || stat(FILENAME, &st) != 0)
        err(1, "Failed to open/stat file %s\n", FILENAME);

    buf = obuf = malloc(st.st_size + 1lu);
    fread(buf, 1, st.st_size, fp);
    buf[st.st_size] = '\0';
    fclose(fp);

    int num_classes = 0;
    double grade = 0;
    while ((tok = strsep(&buf, "\n")) && *tok) {
        double weight = 1;
        if (strstr(tok, "AP"))
            weight = 2;
        else if (strstr(tok, "Honors"))
            weight = 1.5;

        int grd;
        switch(*(buf - 2lu)) {
            case 'A': grd = 4; break;
            case 'B': grd = 3; break;
            case 'C': grd = 2; break;
            case 'D': grd = 1; break;
            default:  grd = 0; break;
        }

        grade += weight*(double)grd;
        ++num_classes;
    }

    printf("The gpa is around %f\n", grade / (double)num_classes);

    free(obuf);
}

A: (1)  Your code does not compile.  'Sum' is undeclared.  Please submit code that compiles.  (2)  The strlen call is trying to evaluate the length of a vector, not a string.  You then compare the string length to a letter.  You need to use the strlen as an index to a string before comparing it.


text:
Q: Transforming lon/lat to tmerc in Python I have shp file of Wrocław city borders and lon-lat coordinates of the bus stops (stops.txt file)
The city borders are in flowing projection
gdf.crs

{'proj': 'tmerc',
 'lat_0': 0,
 'lon_0': 18,
 'k': 0.999923,
 'x_0': 6500000,
 'y_0': 0,
 'ellps': 'GRS80',
 'units': 'm',
 'no_defs': True}

While bus stops coordinates are in plain lon-lat format
How using python can I change projection and plot those on same chart?
EDIT:
When I try to do to_crs method
gdf1 = gdf1.to_crs("EPSG:4326")

or
gdf1 = gdf1.to_crs({'init': 'epsg:4326'})

I get error:
Traceback (most recent call last):

  File "<ipython-input-11-a2ef4c434a50>", line 1, in <module>
    gdf1 = gdf1.to_crs("EPSG:4326")

  File "D:\Anaconda_Python\lib\site-packages\geopandas\geodataframe.py", line 545, in to_crs
    geom = df.geometry.to_crs(crs=crs, epsg=epsg)

  File "D:\Anaconda_Python\lib\site-packages\geopandas\geoseries.py", line 424, in to_crs
    proj_out = pyproj.Proj(crs, preserve_units=True)

  File "D:\Anaconda_Python\lib\site-packages\pyproj\__init__.py", line 362, in __new__
    return _proj.Proj.__new__(self, projstring)

  File "_proj.pyx", line 129, in _proj.Proj.__cinit__

RuntimeError: b'no arguments in initialization list'

A: import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import geopandas as gpd
import pandas as pd

gdf1 = gpd.read_file('GraniceOsiedli.shp')

gdf1 = gdf1.to_crs("EPSG:4326")
#gdf1.to_crs({'init': 'epsg:4326'}) for older versions of gpd

df = pd.read_csv('stops.txt')

proj = ccrs.PlateCarree(central_longitude=0)

fig, ax = plt.subplots(subplot_kw=dict(projection=proj), figsize=(16,16))
ax.set_extent([df['stop_lon'].min()-0.01,
               df['stop_lon'].max()+ 0.01,
               df['stop_lat'].min()- 0.01,
               df['stop_lat'].max()+0.01],
              crs=ccrs.PlateCarree())

fig.canvas.draw()
fig.tight_layout()

ax.scatter(df['stop_lon'].values.tolist(), df['stop_lat'].values.tolist())
ax.add_geometries(gdf1['geometry'], crs=proj, facecolor="none", edgecolor="red")

plt.show()


text:
Q: sys.stdout.writelines("hello") and sys.stdout.write("hello") What is the difference between the following two commands?
In [57]: sys.stdout.writelines("hello")
hello
In [58]: sys.stdout.write("hello")
Out[58]: hello5

A: sys.stdout.writelines accepts an iterable of strings and writes them to stdout one string at a time. Since it does not append newline characters, elements of the iterable will appear to be concatenated if they don't already contain newlines. The return value is None.
sys.stdout.write accepts a single string, and writes it to stdout. It returns the number of characters written.
The first example (writelines) works because a string is an iterable of strings. Each character in the input is written separately. Notice that there is no Out[57] because the return value is None, but the characters are all printed. They are written individually, but you can't tell because they don't have newlines between them.
The second example (write) prints the whole string all at once. Since write doesn't append newline characters either, the return value (5) is printed immediately after. Out[58] is printed because there is a non-None return value in this case.
In general, writelines was meant to mimic/invert readlines, so normally you could see the difference much better. You would normally call writelines with a list or similar iterable, but write only accepts a single string (and returns a value):
>>> sys.stdout.writelines(['hello\n', 'world\n'])
hello
world

>>> sys.stdout.write('hello\nworld\n')
hello
world
10

Barring the return value, for a single string, the result of writelines and write are indistinguishable. writelines is much less efficient though, since it effectively applies write to each character individually.


text:
Q: Double integrals using cylindrical coordinates Suppose we had a vector field $F = (axy^2,ayx^2,x^2\cos(\pi z))$ and wanted to calculate the surface integral of $$\int\int_SF\cdot n \ dS$$
where $S = \{(x,y,z): x^2 +y^2 = 1, 0 \leq z \leq 1/2 \}$
The question does this using cylindrical coordinates,
so we have: $F\cdot n = 2ax^2y^2 = 2ar^4\cos^2(\phi)\sin^2(\phi)$ but $r^2 = x^2 + y^2 = 1$ so $F\cdot n = 2ax^2y^2 = 2a\cos^2(\phi)\sin^2(\phi)$
now we have the Jacobian as $r$, and the question states that "using cylindrical integration we get:
$$2a \int_0^{1/2}\int_0^{2\pi} \cos^2(\phi)\sin^2(\phi) \ d\phi d z$$  but usually we have $drd\phi d z$ why only $\ d\phi d z$ in this case?

A: Because you're doing a surface integral (and there are precisely two degrees of freedom, i.e., two parameters, on a surface), not an integral over the solid cylinder.


text:
Q: location.hash = window.location.hash does not work in Chrome I'm dynamically creating anchors with JavaScript after initial page load and my solution to redirecting to the anchor is calling:
location.hash = window.location.hash;

This works great and as intended in firefox, it jumps straight to the anchor without reloading the page. However when testing in chrome, this simply doesn't work. I've tried the typical approaches I use to get something to work in chrome such as, wrapping it in a timeout, using href instead of hash, and even using hash.substr(1) to try and get chrome to play ball.
I'm at a lost, any tips?

A: setTimeout(function() {save = location.hash; location.hash=''; location.hash=save;},300);

Was the accepted approach given by @Jaromanda X in the comments.


text:
Q: Error While Installing Fabric Chaincode: _lifecycle.syscc: no such file or directory While trying to install chaincode using Fabric v2.1, I am encountering an error. Does anyone face similar issues? My peer is running fine and able to join the channel as well. I am able to list the channel details as well.
Note: I am doing Native installation without using docker images for running orderer and peer.
Highly appreciate for your support and looking forward to hear from you.
Error:

chaincode install failed with status: 500 - error in simulation: failed to execute transaction 44688cc50afeda03e3f5e7735ae650030952477b6bdfce83064582f42bec6c84: could not launch chaincode _lifecycle.syscc: error building chaincode: error building image: failed to get chaincode package for external build: could not get legacy chaincode package '_lifecycle.syscc': open /home/vagrant/ledger/ORG2/peer1-org2/ledger/chaincodes/_lifecycle.syscc: no such file or directory

A: I got this error after upgrading from 1.4. In my case the problem was in the old config file for the peer.
Make sure you have next lines in your core.yaml:
chaincode:
    ...
    # enabled system chaincodes
    system:
        _lifecycle: enable


text:
Q: How do I store a cell range into a variable? So, I wanted to make a "nicer" reference to a cell range soas not to have to copy/paste it throughout my method, but the following code does not work:
Dim cellRange As Range
' fieldIndex = 1, startRow = 10, lastRow = 20
cellRange = s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex))

What am I missing?  I can use it in other ways just fine:
s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex)).Value = "bob"

A: You need to use Set for objects like a Range:
Dim cellRange As Range
' fieldIndex = 1, startRow = 10, lastRow = 20
Set cellRange = s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex))

A: As suggested by Sid you may also need to clarify the Cells part, like this for example.
With s
   Dim cellRange As Range
   ' fieldIndex = 1, startRow = 10, lastRow = 20
   Set cellRange = .Range(.Cells(startRow, fieldIndex), .Cells(lastRow, fieldIndex))
End with


text:
Q: Evaluate $\lim_{r \to \infty} \iint_{D_r} \frac{1}{1+x^2+y^2} dx dy$ Evaluate
$$\lim_{r \to \infty} \iint_{D_r} \frac{1}{1+x^2+y^2} dx dy$$
where $D_r=\{(x,y) \in \mathbb{R}^2 \ \text{s.t.} \ 0 \leq y \leq 1, \ x \geq 0, \ x^2+y^2 \leq r^2 \}$.
My try is the following: I use a change of variable in polar coordinates with pole in the origin, hence
$$D_r \mapsto E_r=\{(\rho, \theta) \in \mathbb{R}^2 \ \text{s.t.} \ 0 \leq \rho \sin \theta \leq 1, \rho \cos \theta \geq 0, \rho^2 \leq r^2, \rho \geq 0, 0 \leq \theta <2\pi\}$$
$$\iff \left\{(\rho, \theta) \in \mathbb{R}^2 \ \text{s.t.} \ 0 \leq \rho \leq \frac{1}{\sin \theta}, 0 \leq \theta \leq \frac{\pi}{2}, 0 \leq \rho \leq r\right\}$$
And
$$\lim_{r \to \infty} \iint_{D_r} \frac{1}{1+x^2+y^2} dx dy=\lim_{r \to \infty}\iint_{E_r} \frac{\rho}{1+\rho^2} d \rho d \theta$$
Since $\rho$ has two upper bounds I discuss $0 \leq \rho \leq \min\left(r, \frac{1}{\sin \theta}\right)$. Now, being interested in what happens when $r \to \infty$, I assume that $r>\frac{1}{\sin \theta}$ and so I get that $\min\left(r, \frac{1}{\sin \theta}\right)=\frac{1}{\sin \theta}$; hence
$$\lim_{r \to \infty}\iint_{E_r} \frac{\rho}{1+\rho^2} d \rho d \theta=\lim_{r \to \infty} \int_0^{\frac{\pi}{2}} \left(\int_0^{\min\left(r,\frac{1}{\sin\theta}\right)} \frac{\rho}{1+\rho^2}d\rho\right)d\theta$$
$$=\lim_{r \to \infty} \int_0^{\frac{\pi}{2}} \left(\int_0^{\frac{1}{\sin\theta}} \frac{\rho}{1+\rho^2}d\rho\right)d\theta$$
At this point both the set is independent of $r$ and so
$$\lim_{r \to \infty} \int_0^{\frac{\pi}{2}} \left(\int_0^{\frac{1}{\sin\theta}} \frac{\rho}{1+\rho^2}d\rho\right)d\theta=\int_0^{\frac{\pi}{2}} \left(\int_0^{\frac{1}{\sin\theta}} \frac{\rho}{1+\rho^2}d\rho\right)d\theta=\int_0^{\frac{\pi}{2}} \frac{1}{2}\log\left(1+\frac{1}{\sin^2 \theta}\right)d\theta$$
$$=\frac{\pi}{2} \log(1+\sqrt{2})$$
The result is correct, however I'm not sure when I declare that since $r \to \infty$ I can assume $r>\frac{1}{\sin \theta}$; the doubt comes from the fact that $\theta \in \left[0,\frac{\pi}{2}\right]$ and so when $\theta$ gets really close to $0$ the function $\frac{1}{\sin \theta}$ is unbounded. So I feel like there is some kind of "battle" between $r$ and $\frac{1}{\sin \theta}$ going to infinity that makes impossible to understand which one is actually bigger for discussing the minimum.
Am I missing something and there is no problem for $\frac{1}{\sin \theta}$ when $\theta \to 0^+$ (and if there isn't, why it isn't? Why can I ignore the fact that it tends to infinity for small values of $\theta$ in the domain of integration?) or I was just lucky and my approach was wrong because I can't make that assumption? Thanks.
Edit: Added a term $\frac{1}{2}$ that I forgot.

A: This is another way, which avoids the problem you are pointing out. For $r>1$,
$$I_r:=\iint_{D_r} \frac{1}{1+x^2+y^2} dx dy=\int_{0}^1\left(\int_{0}^{\sqrt{r^2-y^2}}\frac{dx}{1+x^2+y^2}\right)\,dy
=\int_{0}^1\frac{\arctan\left(\frac{\sqrt{r^2-y^2}}{\sqrt{1+y^2}}\right)}{\sqrt{1+y^2}}\,dy.$$
Now for $y\in[0,1]$ and $r>1$, we have that
$$0\leq \frac{\pi}{2}-\arctan\left(\frac{\sqrt{r^2-y^2}}{\sqrt{1+y^2}}\right)=\arctan\left(\frac{\sqrt{1+y^2}}{\sqrt{r^2-y^2}}\right)\leq
\frac{\sqrt{2}}{\sqrt{r^2-1}}.$$
Hence, as $r\to \infty$,
$$0\leq \frac{\pi}{2}\int_0^1\frac{dy}{\sqrt{1+y^2}}-I_r\leq
\frac{\sqrt{2}}{\sqrt{r^2-1}}\int_0^1\frac{dy}{\sqrt{1+y^2}}\leq \frac{\sqrt{2}}{\sqrt{r^2-1}}\to 0,$$
and we may conclude that
$$\lim_{r\to\infty}I_r=\frac{\pi}{2}\int_0^1\frac{dy}{\sqrt{1+y^2}}=\frac{\pi}{2}\, \log(1+\sqrt{2}).$$


text:
Q: recursive search in cmake post build I want all the files with a particular extension in CMake in a directory. These extension files are generated post running the build.
I tried
file(GLOB_RECURSE GCOV_OBJECTS $ENV{OUTPUT_UT_DIR} *Test.cpp.o)

But this is getting executed before running the build. I want something like this
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                  COMMAND my_command_to_get_all_desired_files

Using file command inside add_custom_command is giving me a syntax error. Not sure how to proceed from here.

A: Create a cmake script:
# mycmakescript.cmake
file(GLOB_RECURSE GCOV_OBJECTS $ENV{OUTPUT_UT_DIR} *Test.cpp.o)
message("${GCOV_OBJECTS}")
#  I need to execute a command on those files. like gcov ${GCOV_OBJECTS}
execute_process(COMMAND gvoc ${GCOV_OBJECTS})

and call it when building:
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
              COMMAND cmake -P mycmakescript.cmake)


text:
Q: Probably recurrent function
Let there be a recurrent function, $f(n) = f(n-1)+f(n-2)+p_1f(n-1)+p_2f(n-2)$, where $p_1, p_2$ accept $0$ or $1$ with a probability of $\frac{1}{2}$.
  What is the mathematical expectation of the function value f(n)?
  P.S. $f(0) = f(1) = 1 $

A: First, factor out each term:
$f(n) = (1+p_1) f(n-1) + (1+p_2) f(n-2)$
Now you need to solve for each combination of these terms $(p_1,p_2)$ so 4 cases.
Now you solve the general equation by calculating the characteristic equation $x^2 = (1+p_1)x + (1+p_2)$.
By calling $\delta = \sqrt{(1+p_1)^2+ 4(1+p_2)}$, the general expression becomes: $u(n) = 2^{-n} (K_1 ((1+p_1) - \delta)^n) + K_2((1+p_1)+\delta)^n)) $ with $K_1$ and $K_2$ two constants.
Now by using $f(0) = f(1) = 1$ you can get: $K_1 + K_2 = 1$ and $\frac{1}{2} (K_1 ((1+p_1) - \delta)+K_2((1+p_1)+\delta)) = 1$. Meaning you can get all the values of $u(n)$ and thus the values of the expected value for all combination of $p_1$ and $p_2$


text:
Q: Minor edits from users with higher reputation I know that it is in general frowned upon users that make minor edits to fix small grammatic issues, add a single tag etc. From my understanding this is primarily so that they will not get free reputation for little to no work, but what is the stance for user that no longer gets reputation.
I see many scenarios where simply adding a tag like for example questions that are missing the core tag. Or capitalizing  multiple lower-case i may not be a major improvement, but remove small annoyances. Is this frowned upon even if done by users that no longer gains reputation, and by-passes the review process?

A: Ideally edits should address all the issues with a post, but there are no mechanisms to stop those with sufficient reputation just making minor edits - even if they are discouraged.
If the capitalisation of an i is all that's required then that's a valid edit, but it does bump the post the same as a major edit and on smaller sites could end up swamping the home page if you are doing a lot of them.
Basically it comes down to using your common sense. You have a privilege, just don't abuse it.

A: Trivial edits are discouraged because they bump the question back to the top of the Active list, and typically we do not want to be bumping non-active questions to the top of this list.
I actually asked another MSO question about SE's "official stance" on trivial edits, and the Editing Privilege Page was pointed out to me

Try to make the post substantively better when you edit, not just
  change a single character. Tiny, trivial edits are discouraged.

So regardless of your reputation, you should be trying not to make trivial edits.
Its not often that the only mistake is just a major missing tag, or a glaring spelling error, so always be sure to check for what else you can fix when editing a post to try and make your edit more substantial.
If absolutely nothing else is wrong with the question but a glaring spelling error, or an important tag missing, you can still go ahead and fix it if you think it will help the post, but trivial edits that don't significantly improve the post are discouraged, especially en masse.

A: If your edits no longer require review (i.e. you have enough reputation), by all means, go fix such annoyances, as and when you encounter them, but do not search for them, as they will bump the question to the front page.
Mind, however, that there are many such and it can become tedious. Most posts will benefit from more improvements, so when you do see such a thing, see if there are other improvements to be made.

A: Minor edits are totally fine for users that don't need approval.
Minor edits are only discouraged if they go into the review system because they tend to generate too much work for so little use.

A: I don't think there's anything wrong with editing old posts and making trivial changes if they:

*

*Improve the chances of people reading and understanding them.

*Improve the chances of finding questions (and subsequent great answers) through the web.

*Prevent the same questions being asked time and time again through poor titling/wording/spelling etc.

I regularly edit trivialities in posts where I'm researching an element, subject or issue. But, (and it's an important but) usually in addition to grammar, formatting etc. Hoping to improve posts for others.
If the active list is getting cluttered with trivial edits, then perhaps it's a sign that a filtering mechanism is required to hide trivial edits...


text:
Q: React map function delivers no result I have a simple array:
const plaene = [
{
"bezeichnung":"P1",
"erstelltAm":"18.07.2020"
},
{
"bezeichnung":"P2",
"erstelltAm":"18.07.2020"
 },
{
"bezeichnung":"P3",
"erstelltAm":"18.07.2020"
 }
]

So if I want to map over that array, I got no result.
Only when I explicitly specify the position in the map function ( plan1.bezeichnung ) do I get the values displayed. So why does the following not work?
export default function Wochen({pl}) {

return ( <div>
    {
        Object.entries(pl).map(plan =>{
            return(
                <Plaene key={plan} title={plan.bezeichnung}/>

            );
        })
    }
    </div> )
};

A: I would try without Object.entries() as:
{
     pl.map((plan, index) => {
         return(
             <Plaene key={index} title={plan.bezeichnung}/>
         );
     })
}

Above .map() has the actual entry in plan on every iteration for your array, also index can be used as key for your component.

A: plan - is the key. Type pl[plan] to access the value


text:
Q: dynamically use radio buttons in asp.net applications I am developping an asp.net application.
When a user clicks on a page, some radio buttons are added to the the page dynamically.
Then when he clicks on another "update" button, I would liek to check, which of the radio buttons are checked and post back them to the server.
The problem is the following:
I add dynamically the radio buttons in the page_load method.
But when I am on the update button onclick method, I cannot use them to check if they are checked ot not.
I have tried several methods like using a static dictionary of radiobuttons, but I cannot keep a reference on them, when I am on my update method.
This is my method when the page is loading:
private static Dictionary<string,RadioButton> buttons;

protected void Page_Load(object sender, EventArgs e)
{
    for (int i=0;i<5;i++)
    {
        RadioButton r = new RadioButton();
        r.Text = i.ToString();
        r.ID = i.ToString();;
        Panel1.Controls.Add(r);
        buttons.Add(i.ToString(), r);
    }
}

And this is my method when the user click on the update button where I would like to access to each of my radiobutton depending their id or their text, but I cannot :
For example, If I want all the buttons from 1 to 3 to be checked :
protected void Button1_Click(object sender, EventArgs e)
{
    for (int i=1;i<4;i++)
    {
        buttons[i].checked=true;
    }
}

A: Asp.net will clear your dynamically added controls on every postback. if you want to get their selection you have to do that on client click of button in JS.
C# Code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            for (int i = 0; i < 5; i++)
            {
                RadioButton r = new RadioButton();
                r.Text = i.ToString();
                r.ID = i.ToString();
                r.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                Panel1.Controls.Add(r);

            }
        }
    }

and JS Code:
<script type="text/javascript">
    function getCheckedRadios() {
        alert(document.getElementById('1').checked);
    }
</script>

aspx code for your button will be:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="getCheckedRadios(); return false;"/>

I hope it will help.


text:
Q: Best way to store a dictionary (of words) into Google Cloud Datastore I was wondering what the most optimal way would be to store a large list of dictionary words such as https://github.com/dwyl/english-words in the google cloud datastore (using Google App Engine/Java Standard), for querying later, query input is the full word.
I need only check the word is valid, i.e. is on the list.
I thought I could use the first couple of characters in each word as the key for an entity, and store a HashSet of all the words that begin with those characters as the value in that particular entity.
then later I check the first couple of characters of the word I'm searching for and look at that key only.
I get the feeling there's a better way to do this. but I've been googling this a lot, to no avail.
any ideas would be very much appreciated !

A: Option 1:
Store it in memory and not in the datastore.  A list of words is quite small in the grand scheme of things.
You can store the data alongside your code.  In one of your modules, read the data from the file into whatever data structure works for you.  This operation will only be performed when an instance is spun up so it won't be a drag on your response times.
Note that you can't write to disk in GAE but you can read from disk.
Option 2:
Store it in a single entity with a JSON property or a Pickle Property or even a repeated string property.  You can use compression to make sure you don't exceed the 1MB entity size.
If you are using Python NDB, the automatic caching will make this quite efficient.


text:
Q: Source code for projects using these 4 asp.net/mvc/silverlight and MS SQL Could anyone guide me where could I get some working projects for learning which use all of these:
1. ASP.NET 2. MVC 3. Silverlight and 4. MS SQL in  back end?

A: Try this is a project from a great italian group.
Model Virtual Casting
Model Virtual Casting è un'applicazione d'esempio che utilizza il .NET Framework 4.1, Silverlight 4.0, ASP.NET 4.0, MVC 3.0, WPF, WCF, RIA Services, Azure, Windows Phone 7, Unity 2.0 e MEF.

Translated
Model Virtual Casting is a sample application that use .NET Framework 4.1, Silverlight 4.0, ASP.NET 4.0, MVC 3.0, WPF, WCF, RIA Services, Azure, Windows Phone 7, Unity 2.0 e MEF.

Hope it helps


text:
Q: Parse json and populate dropdown by jquery this is my json return from server side mvc controller.
[{"Id":"AL","Name":"Alabama"},{"Id":"FL","Name":"Florida"},{"Id":"IA","Name":"Iowa"},{"Id":"MS","Name":"Mississippi"}]

this way i am trying to parse it and trying to populate dropdown by jquery.
 $(function () {
        $('#CountryID').change(function () {
            var dropdownID = $(this).val();
            $.post('@Url.Action("Index", "Home")', { CountryID: dropdownID }, function (result) {

                $("#State").html("");
                for (var i = 0; i < result.length; i++) {
                    var item = result[i];
                    $("#State").append(
              $("<option></option>").val(item.Id).html(item.Name)
        );
                }
                //$('#State').html(items);
                $("#State").prop("disabled", false);
            });
        });
    });

a wired error is coming form jquery code that is as follow and capture by firebug console
TypeError: $(...).prop is not a function
[Break On This Error]

..."Alabama"},{"Id":"FL","Name":"Florida"},{"Id":"IA","Name":"Iowa"},{"Id":"MS","Na...

i am not being able to figure out. so if possible please tell me what kind of mistake i am making in the code. thanks

A: Try this
$("#State").prop("disabled", false);

change to
$("#State"d).removeAttr('disabled');


text:
Q: How to sort list of custom posts to get view like a tree of posts under categories and their children's categories? I'm new here and my english isn't perfect so I'm sorry for this :) I'm here because I'm workin on site with post list sorted by category and I have problem with sort out my posts in categories and children categories under them. Now everything is messed up. I would like to sort my custom  posts like that:
CATEGORY 1

*

*CHILD CATEGORY 1

*

*Post

*Post

*Post

*CHILD CATEGORY2

*

*Post

*Post

*Post

CATEGORY 2

*

*CHILD CATEGORY3

*

*Post

*Post

*Post

CATEGORY 3

*

*Post

*Post

*CHILD CATEGORY4

*

*Post

*Post

*Post

Is it possible with this code:
<?php
$querystr = "SELECT terms.* FROM $wpdb->term_taxonomy tax LEFT JOIN $wpdb->terms terms ON       tax.term_id = terms.term_id WHERE tax.taxonomy = 'MY_CUSTOM_TAXONOMY'";

$categories = $wpdb->get_results($querystr, OBJECT);

foreach( $categories as $category ):
echo '

'.$category->name.'
';
echo '
'.strip_tags(term_description($category->term_id,'MY_CUSTOM_TAXONOMY')).'

';

$posts = get_posts( array( 'MY_CUSTOM_TAXONOMY' => $category->name, 'post_type' => 'MY_CUSTOM_POST' ) );
foreach($posts as $post) :
setup_postdata($post);

 the_title();

endforeach;

endforeach;
?>

I will be grateful for all help, thank You!!

A: ok, this is my working solution:
<?php

$args=array(
'post_type'                => 'biblioteka',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 1,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'kategoria-pozycji',
'pad_counts'               => false
);

$categories=get_categories($args);

foreach ( $categories as $category ) {

if ( $category->parent > 0 ) {
continue;
}

echo '
' . $category->name . '
';

$querystr = "SELECT $wpdb->posts.*
          FROM $wpdb->posts, $wpdb->term_relationships, $wpdb->terms
          WHERE term_id = (" . $category->cat_ID . ")
          AND term_taxonomy_id = (" . $category->term_taxonomy_id . ")
          AND ID = object_id
          AND post_type = 'biblioteka'
          AND post_status = 'publish'
          ORDER BY post_date DESC";
$posts = $wpdb->get_results($querystr, OBJECT);

echo '
';
foreach ( $posts as $post ) {
    setup_postdata($post);

        echo '
'; the_title();   echo '
';

        }
echo '
';

$categories2 = get_terms('kategoria-pozycji',array('parent' => $category->term_id , 'hide_empty'=> '0' ));

foreach ( $categories2 as $category ) {

echo '
' . $category->name . '
';

$posts = get_posts( array( 'kategoria-pozycji' => $category->name, 'post_type' => 'biblioteka' ) );

echo '
';
foreach($posts as $post) {
    setup_postdata($post);

        echo '
'; the_title();   echo '
';

        }
echo '
';

}
}

?>

A: My best solution! (works for any taxonomies,including "category")
$your_taxonomy='category';

function my_Categ_tree($TermName='', $termID, $separator='', $parent_shown=true ){
    $args = 'hierarchical=1&taxonomy='.$TermName.'&hide_empty=0&orderby=id&parent=';
            if ($parent_shown) {$term=get_term($termID , $TermName); $output=$separator.$term->name.'('.$term->term_id.')
'; $parent_shown=false;}
    $separator .= '-';
    $terms = get_terms($TermName, $args . $termID);
    if(count($terms)>0){
        foreach ($terms as $term) {
            //$selected = ($cat->term_id=="22") ? " selected": "";
            //$output .=  '<option value="'.$category->term_id.'" '.$selected .'>'.$separator.$category->cat_name.'</option>';
            $output .=  $separator.$term->name.'('.$term->term_id.')
';
            $output .=  my_Categ_tree($TermName, $term->term_id, $separator, $parent_shown);
        }
    }
    return $output;
}

Then you can output:
1) target category(taxonomy) tree, using specific ID
echo my_Categ_tree($your_taxonomy, 0 );

2) All categories/taxonomies
foreach (get_terms($your_taxonomy, array('hide_empty'=>0, 'parent'=>0)) as $each) {
    echo my_Categ_tree($each->taxonomy,$each->term_id);
}

A: I played a little and this is what I came up with, I tested and it works just like your given example:

<?php

// get initial categories
$categories = get_categories();

foreach ( $categories as $category ) {

// we don't want child categories now, and since get_categories does not support 'depth' parameter, we use ->parent check
if ( $category->parent > 0 ) {
    continue;
}

$i = 0;
echo '
' . $category->cat_name . '
';

$posts = get_posts(
    array(
        'category' => $category->term_id
    )
);

foreach ( $posts as $post ) {

    // let's make sure that the post is not also in any of child categories, if it is, skip it ( we don't want to display it twice )
    $child_categories = get_term_children( $category->term_id, 'category' );

    if ( $child_categories && in_category( $child_categories, $post->ID ) ) {
        continue;
    }

    echo 0 === $i ? '
' : '';
    echo '
' . $post->post_title . '
';
    $i++;

}

// now, after we listed all the posts, we query for child categories
$categories2 = get_categories(
    array(
        'parent' => $category->term_id
    )
);

foreach ( $categories2 as $category ) {

    $j = 0;
    echo '
' . $category->cat_name . '
';
    $posts2 = get_posts(
        array(
            'category' => $category->term_id
        )
    );

    foreach ( $posts2 as $post ) {

        echo 0 === $j ? '
' : '';
        echo '
' . $post->post_title . '
';
        $j++;
    }

    echo null === $posts2 ? '' : '
';

}

echo null === $posts ? '' : '
';

}

?>

A: Here is the solution that I solved the problems as you experience

            //Define Some require
            define(TAX_TYPE, 'category'); //you can also replace your custom taxonomy in category
            $terms = get_terms(TAX_TYPE);
            define(WP_HOME, 'http://yourdomain.com');

        ?>

                <?php
                    foreach( $terms as $tax_term ) :

                    $permalink = WP_HOME . '/' . TAX_TYPE . '/' . $tax_term->slug;

                    // getting posts from each tour type
                    $args=array(
                        'post_type'     => 'tour',
                        'post_status'   => 'publish',
                        'order_by'      => 'post_title',
                        'order'         => 'ASC',
                        'tour-type'    => $tax_term->slug
                    );
                    $posts = get_posts($args);

                ?>

<?php echo $tax_term->name; ?>

                            <?php foreach ($posts as $post) : ?>

<a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?>

                            <?php endforeach; ?>

                <?php endforeach; ?>


text:
Q: TFS 2010 - query needed to join three levels of WorkItems I am just configuring some WorkItem Types to manage our releases - I've got quite far but I cannot see how to get a query to list what I need.
I have User Stories that have "Application Deployment" workitem types as children. Each Application Deployment represents an application to deploy. A User Story might require two applications to be changed. This is a parent/child relationship.
Separately to that, I also have "Release" workitem types. Each Release represents a day on which we will deploy our software. A Release will have several User Stories associated with it - I think using the Network topology of LinkType. This is because a User Story might actually be associated with more than one Release (for example, if we release to one territory first, and then to all remaining territories a week later).
What I would like is a query that lists what applications need to be released:-

*

*Release "14/03/2012"

*

*Application Deployment "MyWebApp1"

*Application Deployment "SomeWindowsService"

Release 14/03/2012
Application

A: If I understand correctly, you're looking to return all the "Application Deployment" work item types associated with a given "Release".
In the query editor, you should be able to select your query type as "Tree of Work Items", and set your query to be Work Item Type = Release, and select linked work items that match the query Work Item Type = Application Deployment.
You can of course add other query filters.
This will give you roughly the following WIQL:
SELECT
    [System.Id], [System.WorkItemType], [System.Title],
    [System.AssignedTo], [System.State]
FROM WorkItemLinks WHERE
    (
        [Source].[System.TeamProject] = @project
        AND [Source].[System.WorkItemType] = 'Release'
        AND [Source].[System.State] <> ''
    )
    AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward')
    AND [Target].[System.WorkItemType] = 'Application Deployment'
ORDER BY [System.Id]
mode(Recursive)


text:
Q: How can I get the free out IPs in our IDC? Our company have a IDC (Internet Data Center), and in our IDC, there are many host machines, every host has 1-3 IPs.
There is a situation, such as one host machine has 3 IPs(eg. 102.23.33.1 -> 102.23.33.3). (means in the host machine, have configured the IPs to it)
If the host machine only use 102.23.33.1, and there free out the 102.23.33.2 and 102.23.33.3. We want to find out the free IPs.
How can I do that? I tried to use the forloop to ping the whole IPs, but this is not accurate, because some host machine are baned  for ping.

EDIT
I means the host machine if has 3 IPs, and all can ping them, but the host machine only use the first IP to connect with public network, how can I find the other 2 IPs host machine do not use (or do not often use)?

EDIT-2
I mean the IPs all configured on the OS but may not be actually using them.

EDIT - 3
So, all the before, there can be understood as bellow:
I have a Router, and under it, there are many host machines, and every host machine have some IPs, and how can I record the IPs that go through the Router everyday.
Is there a tool for record the IPs which get through the Router? Or how can I realize my requirement ?

A: This adds a logging rule into the iptables FORWARD chain:
# iptables -I FORWARD -j LOG --log-prefix 'MYIPS: '

This searches for the matching packets:
# grep MYIPS /var/log/syslog

The file name may depend on your Linux distribution.
And this generates a list of unique IP addresses seen by the forwarding chain in your router:
# grep -oE '(SRC|DST)=[0-9.]*' /var/log/syslog | sed 's/.*=//' | sort -u

A: Still not clear. Your router is a Linux machine? or a networking device?
You may check the dhcp lease list on your dhcp server if you are using a DHCP to assign the IP addresses. that will help you better.


text:
Q: Software-center crashes in Ubuntu 12.10 I'm having a problem with Ubuntu Software Center. When I open it, it closes automatically without any permissions. When I run it in a terminal I get this:
vangjush@vangjush:~$ software-center
2013-05-06 21:41:29,532 - softwarecenter.ui.gtk3.app - INFO - setting up proxy 'None'
2013-05-06 21:41:29,540 - softwarecenter.db.database - INFO - open() database: path=None use_axi=True use_agent=True
2013-05-06 21:41:30,052 - softwarecenter.backend.reviews - WARNING - Could not get usefulness from server, no username in config file
2013-05-06 21:41:30,061 - softwarecenter.fixme - WARNING - logs to the root logger: '('/usr/lib/python2.7/dist-packages/gi/importer.py', 51, 'find_module')'
2013-05-06 21:41:30,061 - root - ERROR - Could not find any typelib for LaunchpadIntegration
2013-05-06 21:41:30,217 - softwarecenter.ui.gtk3.app - INFO - show_available_packages: search_text is '', app is None.
2013-05-06 21:41:30,555 - softwarecenter.db.pkginfo_impl.aptcache - INFO - aptcache.open()
Traceback (most recent call last):
  File "/usr/share/software-center/softwarecenter/db/pkginfo_impl/aptcache.py", line 257, in open
    self._cache = apt.Cache(progress)
  File "/usr/lib/python2.7/dist-packages/apt/cache.py", line 102, in __init__
    self.open(progress)
  File "/usr/lib/python2.7/dist-packages/apt/cache.py", line 149, in open
    self._list.read_main_list()
SystemError: E:Malformed line 57 in source list /etc/apt/sources.list (dist parse)
2013-05-06 21:41:31,504 - softwarecenter.db.enquire - ERROR - _get_estimate_nr_apps_and_nr_pkgs failed
Traceback (most recent call last):
  File "/usr/share/software-center/softwarecenter/db/enquire.py", line 115, in _get_estimate_nr_apps_and_nr_pkgs
    tmp_matches = enquire.get_mset(0, len(self.db), None, xfilter)
  File "/usr/share/software-center/softwarecenter/db/appfilter.py", line 89, in __call__
    if (not pkgname in self.cache and
  File "/usr/share/software-center/softwarecenter/db/pkginfo_impl/aptcache.py", line 277, in __contains__
    return self._cache.__contains__(k)
AttributeError: 'NoneType' object has no attribute '__contains__'
Traceback (most recent call last):
  File "/usr/bin/software-center", line 182, in <module>
    app.run(args)
  File "/usr/share/software-center/softwarecenter/ui/gtk3/app.py", line 1387, in run
    self.show_available_packages(args)
  File "/usr/share/software-center/softwarecenter/ui/gtk3/app.py", line 1325, in show_available_packages
    self.view_manager.set_active_view(ViewPages.AVAILABLE)
  File "/usr/share/software-center/softwarecenter/ui/gtk3/session/viewmanager.py", line 151, in set_active_view
    view_widget.init_view()
  File "/usr/share/software-center/softwarecenter/ui/gtk3/panes/availablepane.py", line 173, in init_view
    self.cache, self.db, self.icons, self.apps_filter)
  File "/usr/share/software-center/softwarecenter/ui/gtk3/views/lobbyview.py", line 80, in __init__
    self.build()
  File "/usr/share/software-center/softwarecenter/ui/gtk3/views/lobbyview.py", line 324, in build
    self._build_homepage_view()
  File "/usr/share/software-center/softwarecenter/ui/gtk3/views/lobbyview.py", line 119, in _build_homepage_view
    self._append_whats_new()
  File "/usr/share/software-center/softwarecenter/ui/gtk3/views/lobbyview.py", line 253, in _append_whats_new
    whats_new_cat = self._update_whats_new_content()
  File "/usr/share/software-center/softwarecenter/ui/gtk3/views/lobbyview.py", line 238, in _update_whats_new_content
    docs = whats_new_cat.get_documents(self.db)
  File "/usr/share/software-center/softwarecenter/db/categories.py", line 131, in get_documents
    nonblocking_load=False)
  File "/usr/share/software-center/softwarecenter/db/enquire.py", line 330, in set_query
    self._blocking_perform_search()
  File "/usr/share/software-center/softwarecenter/db/enquire.py", line 225, in _blocking_perform_search
    matches = enquire.get_mset(0, self.limit, None, xfilter)
  File "/usr/share/software-center/softwarecenter/db/appfilter.py", line 89, in __call__
    if (not pkgname in self.cache and
  File "/usr/share/software-center/softwarecenter/db/pkginfo_impl/aptcache.py", line 277, in __contains__
    return self._cache.__contains__(k)
AttributeError: 'NoneType' object has no attribute '__contains__'

What's wrong? How can I fix it?

A: I think you need to run the software-center using elevated credentials. Most Unixes use a tool called sudo to give users the ability to do this, without having to give them the root password.
Try this command:
sudo software-center

You'll be prompted for a password, this is your normal user's password. It's just re-authenticated you to make sure you're not someone that just happen to sit down at someone else's terminal.
You can read more about the sudo command if you're interested.
References

*

*getting started with sudo tutorial

A: Try updating from the terminal
sudo apt-get update
sudo apt-get upgrade

It would be working.


text:
Q: Reusing function types in flow (static type checker) If I directly write functions like that, it works
declare module.exports: {
    // HTML tags
    div<Props>(...styles: Array<CSSStyles<Props>>): GlamorousComponent<Props>,
    section<Props>(...styles: Array<CSSStyles<Props>>): GlamorousComponent<Props>,
};

But to follow DRY, How do I separate a common type?
I tried:
declare type StyleFunction<Props> = (...styles: Array<CSSStyles<Props>>) => GlamorousComponent<Props>
declare module.exports: {
    // HTML tags
    div: StyleFunction<*>
};

But this doesn't typecheck at all.


text:
Q: How can i use unsigned short int and short int to subtract hugeinteger in C++? I try my best to code something in C++.When i use unsigned int and int  to subtract, that's OK. However, using the unsigned short int and short int to subtract, i have a problem. So what i need to do in my code?
Thanks a lot.
Test value:

21758612232416725117133766166700 1758612232416725117155428849047

In the beginning, i have to define

*this > op2

absolutely.
template< typename T >
HugeInteger< T > HugeInteger< T >::operator-(const HugeInteger &op2)const // subtraction operator; HugeInteger - HugeInteger
{
    int size = integer.getSize();
    int op2Size = op2.integer.getSize();
    int differenceSize = size;
    HugeInteger < T > difference(differenceSize);

    difference = *this;

    Vector<T>::iterator it = difference.integer.begin();

    int counter = 0;

    for (Vector<T>::iterator i = difference.integer.begin(), j = op2.integer.begin(); j < op2.integer.end(); i++, j++) {
        if ((*i - *j - counter) < 10) {
            *i -= (*j + counter);
            counter = 0;
        }
        else {
            *i += 10;
            *i -= (*j + counter);
            counter = 1;
        }
    }

    while (counter == 1) {
        if ((*(it + op2Size) - counter) < 10) {
            *(it + op2Size) -= counter;
            counter = 0;
            op2Size++;
        }

        else {
            *(it + op2Size) += 10;
            *(it + op2Size) -= counter;
            counter = 1;
            op2Size++;
        }
    }

    if (*this == op2) {
        HugeInteger<T> zero(1);
        return zero;
    }

    for (Vector<T>::iterator i = difference.integer.end() - 1; i > difference.integer.begin(); i--) {
        if (*i == 0) {
            differenceSize--;
        }

        else {
            break;
        }
    }

    difference.integer.resize(differenceSize);
    return difference;
}

A: There's not enough information in the code you posted to determine what is going wrong.  I suspect it has something to do with how the "short" types are being converted to a HugeInt.
Below, I show a class definition for something very similar to HugeInt. It keeps track of a value's sign, but unfortunately, it only a few members are defined, enough to demonstrate subtraction.
This class has a nutty template conversion constructor. If none of the other constructors can handle a type, it will try to convert values with that type as if they were some kind of integer value, in a size-independent manner.
main() has two example subtraction operations, both involving a short value and a "huge" value.
#include <iostream>
#include <vector>
#include <string>

// radix-10 arbitrary size integer class
template<typename T>
class HugInt {
    // integer digits are stored in a Vector container
    // The example uses the class Vector, derived (statically)
    // from std::vector<T> in order to mimic the class from
    // code in the Question.  Normally, I would just use a std::vector.
    class Vector : public std::vector<T> { // virtual never needed
    public:
        int getSize() const {
            return static_cast<int>(std::vector<T>::size());
    }   };
    // two member variables
    Vector integer;
    int    sign;

    // For encapsulation and compactness, this class uses a lot
    // of inline-friend functions.  If considering using your own
    // inline-friends, it must always be called passing at least one
    // object from the class where the function is defined.
    // Otherwise, the compiler cannot find it.

    // compares just the magnitude (unsigned) parts of two HugInts
    // returns a>b:1, a==b:0, a<b:-1
    friend int cmpMagnitude(const HugInt& lh, const HugInt& rh) {
        const int lh_size = lh.integer.getSize();
        const int rh_size = rh.integer.getSize();
        if(lh_size != rh_size) return lh_size > rh_size ? 1 : -1;
        for(int i=lh_size-1; i+1; --i) {
            if(lh.integer[i] != rh.integer[i]) {
                return lh.integer[i] > rh.integer[i] ? 1 : -1;
        }   }
        return 0;
    }
    // subtract the magnitude of op2 from the magnitude of *this
    // does not take signs into account, but
    // flips sign of *this if op2 has a greater magnitude than *this
    void subMagnitude(const HugInt& op2) {
        const int cm = cmpMagnitude(*this, op2);
        if(cm == 0) {
            // magnitudes are equal, so result is zero
            integer.clear();
            sign = 0;
            return;
        }
        if(cm < 0) {
            // If op2's magnitude is greater than this's
            // subtract this's Magnitude from op2's,
            // then set this to the negated result
            HugInt temp{op2};
            temp.subMagnitude(*this);
            integer = temp.integer;
            sign = -sign;
            return;
        }
        // perform digit-wise Magnitude subtraction
        // here, this's Magnitude is always greater or
        // equal to op2's
        T borrow = 0;
        const int min_size = op2.integer.getSize();
        int i;
        for(i=0; i<min_size; ++i) {
            const T s = op2.integer[i] + borrow;
            if(borrow = (integer[i] < s)) {
                integer[i] += T(10);
            }
            integer[i] -= s;
        }
        // propagate borrow to upper words (beyond op2's size)
        // i is guaranteed to stay in bounds
        while(borrow) {
            if(borrow = (integer[i] < 1)) {
                integer[i] += T(10);
            }
            --integer[i++];
        }
        // remove zeroes at end until a nonzero
        // digit is encountered or the vector is empty
        while(!integer.empty() && !integer.back()) {
            integer.pop_back();
        }
        // if the vector is empty after removing zeroes,
        // the object's value is 0, fixup the sign
        if(integer.empty()) sign = 0;
    }

    void addMagnitude(const HugInt& op2) {
        std::cout << "addMagnitude called but not implemented\n";
    }
    // get_sign generically gets a value's sign as an int
    template <typename D>
    static int get_sign(const D& x) { return int(x > 0) - (x < 0); }
public:
    HugInt() : sign(0) {}  // Default ctor
    // Conversion ctor for template type
    // Handles converting from any type not handled elsewhere
    // Assumes D is some kind of integer type
    // To be more correct, narrow the set of types this overload will handle,
    // either by replacing with overloads for specific types,
    // or use <type_traits> to restrict it to integer types.
    template <typename D>
    HugInt(D src) : sign(get_sign(src)) {
        // if src is negative, make absolute value to store magnitude in Vector
        if(sign < 0) src = D(0)-src; // subtract from zero prevents warning with unsigned D
        // loop gets digits from least- to most-significant
        // Repeat until src is zero: get the low digit, with src (mod 10)
        // then divide src by 10 to shift all digits down one place.
        while(src >= 1) {
            integer.push_back(T(src % D(10)));
            src /= D(10);
    }   }
    // converting floating-point values will cause an error if used with the integer modulo
    // operator (%). New overloads could use fmod. But for a shorter example, do something cheesy:
    HugInt(double src) : HugInt(static_cast<long long>(src)) {}
    HugInt(float src)  : HugInt(static_cast<long long>(src)) {}
    // conversion ctor from std::string
    HugInt(const std::string& str) : sign(1) {
        for(auto c : str) {
            switch(c) {
                // for simple, short parsing logic, a '-'
                // found anywhere in the parsed value will
                // negate the sign.  If the '-' count is even,
                // the result will be positive.
                case '-': sign = -sign; break;
                case '+': case ' ': case '\t': break; // '+', space and tab ignored
                case '0': if(integer.empty()) break;  // ignore leading zeroes or fallthrough
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9':
                    integer.insert(integer.begin(), T(c - '0'));
                    break;
        }   }
        if(integer.empty()) sign = 0; // fix up zero value if no digits between '1' and '9' found
    }
    // conversion ctor from C-String (dispatches to std::string ctor)
    HugInt(const char* str) : HugInt(std::string(str)) {}

    // The default behavior, using value semantics to copy the
    // two data members, is correct for our copy/move ctors/assigns
    HugInt(const HugInt& src)              = default;
    HugInt& operator = (const HugInt& src) = default;
    // some "C++11" compilers refuse to default the moves
    // HugInt(HugInt&& src)                   = default;
    // HugInt& operator = (HugInt&& src)      = default;

    // cmp(a, b) returns 1 if a>b, 0 if a==b or -1 if a<b
    friend int cmp(const HugInt& lh, const HugInt& rh) {
        if(lh.sign != rh.sign) return lh.sign > rh.sign ? 1 : -1;
        const int cmpmag = cmpMagnitude(lh, rh);
        return lh.sign < 0 ? -cmpmag : cmpmag;
    }
    friend bool operator == (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) == 0;
    }
    friend bool operator != (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) != 0;
    }
    friend bool operator > (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) == 1;
    }
    friend bool operator < (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) == -1;
    }
    friend bool operator >= (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) != -1;
    }
    friend bool operator <= (const HugInt& lh, const HugInt& rh) {
        return cmp(lh, rh) != 1;
    }
    // negate operator
    HugInt operator - () const {
        HugInt neg;
        neg.integer = integer;
        neg.sign = -sign;
        return neg;
    }
    // subtract-assign operator
    HugInt& operator -= (const HugInt &op2) {
        if(op2.sign == 0) { // op2 is zero, do nothing
            return *this;
        }
        if(sign == 0) { // *this is zero, set *this to negative op2
            integer = op2.integer;
            sign = -op2.sign;
            return *this;
        }
        if(sign == op2.sign) { // same signs: use magnitude subtratction
            subMagnitude(op2);
            return *this;
        }
        // opposite signs here: needs magnitude addition (but not implemented)
        addMagnitude(op2);
        return *this;
    }

    friend HugInt operator - (const HugInt& lh, const HugInt& rh) {
        // a - b uses the -= operator to avoid duplicate code
        HugInt result{lh};
        return result -= rh;
    }

    // overload stream output operator for HugInt values
    friend std::ostream& operator << (std::ostream& os, const HugInt& hi) {
        // assumes decimal output and class radix is 10
        if(hi.integer.getSize() == 0) return os << '0';
        if(hi.sign < 0) os << '-';
        for(int i=hi.integer.getSize()-1; i+1; --i) {
            os << char('0' + int(hi.integer[i]));
        }
        return os;
    }
};

int main() {
    using HugeInt = HugInt<char>;
    {
        HugeInt a = "21758612232416725117133766166700 1758612232416725117155428849047";
        unsigned short b = 55427;
        HugeInt c = a - b;
        std::cout << a << " - " << b << " = \n" << c << '\n';
    }
        std::cout << '\n';
    {
        short a = 6521;
        HugeInt b = 1234567;
        HugeInt c = a - b;
        std::cout << a << " - " << b << " = \n" << c << '\n';
    }
}


text:
Q: Update values in array using lib in react-native I want to update values in my array using this lib
My code so far:
import React from "react";
import { StyleSheet, View, Button, Text } from "react-native";
import update from "immutability-helper";

export default function App() {
  const [currentElement, setCurrentElement] = React.useState(0);
  const [initialArray, setInitialArray] = React.useState([0, 0, 0]);

  const array = [0, 0, 0];
  function nextEle() {
    setCurrentElement(currentElement + 1);
  }
  function prevEle() {
    setCurrentElement(currentElement - 1);
  }
  function setNum(num) {
    setInitialArray(update(array, { [currentElement]: { $apply: [num]} }));
  }
  return (
    <View style={styles.container}>
      <Button title="set array[0] = 1" onClick={() => setNum(21)} />
      <Button title="set array[1] = 2" onClick={() => setNum(212)} />
      <Button title="set array[2] = 3" onClick={() => setNum(231)} />
      <Button title="Next element" onPress={nextEle} />
      <Button title="Prev element" onPress={prevEle} />
      <Text>{initialArray[currentElement]}</Text>
      <Text>current element is {currentElement}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    top: 10,
    alignSelf: "center",
    justifyContent: "center",
    flexDirection: "column",
    width: "80%",
    position: "absolute",
  },
});

Values doesn't update at all! I read documentation carefully but i couldn't understand how to fix that. Any help?

A: function setNum(num) {
  setInitialArray(update(array, { [currentElement]: { $set: num } }));
}


text:
Q: Болезнь творца или как создать свой виртуальный мир? Приветствую всех в моем периоде жизни, в котором я решился взяться за свою давнюю мечту. Болезнь творца, или как создать свою виртуальную матрицу, не выходило из моей головы ровно столько, сколько я себя помню. И вот, после стольких отложенных попыток, набравшись массой знания и опыта, я рад что берусь за это дело всерьез.
Мое знание

*

*HTML, CSS

*Javascript, Jquery, Ajax

*PHP, ООП

*MySQL

*Фреймворк Laravel

Перейду к сути. Я хочу создать огромный виртуальный город, времен средневековья, который будет жить своей жизнью, независимо от меня. 3D графику позволить себе не могу, потому все будет пока что в виде обычных графиков и цифр, в дальнейшем придумаю визуальную оболочку всему этому.
Город будет иметь небольшие окрестности, в которых необходимо реализовать рост растительности и активность некой фауны.
Жителей в начала создам в количестве 1000 штук. Каждый должен иметь свой распорядок дня, позицию на карте, финансовые операции, добычу и затраты ресурсов. Реализую скрипт по непредвиденным обстоятельствам в виде отношений, свадеб, болезней, рождений, желаний и так далее.
Так же важной частью реализации станет экономика — примитивная экономика. Цены товаров и услуг будут назначаться в зависимости от спроса и количества.
Итак вопросы
В первую очередь, я нуждаюсь в абсолютно любой информации которая может мне помочь. Я буду сильно благодарен, если вы направите меня на что изучать и что будет полезно для реализации данной цели.
Вопрос - Раз мой город можно разделить по логическим вычислениям на экономику, поведения жителей, рост и активность фауны и так далее, я думаю а не разделить ли мне эти процессы по разным серверам. Один сервер будет вычислять рост деревьев, передвижения оленей по лесам, количества рыб в озерах, пока другой сервер занимается высчитыванием экономики. Будет некий промежуточный сервер, который будет собирать информацию с серверов и передавать пользователю. Что вы думаете об этом? Да и как бы вы реализовали общение между этими серверами?
Вопрос - Как вы знаете, есть одна проблема у скриптовых языков вроде PHP, они умирают сразу же после выполнения. А мне нужно что-то, что будет работать постоянно и заниматься постоянным вычислением. Первое что приходит мне в голову это CRON.
Предлагаю упростить все это дело для понимания до уровня Тамагочи. Есть человечек в MySQL. У этого человечка есть поле Голод. Каждую секунду, этот голод должен увеличиваться. Когда у персонажа голод заполнится, он должен тупо отправлять мне email. Каким образом мне каждую секунду проверять его на голод? Что посоветуете вы?
Опять же, внесу конкретику! Я хочу создать мир, который будет жить своей жизнью. Возьмем к примеру Cities Skyline. Если я запущу игру перед тем как отправится на работу, я буду знать, что там течет жизнь. Что в данный вот момент, определенный персонаж в игре проснулся, сел в свою машину, отправился куда-то и т.п.