text:
Q: Calculated Field Syntax Error - Matrix Output I'm quite new to this, could anyone point out why my calculated field isn't working
Im trying to use a matrix to output a value of critical, high, medium or low
The field Im using is ImpUrg_Total, this is my current failure
=IF(ImpUrg_Total<2,"Critical",IF(AND([ImpUrg_Total]>=2,[ImpUrg_Total]<4,"High",IF(AND([ImpUrg_Total]>=4,[ImpUrg_Total]<9,"Medium",IF([ImpUrg_Total]=>9,"Low"))))))

A: Use your formula like the following:
=IF(ImpUrg_Total<2,"Critical",IF(AND([ImpUrg_Total]>=2,[ImpUrg_Total]<4),"High",IF(AND([ImpUrg_Total]>=4,[ImpUrg_Total]<9),"Medium",IF([ImpUrg_Total]=>9,"Low"))))

Similar issue post for your reference:

*

*SharePoint 2013 calculated column adding multiple if statement

*Calculated Column with Nested IF statments


text:
Q: Is there a simple command for outputting tab-delimited columns? E.g. I have a file (produced with echo -e "var1\tvar2\t\var3\tvar4" > foo) that are output as:
$ cat foo
case    elems   meshing nlsys
uniform 2350    0.076662        2.78
non-conformal   348     0.013332        0.55
scale   318     0.013333        0.44
smarter 504     0.016666        0.64
submodel        360     .009999 0.40
unstruct-quad   640     0.019999        0.80
unstruct-tri    1484    0.01    0.88

I'd prefer the output like this (here I used vim and :set tabstop=14):
case          elems         meshing       nlsys
uniform       2350          0.076662      2.78
non-conformal 348           0.013332      0.55
scale         318           0.013333      0.44
smarter       504           0.016666      0.64
submodel      360           .009999       0.40
unstruct-quad 640           0.019999      0.80
unstruct-tri  1484          0.01          0.88

I can get the same functionality with cat if I use $ tabs=15 in bash (see this question). Is there a program that does this kind of formatting automatically? I don't want to experiment with the tabs value before cating a file.

A: Another tool that can do this is tsv-pretty from eBay's TSV Utilities (disclaimer: I'm the author). It takes the additional step of lining up numeric fields on the decimal point. For example:
$ tsv-pretty foo
case           elems   meshing  nlsys
uniform         2350  0.076662   2.78
non-conformal    348  0.013332   0.55
scale            318  0.013333   0.44
smarter          504  0.016666   0.64
submodel         360   .009999   0.40
unstruct-quad    640  0.019999   0.80
unstruct-tri    1484  0.01       0.88

There are several formatting options. For example, -u underlines the header and -f formats the floats in a field similarly for readability:
$ tsv-pretty foo -f -u
case           elems   meshing  nlsys
----           -----   -------  -----
uniform         2350  0.076662   2.78
non-conformal    348  0.013332   0.55
scale            318  0.013333   0.44
smarter          504  0.016666   0.64
submodel         360  0.009999   0.40
unstruct-quad    640  0.019999   0.80
unstruct-tri    1484  0.010000   0.88

More info is available in the tsv-pretty reference.

A: You can also use rs as an alternative to column -t:
(x=$(cat);rs -c -z $(wc -l<<<"$x")<<<"$x")

-c changes the input column separator, but -c alone sets the input column separator to a tab. -z sets the width of each column to the width of the longest entry of the column instead of making all columns the same width. If some lines have fewer columns than the first line, add -n.

A: Another quick and dirty way around this is to use the tabs command, which is included with ncurses and already installed on a high percentage of *nix systems.
Personally I like this solution because it's super fast and easy to get mostly right.
Based on the example tab delimited file @sebastian provided:
Just run:
tabs 1,20,35,50

Once you're done, probably best to restore tabs to the standard hardware default...
tabs -8

(Yes, I think it's very strange to explicitly set tabs to a -8, but that was my take on the best solution from reading man tabs, and that is the hardware default on every terminal I've seen)
To build a more complete solution, I might would use stty size to check the terminal width, and calculate the width of variable length fields as a % of the terminal width, and truncate long columns in an application sensible way.

A: Several options:
var1=uniform var2=2350 var3=0.076662 var4=2.78

printf '%-15s %-10s %-12s %s\n' \
  case elems messing nlsys \
  "$var1" "$var2" "$var3" "$var4"

printf '%s\t%s\t%s\t%s\n' \
  case elems messing nlsys \
  "$var1" "$var2" "$var3" "$var4" |
  expand -t 15,25,37

printf '%s\t%s\t%s\t%s\n' \
  case elems messing nlsys \
  "$var1" "$var2" "$var3" "$var4" |
  column -t -s $'\t'

column is a non-standard command, some implementations/versions don't support the -s option. It computes the width of the column based on the input, but that means that it can only start displaying once all the input has been fed to it. $'...' is ksh93 syntax also found in zsh and bash.
With zsh:
values=(
  case elems messing nlsys
  "$var1" "$var2" "$var3" "$var4"
)
print -arC4 -- "$values[@]"

A: I usually use the column program for this, it's in a package called bsdmainutils on Debian:
column -t foo

Output:
case           elems  meshing   nlsys
uniform        2350   0.076662  2.78
non-conformal  348    0.013332  0.55
scale          318    0.013333  0.44
smarter        504    0.016666  0.64
submodel       360    .009999   0.40
unstruct-quad  640    0.019999  0.80
unstruct-tri   1484   0.01      0.88

Excerpt from column(1) on my system:
...

-t      Determine the number of columns the input contains and create a
        table.  Columns are delimited with whitespace, by default, or
        with the characters supplied using the -s option.  Useful for
        pretty-printing displays.

...

A: The question was about outputting tab delimited columns.
So the correct answer is a small adaptation of the answer of @nisetama. I added the -C$'\t' option which sets output formatting.
x=$(cat foo2); rs -C$'\t' $(wc -l <<<"$x") <<<"$x"

Kudo's to @nisetama though :)

A: function printTable()
{
    local -r delimiter="${1}"
    local -r data="$(removeEmptyLines "${2}")"

    if [[ "${delimiter}" != '' && "$(isEmptyString "${data}")" = 'false' ]]
    then
        local -r numberOfLines="$(wc -l <<< "${data}")"

        if [[ "${numberOfLines}" -gt '0' ]]
        then
            local table=''
            local i=1

            for ((i = 1; i <= "${numberOfLines}"; i = i + 1))
            do
                local line=''
                line="$(sed "${i}q;d" <<< "${data}")"

                local numberOfColumns='0'
                numberOfColumns="$(awk -F "${delimiter}" '{print NF}' <<< "${line}")"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi

                # Add Header Or Body

                table="${table}\n"

                local j=1

                for ((j = 1; j <= "${numberOfColumns}"; j = j + 1))
                do
                    table="${table}$(printf '#| %s' "$(cut -d "${delimiter}" -f "${j}" <<< "${line}")")"
                done

                table="${table}#|\n"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]] || [[ "${numberOfLines}" -gt '1' && "${i}" -eq "${numberOfLines}" ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi
            done

            if [[ "$(isEmptyString "${table}")" = 'false' ]]
            then
                echo -e "${table}" | column -s '#' -t | awk '/^\+/{gsub(" ", "-", $0)}1'
            fi
        fi
    fi
}

function removeEmptyLines()
{
    local -r content="${1}"

    echo -e "${content}" | sed '/^\s*$/d'
}

function repeatString()
{
    local -r string="${1}"
    local -r numberToRepeat="${2}"

    if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
    then
        local -r result="$(printf "%${numberToRepeat}s")"
        echo -e "${result// /${string}}"
    fi
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true' && return 0
    fi

    echo 'false' && return 1
}

function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}

SAMPLE RUNS
$ cat data-1.txt
HEADER 1,HEADER 2,HEADER 3

$ printTable ',' "$(cat data-1.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+

$ cat data-2.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3

$ printTable ',' "$(cat data-2.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
+-----------+-----------+-----------+

$ cat data-3.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3
data 4,data 5,data 6

$ printTable ',' "$(cat data-3.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
| data 4    | data 5    | data 6    |
+-----------+-----------+-----------+

$ cat data-4.txt
HEADER
data

$ printTable ',' "$(cat data-4.txt)"
+---------+
| HEADER  |
+---------+
| data    |
+---------+

$ cat data-5.txt
HEADER

data 1

data 2

$ printTable ',' "$(cat data-5.txt)"
+---------+
| HEADER  |
+---------+
| data 1  |
| data 2  |
+---------+

REF LIB at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send data in a post request with RestClient I'm trying to mimic a curl request using the RestClient Ruby gem, and so far, I've been having a lot of trouble trying to send in a payload.  My curl request looks something like this
curl URL -X POST -u API_KEY -d '{"param_1": "1"}'
I've been trying to replicate this with RestClient using something like this:
RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: {"param_1" => "1"})
Alas, I keep getting 400 - Bad Requests errors when doing this.  Am I sending data over the wrong way?  Should I be using something other than payload?

A: Change:
payload: {"param_1" => "1"})

To:
payload: '{"param_1": "1"})'

Also, specify the headers.
So, it becomes:
RestClient::Request.execute(method: :post,
                            url: 'your_url',
                            user: 'API_KEY',
                            payload: '{"param_1": "1"}',
                            headers: {"Content-Type" => "application/json"}
                           )

A: Just Change:
payload: {"param_1" => "1"}

To:
payload: {"param_1" => "1"}.to_json

So, then it becomes:
RestClient::Request.execute(method: :post,
                            url: 'your_url',
                            user: 'API_KEY',
                            payload: {"param_1" => "1"}.to_json,
                            headers: {"Content-Type" => "application/json"}
                           )

A: Turns out I had to add an argument to specify that my data was in a JSON format.  The correct answer was something like this:
RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: '{"param_1": "1"}', headers: {"Content-Type" => "application/json"})


text:
Q: Preventing off-by-one errors with CRT secure string functions As of Visual Studio 2005, the CRT has replaced most string functions with secure versions which add a size argument to indicate the limits of the destination buffer(s). This is fine, but it's not clear how it should be used. Does it include the terminating zero? Take the following code for example:
…
TCHAR path[MAX_PATH] = TEXT("");
_tcscpy_s(path, MAX_PATH, filename);
…

