text:
Q: How to get the text of multiple elements split by delimiter using jQuery? I am using jQuery to get the text value of multiple td elements in a row:
var getText = $(this).closest("tr").text();

The value of getText ends up being one long concatenated string of the text of each element with no breaks. Is it possible to add a delimiter for each new td element that it gets the text value from?

A: I'd first suggest retrieving an Array of the cells' text, rather than a single String:
var cellTexts = $(this).closest("tr").find('td').map(function(){
                  return $(this).text();
                }).get();

If you wish to have a single string, with a custom delimiter, you can then call Array.prototype.join(), and specify the delimiter you wish to use, for example a comma:
var cellTexts = $(this).closest("tr").find('td').map(function(){
                  return $(this).text();
                }).get(),
    allText = cellTexts.join(',');

References:

*

*JavaScript:

*

*Array.prototype.join().

*jQuery:

*

*closest().

*find().

*get().


text:
Q: Issues with Event Source creation deploying lambda function using serverless framework I am trying to deploy a Lambda function using serverless framework. The lambda function is invoked based on a Kinesis event source. When I try to deploy the lambda, I get this following problem.

CloudFormation - CREATE_FAILED - AWS::Lambda::EventSourceMapping

Does it mean we don't have permission to create EventSource for the lambda function?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inventory Widget Blueprint I'm creating a GUI inventory widget for the player, basically I have created the widget, it shows, I want to toggle the widget on and off, what I have now is, I can press the inventory key and it shows, on the A flip flop, but when for the B flip flop, it doesn't hide the inventory as it should be, although it prints the string, its not removing the widget as it should be, what should I add to my player blue print?

A: In your code on both sides of the flip-flop you are creating the widget, make sure the widget you are trying to hide is the one you created.
For that, remove the "Create Inventory Widget" node from the B part of the flip-flop and connect the "Set Visibility" node 'target' to the "Create Inventory Widget" 'return value' located in the A part of your flip-flop.
It's also recommended to save it as a variable to avoid confusion in your code if you ever need to something with the widget visibility again.


text:
Q: PostgreSQL combinations without repetitions How to make function in postgres that would take string or array and return all combinations of some length?
For example you have ABC and you want to get combinations with 2 characters, the result shoul be:
AB
AC
BC
Thank you in advance for your help.

A: with chars as (
   select unnest(regexp_split_to_array('ABC','')) as c
)
select c1.c||c2.c
from chars c1
  cross join chars c2

To remove permutations you can use the following:
with chars as (
   select unnest(regexp_split_to_array('ABC','')) as c
)
select c1.c||c2.c
from chars c1
  cross join chars c2
where c1.c < c2.c

A: set search_path='tmp';

WITH ztab AS (
SELECT idx as idx
, substring ( 'WTF!' FROM idx FOR 1) as str
FROM generate_series(1, char_length( 'WTF!' )) idx
)
SELECT t1.str, t2.str
FROM ztab t1
JOIN ztab t2 ON t2.idx > t1.idx
        ;

Result:
 str | str
-----+-----
 W   | T
 W   | F
 W   | !
 T   | F
 T   | !
 F   | !
(6 rows)

Unfortunately I cannot find a way to avoid the double string constant. (but the whole thing could be packed into a function) If there are no duplicate characters (or you want to suppres them) you could do the anti-join on the str instead of the idx.
UPDATE (hint from ypercube) It appears that the OP wants the strings to be concatenated. So be it::
WITH ztab AS (
SELECT idx as idx
, substring ( 'WTF!' FROM idx FOR 1) as str
FROM generate_series(1, char_length( 'WTF!' )) idx
)
SELECT t1.str || t2.str AS results
FROM ztab t1
JOIN ztab t2 ON t2.idx > t1.idx
        ;

Results:
 results
---------
 WT
 WF
 W!
 TF
 T!
 F!
(6 rows)

UPDATE2: (here comes the recursive thingy...)
WITH RECURSIVE xtab AS (
        WITH no_cte AS (
        SELECT
        1::int AS len
        , idx as idx
        , substring ( 'WTF!' FROM idx FOR 1) as str
        FROM generate_series(1, char_length( 'WTF!' )) idx
        )
        SELECT t0.len as len
                , t0.idx
                , t0.str
        FROM no_cte t0
        UNION SELECT 1+t1.len
                , tc.idx
                , t1.str || tc.str AS str
        FROM xtab t1
        JOIN no_cte tc ON tc.idx > t1.idx
        )
SELECT * FROM xtab
ORDER BY len, str
-- WHERE len=2
        ;

Results 3:
 len | idx | str
-----+-----+------
   1 |   4 | !
   1 |   3 | F
   1 |   2 | T
   1 |   1 | W
   2 |   4 | F!
   2 |   4 | T!
   2 |   3 | TF
   2 |   4 | W!
   2 |   3 | WF
   2 |   2 | WT
   3 |   4 | TF!
   3 |   4 | WF!
   3 |   4 | WT!
   3 |   3 | WTF
   4 |   4 | WTF!
(15 rows)

A: How to works with multiple words... inspired from @wildplasser and from this source info
WITH RECURSIVE xtab AS (
    WITH no_cte AS (
    SELECT
    1::int AS len
    , idx as idx
    , unnest(ARRAY['MY','POSTGRESQL','VERSION','9.6']) as str
    FROM generate_series(1, array_length(ARRAY['MY','POSTGRESQL','VERSION','9.6'],1)) idx
    )
    SELECT t0.len as len
            , t0.idx
            , t0.str
    FROM no_cte t0
    UNION SELECT 1+t1.len
            , tc.idx
            , t1.str ||','|| tc.str AS str
    FROM xtab t1
    JOIN no_cte tc ON tc.idx > t1.idx
    )
    SELECT distinct
    array_to_string(ARRAY(SELECT DISTINCT trim(x) FROM unnest(string_to_array(str,',')) x),', ') FROM xtab


text:
Q: Arguments for Discord.js how do I read args in discord.js? I am trying to create a support bot and I want to have an !help {topic} command. how do I do that?
my current code is very basic
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = ("!")
const token = ("removed")

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong');
  }
  if (msg.content === 'help') {
    msg.reply('type -new to create a support ticket');
  }

});

client.login(token);

A: You can make use of a prefix and arguments like so...
const prefix = '!'; // just an example, change to whatever you want

client.on('message', message => {
  if (!message.content.startsWith(prefix)) return;

  const args = message.content.trim().split(/ +/g);
  const cmd = args[0].slice(prefix.length).toLowerCase(); // case INsensitive, without prefix

  if (cmd === 'ping') message.reply('pong');

  if (cmd === 'help') {
    if (!args[1]) return message.reply('Please specify a topic.');
    if (args[2]) return message.reply('Too many arguments.');

    // command code
  }
});

A: you can use Switch statement instead of
if (command == 'help') {} else if (command == 'ping') {}
client.on ('message', async message => {
  var prefix = "!";
  var command = message.content.slice (prefix.length).split (" ")[0],
      topic = message.content.split (" ")[1];
  switch (command) {
    case "help":
      if (!topic) return message.channel.send ('no topic bro');
      break;
    case "ping":
      message.channel.send ('pong!');
      break;
  }
});

A: let args = msg.content.split(' ');
let command = args.shift().toLowerCase();