Is it okay or does it induce an off-by-one error?

A: It'd be a failure of the API design to be MAX_PATH+/-1, as that would be confusing and lead to more buffer overflows.
Documentation states clearly for
dest[10] that _countof(dest) should be used, which would be 10
So a simple MAX_PATH will suffice.


text:
Q: Seaborn Stripplot with Min, Mid, Max lines I'm trying to create strip plot from seaborn and adding lines indicating the Min, Mid, and Max that I set. I would like to set the Min line at the 500 mark, the mid at 2000 and the max line at 3500.
My goal is to display which points are within the min and max and which ones are outside of the range. I tried playing with a mixed boxplot and strip plot, but the boxplot only shows lines for the percentile of the data set.
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import seaborn as sns

data = DataFrame([1000,2000,3000,4000, 8000], columns=["Amount"], index=["EE1","EE2","EE3","EE4", "EE5"])

sns.boxplot(data = data)
sns.stripplot(data=data, size=6, jitter=True)

I get something like this:

So, instead of the lines from the boxplot, is there a way to add lines to mark the  500, 2000, and 3500 values?
The image I edited is what I'm trying to get to:


text:
Q: PyLint in PyDev only analysing files in top-most project directory My project directory is something like
src
    ProjectName
        Package1
            __init__.py
            Module1.py
            Module2.py
        Package2
            __init__.py
            Module3.py
            Moduel4.py
        __init__.py
        main.py
        setup.py

When I do Project->Clean..., PyLint runs, but only on the three files in the uppermost package: __init__.py, main.py, and setup.py.
I have gone into Project->Properties->PyDev - PYTHONPATH, and all of the source folders are definitely listed there, so I'm not sure why most of them aren't being analysed.
Also, like this question, PyDev doesn't seem to be parsing the PyLint output, as the errors and warnings that show up in the console aren't in the 'Problems' output tab, or in the editor margins. This makes me think it might be a version/regression problem, as it was for that question. I might try an older version of PyLint and see if that works.
I'm using Eclipse Helios, PyDev 2.2.1, PyLint 0.25.1, and Python 2.7.

A: The PyLint configuration (window > preferences > pydev > pylint), has a 'maximum number of processes for PyLint', so, it'll only run analysis on 'n' files simultaneously (because spawning too many processes at once could bring your machine to a halt).
So, you can raise that number for the analysis and and it should analyze more files at once (I'd recommend raising it for that analysis and then reducing the number again, as you don't usually want too many processes running at once).
As for the output, it could be that PyLint changed its format (please report that as a bug in the pydev sourceforge tracker if you believe that's the case).

A: This could be caused by recent changes in Pylint's output format which now prints column offset. You should contact the pydev maintainers reporting this.

A:
I have gone into Project->Properties->PyDev - PYTHONPATH, and all of the source folders are definitely listed there.

If you mean you have there subfolders from your project (Package1 and Package2) then it's not necessary. You should have only your project's main folder there.
I use PyDev 2.3.0 and when cleaning a project all project's files are being processed by Pylint.
Problem with parsing Pylint's output was fixed in PyDev 2.2.2 See my answer here.

A: I just discovered that if the file you are trying to lint is not a valid python module name, then pylint will (silently) not run on it. For example if you have an executable python script named do-thing, in your projects bin directory, it will simply not be linted. Rename the file dothing and suddenly it will work (no .py) extension is needed.


text:
Q: How to set section numbers to use whole numbers, rather than decimals, in ConTeXt? I have a document like this:
\setuphead[part][placehead=yes]

\definestructureresetset[default][1, 0, 1, 0][1]
\setuphead[sectionresetset=default]

\starttext
    \part{Animals}
        \chapter{Birds}
            \section{Parrot}
            \section{Pelican}
                \subsection{Australian Pelican}
                \subsection{Great White Pelican}
        \chapter{Crabs}
            \section{Spider Crab}
    \part{Trees}
        \chapter{Coniferous}
            \section{Pine}
\stoptext

After compiling, the sectioning appears like this:
1 Animals
    1.1 Birds
        1.1.2 Pelican
            1.1.2.1 Australian Pelican

I need to change the numbering so that it uses whole numbers and no decimals, like this:
1 Animals
    1 Birds
        2 Pelican
            1 Australian Pelican

I checked the ConTeXt Garden's instructions for \definehead, \setuphead, and \setupheads, but could not find a solution.
How can I set section numbers for all titles to use whole numbers, rather than decimals?

A: Use the sectionsegments key. The value is the section element you want to
display. You can use a single value or more than one, separated by a colon,
e.g. chapter:section.
\setuphead [part] [placehead=yes,page=no]

\setuphead [chapter]    [sectionsegments=chapter]
\setuphead [section]    [sectionsegments=section]
\setuphead [subsection] [sectionsegments=subsection]

\starttext
    \part{Animals}
        \chapter{Birds}
            \section{Parrot}
            \section{Pelican}
                \subsection{Australian Pelican}
                \subsection{Great White Pelican}
        \chapter{Crabs}
            \section{Spider Crab}
    \part{Trees}
        \chapter{Coniferous}
            \section{Pine}
\stoptext


text:
Q: The type `&[u8]` cannot be indexed by `usize`? The following is the test code:
pub fn reverse_complement_seq_u8<T>(seq: T, len: usize) -> Vec<u8>
    where T: std::ops::Index<usize, Output = u8>
{
    (0..len).rev().map(|i| match seq[i] {
            65 | 97  => 84, // 'A' | 'a' => 'T'
            84 | 116 => 65, // 'T' | 't' => 'A'
            71 | 103 => 67, // 'G' | 'g' => 'C'
            67 | 99  => 71, // 'C' | 'c' => 'G'
            n => n,
        }
    ).collect()
}

fn main() {
    let seqs = "ACGATGCTACGA".as_bytes();//generated by another function
    let revcom_seq = reverse_complement_seq_u8(seqs, seqs.len());
    println!("{:?}", revcom_seq);
}

Because call seqs.to_owend() is expensive, so I just want to pass its reference to reverse_complement_seq_u8, however this cause the following errors:
error[E0277]: the type `&[u8]` cannot be indexed by `usize`
  --> src/main.rs:17:48
   |
17 |     let revcom_seq = reverse_complement_seq_u8(seqs, seqs.len());
   |                      ------------------------- ^^^^ `&[u8]` cannot be indexed by `usize`
   |                      |
   |                      required by a bound introduced by this call
   |
   = help: the trait `Index<usize>` is not implemented for `&[u8]`
   = help: the following other types implement trait `Index<Idx>`:
             [T; N]
             [T]
note: required by a bound in `reverse_complement_seq_u8`

A: The problem is that while the slice itself [u8] can be indexed, a reference to the slice &[u8] can't. Most of the time indexing a slice reference works because Rust automatically dereferences as needed, but when using generics you need to be more strict in what you tell the compiler.
One possible fix is to use seq: &T in the arguments so that T will be [u8] which can be indexed. This requires an extra + ?Sized bound, otherwise the compiler adds an implicit Sized bound which slices don't implement:
pub fn reverse_complement_seq_u8<T>(seq: &T, len: usize) -> Vec<u8>
where
    T: std::ops::Index<usize, Output = u8> + ?Sized,
{
    (0..len)
        .rev()
        .map(|i| match seq[i] {
            65 | 97 => 84,  // 'A' | 'a' => 'T'
            84 | 116 => 65, // 'T' | 't' => 'A'
            71 | 103 => 67, // 'G' | 'g' => 'C'
            67 | 99 => 71,  // 'C' | 'c' => 'G'
            n => n,
        })
        .collect()
}

fn main() {
    let seqs = "ACGATGCTACGA".as_bytes(); //generated by another function
    let revcom_seq = reverse_complement_seq_u8(seqs, seqs.len());
    println!("{:?}", revcom_seq);
}

Playground
Another option that will also work with boxed slices is to specify that T must deref to some indexable type:
use std::ops::Deref;
pub fn reverse_complement_seq_u8<T, U>(seq: T, len: usize) -> Vec<u8>
where
    T: Deref<Target = U>,
    U: std::ops::Index<usize, Output = u8> + ?Sized,
{
    (0..len)
        .rev()
        .map(|i| match seq[i] {
            65 | 97 => 84,  // 'A' | 'a' => 'T'
            84 | 116 => 65, // 'T' | 't' => 'A'
            71 | 103 => 67, // 'G' | 'g' => 'C'
            67 | 99 => 71,  // 'C' | 'c' => 'G'
            n => n,
        })
        .collect()
}

fn main() {
    let seqs = "ACGATGCTACGA".as_bytes(); //generated by another function
    let revcom_seq = reverse_complement_seq_u8(seqs, seqs.len());
    println!("{:?}", revcom_seq);
}

Playground

A: As Jmb showed, you can make the constraint "type that is indexable by usize" work.
Depending on how you'll be using the function, or rather, what traits the values implement that you plan to use it with, an iterator approach may be useful as well, though.
Rather than iterating over a list of numbers to index seq with, you can accept an iterator of u8s directly:
pub fn reverse_complement_seq_u8<'a, T>(seq: T, len: usize) -> Vec<u8>
where
    T: std::iter::DoubleEndedIterator<Item = &'a u8> + std::iter::ExactSizeIterator,
{
    seq.take(len)
        .rev()
        .map(|val| match *val {
            65 | 97 => 84,  // 'A' | 'a' => 'T'
            84 | 116 => 65, // 'T' | 't' => 'A'
            71 | 103 => 67, // 'G' | 'g' => 'C'
            67 | 99 => 71,  // 'C' | 'c' => 'G'
            n => n,
        })
        .collect()
}

fn main() {
    let seqs = "ACGATGCTACGA".as_bytes(); //generated by another function
    let revcom_seq = reverse_complement_seq_u8(seqs.iter(), seqs.len());
    println!("{:?}", revcom_seq);
}

Playground
You could then also have your function return the iterator without collecting, making it suitable to chain with additional iterator adapters.


text:
Q: How to block outgoing packets to IP range with iptables? I want to block outgoing packets to an IP range but the iptables command I'm using does not seem to work.
 sudo iptables -P OUTPUT ACCEPT
 sudo iptables -A OUTPUT -s 157.240.0.0/16 -j REJECT
 sudo iptables -A OUTPUT -s 31.13.0.0/16 -j REJECT
 sudo iptables -A OUTPUT -s 192.229.0.0/16 -j REJECT
 sudo iptables -A OUTPUT -s 104.244.0.0/16 -j REJECT

Isn't what I need to do to

*

*allow all packets for the entire range

*then block specific subsets of the entire range?

A: -s means "source". By "outgoing packets to IP range" you most likely mean "destination". Change each -s to -d.
Also keep in mind -A appends a rule to the end of the chain. Rules are processed starting from the head. The rule you append to the end will be processed last (if the flow ever gets to it). Rules previously (and still) existing in the chain may apply and handle the packets you want to block. Use -I instead of -A to add a rule at the head of the chain.
If you suspect you may have added some unwanted rules then investigate with iptables -S OUTPUT and delete them with -D.  There is also -F to flush and start anew.
See man 8 iptables for details.


text:
Q: Not able to start the service Here is my WallePapeAuto.java code:
    package com.demo.wallpaper;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;

public class WallePapeAuto extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent = new Intent(WallePapeAuto.this, BackgroundService.class);
        startService(intent);
    }

}

Here is my BackgroundService.java code:
    package com.demo.wallpaper;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BackgroundService extends Service{

    final String TAG = "BackgroundService";
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId){
        Log.i(TAG,"onStart launched");
        Timer timer = new Timer();

        TimerTask timerTask = new TimerTask(){
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Log.i(TAG,"timerTask launched");
                checkStatus();

            }
        };

        timer.scheduleAtFixedRate(timerTask,15000,15000); //call after every 15 sec
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.i(TAG,"onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG,"onDestroy");
        super.onDestroy();

    }

    public void checkStatus(){

        try{
            Log.i(TAG,"in checking status...");
        } catch (Exception e){
            Log.i(TAG, "Error occur during checking status");
            e.printStackTrace();
        }
    }

}

My AndroidManifest.xml:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.wallpaper"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.demo.wallpaper.WallePapeAuto"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true"
                 android:name=".BackgroundService" />
    </application>

</manifest>

I expect it will display some of the log value when run it, but there is nothing in my Logcat. I not sure which part I done it wrong. Any helps I will appreciate it. Thanks in advance.

A: I think u have to place the service class in manifest as below:
 <service android:name="BackgroundService">
        <intent-filter>
        <action android:name="com.yourpackage.BackgroundService" />
        </intent-filter>
    </service>


text:
Q: Toggle class for one element when accordion is pressed I'm currently making a QA page using Jquery UI accordion.
Right now I managed to make several accordion but the problem is, I need to (+) part turns to (-) when the accordion is pressed, and the jquery I made make all the (+) button turns at the same time whenever I pressed an accordion button.
How can I make the button turn according to when it's corresponding accordion is collapsed ?
Here is my simplified code

$(function() {
  $("#accordion").accordion({
    collapsible: true
  });
});

$(function() {
  $('.qa_accordion_button').click(function() {
    $('.button_outer').toggleClass('pressed');
    $(this).removeClass('pressed');
  });
});
.button_outer {
  color: #ecf0f1;
  background: #e74c3c;
  width: 40px;
  height: 40px;
  border: 0;
  font-size: 1.5em;
  position: relative;
  border-radius: 2rem;
}

.button_outer .minus {
  position: absolute;
  transition: 300ms;
  background: white;
  border-radius: 2px;
}

.button_outer .minus:first-child {
  left: 25%;
  right: 25%;
  height: 10%;
  top: 45%;
}

.button_outer .minus:last-child {
  left: 25%;
  right: 25%;
  height: 10%;
  top: 45%;
  transform: rotate(90deg);
}

.pressed .minus {
  transform: rotate(180deg);
}

.pressed .minus:last-child {
  left: 50%;
  right: 50%;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css" />

ACCORDION BUTTON 1

ANSWER 1

ACCORDION BUTTON 2

ANSWER 2

A: To do what you require hook an event to the beforeActivate and create event handlers of the accordion. Using the arguments passed to these handlers you can get references to the current and previous headers and set the relevant classes on the buttons within them.

$(function() {
  $("#accordion").accordion({
    collapsible: true,
    beforeActivate: (e, ui) => {
      ui.newHeader.find('.button_outer').addClass('pressed');
      ui.oldHeader.find('.button_outer').removeClass('pressed');
    },
    create: (e, ui) => {
      ui.header.find('.button_outer').addClass('pressed');
    }
  });
});
.button_outer {
  color: #ecf0f1;
  background: #e74c3c;
  width: 40px;
  height: 40px;
  border: 0;
  font-size: 1.5em;
  position: relative;
  border-radius: 2rem;
}

.button_outer .minus {
  position: absolute;
  transition: 300ms;
  background: white;
  border-radius: 2px;
}

.button_outer .minus:first-child {
  left: 25%;
  right: 25%;
  height: 10%;
  top: 45%;
}

.button_outer .minus:last-child {
  left: 25%;
  right: 25%;
  height: 10%;
  top: 45%;
  transform: rotate(90deg);
}

.pressed .minus {
  transform: rotate(180deg);
}

.pressed .minus:last-child {
  left: 50%;
  right: 50%;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css" />

ACCORDION BUTTON 1

ANSWER 1

ACCORDION BUTTON 2

ANSWER 2

Also note that you don't need multiple document.ready event handlers - all the logic in the page can be added in to a single one.


text:
Q: How does GQUIC affect the WebRTC process? I am making a simple WebRTC application for myself in order to understand the WebRTC process.
I am using the RTCPeerConnection object to generate an SDP and display it in my logs so I could see exactly what the SDP contains.
This was working fine on all popular browsers until the more recent Chrome update, which no longer displays the SDP.
I used wireshark to examine the packets and I can see that Chrome is using the GQUIC protocol, where other browsers use DNS and STUN protocols.
From this my questions are:

*

*Is GQUIC preventing the SDP from being gnerated or from being displayed?

*How, if at all, can I get the SDP to appear again in Chrome?

A: *

*No

It appears GQUIC is not the reason the update prevented the SDP from being created. GQUIC seems to be a protocol built on UDP to improve latency while allowing for the reliability of TCP, and I could find no reason for it to impact on the SDP business but rather it was a coincidence that I noticed this for the first time when the other problem occured.

*Quick fix: change WebRTC: Use Unified Plan SDP Semantics by default to disabled in chrome:flags

The reason the SDP stopped working for me is that the new Chrome version has enabled WebRTC: Use Unified Plan SDP Semantics by default, since they appear to be moving from Plan-B to the Unified Plan which alters how the SDP is being passed. I am still trying to work out the exact difference this has on the SDP but in the meantime I was able to at least see the site working again when I change the flag so I know now that was the cause.


text:
Q: Datalayer Daynamic values are not coming in Google Analytics I am new to GTM. I am facing issue while passing dynamic values to google analytics from GTM datalayer. event name declared in datalayer is coming in analytics, static values are also coming but dynamic values from datalayer is not coming in analytics. I am using custom Html to push event and values to datalayer my website don't have datalayer code integrated.Below are my code
Custom Html Code:

Trigger to fire custom Html

Tag to fire datalayer values to Analytics

Custom Event for Tag

A: The problem is that your setting for ambient is a string not a datalayer variable.

You have the datalayer page.amtient. So you need to create a datalayer variable in GTM to receive it.

Then modify your GA4 tag.

This should work.


text:
Q: VB6 - Sending data to Telnet I've been looking around for some code examples for sending data from a server application in VB6 to Telnet. From what I've seen (Baring in mind these code examples are 15-20 years old), you can only send raw strings?
I'm just playing around with some source code I made, where I have a custom stand-alone client, so I'm sending byte arrays back and forth to handle strings and values. I'm worried that only being able to send raw strings will massively reduce network performance between the server and client.
Are there any other examples?
Currently I send messages like this:
Public Sub SendMsg(ByVal Index As Long, ByVal Msg As String)
Dim Buffer As clsBuffer

    Set Buffer = New clsBuffer
    Buffer.PreAllocate Len(Msg) + 4
    Buffer.WriteInteger SSendMsg
    Buffer.WriteString Msg

    Call SendDataTo(Index, Buffer.ToArray)
    DoEvents
End Sub

The code there is what I currently have to send data to a custom client, not Telnet. My question is, is it possible to send that type of data to Telnet?


text:
Q: Determine how long a system(), pasthrus(), exec(), operation is taking in php Want to know how to determine how long a call to system(), passthru(), exec() (either of these) takes. For example. I use system() to call an external program, I would like to time how long it takes so that if it's taking too long I can kill it or do another operation on it.

A: $start = microtime(true);
system(....);
$end = microtime(true);

echo "system() call took ", $end - $start, " microseconds";

For the rest, check out shell_exec() timeout management & exec()


text:
Q: How do I extract the elements from a container file (ODP, PDF, etc)? PDF and other container file types like ODP contain several files glued together to a presentation / a document. Is there a way to separate these files after the container has been built? Like from a zip file?
I just wonder because since you can edit these container files afterwards, the elements must be stored separately somewhere.

A: On the Mac, unzipping via the Finder sometimes doesn't work. Then you get a file that ends with .zip.cpgz, after first renaming the .odp file to .zip. I ended up using the terminal command unzip. Before you do this, put the file inside an empty folder, because all files and folders end up in the folder.
mv filename.odp filename.zip
unzip filename.zip -d content

A: I know for sure that it is possible to extract images and other content from an MS Word document (.docx) by opening  it with an archive file manager such as 7zip and navigating through the directories.
I am not sure about PDFs and ODPs, but try opening such a file with 7zip and see how it goes.

A: To add to @SPRBRN's answer, with the ODP format you can extract it directly from the file to a directory:
unzip filename.odp -d unpacked

This is not so easy with PDF for which there is a tool pdfimages from the poppler package.

A: For me, it worked when I rename the file extension from ".odp" to ".zip", and then use a file extractor like 7zip.


text:
Q: How do carry save adders work? I thought I understood the concept but wikipedia has confused me. There are two outputs because one's for a partial sum and one's the carry bits. But why must it be used to "compute the sum of three or more n-bit numbers" why can't it compute 2 n-bit numbers?
Also the example given under the basic concept (where the result is 21122120202022022122111011102212) confuses me more because that is just one output, not two?

A:
But why must it be used to "compute the sum of three or more n-bit
  numbers" why can't it compute 2 n-bit numbers?

The carry save addition of 2 N-bit numbers results in two (N + 1)-bit numbers being produced, the virtual carry (VC) and the virtual sum (VS).But after getting VC and VS you still have to add the two values together with a convectional adder to get your final result, so only adding 2 numbers is pointless.Take this example, lets say one carry-save addition takes k*T ms, where k = number of N - bit numbers being added, and a convectional adder takes 5T ms to add 2 numbers (regardless of bit width), then if:
1) you added 2 numbers, then
$$
\text{Time(Carry-Save) = 2T + 5T = 7T}
$$
$$
\text{Time(Convectional Adder) = 5T}
$$
2) you added 3 numbers, then
$$
\text{Time(Carry-Save) = 3T + 5T = 8T}
$$
$$
\text{*Time(Convectional Adder) = 5T + 5T = 10T}
$$
So carry-save addition is only useful if you have at least 3 operands to add.