this is the simplified answer from @slothiful.
usage
if(command == 'example'){
  if(args[0] == '1'){
  console.log('1');
 } else {
  console.log('2');

A: You can create a simple command/arguments thing (I don't know how to word it correctly)
client.on("message", message => {
  let msgArray = message.content.split(" "); // Splits the message content with space as a delimiter
  let prefix = "your prefix here";
  let command = msgArray[0].replace(prefix, ""); // Gets the first element of msgArray and removes the prefix
  let args = msgArray.slice(1); // Remove the first element of msgArray/command and this basically returns the arguments

  // Now here is where you can create your commands
  if(command === "help") {
    if(!args[0]) return message.channel.send("Please specify a topic.");
    if(args[1]) return message.channel.send("Too many arguments.");

    // do your other help command stuff...
  }
});

A: You can do
            const args =
                message.content.slice(prefix.length).trim().split(' ');
            const cmd = args.shift().toLocaleLowerCase();

A: Word of advice, use a command handler and slash commands - this will solve both the need for a help command and reading arguments. Also helps with readability.
Anyways...
message.content.split(' '): This will split your string into an array of sub-strings, then return a new array.
.shift(): This will remove the first index in the array.
Combining this will get you your arguments: const args = message.content.split(' ').shift()


text:
Q: polynomial fit using pandas dataframe and numpy I have a script in which I take a dataframe, which looks something like this:

and convert some columns to numpy arrays for processing. I then use a small function that I wrote which uses statsmodels.api to compute a linear regression based on two arrays that I pass into the function. The function then returns the statistics and the linear fit equation:
def computeLinearStats(x, y, yName, calc_tau = False):
    '''
    Takes as an argument two numpy arrays, one for x and one y, and a string for the
    name of the y-variable, and a boolean for whether to calculate tau.
    Uses Ordinary Least Squares to compute the statistical parameters for the
    array against log(z), and determines the equation for the line of best fit.
    Returns the results summary, residuals, statistical parameters in a list,
    the best fit equation, and Kendall's tau.
    '''

    #   Mask NaN values in both axes
    mask = ~np.isnan(y) & ~np.isnan(x)
    #   Compute model parameters
    model = sm.OLS(y[mask], sm.add_constant(x[mask]), missing= 'drop')
    results = model.fit()
    residuals = results.resid
    if calc_tau:
        tau = stats.kendalltau(x, y, nan_policy= 'omit')
    else:
        tau = [1, 1]    #   Use this to exclude computation of tau
#

    #   Compute fit parameters
    params = stats.linregress(x[mask], y[mask])
    fit = params[0]*x + params[1]
    fitEquation = '$(%s)=(%.4g \pm %.4g) \\times log_{10}(redshift)+%.4g$'%(yName,
                    params[0],  #   slope
                    params[4],  #   stderr in slope
                    params[1])  #   y-intercept
    return results, residuals, params, fit, fitEquation, tau

For example, say I'm looking for a linear fit between loz(z) and 'B-I' from the dataframe. After calculating these variables, I would call
results, residuals, params, fit, equation, tau = qf.computeLinearStats(log_z, (B-I), 'B-I', calc_tau = False)

to get the linear fit.
Everything works fine, but now I need to fit a polynomial rather than a linear fit.
I've tried
sources['log_z'] = np.log10(sources.z)
mask = ~np.isnan((B-I)) & ~np.isnan(log_z)
model = ols(formula='(B-I) ~ log_z', data = [log_z[mask], (B-I)
[mask]]).fit()

and
model = ols(formula='(B-I) + np.power((U-R),2) ~ log_z', data = [log_z[mask], (B-I)[mask]]).fit()

But I get
PatsyError: Error evaluating factor: TypeError: list indices must be integers or slices, not str
    (B-I) ~ log_z
            ^^^^^

even though both x and y are arrays, not strings.
What's the easiest way to find a polynomial fit in this situation -- say, something like (B-I) + (U-R)**2 against log(z)? Slide 41 and onwards on this site seems to be a starting point, but I'm confused about how to apply it.


text:
Q: compare between more than 2 vectors in R (Voting) I have 5 vectors each item in these vectors is either "yes" or "no"
So I want to compare between these 5 vectors (row by row) and calculate the majority voting for each row and add the result to a new vector.
How can I perform that in an effective way.
v1=c("yes","no","no","yes")
v2=c("no","no","yes","yes")
v3=c("yes","yes","no","yes")
v4=c("yes","no","yes","yes")
v5=c("yes","yes","yes","no")
#The expected output is "yes", "no", "yes", "yes"

A: First put the data in a form that is character based:
dat <- data.frame( v1=c("yes","no","no","yes"),
                  v2=c("no","no","yes","yes"),
                  v3=c("yes","yes","no","yes"),
                  v4=c("yes","no","yes","yes"),
                  v5=c("yes","yes","yes","no"), stringsAsFactors=FALSE)

Then pull out the names of the maximum value for a table object:
 apply(dat, 1, function(x) names(which.max(table(x))) )
[1] "yes" "no"  "yes" "yes"

A: Another method is to use mapply with == to return a matrix of TRUE and FALSE comparing where the elements of the vectors are equal to something (here, "yes"). Then rowMeans calculates the proportion across rows, and > 0.5 checks for majority. We add 1 to convert to a numeric position and then use this as a position to choose from the elements in c("no", "yes").
c("no", "yes")[(rowMeans(mapply("==", moreArgs=list("yes"), myList)) > 0.5) + 1L]
[1] "yes" "no"  "yes" "yes"

An alternative using matrix multiplication is
c("no", "yes")[((do.call(cbind, myList) == "yes") %*%
               rep(1, length(myList)) > (length(myList) / 2)) + 1L]
[1] "yes" "no"  "yes" "yes"

Note that you start by putting the vectors in a list as below.
data
myList <- list(v1=c("yes","no","no","yes"),
               v2=c("no","no","yes","yes"),
               v3=c("yes","yes","no","yes"),
               v4=c("yes","no","yes","yes"),
               v5=c("yes","yes","yes","no"))


text:
Q: Return a list of indices from a PyTorch sparse tensor I have a PyTorch sparse tensor
T = tensor(indices=tensor([[   0,    0,    0,  ..., 2047, 2047, 2047],
                       [   0,   11,   68,  ..., 1899, 1968, 2047]]),
       values=tensor([ 0.1362, -0.1351,  0.0395,  ...,  0.0814, -0.0627,
                      -0.1141]),
       size=(2048, 2048), nnz=31312, layout=torch.sparse_coo)

and I would like to select a list of indices
ind = tensor([[   0,   41,   64,  ..., 1843, 1968, 1969],
              [   0,    0,    0,  ..., 1456, 1456, 1456]])

to return a (0,ind.shape[1]) tensor out.
The only way I found was this
out = [T[i,j] for (i,j) in ind.T]

but this is terribly slow. Can someone help?


text:
Q: Domain-wide delegation using default credentials in Google Cloud Run I'm using a custom service account (using --service-account parameter in the deploy command). That service account has domain-wide delegation enabled and it's installed in the G Apps Admin panel.
I tried this code:
app.get('/test', async (req, res) => {
    const auth = new google.auth.GoogleAuth()
    const gmailClient = google.gmail({ version: 'v1' })
    const { data } = await gmailClient.users.labels.list({ auth, userId: 'user@domain.com' })
    return res.json(data).end()
})

It works if I run it on my machine (having the GOOGLE_APPLICATION_CREDENTIALS env var setted to the path of the same service account that is assigned to the Cloud Run service) but when it's running in Cloud Run, I get this response:
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Bad Request",
    "reason" : "failedPrecondition"
  } ],
  "message" : "Bad Request"
}

I saw this solution for this same issue, but it's for Python and I don't know how to replicate that behaviour with the Node library.