Also the example given under the basic concept (where the result is
  21122120202022022122111011102212) confuses me more because that is
  just one output, not two?

In reality there are two outputs, the representation that has been used there is a redundant arithmetic type representation.The number "21122120202022022122111011102212" will actually be represented as two different numbers, the virtual carry (VC) and the virtual sum (VS)
So A = 21122120202022022122111011102212 will be represented as
VC = 100110101010110110110000000011010
VS = 011001000000000000100111011100010
in your carry save adder.The VC number is obtained by looking at each and digit of A in turn, starting from the LSB, if the digit in a particular bit position, say bit position m, is 2 then place a 1 in the m th bit position of VC, otherwise place a zero.VS is obtained by setting all digits that are non-one in A to zero.You could also convert a redundant number to two non-redundant numbers by using the alternative method below.
Say you have B = 22012
Re-Write B using just binary by using 2 bits per digit, ie B =  10,10,00,01,10
Extract the first bit of each digit to form VC and the extract the last bit of each digit to form VS, ie( VC = 11001, VS =00010 )


text:
Q: What is the most efficient way to read in a partitioned parquet file with pyspark? I work with parquet files stored in AWS S3 buckets. They are multiple TB in size and partitioned by a numeric column containing integer values between 1 and 200, call it my_partition. I read in and perform compute actions on this data in Databricks with autoscaling turned off.
I have found that reading a specific partition path for my parquet object will take 2 seconds, whereas reading the full parquet path and filtering to the partition will take 6 minutes. Searching for answers I found out about InMemoryFileIndex in this StackOverflow. This makes sense to me why the read is so much faster, if I read s3://my_parquet/my_partition=1/ there is a lot less listing/heuristics to perform on file contents than if I read s3://my_parquet/ and perform .filter(col("my_partition")==1).
Strangely, the computation that immediately follows the read is always slower for the specific partition read object, though the spark instructions should be the same. For example:
# Specific partition read + compute
specific_read = spark.read.parquet("s3://my_parquet/my_partition=1/") # Takes 2 seconds
specific_read.count() # Takes 10 minutes

# Full parquet/filter + compute
general_read = spark.read.parquet("s3://my_parquet/").filter(col("my_partition")==1) # Takes 5 minutes
general_read.count() # Takes 1 minute

It seems like reading the full path and filtering is faster overall but I do not understand why, especially when the read operation is so much faster for the reading specific partitions. Why is one method faster than the other? Is there a "best" way to extract data stored in a specific partition for computing on?


text:
Q: How to stop sql logging in debug mode? How do I run django in debug=True without being bombarded by the sql logging?
Being forced to squint through all this noise is making it rather hard to see my debug messages....
[Thu Jul 28 19:56:27 2011] [error] DEBUG:(0.000) SELECT `django_session`.`session_key`, `django_session`.`session_data`, `django_session`.`expire_date` FROM `django_session` WHERE (`django_session`.`session_key` = foobar  AND `django_session`.`expire_date` > 2011-07-28 19:56:27 ); args=('foobar', u'2011-07-28 19:56:27')
[Thu Jul 28 19:56:27 2011] [error] DEBUG:(0.000) SELECT `Users`.`id`, `Users`.`auth_id`, `Users`.`username`, `Users`.`pwhash`, `Users`.`first_name`, `Users`.`last_name`, `Users`.`email`, `Users`.`notes`, `Users`.`force_password_change`, `Users`.`deleted`, `Users`.`deleted_username` FROM `Users` WHERE (`Users`.`deleted` = False  AND `Users`.`id` = 2 ); args=(False, 2)
[Thu Jul 28 19:56:27 2011] [error] DEBUG:(0.000) SELECT `Auths`.`id`, `Auths`.`developer_id`, `Auths`.`application_id` FROM `Auths` WHERE `Auths`.`id` = 2 ; args=(2,)
[Thu Jul 28 19:56:27 2011] [error] DEBUG:(0.000) SELECT `Auths`.`id`, `Auths`.`developer_id`, `Auths`.`application_id` FROM `Auths` WHERE `Auths`.`id` = 2 ; args=(2,)

A: In Django 1.3 this can be done rather simply with the inclusion of logging.  In summary the way I do it is very similar to the docs and keep the focus of logging on my application.  My settings.py file currently looks like this.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': False,
        },
        'apps': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    }
}

If you are using an older version of Django you can setup logging by using filters (Yes you can do this in 1.3 too.)  This SO post should provide you with what you need to get going.
Edit Update
Again following the documentation which gives an example combined with this post should get you where you need to go.

*

*Add in a django handler and propagate it down the chain..

*Add in a django.db.backends which doesn't propagate but raise the noise floor to ERROR

I don't think there is anything else?
HTH


text:
Q: 500,000 GET requests to a random jpeg per day (Apache) So I'm getting this on my Apache log on a small server for a local company:
1.2.3.4 - - [09/Nov/2015:17:00:16 +0000] "GET /wp-content/uploads/2012/08/gold-coins.jpeg HTTP/1.1" 301 342

about 500,000 times per day with 150,000 unique IP's. I've redirected that traffic outside my site (hence the 301) because it was crashing the server. But it is still using some bandwidth. What is the best way to remedy this situation?

A: This issue is called image hotlinking.
Nginx can be configured in a variety of ways to protect you from it. Read it about it here:
http://www.htpcbeginner.com/image-hotlink-protection-nginx/
http://nginxlibrary.com/hotlink-protection/
http://nodotcom.org/nginx-image-hotlink-rewrite.html
Trouble in Nginx hotlink protection
As you are saying some 150K IPs hit it 500K times, that means about 3 times each. With that in mind, you can also add browser caching of such static jpeg files in the mix, to avoid 66% of the requests. Serving static files from a so-called cookieless domain saves another bit.
Another route to consider is banning IPs at the firewall level, for example with the help of Fail2Ban. If you ban each after the first download of that file, it saves you 66% of the requests. Because it never reaches your webserver, this saves a lot of resources. But this doesn't stop it at the source.
Referrer based hotlink protection is ideal, and when you keep a list of such referrers, you can ask them to stop hotlinking so the issue hopefully goes away after a while.

A: In apache you can stop hotlinking quite easily:
https://wiki.apache.org/httpd/DisableImageHotLinking


text:
Q: ODE methods with one evaluation per time step and more state Predictor-corrector method
gives a "Predict–Evaluate–Correct" method for stepping
$y' = F(y)$ (autonomous)
with one evaluation of $F()$ per time step, and state $[y, step]$:
p = y + old step  # predict, look ahead
pstep = h F( p )
step = (old step + pstep) / 2
y += step

Are there variants of this with more state, e.g. the last 3 or 4 steps and psteps, but with only one evaluation of $F()$ per time step, along the lines:
p = linear function of state
pstep = h F( p )
y, state = linear function of state and pstep

As an engineer, not a mathematician, I'd be more interested in
running examples of such methods, with code or pseudocode,
than in convergence proofs.
(Background:
gradient descent with Nesterov momentum is of the form at the top,
with $p = y + m\  \times$ old step, $m$ a "momentum" factor a bit less than 1; see
this question
.)


text:
Q: Getting *buntu 17.04 (or others) to respect my choices when installing to a external drive UEFI/secureboot system I'm trying to install Lubuntu or Kubuntu 17.04 to an external drive. I'm using a IODD 2451 booting an ISO, and installing to an emulated phyical drive backed by a VHD. For all intents and purposes - I'm installing from a livecd/dvd to a regular external hard drive that my firmware detects as a bootable device.
I am running a system with secureboot, and I don't want to turn it off.
Both these variants seem to either not give an option on where to install the bootloader, or ignore it, and don't seem to write the EFI boot files to a ESP partition they create.
While the IODD is a unusual piece of hardware, as far as my computer is concerned, however, these are a regular blueray drive (not important) and a bootable hard drive. It even boots off the drive, sees the other drive and does the install. Lubuntu's installer does not give me a choice of where to install my bootloader, and doesn't create a ESP partition. KDE does, so lets assume I'm using Kubuntu
Kubuntu is happy to create an ESP partition on my external drive. Then proceeds to install my bootloader and EFI boot files to the main drive in my system despite telling it to install to the external drive.
While in theory I could install to a VM then convert, I don't think any free vm software emulates a secureboot system.
So, how do I get either of these flavours of ubuntu to respect my choices and actually install to the drive I want it to without clobbering my other drive?

A: I'd never before heard of that hardware you're using. It looks like an interesting device, but I doubt if it's the source of your problems.
When installing in EFI/UEFI mode, the Ubuntu installer (Ubiquity) prompts for the location of the boot loader, but promptly ignores that information. There are several bugs related to this:

*

*https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1466367

*https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1173457

*https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1396379
I haven't checked Lubuntu and Kubuntu specifically, but I would expect them to have the same bug.
One workaround procedure is as follows:

*

*Boot the installation medium into its "try before installing" mode.

*Open a Terminal window.

*Type ubiquity -b. The -b option tells Ubiquity to not install a boot loader at all.

*Proceed with installation normally.

*Manually install a boot loader. This can get tricky, though. There are several options for how to proceed:

*

*You can install from the installation medium you've already booted or you can use a tool like my rEFInd boot manager on a USB flash drive or CD-R to boot into your disk-based installation on a one-time basis.

*You can install GRUB 2 (Ubuntu's default) or something else.

*You may need to adjust /etc/fstab or otherwise ensure that the ESP you want to use is mounted at /boot/efi.

Note that many (but not all) EFIs delete NVRAM boot entries that point to invalid boot loaders. Thus, if you install your Ubuntu boot loader to an external disk and then unplug that disk and boot, the boot loader entry may go away. The solution is to rename the boot loader path (EFI/ubuntu/ by default) to EFI/BOOT, and rename the boot loader itself to the fallback filename (EFI/BOOT/bootx64.efi). That filename will make an external disk bootable by specifying the disk in the firmware's boot menu. Alternatively, you could install rEFInd on the internal disk. rEFInd is more dynamic than GRUB; it actively scans all media for bootable images, so its options adapt on a boot-by-boot basis, and it won't be bothered by the appearance and disappearance of the external disk. You'll need to jump through some extra hoops to get rEFInd to work with Secure Boot, though, as described in its documentation.
As to VMs, there are EFI firmware images for QEMU that support Secure Boot. There are some links and instructions on using it here, among other places -- try a Web search if you have problems with the link I've provided. I don't know of anything pre-built for VirtualBox.


text:
Q: Power Bi Desktop- Couldn't load the schema for the database model Power BI desktop image Downloaded the Power BI desktop version.
Installed it.
And Opened it.
This message popped up.
"Couldn't load the schema for the database model"
"We couldn't retrieve the data model for this report. Please try again."
And also whenever I want to load Dataset from excel sheet this message popped up.

A: This is being caused by x64 build of Power BI Desktop. I suggest you uninstall the current PowerBI Desktop and reinstall an older x64 build or latest x32 build.
I simply installed the latest x32 build and it worked for me.

A: Not an answer per se, but may help others when troubleshooting:
I've noticed that when using the latest (June 2022, v2.106.582.0) x64 version of the PowerBI desktop app in a Remote Desktop Services environment, where the session hosts are 20212R2, if the "Desktop Experience" windows feature is installed I get the error on launching the app, on Session Hosts without this feature installed, the app launches fine. (I don't have a PowerBI license or access to any datasources to test further, but the fact I'm not getting the error message on launch hopefully counts for something!)
Edit to add: Seems to be OK on Server 2016

A: I got the same error since yesterday (after updating to the newest Power BI version). In all datasets that I tried to open, it gave me this message. I tried complex ones with connections to various power bi online datasets and simple ones with only 1 web data source. When I tried to open the same datasets on a different machine I didn't get the errors.
I'm going to wipe PowerBI from all connections and reinstall it, maybe that'll help.

A: This seems to be resolved in the latest (2.107.683.0, July 2022) x64 build, it loads without errors on Server 2012R2 (with and without the dekstop experience feature installed) as well as Server 2016


text:
Q: What select the keywords from others? import is a keyword while input is a builtin function
In [48]: import keyword
In [54]: keyword.iskeyword('import')
Out[54]: True
In [57]: keyword.iskeyword('input')
Out[57]: False
In [55]: type(input)
Out[55]: builtin_function_or_method

What's the rule to select the current 33 keywords from others(builtins)?


text:
Q: Are the statements about the conditional probability true? Let $P$ be a probability measure on a $\sigma$-Algebra $\mathcal{A}$. I want to prove or disprove the following statement:

*

*$P(C\mid A)>P(C\mid A\cup B)$, for $A, B, C\in \mathcal{A}$ with $C\subset A\cap B$ and $P(B\setminus A)>0$

$$$$
I have done the following:

*

*We have that $P(C\mid A)=\frac{P(C\cap A)}{P(A)}$ and $P(C\mid A\cup B)=\frac{P(C\cap (A\cup B))}{P(A\cup B)}$.
We have that $C\cap (A\cup B)=(C\cap B)\cup (C\cap B)$. Since $C\subset A\cap B$ these two sets are not disjoint, therefore we get $P(C\cap (A\cup B))=P((C\cap A)\cup (C\cap B))<P(C\cap A)+P(C\cap B)$, right?
It holds that $P(A\cup B)>P(A)\Rightarrow \frac{1}{P(A\cup B)}<\frac{1}{P(A)}$.
Therefore we get $P(C\mid A\cup B)=\frac{P(C\cap (A\cup B))}{P(A\cup B)}<\frac{P(C\cap A)+P(C\cap B)}{P(A)}$.
Is everything correct so far? How could we continue?

A: No, all you need is that because $C\subset A\cap B$ , therefore $C\subset A$ , $C\subset B$ , and $C\subset A\cup B$.
Also if $C\subset X$ , then $C=C\cap X$.

So

It holds that since $P(A\cup B)>P(A)$ (why?), so therefore $\frac{1}{P(A\cup B)}<\frac{1}{P(A)}$.

Thus $\frac{P(C)}{P(A\cup B)}<\frac{P(C)}{P(A)}$, and hence...


text:
Q: Removing lines with a single common field I have a tab separated file that looks like this:
123   some text
123   some different text
334   some other text
341   more text

and I want to do two things. One is to order everything numerically (this is easy to do) and the other is to remove a line if it's number is already present. I.e. the output would look like this:
123   some text
334   some other text
341   more text

I tried getting a file of just the unique numbers, i.e.
123
334
341

and joining it with the original file with:
join -j 1 justNumbers.txt original.txt

but this gave me the original file back. Any ideas?

A: If you want to sort/test for uniqueness the first field specifically, and your system has the GNU coreutils version of sort, then I think you could just use
sort -nu file

viz.
$ sort -nu file
123   some text
334   some other text
341   more text

From info coreutils 'sort invocation'

The commands sort -u and sort | uniq are equivalent, but this
  equivalence does not extend to arbitrary sort options.  For
  example, sort -n -u inspects only the value of the initial numeric
  string when checking for uniqueness, whereas sort -n | uniq
  inspects the entire line.

A: Try this awk:
awk '!($1 in a){a[$1];print}' file
123   some text
334   some other text
341   more text

This assumes that file was sorted.


text:
Q: Accepting user input in assembly? Simple program (On macOS) I'm having some trouble with this simple program that accepts a name from the user and prints "Hello, name here"
This is my code so far...
%define SYSCALL_WRITE 0x2000004
%define SYSCALL_EXIT  0x2000001
%define SYSCALL_READ  0x2000003

SECTION .data
  prompt db "Enter name "
  text2 db "Hello, "

SECTION .bss
  name resb 16

SECTION .text
  global _start

_start:
  call _printText1
  call _getInput
  call _printText2
  call _printName
  mov rax, SYSCALL_EXIT
  mov rdi, 0
  syscall

_printText1:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, prompt
  mov rdx, 11
  syscall
  ret

_getInput:
  mov rax, SYSCALL_READ
  mov rdi, 0
  mov rsi, name
  mov rdx, 1
  syscall
  ret

_printText2:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, text2
  mov rdx, 7
  syscall
  ret

_printName:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, name
  mov rdx, 16
  syscall
  ret

When I execute it, the output doesn't print "Hello, ". The first letter of the name entered is printed before the next commandline...
nMy-MacBook:Assembly username$ ame
and the rest of the name is accepted as a command argument, for which the system replies
-bash: ame: command not found
What exactly am I doing wrong? I deleted the _getInput and _printName functions and it still only prints "Enter name " without printing "Hello, ".
Thank you.

A: In Assembly you have to account for every bit; especially when doing input and output.
Below is your partial code with edits for RDX wherein I chose some arbitrary length.
The last line shows the command line program execution, prompt, user input, then final output.
; reference:
; https://stackoverflow.com/questions/47889972/accepting-user-input-in-assembly-simple-program-on-macos

; lsb_release -a
; Distributor ID: Ubuntu
; Description:    Ubuntu 16.04.3 LTS
; Release:        16.04
; Codename:       xenial

; assemble and link
; nasm -f elf64 -g -F dwarf srsrso_001.s -o srsrso_001.o  && ld srsrso_001.o -o srsrso_001

;%define SYSCALL_WRITE 0x2000004
;%define SYSCALL_EXIT  0x2000001
;%define SYSCALL_READ  0x2000003

SECTION .data
  prompt db "Enter name "
  text2 db "Hello, ",0xa,0

        SYSCALL_WRITE equ       1
        SYSCALL_EXIT  equ       60
        SYSCALL_READ  equ       0

SECTION .bss
  name resb 0xff                ; some length

SECTION .text
  global _start

_start:
 call _printText1
 call _getInput
 call _printText2
 call _printName

  mov rax, 60
  mov rdi, 0
  syscall

_printText1:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, prompt
  mov rdx, 11
  syscall
  ret

_getInput:
  mov rax, SYSCALL_READ
  mov rdi, 0
  mov rsi, name
  mov rdx, 0xff ; some length
  syscall
  ret

_printText2:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, text2
  mov rdx, 7
  syscall
  ret

_printName:
  mov rax, SYSCALL_WRITE
  mov rdi, 1
  mov rsi, name
  mov rdx, 0xff ; some length
  syscall
  ret

Example output:
$ ./srsrso_001
Enter name David John Lewis Benjamen Kyle Smith-Wenson
Hello, David John Lewis Benjamen Kyle Smith-Wenson


text:
Q: Get the values of specific rows as output based on user input I have a text file data.txt, containing a table whose first few entries look like this:
                      PERIOD
CHANNELS    1      2      3      4       5
   0       1.51   1.61   1.94   2.13   1.95
   5       1.76   1.91   2.29   2.54   2.38
   6       2.02   2.22   2.64   2.96   2.81
   7       2.27   2.52   2.99   3.37   3.24
   8       2.53   2.83   3.35   3.79   3.67
   9       2.78   3.13   3.70   4.21   4.09
  10       3.04   3.44   4.05   4.63   4.53...

The channel column contains the values of channels of an instrument.
The other 5 columns contain the values of maximum energies a particular channel can detect in 5 different time periods.
I want to write a python program which takes the period, lower energy and higher energy values from the user and based on the period, finds out lower energy channel and higher energy channel corresponding to the lower energy value and higher energy value given by the user.
For example:
Period = input('Enter the period: ')
>> 1
lower_energy = float(input('Enter the lower energy value: '))
>> 2.02
higher_energy = float(input('Enter the higher energy value: '))
>> 2.60
The lower energy channel is 6
The higher energy channel is 9

I can write it using nested if conditions as follows:
If period = 1:
    if lower_energy < 1.51:
        lower_energy_channel = 0
    elif lower_energy < 1.76:
        lower_energy_channel = 5
    elif lower_energy < 2.02:
        lower_energy_channel = 6
    ...

    If upper_energy < 1.51:
    upper_energy_channel = 0
    elif upper_energy < 1.76:
    upper_energy_channel = 5
    ...

Similarly for all periods...
But my table is very long and that would be very cumbersome. I am looking for a cleaner solution to this.
The solution to this can be found here

A: @Neal, you have a look at the below code. I've just tried to solve your problem in my way and written one method for code reusability.

I have used the concept of panda's DataFrame for storing tabular data and accessing data efficiently.

I have stored your given data in a file named data.txt.
data.txt
                     PERIOD
CHANNELS    1      2      3      4       5
   0       1.51   1.61   1.94   2.13   1.95
   5       1.76   1.91   2.29   2.54   2.38
   6       2.02   2.22   2.64   2.96   2.81
   7       2.27   2.52   2.99   3.37   3.24
   8       2.53   2.83   3.35   3.79   3.67
   9       2.78   3.13   3.70   4.21   4.09
  10       3.04   3.44   4.05   4.63   4.53

Python code
import numpy as np
import pandas as pd
def get_energy_details(file_name, period, low_energy, higher_energy, row_names=None, column_names=None):
    # READ FILE AND STORE THE DATA IN 2D LIST
    data_list = [] # FUTURE'S 2D LIST

    with open(file_name) as f:
        lines = f.readlines()[2:]
        for line in lines:
            arr = [float(num) for num in line.split()[1:]]
            data_list.append(arr)

    # PRINT 2D LIST
    print (data_list, '\n')

    # CREATING DataFrame FROM 2D LIST
    df = pd.DataFrame(data_list, columns=column_names, index=row_names)

    # PRINT DataFrame
    print (df, '\n')

    # SELECT THE SPECIFIC PERIOD (It is a Series object)
    print (df[period])

    # SORT THE SERIES AND STORE IT IN sorted_list
    sorted_list = df[period].sort_values() # A Series object

    # PRINT THE SORTED Series object
    print (sorted_list)

    # ************* MAIN LOGIC GOES HERE ****************
    # ************* LOWER ENERGY ************************
    found = False
    low_energy_level = None
    higher_energy_level = None

    for i, item in enumerate(sorted_list):
        print(i, item)
        if low_energy_level is not None and higher_energy_level is not None:
            break

        if item <= low_energy:
            low_energy_level = sorted_list.index[i]

        if item >= higher_energy:
            higher_energy_level = sorted_list.index[i]

    # OUTPUT
    return (low_energy_level, higher_energy_level)

# start
if __name__ == '__main__':
    # INPUT 1
    period1 = int(input('Enter the period: '))
    lower_energy1 = float(input('Enter the lower energy value: '))
    higher_energy1 = float(input('Enter the higher energy value: '))
    row_names = [0, 5, 6, 7, 8, 9, 10]
    column_names = [1, 2, 3, 4, 5]
    energies1 = get_energy_details('data.txt', period1, lower_energy1, higher_energy1, row_names, column_names)

    low_energy_level, higher_energy_level = energies1[0], energies1[1]
    print('\nLower energy: ', low_energy_level, 'Higher energy: ', higher_energy_level, '\n\n');

    # INPUT 2
    period2 = int(input('Enter the period: '))
    lower_energy2 = float(input('Enter the lower energy value: '))
    higher_energy2 = float(input('Enter the higher energy value: '))

    energies2 = get_energy_details('data.txt', period2, lower_energy2, higher_energy2)
    low_energy_level, higher_energy_level = energies2[0], energies2[1]
    print('\nLower energy: ', low_energy_level, 'Higher energy: ', higher_energy_level, '\n\n');

INPUT 1
Enter the period: 1
Enter the lower energy value: 2.02
Enter the higher energy value: 2.60
[[1.51, 1.61, 1.94, 2.13, 1.95], [1.76, 1.91, 2.29, 2.54, 2.38], [2.02, 2.22, 2.64, 2.96, 2.81], [2.27, 2.52, 2.99, 3.37, 3.24], [2.53, 2.83, 3.35, 3.79, 3.67], [2.78, 3.13, 3.7, 4.21, 4.09], [3.04, 3.44, 4.05, 4.63, 4.53]]

       1     2     3     4     5
0   1.51  1.61  1.94  2.13  1.95
5   1.76  1.91  2.29  2.54  2.38
6   2.02  2.22  2.64  2.96  2.81
7   2.27  2.52  2.99  3.37  3.24
8   2.53  2.83  3.35  3.79  3.67
9   2.78  3.13  3.70  4.21  4.09
10  3.04  3.44  4.05  4.63  4.53

0     1.51
5     1.76
6     2.02
7     2.27
8     2.53
9     2.78
10    3.04
Name: 1, dtype: float64
0     1.51
5     1.76
6     2.02
7     2.27
8     2.53
9     2.78
10    3.04
Name: 1, dtype: float64
0 1.51
1 1.76
2 2.02
3 2.27
4 2.53
5 2.78
6 3.04

Lower energy:  6 Higher energy:  9

INPUT 2
Enter the period: 2
Enter the lower energy value: 2.96
Enter the higher energy value: 3.01
[[1.51, 1.61, 1.94, 2.13, 1.95], [1.76, 1.91, 2.29, 2.54, 2.38], [2.02, 2.22, 2.64, 2.96, 2.81], [2.27, 2.52, 2.99, 3.37, 3.24], [2.53, 2.83, 3.35, 3.79, 3.67], [2.78, 3.13, 3.7, 4.21, 4.09], [3.04, 3.44, 4.05, 4.63, 4.53]]

      0     1     2     3     4
0  1.51  1.61  1.94  2.13  1.95
1  1.76  1.91  2.29  2.54  2.38
2  2.02  2.22  2.64  2.96  2.81
3  2.27  2.52  2.99  3.37  3.24
4  2.53  2.83  3.35  3.79  3.67
5  2.78  3.13  3.70  4.21  4.09
6  3.04  3.44  4.05  4.63  4.53

0    1.94
1    2.29
2    2.64
3    2.99
4    3.35
5    3.70
6    4.05
Name: 2, dtype: float64
0    1.94
1    2.29
2    2.64
3    2.99
4    3.35
5    3.70
6    4.05
Name: 2, dtype: float64
0 1.94
1 2.29
2 2.64
3 2.99
4 3.35
5 3.7

Lower energy:  2 Higher energy:  4

A: Well, you have a table right there! Make it into a variable:
 table = [[1.51,   1.61,   1.94,   2.13,   1.95],
          [1.76,   1.91,   2.29,   2.54,   2.38],
          [2.02,   2.22,   2.64,   2.96,   2.81],
          ...
          [3.04,   3.44,   4.05,   4.63,   4.53]]

This is essentially a two-dimensional python list. You could go further by making more lists to "label the axes", so to speak:
period_axis = [1, 2, 3, 4, 5]
channel_axis = [0, 5, 6, 7, 8, 9, 10]

And now you can iterate through this array with one repeated if statement, rather than several similar ones:
period_idx = period_axis.index(period)     # Find table column corresponding to input
period_column = [row[0] for row in table]  # Use list comprehension to get a list
                                           #   comprised of JUST the column we want
lower_energy_idx = 0                       # Initialize lower_energy_channel index
for i in range(len(period_column)):        # Iterate through period_column by index
    if lower_energy < period_column[i]:    # This is your if statement from above
        lower_energy_idx = i

lower_energy_channel = channel_axis[i]     # use the channel axis to translate index
                                           # back into a useful number
...

Python is 0-indexed, so period_axis and channel_axis were necessary in order to convert from python's table indexing to your table's indexing. And I'm not sure I entirely understand your example, as this doesn't look at multiple columns at once. But the general idea here should be more or less clear: you can make a table and iterate over it however you need to, instead of using a bunch of if statements. Might not remove the if statements entirely, but at least it decreases the amount of them you'd have to use.


text:
Q: Error when installing VKT-BOT from the creator of Seniv PS C:\Users\1\Downloads\tg> git clone https://github.com/seniv/vk-tg-bot.git
Cloning into 'vk-tg-bot'...
remote: Enumerating objects: 195, done.
remote: Total 195 (delta 0), reused 0 (delta 0), pack-reused 195
Receiving objects: 100% (195/195), 89.14 KiB | 829.00 KiB/s, done.
Resolving deltas: 100% (94/94), done.
PS C:\Users\1\Downloads\tg> cd vk-tg-bot
PS C:\Users\1\Downloads\tg\vk-tg-bot> npm install
npm WARN old lockfile
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile
npm WARN deprecated ini@1.3.5: Please update to ini >=1.3.6 to avoid a prototype pollution issue
npm WARN deprecated domelementtype@1.3.0: update to domelementtype@1.3.1
npm WARN deprecated har-validator@5.0.3: this library is no longer supported
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated request@2.87.0: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated uuid@3.2.1: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm ERR! code 1
npm ERR! path C:\Users\1\Downloads\tg\vk-tg-bot\node_modules\sharp
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c C:\Users\1\AppData\Local\Temp\install-0402c2d3.cmd
npm ERR! info sharp Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.6.1/libvips-8.6.1-win32-x64.tar.gz
npm ERR! info sharp Creating C:\Users\1\Downloads\tg\vk-tg-bot\node_modules\sharp\build\Release
npm ERR! info sharp Copying DLLs from C:\Users\1\Downloads\tg\vk-tg-bot\node_modules\sharp\vendor\lib to C:\Users\1\Downloads\tg\vk-tg-bot\node_modules\sharp\build\Release
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@16.17.1 | win32 | x64
npm ERR! gyp info find Python using Python version 3.10.7 found at "C:\Users\1\AppData\Local\Programs\Python\Python310\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:122:47)
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:75:16
npm ERR! gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:363:14)
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:71:14
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:384:16
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:408:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1093:16)
npm ERR! gyp ERR! System Windows_NT 10.0.19044
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\1\Downloads\tg\vk-tg-bot\node_modules\sharp
npm ERR! gyp ERR! node -v v16.17.1
npm ERR! gyp ERR! node-gyp -v v9.0.0
npm ERR! gyp ERR! not ok
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\1\AppData\Local\npm-cache_logs\2022-10-06T14_29_48_343Z-debug-0.log
PS C:\Users\1\Downloads\tg\vk-tg-bot>