A: After some days of research, I finally got a working solution (porting the Python implementation):
async function getGoogleCredentials(subject: string, scopes: string[]): Promise<JWT | OAuth2Client> {
    const auth = new google.auth.GoogleAuth({
        scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    })
    const authClient = await auth.getClient()

    if (authClient instanceof JWT) {
        return (await new google.auth.GoogleAuth({ scopes, clientOptions: { subject } }).getClient()) as JWT
    } else if (authClient instanceof Compute) {
        const serviceAccountEmail = (await auth.getCredentials()).client_email
        const unpaddedB64encode = (input: string) =>
            Buffer.from(input)
                .toString('base64')
                .replace(/=*$/, '')
        const now = Math.floor(new Date().getTime() / 1000)
        const expiry = now + 3600
        const payload = JSON.stringify({
            aud: 'https://accounts.google.com/o/oauth2/token',
            exp: expiry,
            iat: now,
            iss: serviceAccountEmail,
            scope: scopes.join(' '),
            sub: subject,
        })

        const header = JSON.stringify({
            alg: 'RS256',
            typ: 'JWT',
        })

        const iamPayload = `${unpaddedB64encode(header)}.${unpaddedB64encode(payload)}`

        const iam = google.iam('v1')
        const { data } = await iam.projects.serviceAccounts.signBlob({
            auth: authClient,
            name: `projects/-/serviceAccounts/${serviceAccountEmail}`,
            requestBody: {
                bytesToSign: unpaddedB64encode(iamPayload),
            },
        })
        const assertion = `${iamPayload}.${data.signature!.replace(/=*$/, '')}`

        const headers = { 'content-type': 'application/x-www-form-urlencoded' }
        const body = querystring.encode({ assertion, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' })
        const response = await fetch('https://accounts.google.com/o/oauth2/token', { method: 'POST', headers, body }).then(r => r.json())

        const newCredentials = new OAuth2Client()
        newCredentials.setCredentials({ access_token: response.access_token })
        return newCredentials
    } else {
        throw new Error('Unexpected authentication type')
    }
}

A: What you can do here is define ENV variables in your yaml file as described in this documentation to set the GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON key.
Then use a code such as the one mentioned here.
const authCloudExplicit = async ({projectId, keyFilename}) => {
  // [START auth_cloud_explicit]
  // Imports the Google Cloud client library.
  const {Storage} = require('@google-cloud/storage');

  // Instantiates a client. Explicitly use service account credentials by
  // specifying the private key file. All clients in google-cloud-node have this
  // helper, see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
  // const projectId = 'project-id'
  // const keyFilename = '/path/to/keyfile.json'
  const storage = new Storage({projectId, keyFilename});

  // Makes an authenticated API request.
  try {
    const [buckets] = await storage.getBuckets();

    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
  } catch (err) {
    console.error('ERROR:', err);
  }
  // [END auth_cloud_explicit]
};

Or follow an approach similar to the one mentioned here.
'use strict';

const {auth, Compute} = require('google-auth-library');

async function main() {
  const client = new Compute({
    serviceAccountEmail: 'some-service-account@example.com',
  });
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);


text:
Q: Command to see the logical volume path, device mapper path and its corresponding dm device path Currently I am using this laborious command
lvdisplay | awk '/LV Path/ {p=$3} /LV Name/ {n=$3} /VG Name/ {v=$3}  /Block device/ {d=$3; sub(".*:", "/dev/dm-", d); printf "%s\t%s\t%s\n", p, "/dev/mapper/"v"-"n, d}'

Would like to know if there is any shorter method to get this mapping of combined output (lvpath, /dev/mapper/ and /dev/dm/* ), possibly a single command.

A: From the man pages for lvdisplay.
Aside from the path to the block device the data can be reported directly from
lvdisplay -C -o "lv_path,lv_dm_path,lv_kernel_minor"

If you execute
lvdisplay -C -o " "

Then lvdisplay will list all of the available fields.


text:
Q: Complex integration Cauchy Formula $\oint_{\left | z \right |=0.5} \frac{dz}{(z-1)(\sin z)} $
Define:
$f(z) = \frac{z}{(\sin z)(z-1)}$
Define:
$g(z) = \frac{f(z)}{z}$
Now integrate using Cauchy Integration Formula
$\oint_{\left | z \right |=0.5} g(z) dz=2i\pi f(0)=-2i\pi $
where the minus sign comes from the following limit:
$\lim_{z \to 0}f(z) = \frac{0}{0} = \frac{1}{(\cos z)(z-1) + \sin z}=-1$
I see that zero is a removable discontinuity point for f(z). Under these conditions may i also apply the Cauchy Integral Formula? Is the result correct?

A: Looks like you are using L'Hospital's Rule in the last step, which doesn't apply in the complex setting. However, you can show that
$$\lim_{z\to 0}\frac{\sin z}{z}=1$$
by using the Taylor expansion of $\sin$.
Other than that, your answer looks fine.


text:
Q: pycparser retrieving function call hierarchy is there a way to get the function call stack with pycparser ?
for example if i have code like this:
static int Func_1(int *val)
{
    unsigned int data_1 = 0;
    int result;

    result = Func_2(val,
                    data_1
                   );

    result = Func_3(val,
                    result
                   );

    return result;
}

so with FuncDefVisitor i can retrieve Func_1 and with FuncCallVisitor i could retrieve Func_2 and Func_3
but how can i retrieve the information that e.g. Func_2 is called from within Func_1  ?

A: You can write a visitor that finds FuncDef nodes and runs another visitor on them that finds all FuncCall nodes. For example:
class FuncDefVisitor(c_ast.NodeVisitor):
    def visit_FuncDef(self, node):
        # Here node is a FuncDef node for the function definition.
        v = FuncCallVisitor()
        v.visit(node)

class FuncCallVisitor(c_ast.NodeVisitor):
    def visit_FuncCall(self, node):
        # do something

In visit_FuncDef, we create a new call visitor and run it on node, which means it only runs within the AST node for the function definition. It will find Func_2 and Func_3 in your code, but not func calls in other functions.

That said, note that you will only get the static call graph from this. In C functions can call others via function pointers and that's not something you can know statically in the general case.


text:
Q: Python - line split with spaces? I'm sure this is a basic question, but I have spent about an hour on it already and can't quite figure it out.  I'm parsing smartctl output, and here is the a sample of the data I'm working with:
smartctl 5.41 2011-06-09 r3365 [x86_64-linux-2.6.32-39-pve] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF INFORMATION SECTION ===
Device Model:     TOSHIBA MD04ACA500
Serial Number:    Y9MYK6M4BS9K
LU WWN Device Id: 5 000039 5ebe01bc8
Firmware Version: FP2A
User Capacity:    5,000,981,078,016 bytes [5.00 TB]
Sector Sizes:     512 bytes logical, 4096 bytes physical
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   8
ATA Standard is:  Exact ATA specification draft version not indicated
Local Time is:    Thu Jul  2 11:24:08 2015 EDT
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

What I'm trying to achieve is pulling out the device model (some devices it's just one string, other devices, such as this one, it's two words), serial number, time, and a couple other fields.  I assume it would be easiest to capture all data after the colon, but how to eliminate the variable amounts of spaces?
Here is the relevant code I currently came up with:
deviceModel = ""
serialNumber = ""
lines = infoMessage.split("\n")
for line in lines:
    parts = line.split()
    if str(parts):
        if parts[0] == "Device Model:     ":
            deviceModel = parts[1]
        elif parts[0] == "Serial Number:    ":
            serialNumber = parts[1]
vprint(3, "Device model: %s" %deviceModel)
vprint(3, "Serial number: %s" %serialNumber)

The error I keep getting is:
File "./tester.py", line 152, in parseOutput
if parts[0] == "Device Model:     ":
IndexError: list index out of range

I get what the error is saying (kinda), but I'm not sure what else the range could be, or if I'm even attempting this in the right way.  Looking for guidance to get me going in the right direction.  Any help is greatly appreciated.
Thanks!

A: The IndexError occurs when the split returns a list of length one or zero and you access the second element. This happens when it isn't finding anything to split (empty line).
No need for regular expressions:
deviceModel = ""
serialNumber = ""
lines = infoMessage.split("\n")

for line in lines:
    if line.startswith("Device Model:"):
        deviceModel = line.split(":")[1].strip()
    elif line.startswith("Serial Number:"):
        serialNumber = line.split(":")[1].strip()

print("Device model: %s" %deviceModel)
print("Serial number: %s" %serialNumber)

A: I guess your problem is the empty line in the middle. Because,
>>> '\n'.split()
[]

You can do something like,
>>> f = open('a.txt')
>>> lines = f.readlines()
>>> deviceModel = [line for line in lines if 'Device Model' in line][0].split(':')[1].strip()
# 'TOSHIBA MD04ACA500'
>>> serialNumber = [line for line in lines if 'Serial Number' in line][0].split(':')[1].strip()
# 'Y9MYK6M4BS9K'

A: The way I would debug this is by printing out parts at every iteration. Try that and show us what the list is when it fails.
Edit: Your problem is most likely what @jonrsharpe said. parts is probably an empty list when it gets to an empty line and str(parts) will just return '[]' which is True. Try to test that.

A: Try using regular expressions:
import re

r = re.compile("^[^:]*:\s+(.*)$")
m = r.match("Device Model:     TOSHIBA MD04ACA500")
print m.group(1)   # Prints "TOSHIBA MD04ACA500"

A: Not sure what version you're running, but on 2.7, line.split() is splitting the line by word, so
>>> parts = line.split()
parts = ['Device', 'Model:', 'TOSHIBA', 'MD04ACA500']

You can also try line.startswith() to find the lines you want https://docs.python.org/2/library/stdtypes.html#str.startswith

A: I think it would be far easier to use regular expressions here.
import re

for line in lines:
    # Splits the string into at most two parts
    # at the first colon which is followed by one or more spaces
    parts = re.split(':\s+', line, 1)
    if parts:
        if parts[0] == "Device Model":
            deviceModel = parts[1]
        elif parts[0] == "Serial Number":
            serialNumber = parts[1]

Mind you, if you only care about the two fields, startswith might be better.

A: When you split the blank line, parts is an empty list.
You try to accommodate that by checking for an empty list, But you turn the empty list to a string which causes your conditional statement to be True.
>>> s = []
>>> bool(s)
False
>>> str(s)
'[]'
>>> bool(str(s))
True
>>>

Change if str(parts): to if parts:.
Many would say that using a try/except block would be idiomatic for Python
for line in lines:
    parts = line.split()
    try:
        if parts[0] == "Device Model:     ":
            deviceModel = parts[1]
        elif parts[0] == "Serial Number:    ":
            serialNumber = parts[1]
    except IndexError:
        pass


text:
Q: calling a background.js function from webpages hi i have a function at background.js
function cookielog()
{
chrome.cookies.getAll({},function(c){console.log(c);});
}

i want to call this cookielog from any webpage
i have seen this
sending message to chrome extension from a web page
but it didn't work for me, i get this error
attempting to use a disconnected port object

in my webpage's execute js
var customEvent = document.createEvent('Event');
customEvent.initEvent('cookieyolla', true, true);
function fireCustomEvent(data) {
    hiddenDiv = document.getElementById('cookieyolla');
    hiddenDiv.innerText = data;
    hiddenDiv.dispatchEvent(customEvent);
}
fireCustomEvent(5);

background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.url.indexOf('http') == '0' && changeInfo.status == 'complete') {
    try {
        chrome.tabs.executeScript(tabId, {
            code: 'if(typeof onceworked==\'undefined\'){var onceworked=true;var port=chrome.extension.connect();port.onMessage.addListener(function(msg){if(msg.message==\'cookieyolla\'){setTimeout(function(){alert(\'sik beni\');chrome.cookies.getAll({},cookielog);},msg.values*1000);}});var iDiv=document.createElement(\'div\');iDiv.id=\'cookieyolla\';iDiv.style.display=\'none\';document.getElementsByTagName(\'body\')[0].appendChild(iDiv);document.getElementById(\'cookieyolla\').addEventListener(\'cookieyolla\',function(){port.postMessage({message:\'cookieyolla\',values:document.getElementById(\'cookieyolla\').innerText});});};',
            allFrames: true,
            runAt: 'document_end'
        });
    } catch (e) {
    }
}

});
what i am doing wrong?
if (typeof onceworked == 'undefined') {
    var onceworked = true;
    var port = chrome.extension.connect();
    port.onMessage.addListener(function (msg) {
        if (msg.message == 'cookieyolla') {
            setTimeout(function () {
                alert('sik beni');
                chrome.cookies.getAll({}, cookielog);
            }, msg.values * 1000);
        }
    });
    var iDiv = document.createElement('div');
    iDiv.id = 'cookieyolla';
    iDiv.style.display = 'none';
    document.getElementsByTagName('body')[0].appendChild(iDiv);
    document.getElementById('cookieyolla').addEventListener('cookieyolla', function () {
        port.postMessage({
            message : 'cookieyolla',
            values : document.getElementById('cookieyolla').innerText
        });
    });
};

code:"" part as formatted
best regards

A: @Mustafa, you should read though long-live connection.

Sometimes it's useful to have a conversation that lasts longer than a single request and response. In this case, you can open a long-lived channel from your content script to an extension page , or vice versa, using runtime.connect or tabs.connect, respectively . The channel can optionally have a name, allowing you to distinguish between different types of connections.

Also, try using Dev Tools. This will help you pause the action on uncaught errors/exceptions.


text:
Q: Is it possible to send Bluetooth data to Android from iOS? I was wondering if it was possible to make GameKit broadcast data so that an Android device can get the information. I plan on sending XML data, (a Plist, nothing complex) if this is possible. I don't need any confirmation on the iOS device, I just want to send the information.
In theory, Android should be able to receive the raw encoded bytes (or bits) and then the decoding them on Android, becomes my problem, but I can't imaging GameKit broadcasting information until it has a "peer" to send to.
Is it possible to send information from an iOS device to an Android device through bluetooth?

A: It is not possible,
GameKit requires iOS devices or MFi complaint devices, so it will not even connect with a standard Android or any other device unless it is MFi complaint and thus will not be able to send any data to it.

A: It IS possiple (by Bluetooth), but you have to be jailbroken and download a package (AirBlue Sharing) from bigboss repo (or *cough*a cracked version*cough*)that allows you to transfer files between that idevice and other non-apple devices via Bluetooth. Here is a link to an article about it:
JailBreak
There is also another similar package called celeste, but I haven't looked at it so don't ask me about it.


text: Q: Opening contact list on button press . I am building a mobile application in react native .I need to see the contact list on my phone after clicking a button in the header in a screen , Can anyone suggest me some solutions


text:
Q: Proper OAuth2 Grant I'm looking to build a mobile application (iOS / Android) that digests information from a secured API.  The API will require OAuth2 authentication to be able to digest any resources.  The service I'm providing via this API contains both information that is considered public, as well as information that requires an authorization scope by the end user.  In an ideal world, only my official mobile app would be allowed to access the API, so I believe I need 2 different grants - one for the client (mobile app itself), and a second grant if the person using the app actually creates an account.
What I'm not exactly wrapping my head around is how to securely ensure that it's my official app that's requesting resources from the API, and not another program.  The Implicit grant will work just fine for the second case, where I have a known user in the system.  What kind of grant would I use for the first case, where I don't have a user to authorize access, but still want the client to retrieve information from the API?

A: Can you use a client_credentials grant for the first type? It only requires the clientId & clientSecret in order to get a token. I believe it is meant to support application access, opposed to user access (where authorization is granted)

A: I'm not very experienced in this area, but I will suggest a few things that I have learned and that I can prospect based on my readings, which should be taken with a grain of salt and researched a bit more before actual implementation.
API Questions to be Answered
Is your API meant to be completely public? Will you have multiple clients using your API (think of Facebook or Twitter)? Is your API entirely restricted (meaning only your 'official' app should be using it? Will users be authenticated in your API?
These are all question that need to be answered before continuing, because they will result in different architectures.
Completely public API
In this case, you are offering your API for general use and you should consider that spammers will eventually come along to take over your service. In this case, you should be worried about spam-bots and malicious end-users. There are several libraries in so many languages that aid with this. Consider googling anti-spam XXX where XXX is your programming language. Don't re-invent the wheel.
Keep in mind that even the best of libraries will only limit spammers in the most obvious of ways; this means that a determined attacker can DOS or DDOS your API if they really want to fight your anti-spam system.
"Official app" API
If your API should only be used by your 'official app' and no other clients (e.g. not the cURL utility, nor another programmer writing an app to interface with your API), I cannot really offer you any advice other than that again, a determined attacker will make his way in eventually.
I cannot vouch for high-profile targets like Twitter or Facebook as to what they do. My guess is that any public information that does not require authentication by user-specific credentials (e.g. a public profile page) will inevitably be spammed by bots or malicious users. However, these entities have sufficient scaling to handle such activity.
For your particular app, we had previously discussed very simple security techniques, such as taking the MD5 of your official app and using it in your API to 'authenticate' your app with the API server. However, an attacker could simply decompile your app and spam your server with the MD5, assuming they spent the time to figure out that your API required such 'authentication'.
Basically, the only way your API can know that your app is the 'official' app is if you store some secret in the app so that it can authenticate itself with the server. That could be some secret string, an MD5 of your compiled app, or even a request to some 'super secret' URL such as myapp.com/api/auth/mobile/android that would give the Android app an API key to use on subsequent requests. But, then an attacker could mimic the request from Android to get the same key.
I think you get the point. Preventing 'unofficial' apps from communicating with your API server is hard, and I honestly cannot think of a good way to prove the official app's identity, given that once an attacker has the binary package, they can decompile and sift through until they find what they need.
The same would apply if you had your 'official API clients' in your database (such as Twitter, Facebook, etc). Clients still need to use secrets and access tokens (with Oauth 2); so, theoretically, you could decompile just about any app that interacts with a 3rd-party API and use their access token and secret, impersonating their app. You can obscure your 'secret strings' all you want but, again, a determined attacker will find a way. Better to just build a system that can detect abuse and recover quickly!
Another term for this is Digital Rights Management, though in a slightly different context, and it never works! How hard you try to keep intruders out is up to your business constraints, really.
Per-user authentication
Now this is something I can actually answer!
If you ever have a user log in, even though a 3rd-party Oauth solution such as Facebook or Google login, always use TLS (SSL)! If you send usernames and passwords in plain-text, you may as well give up on securing your API because you failed the most basic step.
Once you have TLS set up, users should receive an 'API access key' per session. For a concrete example, I have the following architecture:
User has typical account information: username, password (hashed and salted of course), email, etc. A User will also be tied to an APIAccessKey in a 1:1 relationship. This means that a User will only ever have exactly 1 APIAccessKey associated with their account.
When a User authenticates (via any method), their APIAccessKey is regenerated and sent back in the API response. Any client using the API (e.g. Android, iOS, web, etc) should keep track of this access key. The next time a user makes an API request for a resource that should be restricted to only them, or scoped to them, they should send this access key in the request. The server will then validate it and respond accordingly or, if the access key is invalid, reject the response and ask for re-authentication.
How you determine whether or not the APIAccessKey is valid is completely dependent on your business constraints. For example, a government agency or bank would probably expire this access token in about 15-30 minutes. A social app would probably never expire the access token (have you ever been forced to log back in to Facebook in iOS/Android?).
But perhaps you see how this could be employed. You can also implement abuse protection per access token. For example, rate-limit requests based on the access token, such that if one token makes 1000 requests per second, you could reasonably believe that token to be compromised. Then, for all requests to that token that is now 'banned' (rate-limited), simply send the response reauthenticate: true or something similar. Any client correctly implementing your API will redirect them to the login screen. Once their token is regenerated, the attacker who had the previous token is now locked out of the API.
Multiple clients using your API
You should implement Oauth 2 for this!
This is essentially the exact same problem as per-user authentication. Anyone who wants to use your API should request an access token (and secret!) from you via a web interface or manual interaction with your support team, whatever you prefer. From there, you identify users via their API access token and can rate-limit them if need be. If their API token is compromised, you can simply regenerate it for them and the attacker will lose access in the same way as before.
This all works because users have a username or email and password, which should be completely unrecoverable by attackers in the most general sense. Attackers can intercept tokens mid-transit (man in the middle attack) or through other methods; but, if it changes, they can't do squat without knowing the password of the user who owns the token.
The best approach
The most secure approach would be to give each user who authenticates with the API an access token that regenerates with every request. This means that if a user sends a GET /posts, they must provide their access token. Their access token would then change during the GET request and be sent to them back in the response, which they would then use for the next request. An attacker who intercepts an access token will therefore only have it work for one request (that is, unless they are intercepting the TLS traffic and can decrypt it, in which case, whatever security measure you previously implemented is null and void).
Obviously this is computationally expensive; you're regenerating an access token on every single API request which could bog down your server(s), depending on your implementation. In any case, this should be a last resort and only used if you really need it. However, for forward-compatibility it might be worth setting up consumers (Android, iOS, etc) to use this schema, but for the meantime simply have the server send null for the value next_api_token (or what-have-you). That way, you don't have to force users to update to implement this schema if you really need to, and the integration will be seamless.

Hopefully all of this gave you some good ideas and will serve others in the future. It's a 'digital rights management' problem, none of which ever have a simple or straight-forward solution. All we can do is delay...


text:
Q: How to negate regex expressions containing ranges? I've got the following regex expression that identifies indexed variable names within a string (a symbolic math equation):
[a-z][0-9]
I'd like to remove all parts of the string that are not indexed variable names. I've seen negative lookahead expressions that do this, however the examples I've seen use anchors. These examples would reject the entire string if they contain a variable name, instead of replacing the parts of the string that are not variable names. Is there an efficient way of accomplishing this? I'm using Java's replaceAll() method to try and implement this:
String s = "5x0 +3x2 = 7"; // I should get "x0 x2" after the regex
s.replaceAll("[a-z][0-9]", ""); // this should be negated

A: I'm pretty sure what you want can't be done, but what can be done and what is easier to understand and code is:
Matcher m = Pattern.compile("[a-z][0-9]").matcher(s);
while (m.find()) {
    String variable = m.group(); // do with it what you will
}


text:
Q: If a system's Hamiltonian is non-interacting, does it mean that the system is not entangled? My book is generally being quite unclear about something.
So firstly I know that if the system is not entangled, we can write its state as $|ab\rangle=|a\rangle|b\rangle$ (if we understand the product is actually a tensor product). If it is entangled, we cannot do this.
It states that in general the composite system has Hamiltonian $H_{ab}=H_a+H_b+H_{int}$. Then it does some maths and works out that if $H_{int}=0$, the systems will remain unentangled provided they begin unentangled, otherwise the systems have to be entangled.
Somewhere else it says to consider two non-interacting subsystems (which I interpret as $H_{int}=0$) so that $|ab\rangle=|a\rangle|b\rangle$ - this disagrees with the above in that we haven't ruled out the prospect of the system being initially entangled, which would mean we couldn't write $|ab\rangle=|a\rangle|b\rangle$.
So my question is, which of the books two statements are correct? I.e, does $H_{int}=0$ imply the system is not entangled, or does it imply that the system is not entangled only if it is not entangled at time zero?

A: You might be misunderstanding entangled states. An entangled state, is a state which we cannot express as a factorised tensor product, i.e it cannot be cast in this form:
$$ |\psi_A\rangle \otimes |\psi_B\rangle \equiv |\psi_A\psi_B\rangle. $$
Consider the state
$$ |\psi\rangle = \frac{1}{2}\Big (|0\rangle_A|0\rangle_B + |0\rangle_A|1\rangle_B + |1\rangle_A|0\rangle_B + |1\rangle_A|1\rangle_B \Big). $$
This state can be factorised, i.e it can be expressed into a tensor product of two other states:
$$ \to |\psi\rangle_A \otimes  |\psi\rangle_B = \frac{1}{\sqrt 2}\Big (|0\rangle_A + |1\rangle_A \Big ) \otimes \Big (|0\rangle_B + |1\rangle_B \Big). $$
Now consider the Bell state:
$$ |\Phi ^{+}\rangle = \frac {1}{\sqrt 2} \Big (|0\rangle_A|0\rangle_B + |1\rangle_A |1\rangle_B \Big) $$
There is no way to decompose this state now into the tensor product of two states (try it!), hence $|\Phi ^{+}\rangle$ is said to be entangled.
Bear in mind that I have suppressed tensor notation when I wrote down the basis states, i.e technically I should have written for example:
$$ |\psi\rangle = \frac{1}{2}\Big (|0\rangle_A \otimes |0\rangle_B + |0\rangle_A \otimes |1\rangle_B + |1\rangle_A \otimes |0\rangle_B + |1\rangle_A \otimes |1\rangle_B \Big), $$
but do not confuse products of states with entanglement. Entanglement exists when a system cannot be separated into two subsystems, therefore you can only consider them together and describe them using an entangled state. In your case, as you yourself has said, $|ab\rangle$ can be decomposed into $|a\rangle \otimes |b\rangle$ so the states are not entangled and the system can be described in terms of two independent subsystems.


text:
Q: Configure logging for System.Net.Http.HttpClient via environment variable in Linux I'm trying to configure the Loglevel for HttpClient and a custom component using environment variables. the configuration in json would be something like this:
{
  "Logging": {
    "LogLevel": {
      "System.Net.Http.HttpClient": "Debug",
      "MyCompany.MyProduct.MyComponent": "Debug"
    }
  }
}

Tried this values in windows and works:
"Logging__LogLevel__System.Net.Http.HttpClient"
"Logging__LogLevel__MyCompany.MyProduct.MyComponent"

Tried this in Linux but it doesn't work:
"Logging__LogLevel__System_Net_Http_HttpClient"
"Logging__LogLevel__MyCompany_MyProduct_MyComponent"

What is the correct way to configure that kind of variable in Linux?


text:
Q: Efficient search for equilateral triangles, squares and regular pentagons in a set of 3D points For an algorithm to identify cubic point groups from a set of atom positions $r_i$ forming a molecule, I would need an efficient and fast algorithm to identify equilateral triangles, squares and regular pentagons with their vertices being the atom positions $P=\{r_i:i=1..n\}$ and $n$ being the number of vertices. These elements determine the z-axis of the coordinate system to be used to analyse the symmetry of the molecule.
A straightforward but brute-force approach is the subdivision of the point set into subsets of atom positions $S \subset P, \lvert S \rvert=m$ with $m={3,4,5}$ respectively.
The criteria for identifying the three regular polygon types are

*

*Equilateral triangle(m=3): For each set S the distances $\lvert r_{ij}\rvert=\lvert r_i-r_j \rvert$ are identical.

*Square($m=4$) and Pentagon($m=5$): For each set $S$ the centroid is calculated as
$r_c=\frac{1}{k}\sum_{i=1}^{m} r_i$. Then the set $S$ is forming a square and pentagon respectively if all distances $\lvert r_{ci}\rvert=\lvert r_i - r_c \rvert$ are equal.

For case 2 we further need to test if the point sets are coplanar. This can be done by simply testing if the matrix $\begin{pmatrix}r_1\\r_2\\r_3\\\vdots\\r_m\end{pmatrix}$ is of rank 2.
Furthermore for case 2 we have to identify if the polygon is really regular (with the current test we would find rectangles and irregular pentagons too, thanks for the hint user58697 !)
Now here is my problem (besides the open issue how to distinguish between irregular and regular polygons for case 2): With the brute-force approach, for e.g the spherical $C_{60}$ molecule (the Buckminster Fullerene) consisting of 60 atoms, I end up with 34220, 487635 and 5461512 subsets to test for m=3,4 and 5 respectively. Any idea how to segment potentially the problem further to make it more tangible?

A: Do you have exact values for the co-ordinate or not?
If they are exact it is probably quicker to look at angles (or the cosine of the angle which the dot product would give). That would be 34220 calculations for the angle $(A_{abc})$ at $r_a$ between points $r_b$ and $r_c$. You can then quickly reject all but the 60°, 90° and 108° cases. Then you can try to look for loops of the required length. This will avoid having to check for coplanar.
E.g. if $A_{abc}$ is 108° then you want to look for an angle like $A_{bcd}$ then $A_{cde}$ then $A_{dea}$ and finally $A_{eab}$.


text:
Q: approximation of a trigonometric sum I have a trigonometric sum as below
$$\frac{1}{N^2}\sum_{r=0}^{N-1}\frac{\sin^2(\pi e)}{\sin^2(\frac{\pi(r-n+e))}{N})}\frac{\cos^2(\frac{\pi(Ne-e-r+n)}{N})}{\cos^2(\frac{\pi(Ne-e)}{N})}$$
and I want to show analytically that for small $e$ ($e<0.2$) and large $N$ the above sum approximately equals $1$.   I have showed this numerically in MATLAB but I cant show it analytically. By the way $n$ is an integer between $0$ and $N-1$.
Can any one help?
Thanks in advance.


text:
Q: How to Run SVN Commands and Shell Scripts using command prompt I am trying to get an solution but i have found any thing  on it. I want to create an GuI Application where i am accepting Host Port Number,User Name and Password .
After a Successful connection i want to execute some Tortoise Svn Commands through GUI.
Then I want to run one shell Script.
Please help me for doing this.Thanks in Advance.
Thanks for reply I am Trying to connect to remote Host through Telnet or ssh and then i want to export data from svn on some destination folder. and then need to run a default.sh shell script which creates zip of extracted data and other stuff.
i am  using java 1.6, Tortoise Svn  1.6.16, My operating system is Win Xp.

A: Look at SVNKit. It might help you.
And for the record - all svn commands are the same everywhere, they does not depend on the client you are using. Tortoise is just one of implementations which calls the svn commands.

A: You don't use Tortoise for this. Install the Subversion command-line client, and run your commands that way.
http://www.collab.net/downloads/subversion/


text:
Q: Student Subject and Course Completion Would someone be able to direct me to the correct API that I could use to mark a Student Subject and Course to 'Complete'?
I found out 'Grade.CourseCompletion' API could serve the purpose, but not sure if that's correct understanding.
Also, where could I find below highlighted fields and how I can change their value?
"OrgUnitId": <number:D2LID>,
**"CompletionId": <number:D2LID>,**
"UserId": <number:D2LID>,
**"CompletedDate": <string:UTCDateTime>,**
"ExpiryDate": <string:UTCDateTime>|null

Thanks
Vivek

A: You cannot change a CompletionId; it's an entity identifier for the completion record that gets created by Brightspace when the completion record gets created. (I believe you could, however, delete a completion record and create a new one.)
You use the POST and PUT routes for course completion to create new (or update existing) course completion records. The JSON structure you provide when you do a create or update operation allows you to specify a CompletedDate.
I would also point out that D2L has a developer-specific community to support clients and partners and you may find that answers to your questions are more timely there.


text:
Q: UPDATE syntax error for SET WHERE LIKE UPDATE isc_products SET prodretailprice=145 WHERE prodcode LIKE TSACR3

I'm trying to update prodretailprice for all the products that have prodcode "TSACR3" but I keep getting this error:

#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 '[TSACR3]' at line 1

A: UPDATE `isc_products` SET `prodretailprice`=145 WHERE `prodcode` LIKE 'TSACR3'

Enclose the search pattern in single quotes.
LIKE syntax: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
LIKE can be used with the following wildcard characters

*

*% Matches 0 or more characters.
 E.g. LIKE 'TSACR3%' will match TSACR3 bla blah

*_ Matches exactly one character.
 E.g. LIKE '_TSACR3' will match 2TSACR3 but NOT 42TSACR3


text:
Q: Get disk activity like in the windows task manager I need to get the performance from the disk C:/ from my computer with python.
I'm using psutil but there's no method to get this information.
I want it exactly like in the task manager from windows but I can't get it :

I tried different code found on stackoverflow but i don't get the right information.
For example this one :
p = psutil.Process()
io_counters = p.io_counters()
disk_usage_process = io_counters[2] + io_counters[3] # read_bytes + write_bytes
disk_io_counter = psutil.disk_io_counters()
disk_total = disk_io_counter[2] + disk_io_counter[3] # read_bytes + write_bytes
print(disk_usage_process/disk_total * 100)
#Result 0.0004283707980337007

but i don't get the usage only the writing and the reading from the disk.
i tried to put the code in a loop and wait 1 second but i doesn't change.
If anyone have a solution maybe with another library.
Thanks !


text:
Q: fscanf from text file to struct pointer I'm trying to read from a text file to a struct that has a pointer to another struct.
The text file has the following format:
279288151 1 John Doe
002 1 30 04 2018
23189842 0 Jane Doe
0
282676381 1 Mark Examp
001 0 28 03 2018 03 04 2018
243897574 1 Joe Soap
003 2 14 04 2018 21 04 2018

This is my .h file:
#ifndef Clientes_h
#define Clientes_h

#include <stdio.h>
#include <stdlib.h>
#include "Alugueres.h"
#define ST_TAM 50

typedef struct info_cliente Cliente;

struct info_cliente{
    char nome[ST_TAM];
    long nif;
    int n_alugueres;
    int n_hist;
    pAluga aluguer;
};

typedef struct aluga Aluguer, *pAluga;
typedef struct data DataIn, *pDataIn;
typedef struct data DaraEn, *pDataEn;

struct aluga{
    int id_unico;
    int estado;
    pDataIn dataIn;
    pDataEn dataEn;
    pAluga prox;
};

struct data{
    int dia;
    int mes;
    int ano;
};

Cliente* le_fich(char *nome, int *n);

#endif /* Clientes_h */

And my read_file func is as follows:
#include "Clientes.h"

Cliente* le_fich(char *nome, int *n){

    FILE *f = fopen(nome, "r");
    Cliente *aux;
    int conta = 0;

    if(!f){
        printf("Error\n");
        return NULL;
    }

    while(getc(f) != EOF){
        aux = (Cliente*)malloc(sizeof(Cliente));
        fscanf(f, "%ld %d %49[^\n]", &aux[conta].nif, &aux[conta].n_alugueres, aux[conta].nome);
        if(aux[conta].n_alugueres != 0){
            fscanf(f, "%d %d %d %d %d", &aux[conta].aluguer->id_unico,
            &aux[conta].aluguer->estado, &aux[conta].aluguer->dataIn->dia,
            &aux[conta].aluguer->dataIn->mes, &aux[conta].aluguer->dataIn->ano);
        }
        conta++;
    }
return aux;
}

It gives me a bad_access error when trying to run the fscanf after the if is successful (when accessing the pointer of the struct for my date). If anyone could help me out, would really appreciate it.

A: Right now you allocating memory for aux in the loop and then try to access an element using an index which will not work. Instead you need to allocate memory for all Cliente records. If you know the number of records in the file you could simply do aux = (Cliente*)malloc(size * sizeof(Cliente));. You might also check on how you can use realloc() in the actual loop.

A:
It gives me a bad_access error when trying to run the fscanf after the if is successful

2 problems:

*

*As @Rishikesh Raje, @Cyclonecode pointed out, the allocation is only good for aux = aux[0] as well as other missing allocations.

*The usual suspect to scanning problems are that the fscanf() did not scan what was expected and code lacked checks of the return value.  (Hint: when line is only "0\n", the 2nd fscanf() reads more than OP expected.)
ret = fscanf(f, "%ld %d %49[^\n]", ...);
if((ret ==3) && (aux[conta].n_alugueres != 0)){
    fscanf(f, "%d %d %d %d %d", ...
    // code errantly does not check the return value of `fscanf()`.
}
else {
  break; // This code missing, what to do when `ret != 3`
}

A simply solution to both problems to (re)allocate as needed and check success of reading 2 lines and scanning them.
I recommend to not allocate data for the new pair of lines until the input have been validated.
Cliente *aux = NULL; // Initialize to NULL
size_t n = 0;    // Keep count of record count
char buf1[150];  // Use generous buffers.  Suggest 2x maximum expected need
char buf2[100];

// while 2 lines successfully read
while (fgets(buf1, sizeof buf1, f) && fgets(buf2, sizeof buf2, f)) {
  // Form objects to be scanned into with default values.
  struct info_cliente cli = { 0 };
  struct aluga alu = { 0 };
  struct data dat = { 0 };

  if (sscanf(buf1, "%ld %d %49[^\n]", &cli.nif, &cli.n_alugueres, cli.nome) != 3) {
    perror("Unexpected 1st line");
    break;
  }
  if (cli.n_alugueres == 0) {
    if (sscanf(buf2, "%d", &alu.id_unico) != 1 || alu.id_unico != 0)) {
      perror("Unexpected 2nd line 0");
      break;
    }
  }
  else if (cli.n_alugueres == 1) {
    if (sscanf(buf2, "%d %d %d %d %d", &alu.id_unico, &alu.estado, &dat.dia,
        &dat.mes, &dat.ano) != 5) {
      perror("Unexpected 2nd line");
      break;
    }
    alu.dataIn = malloc(sizeof *alu.dataIn);
    *alu.dataIn = dat;
    cli.aluguer = malloc(sizeof *cli.aluguer);
    *cli.aluguer = alu;
  } else {
    perror("Unexpected 2nd line n_alugueres");
    break;
  }
  Cliente *tmp = realloc(aux, sizeof *aux * (n+1));
  aux = tmp;
  aux[n] = cli;
  n++;
}

Cliente *tmp = realloc(aux, sizeof *aux * (n+1));
aux = tmp;
aux[n] = NULL;  // NULL terminate the list

Note Error checking on malloc()/realloc() omitted for brevity on the above sample code.

A: You are using both getc and fscanf to access the file.
If you want to use fscanf, you should not use getc.
Use the return value of fscanf to let you know when the file has ended. fscanf will return the number of items matched. In your case if successful it should return 3.
int ret;
do{
    aux = (Cliente*)malloc(sizeof(Cliente));
    ret = fscanf(f, "%ld %d %49[^\n]", &aux[conta].nif, &aux[conta].n_alugueres, aux[conta].nome);
    if((ret ==3) && (aux[conta].n_alugueres != 0)){
        fscanf(f, "%d %d %d %d %d", &aux[conta].aluguer->id_unico,
        &aux[conta].aluguer->estado, &aux[conta].aluguer->dataIn->dia,
        &aux[conta].aluguer->dataIn->mes, &aux[conta].aluguer->dataIn->ano);
    }
    conta++;
}while (ret == 3);


text:
Q: How do you update the playback of an audio source which is streaming? http://stream.radioreklama.bg/radio1.ogg
^ let's say that's a stream. This is the initializing part:
var audio = document.createElement('audio');
audio.src = "http://stream.radioreklama.bg/radio1.ogg";

And I use this code to pause/play it (don't worry about the toggle, it works):
if(toggle === true) {
    audio.play();
} else {
    audio.pause();
}

Question is, once I pause it, the playback stays where it was paused, so my question is: how do you "update" the playback?


text:
Q: Compiling x64 with Rust on Windows I am trying to compile x64 on Windows with Rust.
I have set: rustup default stable-x86_64-pc-windows-msvc
With the following program
fn main() { println!("{}", std::usize::MAX); }

cargo run prints out 4294967295
but cargo run --target --target x86_64-pc-windows-msvc gives me:
error[E0463]: can't find crate for 'std'
  |
  = note: the 'x86_64-pc-windows-msvc' target may not be installed

Also x86_64-pc-windows-msvc is in rustc --print target-list
I have no idea what to do...

A: This was fixed by uninstalling a rust nightly build found using rustc --print sysroot and reinstalling latest stable build.

A: The answer is in the note section of the error message:
   = note: the 'x86_64-pc-windows-msvc' target may not be installed

To f


text:
Q: Setting the Android System Volume I am writing an application which handles the following:

*

*Silent - Makes the phone volume silent

*Low - Makes the phone volume 1 point above the silent

*Medium - Makes the phone volume medium

*High - Makes the phone volume maximum

Phone volume includes Ringer, video, audio , games volume etc.
I know how to achieve Silent mode through AudioManager. But for 2-4 , I could not find any helpful code snippets. What do I need to do?

A: Check out
http://thinkandroid.wordpress.com/2010/04/05/dealing-with-the-android-media-player/
The steps are:

*

*get the audio man.

*fetch the required stream.

*call appropriate method on stream.

e.g.:
mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);

*

*to get max vol:
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

A: Add this in onCreate() method of your code and then play around with the 0 value to increase or decrease the volume where 0 means OFF.
AudioManager mgr=null;

mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
mgr.setStreamVolume(AudioManager.STREAM_RING, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
mgr.setStreamVolume(AudioManager.STREAM_ALARM, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
mgr.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
mgr.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);


text:
Q: How to load related data to table when user click Ui button? I have a view with 2 buttons (active and inactive) and a table view to show all my users. I want how can I load the related data if the user clicks one of the buttons using show active/inactive users?
import UIKit

class ViewController: UIViewController,UITableViewDataSource, UISearchBarDelegate {
    var users:[User] = []
    let user1 = User(username: "user1",email: "user1@mail.com",active: true)
    let user2 = User(username: "user2",email: "user2@mail.com",active: true)
    let user3 = User(username: "user3",email: "user3@mail.com",active: false)

    @IBOutlet weak var btnActiveUser: UIButton!
    @IBOutlet weak var btnInActiveUser: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        users.append(user1)
        users.append(user2)
        users.append(user3)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  UITableViewCell()
        cell.textLabel?.text =  "this cell index for \(users[indexPath.row].username) "
        return cell
    }

    @IBAction func ActionShowActiveUsers(_ sender: Any) {
        let activeUser =  users.filter( { return $0.active == true } )
        print(activeUser.count)
    }

    @IBAction func btnShowInActiveUser(_ sender: Any) {
        let inactiveUser =  users.filter( { return $0.active == false } )
        print(inactiveUser.count)
    }
}

A: You need
var allUsers = [User]()
var currentUsers = [User]()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return currentUsers.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    cell.textLabel?.text =  "this cell index for \(currentUsers[indexPath.row].username) "
    return cell
}

@IBAction func ActionShowActiveUsers(_ sender: Any) {
    currentUsers =  users.filter {$0.active}
    print(currentUsers.count)
    tableView.reloadData()
}

@IBAction func btnShowInActiveUser(_ sender: Any) {
    currentUsers  = users.filter { !$0.active }
    print(currentUsers.count)
    tableView.reloadData()
}

Add this in viewDidLoad
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

A: As first, you need outlet for your table view, since you don't use UITableViewController
@IBOutlet weak var tableView: UITableView!

then inside viewDidLoad set its delegate and data source as your view controller
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        tableView.delegate = self
        tableView.dataSource = self
    }
    ...
}