text:
Q: ERROR: Failed building wheel for skranger I am trying to install the package skranger using pip install skranger. However, I get an error ERROR: Could not build wheels for skranger, which is required to install pyproject.toml-based projects.
In the traceback, I also see an error ModuleNotFoundError: No module named 'setuptools'. However, setuptools is already installed.
I have tried related solutions already on stackoverflow, but have yet to find a solution. Any help would be greatly appreciated!


text:
Q: Sort columns active scaffold I am trying to list/order my columns in a custom order with active scaffold, Rails 5.1.2 and Ruby 2.3.3p222.
Migration as follows:
class CreateResources < ActiveRecord::Migration[5.1]
  def change
    create_table :resources do |t|
      t.string :firstname
      t.string :surname
      t.date :date_of_birth
      t.string :identity_number
      t.string :nationality
      t.string :state_province
      t.date :interview_date
      t.string :available
      t.string :home_phone
      t.string :mobile_phone

      t.timestamps
    end
  end
end

And I have added columns, the migration is as follows:
class AddColumnsToResources < ActiveRecord::Migration[5.1]
  def change
    add_column :resources, :expected_salary, :string
    add_column :resources, :current_ctc, :string
    add_column :resources, :years_of_experience, :string
    add_column :resources, :notice_period, :string
  end
end

I then used paperclip to add an attachment to the table:
class AddAttachmentAttachmentToResources < ActiveRecord::Migration[5.1]
  def self.up
    change_table :resources do |t|
      t.attachment :attachment
    end
  end

  def self.down
    remove_attachment :resources, :attachment
  end
end

I need to sort my columns so they appear in the following order:

*

*firstame

*surname

*identity number

*...


text:
Q: What is wrong with my MySQL create a table code? Why do I get this error from this code
CREATE TABLE `a9311211_AppBook`.`Requests`
(
   `Name` VARCHAR( 15 ) UNSIGNED CHARACTER SET hp8 COLLATE hp8_bin NOT NULL ,
   `Category` BLOB UNSIGNED NOT NULL ,
   `Dificulty` FLOAT( 2 ) UNSIGNED NOT NULL ,
   `Discription` LONGTEXT UNSIGNED CHARACTER SET hp8 COLLATE hp8_bin NOT NULL
) ENGINE = MYISAM CHARACTER SET hp8 COLLATE hp8_bin

MySQL said:
   #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNSIGNED CHARACTER SET hp8 COLLATE hp8_bin NOT NULL, Category BLOB UNSIGNED NO' at line 1`

A: remove the unsigned
 CREATE TABLE `a9311211_AppBook`.`Requests` (
    `Name` VARCHAR( 15 ) CHARACTER SET hp8 COLLATE hp8_bin NOT NULL ,
    `Catagory` BLOB NOT NULL ,
    `Dificulty` FLOAT( 2 ) UNSIGNED NOT NULL ,
    `Discription` LONGTEXT CHARACTER SET hp8 COLLATE hp8_bin NOT NULL
) ENGINE = MYISAM CHARACTER SET hp8 COLLATE hp8_bin

only numeric types can be unsigned

A: it should be:
`Catagory` BLOB NOT NULL

BLOBcannot be positive nor Negative (because it is not numeric).


text:
Q: Replacing numbers by random numbers in a changing file in Python/C++ I need to mix my data. I've got some numbers in a file and I need it to be mixed, like for example, change all 4's on 20, but don't change 14's to 120's doing this. I thought a lot and I'm not really sure if it's possible, because there's a big number of digits and I need to do replacement hundred times with a random values.
Anyone did something like that? Anyone knows it's possible?

A: Here is a python example that might help you :
import re
import random

def writeInFile(fileName, tab): //This function writes the answer in a file
    i = 0
    with open(fileName, 'a') as n:
        while i != len(tab):
            n.write(str(tab[i]))
            if i + 1 != len(tab):
                n.write(' ')
            i += 1
        n.write('\n');

def main():
    file = open('file.txt', 'r').readlines() //Reading the file containing the digits
    tab = re.findall(r'\d+', str(file)) //Getting every number using regexp, in string file, and put them in a list.
    randomDigit = random.randint(0, 100) // Generating a random integer >= 0 and <= 100
    numberToReplace = "4" //Manually setting number to replace
    for i in xrange(len(tab)): //Browsing list, and replacing every "4" to the randomly generated integer.
        if tab[i] == str(numberToReplace):
            tab[i] = str(randomDigit)
    writeInFile("output.txt", tab) //Call function to write the results.

if __name__ == "__main__":
        main()

Example :
file.txt contains : 4 14 4 444 20
Output.txt will be : 60 14 60 444 20, considering that the randomly generated integer was 60.
Important : In this example, I considered that your file is only containing positive numbers. So you will have to modify regexp to get negative numbers, and change it a bit if you have characters other than digits.
It might not be exactly the way you need it, but I think it's a good start.


text:
Q: Creating a memory leak in PhP Today I was asked to create a memory leak (on purpose) in PhP. Now, I am more experienced in #c & c++.
I know that there is no garbage collector in #c, so memory leak in c+ is usually created by losing a reference from a variable before using malloc to remove it from the stack.
In java and PhP I understand memory is leaked when you forget to remove references.
So one of the simplest ways anyone could create a leak would be:
$leak = [];
$ticks = 0;
while(true){
    $leak[$ticks] = getHugeObject();
    $ticks++;
    unset($leaks[$ticks]); //This creates a memory leak because the tick was already added, before that object gets removed.
}
//Program should crash after reaching memory limit.

This is pretty easy. However, I am not allowed to use arrays to create the leak. So I feel incredibility dumb for not being able to complete such a simple task. Ideas?


text:
Q: How to divide tableview to sections and give headlines I have a tableview in my app.
I want to divide my cells into sections and give headlines.
Below I attach the picture (animals, birds headlines):

How do I do that in dynamic prototype cells?
My section data:
   var sectionsData = [
       "header",
       "description",
       "diagnoses",
       "perscription",
       "notes",
       "addFaxHeadline",
       "addFax",
       "addEmailHeadline",
       "addEmails",
       "givePermissionHeadline",
       "select answer"
   ]

Here is my cell at row function:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        print ("indexPath: ", indexPath)
        print ("indexPath: ", indexPath[0])
        print ("-------")

        if (sectionsData[indexPath[0]] == "header") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "description") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "headerInfoCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "diagnoses") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "diagnosisCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "perscription") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "perscriptionCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "notes") {
            let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "addFaxHeadline") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "addFax") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "addEmailHeadline") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "addEmailCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "addEmails") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "givePermissionHeadline") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "permisionCell", for: indexPath)

            return cell

        } else if (sectionsData[indexPath[0]] == "select answer") {

            let cell = tableView.dequeueReusableCell(withIdentifier: "selectAnswerCell", for: indexPath)

            return cell

        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)

        // <<<< ???

        return cell

    }

and my numbers in row per section function:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows

        if (sectionsData[section] == "header") {
            print ("returning 1 ?")
            return 1
        } else if (sectionsData[section] == "description") {
            return 1

        } else if (sectionsData[section] == "diagnoses") {

            //return visitSummary.diagnoses.count
            return 2

        } else if (sectionsData[section] == "perscription") {
            //return visitSummary.prescriptions.count
            return 2

        } else if (sectionsData[section] == "notes") {
            return 1

        } else if (sectionsData[section] == "addFaxHeadline") {
            return 1

        } else if (sectionsData[section] == "addFax") {
            return faxAdded.count

        } else if (sectionsData[section] == "addEmailHeadline") {
            return 1

        } else if (sectionsData[section] == "addEmails") {
            return emailsAdded.count

        } else if (sectionsData[section] == "givePermissionHeadline") {
            return 1

        } else if (sectionsData[section] == "select answer") {
            return 1

        } else {
            return 0
        }

        return 0
    }

and my number of sections:
 override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        print ("sectionsData.count: ", sectionsData.count)
        return sectionsData.count
    }

All of the tutorials I find is for one section and I have a very amount of sections to show.
How would I divide it and give them headlines?

A: Let's clean up your code first:
enum Section: Int, CaseIterable {
   case header = 0, description, diagnoses, prescription, notes, addFaxHeadline,  addFax, addEmailHeadline, addEmails, givePermissionHeadline, selectAnswer
}

var sectionData: [Section] = [
   .header,
   .description,
   .diagnoses
   ...
]

override func numberOfSections(in tableView: UITableView) -> Int {
    return sectionsData.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int {
    let section = sectionData[sectionIndex]

    switch section {
       case .header:
          return 1
       case .description:
          return 1
       // ...
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let section = sectionData[sectionIndex]

    switch section {
       case .header:
          let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)

          return cell
      // ... etc
    }
}

Now, we can return section title just using a String:
override func tableView(_ tableView: UITableView, titleForHeaderInSection sectionIndex: Int) -> String? {
    let section = sectionData[sectionIndex]

    switch section {
       case .header:
          return "Header title"
       case .description:
          return "Description title"
       default:
          return nil
    }
}

Another option is to use tableView(:viewForHeaderInSection:) and tableView(:heightForHeaderInSection:):
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    let label = UILabel()
    view.addSubview(label)
    // setup constraints accordingly
    // setup title of the label
    return view
}

You can also use a custom reusable header which would be registered and dequeued in the same way cells are dequeued.

A:  var sectionsData = [
           "header",
           "description",
           "diagnoses",
           "prescription",
           "notes",
           "addFaxHeadline",
           "addFax",
           "addEmailHeadline",
           "addEmails",
           "givePermissionHeadline",
           "select answer"
       ] // Your Array

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? //*Data Source method for header title*
    {
        // Safe cast
        if let sectionArray = sectionsData as? [String]
        {
            return sectionArray[section]
        }

        // A fail safe
        return "No Header"
    }