You can have two arrays. One for all users and one for filtered users by your condition (active or not)
var users = [User]()
var filteredUsers: [User] = users /* or just some other default value, e.g empty array */

This filtered array you can assign by filtered array every time you press certain button and don't forget to reload data of your table view then
@IBAction func ActionShowActiveUsers(_ sender: Any) {
    filteredUsers = users.filter { $0.active }
    tableView.reloadData()
}

@IBAction func btnShowInActiveUser(_ sender: Any) {
    filteredUsers = users.filter { !$0.active }
    tableView.reloadData()
}

then as data source array for your table view use filteredUsers
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredUsers.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell =  UITableViewCell()
    cell.textLabel?.text = "this cell index for \(filteredUsers[indexPath.row].username)"
    return cell
}

A: You can have a main array which holds all the users, and use another array as the dataSource of your tableView:
var mainUsers: [User] = []
var userDataSource: [User] = []

In viewDidLoad:
override func viewDidLoad() {
    super.viewDidLoad()
    mainUsers.append(user1)
    mainUsers.append(user2)
    mainUsers.append(user3)

    userDataSource = mainUsers
}

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userDataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  UITableViewCell()
        cell.textLabel?.text =  "this cell index for \(userDataSource[indexPath.row].username) "
        return cell
    }

Then in your action buttons:
    @IBAction func ActionShowActiveUsers(_ sender: Any) {
        userDataSource =  mainUsers.filter( { return $0.active == true } )
        tableView.reloadData()
    }

    @IBAction func btnShowInActiveUser(_ sender: Any) {
        userDataSource =  mainUsers.filter( { return $0.active == false } )
        tableView.reloadData()
    }