A: Now I see. You are misunderstanding how these methods work. They are called for every cell in every section.
So, if you return 4 in numberOfSections, the method numberOfRowsInSection will be called 4 times, and sectionIndex (now called section in latest versions) will have the current section (0 to 3 in our example).
Therefore, if you want to call the second section "Birds" and let all the others nil, your code will look like this:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 1 {
        return "Birds"
    }
    // Otherwise
    return nil
}

Same thing for how many rows each section will have:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        // 1 row for the first section
        return 1
    } else if section == 1 {
        // 3 rows for the second section
        return 3
    }
    // 2 rows for every other section
    return 2
}

And, finally, what cell will be used in each indexPath:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Figure out which row and section you are talking about
    let row = indexPath.row
    let section = indexPath.section

    // Now you know where you are in the TableView, create the corresponding cell according to your project
    // Start by dequeueing a custom cell using the identifier and forcing the cell to become your custom cell
    let cell = tableView.dequeueReusableCell(withIdentifier: customCellID) as! CustomTableViewCell

    // Do aditional setup to this cell
    cell.textLabel?.text = "This is cell \(row) in section \(section)"

    // Return the cell when you are ready
    return cell
}

Remember Sulthan's suggestion to create an enum for your sections.


text:
Q: getUserMedia/RecordRTC performance issue at 720p I am using the RecordRTC script for recording video/Audio.
Everything is fine until I require 720p.
If you visit the RecordRTC site and choose 1280x720 for both video and canvas options you'll notice considerable slow down when compared to smaller sizes (expected).
if I record ONLY video it works perfectly but I require both.
$('.btn.record').on('click',function() {
!window.stream && navigator.getUserMedia(
  {
    audio: true,
    video: {
      optional: [],
      mandatory: {
        minWidth: 1280,
        minHeight: 720,
        maxWidth: 1280,
        maxHeight: 720,
        minAspectRatio: 1.7777777778,
        maxAspectRatio: 1.7777777778,
      }
    }
  },
  function(stream) {
    window.stream = stream;
    onstream();
  },
  function(error) {
    alert(error);
  }
);

window.stream && onstream();

function onstream() {
    preview.src = window.URL.createObjectURL(stream);
    preview.play();
    preview.muted = true;

    recordAudio = RecordRTC(stream, {
        onAudioProcessStarted: function() {
            if(!isFirefox) {
                recordVideo.startRecording();
            }
        }
    });

    recordVideo = RecordRTC(stream, {
        type: 'video',
        video: {
          width: 1280,
          height: 720
        },
        canvas: {
          width: 1280,
          height: 720
        }
    });

    recordAudio.startRecording(); // DISABLE THIS AND VIDEO IS PERFECT
}

A: Use <canvas> width/height as low as possible; 320*240 are suggested values:
recordVideo = RecordRTC(stream, {
    type: 'video',
    video: {
        width: 1280, // redundant because offsetWidth/videoWidth   will be 1280
        height: 720  // redundant because offsetHeight/videoHeight will be 720
    },
    canvas: {
        width: 320,   // suggested width
        height: 240   // suggested height
    }
});


text:
Q: Equality of hash of string and hash of the reverse of a string Is it possible to write a hash function in such a way that hash of a string is equal to the hash of the same string but reversed? e.g.
hash("life") == hash("efil")
hash("life") == hash("life")

A: It would most likely defeat the purpose of it being a good uniform hash function, but sure, you can define a function like that. Anything that maps data of arbitrary size to data of fixed size is a hash function.
You could e.g. sort the characters in the input before passing the string to some other hash function, example in Python:
def myhash(s):
    return hash(''.join(sorted(s)))

myhash("life") == myhash("efil")

returns True.
Another option, as sketched before in the comments:
def myhash2(s):
    return hash(''.join(sorted([s,''.join(reversed(s))])))

from itertools import permutations
for r in sorted(((myhash2(s),s) for s in (''.join(p) for p in permutations('life')))):
    print r

returns
(-8040601677570703892, 'efil')
(-8040601677570703892, 'life')
(-7809799233501675124, 'feli')
(-7809799233501675124, 'ilef')
(-7087163641342373728, 'feil')
(-7087163641342373728, 'lief')
(-3309334617147859636, 'ifel')
(-3309334617147859636, 'lefi')
(-1342443318618769016, 'flei')
(-1342443318618769016, 'ielf')
(-1101501415991241164, 'elif')
(-1101501415991241164, 'file')
(-94298563527211992, 'elfi')
(-94298563527211992, 'ifle')
(1475311783909651192, 'efli')
(1475311783909651192, 'ilfe')
(1616670693919962800, 'eifl')
(1616670693919962800, 'lfie')
(1783747732969301136, 'iefl')
(1783747732969301136, 'lfei')
(1880557847288313568, 'fiel')
(1880557847288313568, 'leif')
(4933084291912123320, 'eilf')
(4933084291912123320, 'flie')

I still like the comment/solution of @deceze best...


text:
Q: HLSL: Index to unaligned/packed floats I have a vertex shader (2.0) doing some instancing - each vertex specifies an index into an array.
If I have an array like this:
float instanceData[100];

The compiler allocates it 100 constant registers. Each constant register is a float4, so it's allocating 4 times as much space as is needed.
I need a way to make it allocate just 25 constant registers and store four values in each of them.
Ideally I'd like a method where it still looks like a float[] on both the CPU and GPU (Right now I am calling EffectParamter.SetValue(Single[]), I'm using XNA). But manually packing and unpacking a float4[] is an option, too.
Also: what are the performance implications for doing this? Is it actually worth it? (For me, this will save about one batch in every four or five).

A: Does that helps?:
float4 packedInstanceData[25];
...
float data = packedInstanceData[index / 4][index % 4];


text:
Q: Why are there so few Euclidean geometry problems that remain unsolved? Stillwell mentions in his book Mathematics and its History that:

Most of the really old unsolved problems in mathematics, in fact, are
  simple questions about the natural numbers...

What is it about Euclidean geometry that makes it have so few classical unsolved problems, relative to number theory?
*** Inspired by this question, Why are so many of the oldest unsolved problems in mathematics about number theory? and motivated by this comment.

A: Because Euclidean geometry is currently not fashionable, most people do not study topics in it or discuss problems in it, and so you simply hear of fewer problems, solved or unsolved.
Any claims that all Euclidean geometry problems are decidable, as given in the comments to the question, will depend on some restricted definition regarding the form that a "problem" can take.
There are plenty of unsolved geometry problems.  I recommend the book Unsolved Problems in Geometry by Croft, Falconer, & Guy (1991).  In addition to hundreds of problems, the book even points to 17 other collections of unsolved geometry problems.
Many of these unsolved problems are fairly easy to state.  For example: Among all configurations of $n$ points not all on one line, what is the minimum number of lines they might determine?  Explainable to a small child, yet unsolved.
There are many, many beautiful unsolved geometry problems, including ones with Erdös rewards, and I cannot do them justice in this answer.


text:
Q: Using SignalR and jquery to change css on a span I'm using SignalR to update this span that is changing color based on a real time source. The connection works fine, but I have some trouble with the update part of the css classes on the span.
Problem is that when I need to update several classes on one element, the class names just get appended and not changed.
Here's my markup:

        @Model.ActivityMessage

In the outer span the classes sl-badge-normal and connection-false are the classes that needs to be changed.
sl-badge-normal can be the following values:

*

*sl-badge-ok

*sl-badge-warning

*sl-badge-error

*sl-badge-normal

and connection-false can only change between that and connection-true.
Before you ask, yes, the two needs to be separated into two different jquery-updates as it's completely different messages :)
My jquery looks like this for the connection part:
messageHub.client.notifyAlive = function (aliveMessage, unitId) {
    if (aliveMessage) {
        $('#activity-' + unitId).addClass("connection-true");
    } else {
        $('#activity-' + unitId).addClass("connection-false");
    }
};

And for the badge part it looks like this:
messageHub.client.notifyActivityStatus = function(statusColor, statusText, unitId) {
    $('#activity-' + unitId).addClass("badge " + statusColor);
    $('#activityMessage-' + unitId).text(statusText);
};

My problem here being that the following statement will go from this:

to this:

Could anyone please suggest a solution for this? Is posting the entire class string neccesary each time there's an update or can I simply swap single class names?

A: you can use toggleClass to remove/add a class based on boolean.
messageHub.client.notifyAlive = function (aliveMessage, unitId) {
       $('#activity-' + unitId).toggleClass("connection-true",aliveMessage).toggleClass("connection-false", !aliveMessage);

};

A: You are mixing a lot of technologies here. Have you considered something like knockout?
Here is a short example how to do it:
<!DOCTYPE html>

 <button data-bind="click: toggleConnection">connection</button>
 <button data-bind="click: toggleStatus">status</button>


text:
Q: Why is return false and return true used after this inline event-handler? <button onclick="alert('Hello'); return false;">Hello</button>

What is the return false part supposed to do? Also, what would return true do if it were there?

A: The return false will disregard default behavior for the onclick event. So, for example, if you had a link:
Link

when the user clicks on the link they'd get a popup but wouldn't actually go the target of the link.

A: The default button type is submit, so <button> is the same as <button type="submit"> (except on IE).  The return false stops the default button action so it will stop form submission from happening.
You can avoid that by defining the button type explicitly
<button type="button" onclick="alert('Hello');">Hello</button>

A: It depends on the context.
For example return true|false on a submit button either does or does not submit the form which you can use for form validation,  i.e. return false if the validation fails and prevent the form from submitting.
In many cases it will acheive nothing for example the button in your code example to my knowledge does nothing with the retirn value.


text:
Q: File Permission in SFTP in marketing cloud I wanted to set permission for a file present sftp like read access only or read/ write access.
Currently we are using fileZilla is there any way where we can provide permission to the file in marketing cloud.

A: You cannot do this on a file level.
Marketing Cloud however since one of the latest releases has been giving the option of three accounts per Business Units, for which you can set those permissions.
So to a very limited degree, you can work with separating your usecases into (3) different sFTP accounts with read only / full access respectively.
Setup / Data Management / FTP accounts, on your account there is a little downward arrow which lets you change these settings:

A: You can't do that with Marketing Cloud's SFTP - you cannot set permissions on a file level.
The only permission control that is possible in Marketing Cloud's FTP is to restrict access for a user:

You can have up to 3 users per FTP, so I would suggest creating one with full access, and a second one with read-only access.