A: First at all you need several new variables:
enum FilterType { // you can add here any filter options you want
        case allUsers, active, inactive
    }

var users = [User]()
var activeUsers = [User]()
var inactiveUsers = [User]()
var filterType = FilterType.allUsers

After this edit numberOfRowInSection method:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch filterType {
        case .allUsers:
            return users
        case .active:
            return activeUsers
        case .inactive:
            return inactiveUsers
        }
}

And don't forget to add tableView.reloadData() in the end of your button actions:
@IBAction func ActionShowActiveUsers(_ sender: Any) {
        let activeUser =  users.filter( { return $0.active == true } )
        print(activeUser.count)
        filterType = .active
        tableView.reloadData()
    }

@IBAction func btnShowInActiveUser(_ sender: Any) {
        let inactiveUser =  users.filter( { return $0.active == false } )
        print(inactiveUser.count)
        filterType = .inactive
        tableView.reloadData()
}


text:
Q: prevent queuing of asynctask tasks in android I need to prevent execution of two or more asynctask at the same time, For example:
AsyncTask t1 = new myTask();
AsyncTask t2 = new myTask();
AsyncTask t3 = new myTask();
t1.execute();
t2.execute();
t3.ececute();

I need t2 and t3 to be canceled and not be executed at all in  case t1 is running.
Is Executors.newSingleThreadExecutor() what i need ?
Thanks

A: you can check in onPreExecute() of t2 and t3 if t1 is running or not, if it's running then cancel the current(t2 or t3) task.

A: Executors.newSingleThreadExecutor() will run everything on a single thread, i.e. One after the other. The best way to do what you want to do would be to not allow new tasks to be created if current tasks are already running. You can use the following code as example:
MyAsyncTask task = new MyAsyncTask();
private void createNewTask(Object o) {
  if(task.getStatus() == AsyncTask.Status.RUNNING) {
    //Do Something?
  } else {
    task = new MyAsyncTask();
    task.execute(arg0);
  }
}

A: Why not create an asynctask manager class, that just won't execute an asynctask if one is already executing and just use flags to keep track of, if a current task is executing.
I believe you can control the Thread executor pool as well to force Android to do this but, why rely on that if you don't have.


text:
Q: Transformar JSONArray em Objeto da classe Eu estou consumindo uma API no meu aplicativo que me retorna um Array de nomes, criei uma classe para atribuir cada nome a 1 instância porém estou tendo problemas na hora de pegar esse JSONArray e transformar em objeto, todos os métodos que tentei não deram certo, alguém sabe como fazer isso em Java (Android) ?
public void jsonToObj(JSONArray resultadoDaPesquisa) {

    try {
        JSONObject jsonObject = null;
        JSONArray jsonArray = resultadoDaPesquisa;

        jsonObject = new JSONObject(resultadoDaPesquisa.toString());
        System.out.println("resultado " + jsonObject);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

org.json.JSONException: Value [{"id":67377,"name":"Shiren the Wanderer 4: The Eye of God and the Devil's Navel"}] of type org.json.JSONArray cannot be converted to JSONObject

A: Este é o código que utilizo para ser JSON e transformar em objeto:
public class JsonReader {

    static String secretKeyCaptcha = "6Ld5NXMUAAAAAOXPv-EbwycOMHfoxJrSSdLcLl-I";

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String cep) throws IOException, JSONException {
        InputStream is = new URL("https://viacep.com.br/ws/" + cep + "/json/").openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    public static JSONObject validarTokenRecaptcha(String token) throws IOException {
        System.out.println("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKeyCaptcha + "&response=" + token);
        InputStream is = new URL(
                "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKeyCaptcha + "&response=" + token)
                        .openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }
}

Depois é so fazer:
            JSONObject jsonObj = new JSONObject();
            JsonReader jr = new JsonReader();
            jsonObj = jr.readJsonFromUrl(frete.getCepDestino());

enderecoDestino = jsonObj.get("logradouro").toString() + " - " + jsonObj.get("bairro").toString()

A: Obrigado pela ajuda !
Consegui fazer de uma outra forma.
    JSONObject jsonObject = null;
    try {
        for(int i = 0; i<resultadoDaPesquisa.length(); i++) {
            jsonObject = resultadoDaPesquisa.getJSONObject(i);
            String id = jsonObject.getString("id");
            String nome = jsonObject.getString("name");

            Anuncio anuncio = new Anuncio();
            anuncio.setUid(id);
            anuncio.setTitulo(nome);

            System.out.println(anuncio);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

A: Você pode usar a biblioteca GSON para facilitar o trabalho.
Com ela, a partir da String de JSON que você recebe, você consegue criar uma instância da classe desejada.
Veja um exemplo:
Gson gson = new Gson();
SuaClasse suaClasse = gson.fromJson(stringJson, SuaClasse.class);

Aqui está o Guia do Usuário da lib.


text:
Q: qt resize window after widget remove I'm adding widget in layout
ui->horizontalLayout->addWidget(tabwidget);

and qmainwindow resizes itself. But then I do
tabwidget->setVisible(false);
qs = sizeHint();
resize(qs);

I get the size like tabwidget was not removed from window.
I've made new button
void MainWindow::on_pushButton_2_clicked()
{
    qs = sizeHint();
    resize(qs);
}

and it gives correct size.
Seems I need some update function but I can't find it. Please advice

A: This is caused by a long-time internal Qt issue (I remember experiencing it first with Qt3). The top widget needs to receive an event to truly update its geometry, and know its boundaries. This event seems to be always received after the resize event generated by the layout, and therefore it is always too late to shrink the widget.
The solution posted in the accepted answer works. However a simpler solution posted below also works, when added after the layout :
layout()->removeWidget( widget );

QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
resize( sizeHint() );

Basically all we need is to let the event loop run and deliver the necessary events so the top widget geometry is updated before resize() is run.
Note that this code might have side effects if you have multiple threads running, or there are events delivered to your slots. Hence it is safer not to have any code in this function after resize().

A: If the button slot gives you the correct result then you can always call the sizeHint() and subsequent resize() in a slot which is called by a single shot timer:
void MainWindow::fixSize()
{
    QSize size = sizeHint();
    resize(size);
}

void MainWindow::methodWhereIHideTheTabWidget()
{
    tabwidget->setVisible(false);
    QTimer::singleShot(0, this, SLOT(fixSize()));
}

This timer is set to zero delay. This means that the slot will be called immediatelly when the program returns to the main loop and hopefully after the internal widget state gets updated. If this doesn't resolve your problem you may try replacing zero with 1.


text:
Q: ggerrorplot: how can I change the colors on the Plot?
Is it possible to give every variable a different color and how?
I would like to keep the legend.
Please note that it is made with ggerrorplot function.

A: You can use a different palette in your ggerrorplot function. I will use the ToothGrowth dataset as an example:

the color palette to be used for coloring or filling by groups.
Allowed values include "grey" for grey color palettes; brewer palettes
e.g. "RdBu", "Blues", ...; or custom color palette e.g. c("blue",
"red"); and scientific journal palettes from ggsci R package, e.g.:
"npg", "aaas", "lancet", "jco", "ucscgb", "uchicago", "simpsons" and
"rickandmorty".

For example use palette="Paired" for blue color:
df<- ToothGrowth

library(ggpubr)
ggerrorplot(df, x = "dose", y = "len",
            color = "supp", palette = "Paired",
            error.plot = "pointrange",
            position = position_dodge(0.5))

Output:

Or palette="npg":


text:
Q: Exercise: Evaluate a polynomial function such as $P(x)=2x^3-3x^2+7x-2$ at a surd such as $x=1+2\sqrt{3}$. Exercise: Given polynomial function $P(x)=2x^3-3x^2+7x-2$ evaluate $P(x)$ at the surd $x=1+2\sqrt{3}$.

A: Solution: Divide $P(x)$ by the divisor
\begin{equation}
D(x)=[x-(1+2\sqrt{3})]\cdot[x-(1-2\sqrt{3})]=x^2-2x-11
\end{equation}
Then
\begin{equation}
P(x)=(2x+1)(x^2-2x-11)+31x+9
\end{equation}
Therefore
\begin{equation}
P(1+2\sqrt{3})=0+31(1+2\sqrt{3})+9=40+62\sqrt{3}
\end{equation}


text:
Q: Console.getLine and Console.getString not taking in all of user input - JAVA I am trying to take in user input (the name of a country) to add to a list of countries that I display. However, it is not letting me enter the name of a country longer than 8 characters.
For example, when I input "Venezuela" the output is "Venezuel" and when I input "United States" the output is "United S"
Below is the method I used to accept the user input. I have tried Console.getString as well as Console.getLine and neither are working to accept more than 8 characters.
 public static void addCountry() {
    String name = Console.getString("Enter country name: ");

    Country country = new Country();
    country.setName(name);
    countryDAO.add(country);

    System.out.println();
    System.out.println(name
            + " has been added.\n");
}

I also have these methods in the Console class
import java.util.Scanner;

public class Console {

private static Scanner sc = new Scanner(System.in);

public static String getLine(String prompt) {
    System.out.print(prompt);
    String s = sc.nextLine();
    return s;
}

public static String getString(String prompt) {
    System.out.print(prompt);
    String s = sc.next();
    sc.nextLine();
    return s;
}
}

A: Use this to take input instead of sc.next():
String s = sc.nextLine();

and remove the next line where you have added sc.nextLine()
Hope that helps!


text:
Q: specs2 - how to use the same variable inside around and inside the test itself? I am using specs2 as my test framework.
I want to generate a uniq key that will be available in the test itself.
def around[R: AsResult](r: => R): Result = {
   val uniqueToken = before()
   try AsResult(r)(uniqueToken)
   finally after(uniqueToken)
}

"foo" should {
   "bar" in {
     do something with uniqueToken
   }
}

Couldn't find any good way to do it..
Any idea?

A: You can write this
class MySpec extends Specification with ForEach[Token] {
  "foo" should {
     "do something" in { token: Token =>
        ok
     }
  }

  def foreach[R : AsResult](f: Token => R): Result = {
    val token = createToken

    try AsResult(f(token))
    finally cleanup(token)
  }
}

This is documented here.

A: You should get the general idea from this pseudocode:
class Around[R: AsResult](r: => R) {
   val uniqueToken = before()

   try AsResult(r)(uniqueToken)
   finally after(uniqueToken)
}

"foo" should {
   "bar" in new Around(r) {
     do something with uniqueToken
   }
}


text:
Q: Client Side Redirect on Form Submission I have a cshtml page that makes a call to a controller method and passes data to that method via a jquery call on form submission as follows:
$('form').submit(function () {

    //create instance for datePicker.
    // only after control creation we can get dateObj otherwise it throws exception.
    var dateObj = $("#datepick").ejDatePicker('instance');
    var obj = dateObj.option('value')

        //$.datepicker.formatDate('dd/MM/yyyy', new Date());
    var d = new Date(2011, 10, 30);
    alert(obj);
    alert(d);

    $.ajax({
        url: '/AutoComplete/AutocompleteFeaturesNew',
        data: {
            RequestedUntilDate: obj.toISOString(),
            RoomNo: '13a'
        },
        type: 'POST',
        success: function (data) {
            alert("key is suucessfully got in controller through form submit, Key:" + data);
        }
    });
});

The controller method itself is as follows:
[HttpPost]
public JsonResult AutocompleteFeaturesNew (RequestCreateViewModel createRequestViewModel)
{
    return Json(createRequestViewModel.RequestedUntilDate);
}

What I want to be able to do is, once the form has been submitted is to re-direct the control either to a) another page b) another controller method on successful submission of the form.
So, something like:
return RedirectToAction("Index");

But on the client side.
Any suggestions?

A: You can do it only from javascript, by adding the following line to the ajax success function body:
window.location.replace("http://...");

A: Thanks for all your replies.
What I needed to do was to ensure that the $('form').submit(function () {returns false.
So:
//bind below onClick action to button
        $('form').submit(function () {
        //create instance for datePicker.
        // only after control creation we can get dateObj otherwise it throws exception.
        var dateObj = $("#datepick").ejDatePicker('instance');
        var obj = dateObj.option('value')

        //$.datepicker.formatDate('dd/MM/yyyy', new Date());
        var d = new Date(2011, 10, 30);
        alert(obj);
        alert(d);

        $.ajax({
            url: '/AutoComplete/AutocompleteFeaturesNew',
            data: {
                RequestedUntilDate: obj.toISOString(),
                RoomNo: '13a'
            },
            type: 'POST',
            dataType: 'json',
            success: function () {
                window.location.replace("http://stackoverflow.com/questions/41719249/client-side-redirect-on-form-submission?noredirect=1#comment70633597_41719249");
                }
        });
        return false;
    });

Thanks again,
Sean


text:
Q: Select Parent, Children, Children's Children, etc in single MySQL query I feel like this must be a classic problem, but I can't find the answer.
I have a table Person, which has basic details describing a person. Then, I have a ParentChildRelationship table, which looks something like this:
CREATE TABLE `ParentChildRelationship` (
    `ParentId` INT(10) UNSIGNED NOT NULL,
    `ChildId` INT(10) UNSIGNED NOT NULL,
 PRIMARY KEY(ParentId,ChildId),
 CONSTRAINT `FK_ParentRelationship`
    FOREIGN KEY (`ParentId` )
    REFERENCES `Person` (`idPerson` ),
 CONSTRAINT `FK_ChildRelationship`
    FOREIGN KEY (`ChildId` )
    REFERENCES `Person` (`idPerson` )
);

I need a select query that simply returns all Person records for the Parent and all Children down the tree.
For example, with the following data:
Parent   Child
1        3
1        8
2        4
3        5
3        6
6        9
4        7

Select all Person records where the ParentId = 1 OR ChildId is in the tree below ParentId of 1. This query should return the Person information (SELECT * FROM Person...) for the following PersonId's:
1,3,8,5,6,9
I don't know if this matters, but the order of how these are returned do not matter, as I will need to order based off of something like "LastName" or something like that. In other words, the result could also have been 1,3,5,6,9,8.

A: If you have a known limited depth, you can unroll the recursion and use a stored procedure or view.  For MySQL, the following work:
Stored Routine solution:
DELIMITER $$

CREATE PROCEDURE GetRelatedPersonsWithPersonId( IN pId VARCHAR(36))
        BEGIN
                select * from Person where idPerson in (
                        select ParentId from ParentChildRelationship where ParentId = pId
                        union
                        select ChildID from ParentChildRelationship where ParentId = pId
                        union
                        select ChildID from ParentChildRelationship where ParentId in (select ChildID from ParentChildRelationship where ParentId = pId)
                        union
                        select ChildID from ParentChildRelationship where ParentId in (select ChildID from ParentChildRelationship where ParentId in (select ChildID from ParentChildRelationship where ParentId = pId))
                ) ;

        END $$

View solution:
Create view ChildRecurse
As
Select ParentId, ChildID from ParentChildRelationship
Union
Select x1.ParentId, x2.ChildId from ParentChildRelationship x1
               Inner join ParentChildRelationship x2 on x2.ParentId = x1.ChildId
Union
Select x1.ParentId, x3.ChildId from ParentChildRelationship x1
               Inner join ParentChildRelationship x2 on x2.ParentId = x1.ChildId
               Inner join ParentChildRelationship x3 on x3.ParentId = x2.ChildId
Union
Select x1.ParentId, x4.ChildId from ParentChildRelationship x1
               Inner join ParentChildRelationship x2 on x2.ParentId = x1.ChildId
               Inner join ParentChildRelationship x3 on x3.ParentId = x2.ChildId
               Inner join ParentChildRelationship x4 on x4.ParentId = x3.ChildId

Then select as such:
select * from person where idPerson=@ID or idPerson in (select ChildId from ChildRecurse where ParentId=@ID)

A: Your data model is called the adjacency list model. You cannot do the query you are describing with that model (although a stored procedure could).
The usual way of resolving this is to change to the nested set model. The Wikipedia article has some sample code and there's a nice tutorial about it here (along with a good description of what's involved in using the adjacency list model).

A: I think this would be a job for the GROUP BY and HAVING statements.
Does something like this point you in the right direction?
SELECT * FROM ParentChildRelationship pcr
GROUP BY ParentID , ChildID
HAVING ParentID=1 OR Count(ChildID)>0

This would give you a list of parent child relations that you could join to the persons table with an INNER JOIN.


text:
Q: What targets are available for the swiftc -target and -target-cpu option? this question is about cross compilation.
What kind of different targets are available using the -target or -target-cpu option of the swift compiler?
Where can I find an overview?
Is it only there to create iOS/watchOS apps or can I use it to create linux programs (regular x86-64 processor) on macOS?
I tried searching the github repository and found 'x86_64-unknown-linux-gnu' as a target. However when I try to compile a simple "hello world" program (swiftc -target x86_64-unknown-linux-gnu test.swift) I get this error:
<unknown>:0: error: unable to load standard library for target 'x86_64-unknown-linux-gnu'

Edit:
I agree with CristiFati. The last part of this question is rather about how to properly include/reference the glibc (?!?).

A: If you look at Swift repository on Github (Exact location: swift/utils/swift_build_support/swift_build_support/targets.py) You will see all host targets at line 149-192 in target.py.
Supports:
def host_target():
    """
    Return the host target for the build machine, if it is one of
    the recognized targets. Otherwise, throw a NotImplementedError.
    """
    system = platform.system()
    machine = platform.machine()

    if system == 'Linux':
        if machine == 'x86_64':
            return StdlibDeploymentTarget.Linux.x86_64
        elif machine.startswith('armv7'):
            # linux-armv7* is canonicalized to 'linux-armv7'
            return StdlibDeploymentTarget.Linux.armv7
        elif machine.startswith('armv6'):
            # linux-armv6* is canonicalized to 'linux-armv6'
            return StdlibDeploymentTarget.Linux.armv6
        elif machine == 'aarch64':
            return StdlibDeploymentTarget.Linux.aarch64
        elif machine == 'ppc64':
            return StdlibDeploymentTarget.Linux.powerpc64
        elif machine == 'ppc64le':
            return StdlibDeploymentTarget.Linux.powerpc64le
        elif machine == 's390x':
            return StdlibDeploymentTarget.Linux.s390x

    elif system == 'Darwin':
        if machine == 'x86_64':
            return StdlibDeploymentTarget.OSX.x86_64

    elif system == 'FreeBSD':
        if machine == 'amd64':
            return StdlibDeploymentTarget.FreeBSD.x86_64

    elif system == 'CYGWIN_NT-10.0':
        if machine == 'x86_64':
            return StdlibDeploymentTarget.Cygwin.x86_64

    elif system == 'Windows':
        if machine == "AMD64":
            return StdlibDeploymentTarget.Windows.x86_64

    raise NotImplementedError('System "%s" with architecture "%s" is not '
                              'supported' % (system, machine))


text:
Q: Cannot change parameters in all treeview tables in same time - python I have several treeview tables.
After some moment I need to apply some property to all tables.
All tables are combined in dictionary, for example:
all_trees = {1: some_tree, 2: one_more_tree, 3: another_tree}

When the moment appears I need to make this type of operation to change one property in all tables:
for key in all_trees.keys():
    tree = all_trees[key]
    tree.bind("<Button-3>", lambda event: new_property(event, tree))

New property makes appearing text 'hello' after right click mouse to the row in table.
After executing this operation only the last table has the new property.
What's the problem? Why this property is not applied to all tables?
P.S: i need to make my project using python2.7, so all my code is written using old version of python
Below is a full code:
import Tkinter as tk
from ttk import Treeview, Frame
from Tkinter import Menu, LEFT, NO, YES

data_for_tables = {1: 'one', 2: 'two', 3: 'three'}
list_of_tables = [1, 2, 3]

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

def make_tree(frame):
    """creating Treeview table"""

    tree = Treeview(frame)
    tree["columns"] = ("one", "two", "three")
    tree.heading("#0", text="")
    tree.column("#0", minwidth=0, width=5, stretch=NO)
    tree.heading("one", text="Port")
    tree.column("one", minwidth=0, width=30, stretch=NO)
    tree.column("two", minwidth=0, width=60, stretch=NO)
    tree.heading("three", text="State")
    tree.column("three", minwidth=0, width=60, stretch=YES)
    tree['height'] = 3
    tree.pack(side=LEFT)
    return tree

def insert_value(info, tree):
    """Inserting values to Treeview table"""

    for key in info.keys():
        tree.insert("", "end", values=(str(key), info[key], "<><><>"))

def new_property(event, tree):
    """after right ckick mouse appears text 'hello' in console"""

    row_id = tree.identify_row(event.y)
    if row_id:
        print('hello')

global all_trees
for num in list_of_tables:
    all_trees = {num: make_tree(frame)}
    for key in all_trees.keys():
        tree = all_trees[key]
        insert_value(data_for_tables, tree)

for key in all_trees.keys():
    tree = all_trees[key]
    tree.bind("<Button-3>", lambda event: new_property(event, tree))

root.mainloop()

A: There are few issues in your code:
global all_trees   # <-- not necessary
for num in list_of_tables:
    all_trees = {num: make_tree(frame)} # <-- reset all_trees
    # below for loop is not necessary
    for key in all_trees.keys():
        tree = all_trees[key]
        insert_value(data_for_tables, tree)
# at here, all_trees has only the last item created in the above for loop

for key in all_trees.keys():
    tree = all_trees[key]
    tree.bind("<Button-3>", lambda event: new_property(event, tree))
    #                                                          ^
    # 'tree' used inside lambda will be always the last 'tree' after the for loop
    # actually this argument is not necessary

Below is sample how to fix the above issues:
def new_property(event):
    tree = event.widget
    row_id = tree.identify_row(event.y)
    if row_id:
        print('hello', tree, row_id)

all_trees = {num: make_tree(frame) for num in list_of_tables}
for tree in all_trees.values():
    insert_value(data_for_tables, tree)
    tree.bind("<Button-3>", new_property)


text:
Q: Multiple installations of Python on Mac OS - can't install pip package I'm a beginner with both mac & python and kinda messed up python installations in order to install pip.
Here is the point where i am stuck right now:
I've 3 versions of python installed - (i) pre-installed by mac OS (ii) python 3.5.1 installation from python.org (iii) python 2.7 installation by home-brew
pip was not working, till I uninstalled the brew version by this command  brew uninstall python
now pip is showing command options but not able to install packages.
Here is the screenshot of errors I'm getting, after I gave command pip install requests :
error screenshot
I checked earlier links on stack overflow here- bad python install & here- uninstalling python2.7 but can't resolve it.
guys i know i overdid while installing, but it's because pip was not getting installed. thanks a lot for helping me out !!
best

A: try this instead:
sudo pip install requests

A: If you are trying to install request for your python 3.5 installation, try using pip3 install requests
using pip will use the OSX default installation instead of installing it for 3.5