text:
Q: How can I create subsegments in AWSXRay? Objective: show errors on AWS X-ray (all errors from lambda).
'use strict';

const AWSXRay = require('aws-xray-sdk-core'),
     AWS = AWSXRay.captureAWS(require('aws-sdk')),
    env = process.env;

AWS.config.update({
    region: env.REGION
});

const dynamodbDocumentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context, callback) => {
    let seg=AWSXRay.getSegment();
    try {
        const params = {
            /*PARAMS HERE*/
          };
          let res = await dynamodbDocumentClient.scan(params).promise();
        throw('ERROR FOR TESTING');
        return res;
        //callback(null,res);

    }
    catch(err) {
        let subseg=seg.addNewSubsegment('error');
        subseg.addMetadata("error", "error", "my_error");
        subseg.addAnnotation('errr', 'this is a test');
        subseg.addError(err);
        subseg.addErrorFlag();
        subseg.close();
        console.log('==ERROR==',err);
        return err;
    }
};

When I use AWSXRay.captureAWS the subsegment 'error' doesnt show on X-ray. If I dont use captureAWS the error appear in X-ray correctly.

A: The issue is likely with how you're structuring your Lambda. First, you shouldn't be using callback in an async function handler, async function handlers should return native promises or errors per the docs.
If you want to use a callback to return the result of your function, which it seems like you do, the handler should be synchronous. That being said, you're throwing your error after the callback, which will not be reflected in X-Ray because the X-Ray segment for Lambda functions closes when the callback is called. If an error is thrown before the callback (e.g. during the DynamoDB call) it should be captured in your error subsegment.
EDIT
After the original post was edited, I was unable to reproduce the error with this code:
const AWSXRay = require('aws-xray-sdk');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));

const ddb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
    try {
        const res = await ddb.scan({TableName: 'scorekeep-game'}).promise();
        throw('Test Error');
        return result;
    } catch (e) {
        console.log('caught!');
        var sub2 = AWSXRay.getSegment().addNewSubsegment('err');
        sub2.addError(e);
        sub2.addErrorFlag();
        sub2.close();
        return e;
    }
};


text:
Q: linked list in c, unexpected results I'm new at programming and am trying to learn linked lists. I've decided to experiment with linked lists by writing a simple program that will read from a file, one character at a time, and insert each character into a linked list. Then I print the linked list out. Simple, right? Well, maybe not if it's your first time. I'm following the online tutorials oh, so carefully, but my output isn't what it's supposed to be. (The program compiles and runs with no errors or warnings. I'm using Code Blocks.) Instead of getting any characters, I get two numbers, and that's all.
Here is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Tokens_read_in{
    char character;
    int number;
    char whichOne[5];
    struct Tokens_read_in* next;
}Tokens;

int main()
{

    //declare variables
    char c;

    //create a struct for the array that will hold the tokens
    Tokens* token_array;
    token_array = malloc(sizeof(Tokens));
    token_array->next = NULL;

    //open the input file
    FILE *ifp;  //input file pointer
    char *filename = "input.txt";
    ifp = fopen(filename, "r");

    if(!ifp){
        printf("Error in opening '%s' for reading!", filename);
        exit(0);
    }

    while(!feof(ifp)){

        //prepare to read in file one character at a time
        c = getc(ifp);

        //create a struct for the current token that is read in
        Tokens* current_token = token_array;

        //let the current_token point to the beginning of token_array
        current_token = token_array;

        //let the current_token point to the LAST of token_array
        while(current_token->next != NULL){
            current_token = current_token->next;
        }

        //create a node at the end of token_array
        current_token->next = malloc(sizeof(Tokens));

        //move the current_token to the last (new) of token_array
        current_token = current_token->next;
        if(current_token == NULL){
            printf("Out of memory");
            exit(0);
        }

        //plug character into current_token
        current_token->next = NULL;
        //letter
        if(isalpha(c)){
            printf("%c", c);
            current_token->character = c;
            strcpy(current_token->whichOne, "char");
        }
        //number
        else if(isdigit(c))
        {
            printf("%d", (int)c);
            current_token->number = (int)c;
            strcpy(current_token->whichOne, "num");
        }
        //space
        //this does not need to go into the token array
        else if (c == ' '){
            printf(" ");
        }
        //newline
        //this does not need to go into the token array
        else if (c == '\n'){
            printf("\n");
        }
        //anything else
        else if ((!isdigit(c) && !isalpha(c))){
            printf("%c", c);
            current_token->character = c;
            strcpy(current_token->whichOne, "char");
        }

        //now that the current_token is plugged into token_array, free current_token
        free(current_token);

    }//end while(!feof(ifp))

    //print the token_array
    Tokens* conductor;
    conductor = token_array;
    while(conductor != NULL){
        if(strcmp(conductor->whichOne, "num")){
            printf("%d ", conductor->number);
        }
        else if(strcmp(conductor->whichOne, "char")){
            printf("%c ", conductor->character);
        }
        conductor = conductor->next;
    }
    //done printing, so free conductor
    free(conductor);

    //done with program, so free token_array
    free(token_array);

    //close input file
    fclose(ifp);

    return 0;
}//end main

And here is the input file I'm using (named input.txt):
<I don't know why every beginner program says hello world,
but hello world anyway.>

I really appreciate anyone who looks at this and points me into the right direction.

A: You should not free current_token at the end of your read loop. This will cause problems, because you are freeing memory of a node that is inside your linked list.
Also, as a side note, isdigit succeeds when given a character that represents a digits, so character '1' for instance. You should still be using %c to print this out, because %d will give you the ascii number for character '1'.

A: You need if (strcmp(a,b)==0) to test for equality.

A: *

*You absolutely do not want to free(current_token).

*If you want to convert a char to an int, a simple way (in ASCII) to do that is:

    char c = '3';
    int i = c - '0';
    printf("As a char: %c\n", c); // Prints 3.
    printf("As an int: %d\n", i); // Prints 3.

*

*When you malloc data, it is possible and likely that there will be random data in that region. You should clear your entire struct once you malloc it with a memset.

*As mentioned in other answers, strcmp returns 0 on a match. That means that you are doing the inverse of the comparison that you want.

*The data in your struct is quite odd when the character is a space or newline. This is because the data starts in an undetermined state.

If you fix the above errors (excluding the memset), The output from your program is much more like what you want.

A: strcmp returns zero when two string are equal
http://pubs.opengroup.org/onlinepubs/007904875/functions/strcmp.html
and presumably you want to avoid the eof character.
in line 99 you want
conductor = (token_array->next);

instead of
conductor = token_array;

A: //now that the current_token is plugged into token_array, free current_token
        free(current_token);

    }//end while(!feof(ifp))

Try commenting the call to free(current_token);
The job of malloc and free are to keep track of what memory has been allocated. When you call free, the next malloc call may be sending you back the same memory address you just used.
Additionally
//create a struct for the current token that is read in
Tokens* current_token = token_array;

//let the current_token point to the beginning of token_array
current_token = token_array;

The second assignment is redundant. Not a bug (yet), but just a note for a new programmer.
Also, let us know what numbers you are getting. Getting numbers instead of characters can sometimes indicate you are outputting ASCII codes instead of the characters themselves.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Database.SaveResult.getId() returns null I'm trying to update an account list and I need to get the Ids when the update fails.
I use the getId() method but for accounts which fail I get null.
It's an update so my account already has an Id.
Is it normal ? If it is, how can I get the Ids list of non-updated accounts ?
Here is my code :
List<Account> accountsList = [select Id from Account];

for(Account a : accountsList) {
    a.Name = 'Test',
}

List<Database.SaveResult> res = Database.update(accountsList, false);

for (Database.SaveResult s : res) {
    if (!s.isSuccess()) {
        system.debug(s.getId()); // I get null here
     }
}

A: See the SaveResult class docs: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database_saveresult.htm
and the example use:
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

The docs say that the getId() method only returns on success.

If this field contains a value, the object was successfully inserted
  or updated. If this field is empty, the operation was not successful
  for that object.

A: You can match the updated records with the Database.SaveResults using a list iterator, which will give you access to the original record:
List<Account> accountsList = [select Id from Account];

for(Account a : accountsList) {
    a.Name = 'Test',
}

List<Database.SaveResult> res = Database.update(accountsList, false);

//for (Database.SaveResult s : res) { //replaced by the following line
for (Integer i = 0; i < accountsList.size(); i++) {
    Database.SaveResult s = res[i];
    Account origRecord = accountsList[i];
    if (!s.isSuccess()) {
        system.debug(s.getId()); // I get null here
        system.debug(origRecord.Id); //This should be the Id you're looking for
     }
}


text:
Q: CCPoint to float conversion What I'm trying to do : Have the coordinates of where i touch the screen put into 2 floats, x and y.
What I understand is that to get the coordinate of where I'm touching I should be using getLocation(). So I wrote a small piece of code :
CCTouch *pTouch;
CCPoint *xy = pTouch->getLocation();

How I understand it (Which could quite possibly be wrong), this should have the variable xy set to equal the opengl coordinates of where the screen was touched. IF this is the case, how would I convert this CCPoint variable into a float or two(x and y float values)?

A: Here's what you can do. In the init() function of your scene class add the call
setTouchEnabled( true );

to tell cocos2d-x to tell you about touch events by calling ccTouchBegan, ccTouchMoved, ccTouchCancelled and ccTouchEnded on the scene as appropriate. Now, when these functions are called you get passed a
cocos2d::CCTouch *touch

which you can use to get the touch coordinates. What I do in my game is
CCPoint p = touch->getLocationInView();
p = CCDirector::sharedDirector()->convertToGL(p);

and p will contain the coordinates of the touch. You can get the float values of the x and y coordinates of the touch by doing
float x = p.x;
float y = p.y;

Hope that helps. :)

A: Try this:
float x,y;
x = *xy->x;
y = *xy->y;

PS: Using getLocationInView() is more recommended since this function will return location in screen coordinates, which is what cocos2d-x mainly used. You don't need to translate OpenGL coordinates to screen coordinates later.
Read:
http://www.cocos2d-x.org/reference/native-cpp/de/d9b/classcocos2d_1_1_c_c_touch.html


text:
Q: I keep getting the wrong output I've created a userAgent sniffing javascript application (for experimental/learning purposes only) and I'm almost finished. But, for the $browser.version, I'm getting the whole userAgent string. I've google'd and google'd and cannot find the answer. Here's my code:
// contemplate new $browser module
var $browser, versionOffset, ua = navigator.userAgent;

if(ua.toLowerCase().indexOf('opera') > -1) {
    $browser = {
        name: "Opera",
        engine: "Presto",
        prefix: "-o-",
        publisher: "Opera Software ASA",
        version: ua.substring(versionOffset + 6)
    }
}

else if(ua.toLowerCase().indexOf('msie') > -1) {
        $browser = {
        name: "Internet Explorer",
        engine: "Trident",
        prefix: "-ms-",
        publisher: "Microsoft",
        version: ua.substring(versionOffset + 5)
    }
}

else if(ua.toLowerCase().indexOf('chrome') > -1) {
    $browser = {
        name: "Chrome",
        engine: "WebKit",
        prefix: "-webkit-",
        publisher: "Google Inc.",
        version: ua.substring(versionOffset + 7)
    }
}

else if(ua.toLowerCase().indexOf('safari') > -1) {
    $browser = {
        name: "Safari",
        engine: "WebKit",
        prefix: "-webkit-",
        publisher: "Apple Computer Inc.",
        version: ua.substring(versionOffset + 8)
    }
}

else if(ua.toLowerCase().indexOf('firefox') > -1) {
    $browser = {
        name: "Firefox",
        engine: "Gecko",
        prefix: "-moz-",
        publisher: "Mozilla",
        version: ua.substring(versionOffset + 8)
    }
}

So in my HTML, I'm doing:
<script>
    alert($browser.name + " " + $browser.version);
</script>

But my output in chrome is:

[JavaScript Alert]:
Chrome ($browser.name)
 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.91 Safari/537.4 ($browser.version)

But I want, obviously "Chrome 22" or "Chrome 22.0.1229.91"

A: This fixes it - 2digit version number returned.
You need to set the versionOffset, as has already been mentioned.
else if(ua.toLowerCase().indexOf('chrome') > -1)
{
    versionOffset = ua.toLowerCase().indexOf('chrome');

    $browser = {
        name: "Chrome",
        engine: "WebKit",
        prefix: "-webkit-",
        publisher: "Google Inc.",
        version: ua.substr(versionOffset+7, 2)
    }
}

A: Your code doesn't make much sense to me as it stands. You have to use things like versionOFfset, etc. Also, note that doing something like this: ua.substring(versionOffset + 8) will return the entire string starting from versionOffset+8. So, since you never actually SET versionOffset, it it is undefined, so doing: versionOffset+8 returns NaN, JS helpfully ignores that and decides to just substitute a zero for NaN (basically), so you end up with the entire ua string being returned. Here's a fiddle that may be closer to what you're looking for:
http://jsfiddle.net/WFEZW/
else if((versionOffset = ua.toLowerCase().indexOf('chrome')) > -1) {
    $browser = {
        name: "Chrome",
        engine: "WebKit",
        prefix: "-webkit-",
        publisher: "Google Inc.",
        version: ua.substring(versionOffset + 7).substring(0, ua.indexOf(" "))
    }
}

See how I set versionOffset in the if statement, and then I look for the first " " after the version. This is NOT meant to be used in the real world, but like you said, you're just trying to learn.


text:
Q: display update and cancel button after clicking edit button we have marketplace site, where each seller/vendor have their own account. they can see list of products. sku ,qty in their account.
now its displaying like this : image 1 =http://prnt.sc/8wm25g
if i click on cancel button , than its displaying like this : http://prnt.sc/8wm2fv
what i need is :
a)if we click on edit button, than only "Update" & "cancel" button should visible and "Edit" button should hide.
b)Later if we click on "cancel" button, than "Update & cancel" button should hide and "Edit" button should visible.
<?php echo (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($products)->getQty(); ?>
      <input type = "text" id = "qty_<?php echo $products->getId(); ?>" name = "qty" value = "<?php echo (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($products)->getQty(); ?>" style = "display:none"/>

    <span class="label wk_action" id="edit_link_<?php echo $products->getId(); ?>">
            <img onclick="showField('<?php echo $products->getId(); ?>'); return false;" src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?>"/>

        <button id="update_button_<?php echo $products->getId(); ?>" class="button wk_mp_btn1" onclick="updateField('<?php echo $products->getId(); ?>'); return false;" >
            <?php echo $helper->__('Update') ?>
        </button>

        <button id="reset_button_<?php echo $products->getId(); ?>" type="reset" class="cancel" onclick="hideReset('<?php echo $products->getId(); ?>'); return false;">
            <?php echo $helper->__('Cancel') ?>
        </button>


text:
Q: How can I scale a drawing from an HTML canvas and copy it to another canvas? If I draw something on my canvas I would like to press save and then on save scale the image of the drawing to fit a smaller canvas in another part of the page. I think it would have something to do with the base64 src of the drawing but I'm not entirely sure how it could be done.
Suppose if the original canvas I drew on was 600px by 400px and the smaller canvas was 300px by 150px when what would the code look like?

A: Since the two canvases have different aspect ratios, I would use the following syntax:
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
In this cases sx, sy, sWidth and sHeight specify which part of the original canvas should be copied, while dx, dy, dWidth and dHeight specify which part of the canvas they should be rendered on.

const canvas1 = document.getElementById("c");
const ctx1 = canvas1.getContext("2d");

ctx1.beginPath()
ctx1.arc(125,125,100,0,2*Math.PI);
ctx1.stroke()

const canvas2 = document.getElementById("c1");
const ctx2 = canvas2.getContext("2d");

ctx2.drawImage(canvas1,0,0,600,400,0,0,300,150);
canvas{border:1px solid}
<canvas id="c" width="600" height="400"></canvas>
<canvas id="c1" width="300" height="150"></canvas>


text:
Q: Javascript - Streaming Audio On The Fly (Web Audio API & XHR) I have a simple xmlhttprequest running for fetching an audio file, when it's done fetching it decodes the audio and plays it.
        var xhr = new XMLHttpRequest();
        xhr.open('GET', /some url/, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function() {
            decode(xhr.response);
        }.bind(this);
        xhr.send(null);

The problem with this however, is that the file decodes only after the request is loaded/finished downloading. Is there an approach for streaming audio without having to wait for it to finish downloading?, without the usage of <audio> tags

A: You still need HTML5 Audio object but instead of using it directly and playing with it you can use use MediaElementAudioSourceNode along with Audio element to take advantage of Web API.
Excerpt from here

Rather than going the usual path of loading a sound directly by
  issuing an XMLHttpRe quest and then decoding the buffer, you can use
  the media stream audio source node (MediaElementAudioSourceNode) to
  create nodes that behave much like audio source nodes
  (AudioSourceNode), but wrap an existing  tag. Once we have this
  node connected to our audio graph, we can use our knowledge of the Web
  Audio API to do great things. This small example applies a low-pass
  filter to the  tag:

Sample Code:
window.addEventListener('load', onLoad, false);

function onLoad() {
 var audio = new Audio();
 source = context.createMediaElementSource(audio);

 var filter = context.createBiquadFilter();
 filter.type = filter.LOWPASS;
 filter.frequency.value = 440;

 source.connect(this.filter);
 filter.connect(context.destination);

 audio.src = 'http://example.com/the.mp3';
 audio.play();
}


text:
Q: Getting class cast exception where both classes are exactly the same I am doing a JBoss SEAM project and when I view a form I get this error.
java.lang.ClassCastException:
it.cogitoweb.csi.entity.csiorelav.CsiTipoLav cannot be cast to
it.cogitoweb.csi.entity.csiorelav.CsiTipoLav

Its alway the same JPA class which is related to the form which is shown on the screen, it doesn't make sense to me why is it the same class, it seems impossible.

A: As Joachim explained earlier, java.lang.ClassCastException typically occurs when two classloaders load the classes with the same name. However, i have come across another situation when this could occur.
This could occur with some IDE's that automatically reloads classes that have been modified. In such cases there might be older versions of the class retained in memory causing ClassCastException.
Here are a few ways you could resolve this issue :

*

*If you are writing a custom class loader, while loading a class make sure that the base/default class loader does not already have an instance of that class loaded.

*Make the class being loaded a sub-class of the class that is already loaded by the default class loader.

*Make the class being loaded implement an interface that is already loaded by the default class loader.
More info here - http://www.jspwiki.org/wiki/A2AClassCastException

A: This is because the class has been loaded by two different classloaders. You cannot cast between them.
You've likely got a duplicate copy of CsiTipoLav in your application, and the two different copies are being loaded at different times from different classloaders. JBoss has a plethora of different classloaders in a hierarchy, and it's easy to get things in a twist.
Make sure you only have one copy of the class.

A: This happens when two different ClassLoader objects load classes with the same name. The equality of two classes in Java depends on the fully qualified name and the class loader that loaded it.
So if two independent class loaders load classes from the same location, then objects of those types will not be able to be cast to each others type, even if their classes are called the same.

A: The object you are trying to cast, is loaded by a different classloader than the one which has loaded the class you are trying to cast into.

A: In my case i had two different *.ear and wanted to load a class from the other.
So i had to isolate the classloader. I used this description:
http://www.thorgull.be/wiki/index.php?title=ClassLoader_isolation_in_JBOSS
It worked for me.


text:
Q: Where are kubelet logs in AKS stored? I would like to view kubelet logs going back in time in Azure AKS. All I could find from Azure docs was how to ssh into the nodes and list the logs (https://learn.microsoft.com/en-us/azure/aks/kubelet-logs) but I feel like this has to be aggregated in Log Analytics somewhere right ?
However I wasn't able to find anything in Log Analytics for Kubernetes. Am I missing something ?
We have omsagent daemonset installed and Microsoft.OperationalInsights/workspaces is enabled
Thanks :)

A: I tried to reproduce this issue in my environment and got below results:
I created resource group and VM by setting up the Subscription
az account set --subscription "subscription_name"
az group create --location westus resourcegroup_name

*

*created the AKS Cluster with the parameter to enable the AKS Container Insights

*The following Example will creates the Cluster with name AKSRG.

az aks create -g myResourceGroup -n resourceGroup_name --enable-managed-identity --node-count 1 --enable-addons monitoring --enable-msi-auth-for-monitoring  --generate-ssh-keys

*

*Here I have configured the kubectl to connect the kubernetes cluster with the get-credentials command

I have created the interactive shell connection to the node
using kubectl debug
kubectl debug node/pod_name -it --image=mcr.microsoft.com/dotnet/runtime-deps:6.0

I have used the below Command in after hash(#) tag
journalctl -u kubelet -o cat

To get the logs check the nodes and pods

We can use the below command to check the KUBE LOGS
kubectl logs pod_name

Reference:
View kubelet logs in Azure Kubernetes Service (AKS) - Azure Kubernetes Service | Microsoft Docs


text:
Q: Is there a multi-directory DirectoryCatalog available in MEF or open source? I'd like to separate extensions into their own subdirectory of some Extensions directory. I can specify multiple DirectoryCatalog of course and put them into an AggregateCatalog. But I have to go scan that directory and create those. Not a big deal, but is there something like MultiDirectoryCatalog out there?

A: Nope the best you will be able to do is an AggregateCatalog with a multiple DirectoryCatalogs. At least with what ships in the .NET Framework itself.


text:
Q: Split columns once a group of numbers is repeated I need help with data processing. I have data columns (force and displacement) for a piston-like mechanism. The data output has the values for 3 strokes which is initial height, bottom, back to initial height (1 stroke) then 2 more strokes. I need help splitting the columns into 3, force and displacement for each stroke. Which makes it harder is that there is some error in the force sensor,  so the second time the piston goes back to initial height, it is not the exact same a the as the initial position.
This is what I have so far.
TestData= csvread(fileName, 1, 0);
%add height of piston stop
AdjHeight= TestData(:,2)+ height;
%Concatenate new column of the adjusted heights with 2 columns of raw
%data
NewPistonData=horzcat(TestData,AdjHeight);
%column headers

% Locate the zeros in the 4th column
index = find(NewPistonData(:,1)==0);

Picture of simplified data example, actual data is in the magnitude of hundreds of points per sec:

In the code line
    index = find(NewPistonData(:,1)==100);
I get a column of where I there is 100, but I am stuck in the logic. How do I tell matlab to split columns every time one stroke has been performed


text:
Q: On periods of symmetric algebras Let $A$ be a symmetric finite dimensional algebra over a field of characteristic two (or even over the field with two elements) such that every simple $A$-module has the same period equal to $n$.

Question: Is the period of the algebra $A$ also equal to $n$?

This is not true in other characteristics, but I am not aware of an example in characteristic two, but there probably is one out there.


text:
Q: Selecting from a dropdown which then can be used at an WHERE later? I am aware this is the old MySQL driver, not MySQLi or PDO. I am wanting to finish my web site using what I know and then going to ask some lovely person to convert it for me for a price.
I have an entry form. The first dropdown is Select Event which pulls data from the database. Code below:
 Select Event:

        <select name="event" id="event">
          <?php
            $query = mysql_query("SELECT * FROM skiptonevents ORDER BY id ASC");
            echo "<option value=\"\">Please select one...</option>";
            while($result = mysql_fetch_array($query)){
              echo "<option value=\"" . $result['name'] . "\">" . $result['name'] . "</option>";
            }
            ?>
        </select>
      Please select an event.

Once the person has selected which event they want they continue to fill out the remainder of the form with their personal details.
At the bottom of the form there is "Payment: 'dropdown'"
Code:

      <select name="amount" id="amount">
          <?php
            $query = mysql_query("SELECT * FROM skiptonevents WHERE name = '". $event . "' ");
            echo "<option value=\"\">Please select one...</option>";
            while($result2 = mysql_fetch_array($query)){
              echo "<option value=\"" . $result2['quote'] . "\">" . $result2['quote'] . "</option>";
            }
            ?>
        </select>

As you can see I have added WHERE '" . $event . "' which is the dropdown at the tops 'ID'. This does not work. So when the WHERE matches what has been selected at the top it will show the quote from the database for that event.
How can I fix this problem?

A: The data that comes from the <form> is placed in an array for you to use and not ( unless you are using a very old PHP and still have safe_mode turned on) in a variable. And even if it is you should use the arrays or your code will not port to a newer version of PHP
The arrays are $_GET and $_POST, depending on the method attribute you use <form method="get"> or <form method="post">
So assuming your using method="post" amend your query like so
$query = mysql_query("SELECT *
                      FROM skiptonevents
                      WHERE name = '{$_POST['event']}'");

You should really validate/sanitize the $_POST['event'] before you use it as it came from an untrusted source.
You should also look at changing from using the mysql_ extensions to mysqli_ or PDO as the mysql_ extensions are deprecated and have been removed from PHP7, which is soon to be released.


text:
Q: Examples of semi-complements A semi-complement (for the purpose of this question) on a poset $P$ is an involution (self-inverse w.r.t. to composition) $\neg : P\to P$, such that:
$$\neg\left(\bigvee_{i\in I} x_i\right) = \bigwedge_{i\in I} \neg x_i$$
 $$\neg\left(\bigwedge_{i\in I} x_i\right) = \bigvee_{i\in I} \neg x_i$$
whenever these suprema / infima exist.
Obviously every Boolean algebra has a semi-complement. Here are some examples, where $P$ is not a Boolean algebra:

*

*the poset $[0\,..\infty]$ with $\neg x := 1/x$, where $\neg 0 = \infty$.

*using the previous example: the poset of functions $X\to [0\,..\infty]$ with $\neg f = 1/f$

*the poset of measurable functions $E \to [0\,..\infty]$ for some measurable space $(E,\mathcal{E})$ with $\neg f = 1/f$

*the "Cheng space construction": Let $L$ be a Heyting algebra and let:
$$P := \{(x,y) \in L \times L^{\operatorname{op}} : x\wedge y =\bot\}$$ Then, let $\neg(x,y) = (y,x)$. (I believe this should work possibly with some tweaking, inspired by this)

What other examples are there of semi-complements?

A: Generalizing your examples: they are related to lattice ordered groups, where the involution is $x\mapsto x ^ {-1}$. It's not hard to prove that in any lattice ordered group, $x\mapsto x ^ {-1}$ meets your criteria yet the lattice is not Boolean (l-groups cannot be bounded, for one thing).
This generates wide variety of examples, e.g. $G =(\mathbb Q ^ n, +)$. Or a more exotic one: consider some totally ordered set $\Omega$ and let $G$ be the group of all order preserving automorphisms on $\Omega$ where we define $f\leq g\equiv\forall x: f(x)\leq g(x)$.
Here's an interesting question: suppose we are working with an l-group and some function $x\mapsto x ^*$ meets your criteria. Must $x ^*= x ^ {-1}$? I think the answer is "yes", but I am not sure.
EDIT: answering your comment from below.
I agree that $0,\infty$ are problematic in your first example. I think the most obvious way to relate them to a group is to just drop the problematic elements and look at $(\mathbb R ^ +,\cdot)$, but you could try something like the hyperreal numbers instead. In any case, let's assume you have figure out some way to handle this – then I claim your second example can handle its problematic elements in the same way. Let's say your first example is some group $G$.
Observe that in the case that $| X | = 1$ your second example is exactly the same as the first (do you see why?). More generally, once you handle $0$ and $\infty$ there's a natural isomorphism between your second example and $G ^ {| X |}$ under component-wise multiplication given by $\varphi (f) = (f(x_0), f(x_1),\dots)$. (I.e. your second example is just the direct product of the first example some number of times.)
So, to elaborate on your (correct) point that there are more than 2 problematic elements: if $X =\{1, 2\}$, there are an infinite number of  functions $f_z$ where $f_z(1) = 0, f_z(2) = z$. But clearly $\neg f_z(1) =\neg 0$, where $\neg 0$ is whatever you defined the inverse to be in your first example.
This is why, even though there are an infinite number of elements "without inverses", you only need to handle the two cases from your first example.


text:
Q: If $m^*(E)$ > $0$ then there exists a bounded subset $K$ of $E$ s.t $m^*(K) > 0$ If $m^*(E)$ > $0$ then there exists a bounded subset $K$ of $E$ s.t $m^*(K) > 0$
Since $m^*(E)$ = inf{$\sum_{k=1} ^\infty l(I_k) | E \subset \cup_{k=1}^\infty I_k$} s.t $I_k$ :open sets.
Set $\cup_{k=n}^\infty I_k$
Then for some m, $\cup_{k=m}^\infty I_k$ $\subset E$
Set K=$\cup_{k=m}^\infty I_k$ then it is done.
Did I prove appropriately? If not, what is worng?

A: Since $$\mathbb{R}^d = \bigcup \limits_{n=1}^\infty B(0,n),$$
we have
$$E= \bigcup \limits_{n=1}^\infty \left( B(0,n) \cap E \right),$$
and by countable subadditivity of $m^*$
$$m^*(E) \leq \sum \limits_{i=1}^\infty m^*(B(0,n) \cap E ).$$
Since $m^*(E) > 0$, an element of the series has to be nonzero. This element corresponds to a bounded subset of $E$ that has nonzero measure.


text:
Q: Mouse clicks stop working shortly after login I am not sure if this is the right place to ask this but I am really out of ideas:
When I log in (Windows 10), my mouse works fine for a short duration. Then this sound appears when you plug in a device, like an USB stick, and I cannot click anymore. This affects left, right and middle click, but not the movement of the mouse or the scroll wheel.
I already tried

*

*Rebooting

*Unplugging and plugging it back in

*Plugin it into a different port

*Uninstalling the device and rebooting

*sfc /scannow . This finds no problems.

*Creating a new user profile. The problem disappears under the new user, but persists under the old one.

*Booting in safe mode. The problem disappears

There are articles on the internet that the user profile might be corrupted, which sounds reasonable to me as the problem only exists under one user profile, but I have no idea how to fix this.

A: Ok, I found a solution, although I don't fully understand the problem. Uninstalling the "Logitech Gaming Software" fixed the problem. While uninstalling the sound indicating a disconnected device appeared, so this seems to match.
For verification purposes, I reinstalled it, and the problem started again, but only under the same user as before. My guess is that some sort of profile got corrupted, that was not deleted during installation and that is only present for one user.


text:
Q: Анимация не проигрывается повторно android Есть анимация и я хочу что бы она проигрывалась каждый раз по нажатию на кнопку, но она проигрывается только при первом нажатии. Что я делаю неправильно?
mButtonNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mButtonNext.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.button_next_anim));
        }
});

anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
>

<translate
    android:fromXDelta="0"
    android:toXDelta="100"
    android:duration="100"
    />

</set>

my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackgroundGrey"
android:orientation="vertical">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/header_button_shape_baground"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        />

</android.support.design.widget.AppBarLayout>

<util.CustomViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/appBarLayout"
    android:layout_alignParentBottom="true" />

<LinearLayout
    android:id="@+id/button_next_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    >
    <Button
        android:id="@+id/btnNext"
        android:layout_width="match_parent"
        android:layout_height="@dimen/button_next_height"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="@dimen/default_marginRight"
        android:background="@drawable/button_next_word_rectangle"
        android:text="СЛЕДУЮЩЕЕ СЛОВО"
        android:textSize="@dimen/button_next_font_size"
        android:textColor="@color/colorFontBlue"
        android:gravity="center"
        />

</LinearLayout>

</RelativeLayout>

A: metalurgus намекает Вам, что вы забыли указать проценты:
<translate
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:duration="100"
    />

Попробуйте после воспроизведения анимации чистить её
mButtonNext.clearAnimation();

A: Не знаю, в чем у вас ошибка. У меня в таком варианте все отлично работает - при нажатии кнопка смещается вправо, возвращается назад. При следующем нажатии все повторяется:
    animButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.animation);
            v.startAnimation(animation);
        }
    });

res/anim/animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="100"
    android:duration="100" />


text:
Q: filter messages from certain groups and redirect it to a chat in my telegram? I am getting to know the telegram api and I am trying to filter messages from certain groups to redirect the message to a chat if I find a match in the text.
for now I just need that when they write to me from certain groups it captures the message and then I can redirect that message.
this is my current code, what am I doing wrong?
messages are not triggered
const TelegramBot = require("node-telegram-bot-api");

// replace the value below with the Telegram token you receive from @BotFather
const token = "MI_TOKEN";

const bot = new TelegramBot(token, {
  polling: true,
  chats: ["ID_GROUP_1", "ID_GROUP_2", "ID_GROUP_3", "ID_GROUP_4"],
});

// Listen for any kind of message. There are different kinds of
bot.on("message", (msg) => {
  const chatId = msg.chat.id;
  // send a message to the chat acknowledging receipt of their message
  bot.sendMessage("ID_MY_CHAT_BOT", msg.text);
});


text:
Q: Using @auth owner directive with Auth.federatedSignIn() in Amplify/Cognito I am building an app using Ionic, Capacitor and AWS Amplify. I am having some issues
I have set up federated sign-in for my app using the capacitor plugin https://github.com/capacitor-community/facebook-login and call Auth.federatedSignIn() as per the below. This logs my user in with a federated identity. This is great, but it means I cannot use @auth(rules: [{ allow: owner }]) in my graphql schema. Is there any way to create a user in the userpool when calling Auth.federatedSignIn()? I know that calling Auth.federatedSignIn({ provider: "Facebook" }) and using the hosted UI works like this, but I do not want to redirect my user to a browser/chrome tab to sign in. I would like the authentication to be provided by the native functionality provided by the above capacitor plugin.
Using the federated identity allows me to restrict access to my graphql schema using IAM: @auth(rules: [{ allow: private, provider: iam }]) but this is limited to private and public rules. I want to limit the graphql api so that users can see only their own entries with functionality like @auth(rules: [{ allow: owner }]).
Maybe I am going about this the wrong way? I'm stumped. Any help is appreciated. Thanks.
const FBLogIn = async () => {
    const result = await FacebookLogin.login({ permissions: FACEBOOK_PERMISSIONS });
    const { email } = await FacebookLogin.getProfile({ fields: ['email'] });

    try {
      const userDetails = await Auth.federatedSignIn("facebook", { token: result.accessToken.token, expires_at: result.accessToken.expires }, { name: result.accessToken.userId, email: email })

    } catch (error) {
      console.log(error)
    }
  }


text:
Q: Bcp out - order and locking I wanted to understand a bit more about the order in which data is exported using bcp out command. It's written in some places that it returns values in index order, but what if there is no index on the table?(1) I understand that if we want data to be in a particular order we should use the ORDER BY clause in bcp queryout but what about bcp out?(2) If there is no particular order for bcp out then how are batches defined while writing to a file. Internal architecture says that it does a simple select * on the table. If this is the case then is it that in bcp, select * just streams data and then data is divided into batches just for the sake of writing to a file?(3)
Also, while doing bcp out, is the lock acquired on the whole table or just the batch?(4) There is a TABLOCK option but that can be used only during bulk import of data. Is it that bcp is just a client doing select * on the table and it will follow the locking principles of whatever isolation level we set for the transaction?(5) Here, it is said that bcp cannot be used with snapshot isolation, can someone please explain the reason more clearly?(6)
Is there any article explaining bcp internal architecture in more detail with ordering and locking of rows.
There are many articles with related questions for bcp import but couldn't find much on bcp export and hence asking here.
Thanks

A:
order in which data is exported using bcp out command

Without an ORDER BY column in a query the order is undocumented and plan-dependent.  If you care, use the queryout option and an ORDER BY clause includes some key.

bcp is just a client doing select * on the table

Yes.  Nothing special.  You can use Profiler if you want to see what it's doing.


text:
Q: Is it possible to make a rolling randomForest reproducible? I have the following randomForest loop:
require(randomForest)
require(xts)
require(quantmod)
getSymbols("MSFT", from = '2017-01-01', to = '2017-09-13', src = "yahoo")
rets <- diff(log(Ad(MSFT))); rets[is.na(rets)]=0
rets1 <- ifelse(rets>0,"up","dn")
Lag1 <- lag(rets,1);Lag1[is.na(Lag1)]=0;Lag1 <- ifelse(Lag1>0,"up","dn")
Lag2 <- lag(rets,2);Lag2[is.na(Lag2)]=0;Lag2 <- ifelse(Lag2>0,"up","dn")
Lag3 <- lag(rets,3);Lag3[is.na(Lag3)]=0;Lag3 <- ifelse(Lag3>0,"up","dn")
preds <- rets* 0
win=20

for(i in win:(NROW(rets)-1)){
    RFDataf <- data.frame(factor(Lag1),factor(Lag2),factor(Lag3))
    fit <- try(randomForest(RFDataf[(i-win+1):i,], factor(as.character(rets1[(i-win+1):i])), ntree=1000, mtry=round(sqrt(NCOL(RFDataf)),0)))
    if(class(fit) != "try-error"){
        fit0 <- fit
        preds[(i+1)] <- predict(fit, RFDataf[(i+1),])
    }else{
        if(exists("fit0")){
            preds[(i+1)] <- predict(fit0, RFDataf[(i+1),])}else{next}
        }
    }
}

I read these carefully:
https://stats.stackexchange.com/questions/120446/different-results-from-several-passes-of-random-forest-on-same-dataset
https://github.com/mlr-org/mlr/issues/938
I understand that if in the R function is used a different language, set.seed() won't work.
I have the additional problem of a loop.
If I used a function with no foreign languages but r in a loop, how could I preserve the reproducibility?
Is there a way to make set.seed() work in a loop? Any alternative solution?


text:
Q: Return Different Types Within One Function C# I am creating a project data pipeline and I need to return different types from a single class
in this class I have a number of Dictionaries that hold and separate the elements/content i want to load up but i need a way to return them with a single string... as i am not to familiar with these Type functions i am lost as to how to return the content properly
I need this in a separate class so i can do a XML serialization later
Here is what I have now
DataClass contents;
public T ReturnType<T>(string asset)
{
    if(typeof(T) == typeof(int))
    {
        return contents.Integers[Asset];
    }
    if(typeof(T) == typeof(float))
    {
        return contents.Floats[Asset];
    }
    if(typeof(T) == typeof(double))
    {
        return contents.Doubles[Asset];
    }
    return default(T);
}

it will allow me to use a base Object class to parse the content but i dont want anything to get lost in transit so i am weary in using this method
my question is how to return one of the different objects of a certain types within the class that i am using for serialization with a function like that
If i wanted to use the previous function to grab content within the class eg
public Object someobject;
//button event handler to change the current object
//preferably this would be changed depending on the object i would be calling
//but this should do for showing how it is supposed to work
public void ChangeCurrentObject(event e)
{
    someobject = (Object)ReturnType<Object>("23rdObject");
}

it sends a string to the function called 'ReturnType' and returns an object ie(int, float,etc) within there own respective dictionary

A: The generics in this case will only help you not to write diferent method for every asset type. You can also use this aproach to make it more modular.
     static  class Assets
    {
        public interface IAssetHandler<out T>
        {
            T GetAsset(string name);
        }

        private static readonly Dictionary<Type,object> _handlers=new Dictionary<Type, object>();

        public static T GetAsset<T>(string name)
        {

            object assetHandler;

            if(!_handlers.TryGetValue(typeof(T),out assetHandler))
            {
              throw  new Exception("No handler for that type of asset");
            }

            return (assetHandler as IAssetHandler<T>).GetAsset(name);

        }

        public static void RegisterAssetHandler<T>(IAssetHandler<T> handler)
        {
            _handlers[typeof (T)] = handler;
        }

    }

 public class IntAssetsHandler:Assets.IAssetHandler<int>
        {
            #region Implementation of IAssetHandler<out int>

            public int GetAsset(string name)
            {
                return 0;
            }

            #endregion
        }

        static void Main(string[] args)
        {
            Assets.RegisterAssetHandler(new IntAssetsHandler());

            Console.WriteLine(Assets.GetAsset<int>("test"));

        }

A: You could use external class, set the properties types as you wish, then use it in your function.
public class MultipleOpjects
{
    public List<string> ObjectOne { get; set; }

    public List<object> ObjectTwo { get; set; }

    public object ObjectThree { get; set; }

}
public MultipleOpjects GetAnything()
{
    MultipleOpjects Vrble = new MultipleOpjects();
    Vrble.ObjectOne  = SomeThing1;
    Vrble.ObjectTwo = SomeThing2;
    Vrble.ObjectThree = SomeThing3;

    return Vrble;
}


text:
Q: How to change an UIView size according to its content? So I have a checkbox and a label, I put them together within a UIView so I can use the checkbox and label as one component later on and for other projects, the thing is  I want the view to change size (specifically width) according to the label text length. So far I can only seem to get this. The red part is a UIStackView containing the Checkbox and the label, the blue part is the UIView Class containing the stackView. What can I do to modify the Views size to match the Stackviews size, so if the label gets shorter so will the View. Thanks in advance!

A: You need to use constraints. In this instance, you want the UIStackView to have constraint anchors each with a set value of zero for each side of the blue UIView - this will fill the blue UIView with the UIStackView.
Assuming that you will want the checkbox to remain the same size, you can set a width and height constraint, with a leading constraint of 0 to the left edge of the UIStackView.
Lastly, give the label constraints of 0 for the top and bottom edges of the UIStackView, and some number value for the leading and trailing constraints so that is has a bit of padding on either side of it (away from checkbox and right edge).
UIStackView Constraints
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: blueView.topAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: blueView.bottomAnchor, constant: 0).isActive = true
stackView.leadingAnchor.constraint(equalTo: blueView.leadingAnchor, constant: 0).isActive = true
stackView.trailingAnchor.constraint(equalTo: blueView.trailingAnchor, constant: 0).isActive = true

CheckBox Constraints
checkBox.translatesAutoresizingMaskIntoConstraints = false
checkBox.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 0).isActive = true
checkBox.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 0).isActive = true
checkBox.heightAnchor.constraint(equalToConstant: given_height).isActive = true
checkBox.widthAnchor.constraint(equalToConstant: given_width).isActive = true

Label Constraints
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 0).isActive = true
label.bottomAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 0).isActive = true
label.leadingAnchor.constraint(equalTo: checkBox.trailingAnchor, constant: given_space).isActive = true
label.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 0).isActive = true

In order for the view's height to adjust to the label (if its associated text is longer than one line), then add the following line of code: label.numberOfLines = 0

 Please note that your blueView will also need constraints.
You can find out more about constraints here.
Or if you prefer to use storyboards, you don't have to programatically add the constraints - see this tutorial.


text:
Q: Time picker access 2007 I want my users to select only time for datetime filed in access 2007. I found that there's a built-in date control, but cannot find time control. Does anyone know if there's a way to have a time picker control?

A: For entering time values, a specialized control doesn't offer the user much more, if any, convenience than directly entering time values into a text box bound to a Date/Time field, IMO.
For 1:30 PM, she can just enter 1:30p, and it will be accepted appropriately.  She could also enter that time as 13:30 if she prefers.
If your concern is preventing the user from entering a (non-zero) date value along with the time, you can discard the date portion in the text box's after update event.  Users tend to catch on real fast when the date portions of values they enter are discarded.
Private Sub txtTimeOnly_AfterUpdate()
    Me.txtTimeOnly = TimeValue(Me.txtTimeOnly)
End Sub

Actually that will convert the date portion to VBA's day zero, #1899/12/30#.  But that's the best you can hope for to store a "time only" value because Date\Time values always include a date in both VBA and the database field type.
If you want more assurance the field will store time values (with #1899/12/30# as the date), you can set a validation rule on the table:
IsNull([time_only_field]) Or DateValue([time_only_field])=CDate("1899/12/30")

If you still feel you need a time picker control for this, search the web to see if anyone has created one.  I would avoid an ActiveX control because they wind up creating version problems.
Or I suppose you could create your own custom time picker with combo boxes: one for hours; one for minutes; and, if needed, one for seconds.  In the combo after update events, build your time value from those pieces and store them in a control bound to the time_only_field.  That control needn't be editable by the user, but making it visible would allow them to see the completed value.


text:
Q: Unable to fetch data from firebase firestore database with react native using state I am building a react native app where I need to place all the data of users in a firebase firestore database into a flatlist. I am unsure of how to do this with all updated react native code, as all other stack overflow questions do not answer this question and I can not find any help elsewhere.
My code for fetching the react native data is:
state = {
    data: []
  };

  unsubscribe = null;

  componentDidMount() {
    const user = this.props.uid || Fire.shared.uid;
    const list = [];

    this.unsubscribe = Fire.shared.firestore
      .collection("users")
      .doc(data)
      .onSnapshot(doc => {
        list.push(data);
      });

      this.setState({
            data: list
      )};
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

The database structure is that the user has a name and an email. I try to call this by typing: "{this.state.name.email}", which does not work in the Flatlist. I already initialized my app in another file, where Fire.shared = new Fire(); is exported. If any help would be given on how to export such data into the state properly, I would be largely grateful. Thank you in advance!

A: The call to setState needs to be in the callback, so:
componentDidMount() {
  const user = this.props.uid || Fire.shared.uid;
  const list = [];

  this.unsubscribe = Fire.shared.firestore
    .collection("users")
    .doc(data)
    .onSnapshot(doc => {
      list.push(data);
      this.setState({
        data: list
      )};
    });
}


text:
Q: Time Complexity Analysis Using Big (O) arr = [1, 2, 5, 6, 7]
total = 0
for i in range(len(arr)):
    total += sum(arr[i:])

Is the time complexity for the above code is O(n^2) or O(n^3), the confusion because of the slicing of the list arr. So how does slicing arr effects the time complexity?

A: Slicing a list is O(k) with k being the size of the slice, which in this case rounds up to O(n). However, in this case, the time complexity is still O(n^2), because arr[i:] is additive with sum(), not multiplicative. We can see this if we decompose it into two separate steps:
for i in range(len(arr)):        # executes n times
    things_to_sum_over = arr[i:]      # runs in (k -> n) time
    total += sum(things_to_sum_over)  # operates over (k -> n) elements

This gives a total  n * 2(k -> n), or 2n^2 = O(n^2).


text:
Q: Texcount.pl with Texmaker word.count file not found error I'm trying to get texcount.pl http://app.uio.no/ifi/texcount/ to work inside Texmaker but I get the error about the word.count that is not found. The documentations says that I have to add --shell-escape to solve the problem but I don't know where to put that. Does anyone know?

A: To summarise the answer (so far):
Running TeXcount, or any other OS command, from TeX or LaTeX is done by entering code similar to this
\immediate\write18{texcount test.tex > test.sum}

in the TeX/LaTeX document (which I've checked and work when I do it from TeXworks). A somewhat improved version of this is provided on the help pages of TeXcount
\immediate\write18{texcount \jobname.tex -out=\jobname.sum}

provided you have a more recent version of TeXcount. In either case, this requires texcount to be in the path, or the OS will not find it.
TeX and LaTeX (and other TeX versions) will by default not execute \write18 commands unless you give the options --shell-escape (for TeX I believe) or --enable-write18 (for LaTeX I believe).
Changing the LaTeX options is explained in the Texmaker manual.
Note that TeXcount may have slightly different filenames from system to system depending on where you got it from: texcount or texcount.pl, and I know some have also compiled it into texcount.exe.
If it still doesn't work, you should try to figure out which thing goes wrong. Try running LaTeX from the command line instead of Texmaker to see if that works or what errors are given. Or try executing something like dir > dir.txt in the \write18 to see if you can get it to execute at all.


text:
Q: "No column name was specified for column..." when aliasing results of CROSS APPLY I have this table:

from which I create this View:

This view's CardId allows me to JOIN against the Card table with so I can retrieve the Count from any CardId. Here's my SQL:
SELECT * FROM (
    SELECT
        si.CardId SourceCardId,
        ti.CardId TargetCardId,
        (SELECT TOP 1 r.Name
        FROM dbo.Relationship r
        WHERE r.Id = rac.RelationshipId) [Name],
        Count(*) [Count]
    FROM dbo.Relationship_AcquiredCard rac
    JOIN dbo.AcquiredCard sac ON rac.SourceAcquiredCardId = sac.Id
    JOIN dbo.AcquiredCard tac ON rac.TargetAcquiredCardId = tac.Id
    JOIN dbo.CardInstance si ON sac.CardInstanceId = si.Id
    JOIN dbo.CardInstance ti ON tac.CardInstanceId = ti.Id
    GROUP BY si.CardId, ti.CardId, rac.RelationshipId
    -- you can probably ignore everything above
    ) X
CROSS APPLY
    (values (X.TargetCardId),
            (X.SourceCardId)
    ) whatdoesthisdo(CardId) --wut

What does whatdoesthisdo do? I got the CROSS APPLY from this answer. If I try to alias in the usual way, I get this error:

Thanks!

A: It should be clear from the below
SELECT WhatDoesThisDo.CardId
FROM   (VALUES (1),
               (2) ) WhatDoesThisDo(CardId)

WhatDoesThisDo provides the table alias for the derived table defined by the VALUES clause. It then requires a comma delimited list of all column names (as there is no way of naming them inside the VALUES itself).
In this case it only returns one column so the complete column list is (CardId)
The relevant part of the grammar is
derived_table [ [ AS ] table_alias ] [ ( column_alias [ ,...n ] ) ]

though the optionality indicated by the square brackets above does not apply with table value constructors.


text:
Q: Why need to include dataType to JQuery ajax I have the next code:
$.ajax({
     type: "GET",
     url: url,
     data: {language: language},
     contentType: "application/json",
     success: function (result) {
        console.log(result);
        result.forEach(function(item) {
           var option = $("");
           option.text(item);
           option.val(item);
           node.append(option);
        });
        if (self.value.country) {
            $("#countrySelect").val(self.value.country);
        }
    }
});
why at first case (when I refresh page or visit it at first time) it returns json and at the next case (postback) it returns string
Then I add dataType: "json"
And now it returns only json.
Why without adding it not worked correctly?
1) with dataType
2) without dataType (first load)
3) without dataType (postback)

A: Because without specifying dataType, it takes a guess at the type. By specifying it to JSON, it will expect a JSON data response. You also can't specify multiple data types - if you need different data types returned, you have to leave it set to the default value.


text:
Q: Excel VBA Copy and Paste Loop within Loop I've been working on this VBA code for a while and since I'm a complete noob I feel like I haven't gotten anywhere. I've been researching a ton, but can't seem to combine answers to help with my scenario.
Essentially what I'm trying to do is grab data, line by line, from one worksheet and extrapolate it to another worksheet. I believe this will involve loops and I'm so new with VBA I don't know how to do it.
Here's the logic I'm attempting:
For each row on worksheet 1, I would like to perform 3 different copy and paste activities to worksheet 2 and then it will loop down to the next row on sheet1 and do the 3 activities and so on. This will continue downwards until column A is blank in sheet1. Sheet1 data starts at A3 and sheets2 paste area starts at A2.
The first activity is to copy cells F3,D3,A3, and H3 (in that order so F3 will be A2, D3 will be B2 etc) from sheet 1 to sheet 2 to A2,B2,C2, etc. A destination functions can't be used because I need just the values and no other formats—one of the many issues I've ran in to.
The next activity is to copy cells F3,D3,A3 and I3 from sheet 1 to sheet2  pasted below the previous copy and paste—again no formats just values. Also to note, some of these may be blank (except A column) but I still need that row there with at least column A data—this goes to say with all these activities.
The third activity is to copy and paste sheet1's F3,D3, and A3 a certain number of times referencing K3's number—and each copy and paste will be in the next available blank cell. So if the number in K3 it will look like it created 3 rows in sheet2—totaling 5 rows on sheet2 since activity1 and 2 each create their own row.
After these three activities are completed for row 3 on sheet 1, it will then move to row 4 and do the previous three activities and paste to sheet2. And again it will be pasting no formats and in the next blank row on sheet 2. Also again, this loop will stop once the cell in Column A is blank.
Below is my incomplete code. I don't even think it will help one bit and it would probably be better not to even look at it. I've just started to get frustrated since I can't even do a simple copy and paste, yet alone loops within loops. I also haven't even started on my third activity. I greatly appreciate it!
Sub copyTest3()

Dim proj As Range, release As Range, pm As Range, lead As Range, coord As Range
Dim leadCopy As Range, coordCopy As Range
Dim i As Range

Set proj = Range("A3", Range("A3").End(xlDown))
Set release = Range("D3", Range("D3").End(xlDown))
Set pm = Range("F3", Range("F3").End(xlDown))
Set lead = Range("H3", Range("H3").End(xlDown))
Set coord = Range("I3", Range("I3").End(xlDown))

Set leadCopy = Union(pm, release, proj, lead)
Set coordCopy = Union(pm, release, proj, coord)

For i = 1 To Range(ActiveSheet.Range("A3"), ActiveSheet.Range("A3").End(xlDown))
    leadCopy.Copy
    Sheets("Sheet2").Activate
    Range("A2").Select
    ActiveSheet.PasteSpecial xlPasteValues

    Application.CutCopyMode = False

    Sheets("Sheet1").Activate
    coordCopy.Copy
    Sheets("Sheet2").Activate
    Range("A2").Select
    ActiveSheet.PasteSpecial xlPasteValues

Next i

End Sub

A: The way I usually approach copying data between sheets in Excel is to create source range and destination range objects, each range referring to just one row. When I want to move on to the next row, I use Offset to return a range offset to the next row.
Since the ranges only refer to one row, you can index them with an integer to get the cells in the row. E.g. if cursor refers to columns A through D in row 3, cursor(3) will give you the cell C3.
Dim src_cursor As Range
Dim dest_cursor As Range

Set src_cursor = ActiveSheet.Range("A3:I3")
Set dest_cursor = Sheets("Sheet2").Range("A2:D2")

'' Loop until column A is empty in source data
Do Until IsEmpty(src_cursor(1))
    dest_cursor(1) = src_cursor(6) '' copy F -> A
    dest_cursor(2) = src_cursor(4) '' copy D -> B
    '' and so on

    '' move cursors to next row
    Set src_cursor = src_cursor.Offset(1, 0)
    Set dest_cursor = dest_cursor.Offset(1, 0)
Loop

Also, this might be getting a little off topic, but it's a better practice to use an Enum to name the column numbers instead of hardcoding them like I did here.

A: There are many ways to do this, and some are more efficient than others. My solution may not be the most efficient, but hopefully it will be easy for you to understand so that you can learn.
It's very difficult to understand what you're attempting to do in activity three, so I wasn't able to provide a solution to that step. Use my code as a template for step three and if you run into issues, feel free to leave a comment.
Notice that I don't use .Activate, .Select, or .Copy in this code. .Activate and .Select are huge efficiency killers, and they make it easier for your code to "break," so avoid using them when possible. .Copy isn't necessary when working with values or formulas and will also slow your code down.
Untested
Sub testLoopPaste()

Dim i As Long
Dim ii As Long
Dim i3 as Long
Dim LastRow As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Sheet1")
Set sht2 = wb.Sheets("Sheet2")

'Find the last row (in column A) with data.
LastRow = sht1.Range("A:A").Find("*", searchdirection:=xlPrevious).Row
ii = 2

'This is the beginning of the loop
For i = 3 To LastRow
    'First activity
    sht2.Range("A" & ii) = sht1.Range("F" & i).Value
    sht2.Range("B" & ii) = sht1.Range("D" & i).Value
    sht2.Range("C" & ii) = sht1.Range("A" & i).Value
    sht2.Range("D" & ii) = sht1.Range("H" & i).Value
    ii = ii + 1

    'Second activity
    sht2.Range("A" & ii) = sht1.Range("F" & i).Value
    sht2.Range("B" & ii) = sht1.Range("D" & i).Value
    sht2.Range("C" & ii) = sht1.Range("A" & i).Value
    sht2.Range("D" & ii) = sht1.Range("I" & i).Value
    ii = ii + 1

    'Third activity
    For i3 = 1 To sht1.Range("K" & I)
        sht2.Range("A" & ii) = sht1.Range("F" & i).Value
        sht2.Range("B" & ii) = sht1.Range("D" & i).Value
        sht2.Range("C" & ii) = sht1.Range("A" & i).Value
        ii = ii + 1
    Next i3

Next i

End Sub


text:
Q: How to protect a NFC chip from being copied? I want to develop an NFC access application and I'm thinking about how to prevent people from copying their tag.
I read that some NFC chips have a "password secured memory" part where data can be stored that it is protected with a password. If I understand correctly, this password is required every time the chip is read. This way I can protect the NFC tag from being copied by simply storing the user GUID into the "password secured memory". As the data can't be read, it can't be copied, right?
The only chip I found that supports this are the "MIFARE Classic" and "MIFARE DESFire" chip, where the "MIFARE DESFire" chip is too expensive for our application.
So now my questions:

*

*How are NFC chips usually protected from being copied in access control applications? (e.g. hotel rooms, garage doors or office buildings?)

*Are there other cards than the mentioned MIFARE cards that have a "password protected memory" ?

*How secure is the password protected memory on e.g. a MIFARE Classic card. (if there are ways to read the data after a few seconds (e.g. bruteforce) it may not secure enough for us)

There is a lot of information available on the internet about NFC chips but in my experience its kind of a wild west where everyone writes something but not everything is supported by all chips/readers and writers. I don't see the woods for the trees anymore..


text:
Q: Problem updating a resource array due to node single thread concurrency Tables:

users
user_category
categories

user_id (PK)
user_id (PK)
category_id (PK)

name
category_id (PK)
name

I'm having problems with concurrency on node, I'll describe an example to reproduce the error I have:
When receiving 5 requests in parallel to perform a PUT on the same existing user and their categories:
PUT users/userId123
body
{
    "name": "other name"
    "categories" : [
    "categoryId123",
    "categoryId456",
    "categoryId789",
    ]
}

Upon receiving this payload in a simulation, first a DELETE query is performed on user_category and then an INSERT on user_category to insert the new categories.
It turns out that as the node is a single thread, the main thread competes, and when performing 5 identical requests in parallel, it is happening to perform two DELETES of two different requests and then the 2 INSERTs, which will generate a primary key error in the table user_category, I already tried to use a transaction for these two queries, but the error still occurs, blocking the main thread until doing these two operations is not an option defied the loss in performance.
Attempt-1
Below is an excerpt from UserController code that does this
if (Array.isArray(user.categories)) {
      await userCategoriesRepository.deleteHardByUserId(user.userId)

      const userCategories = []
      for (const categoryId of user.categories) {
          userCategories.push({userId: user.userId, categoryId})
      }
      await userCategoriesRepository.save(userCategories)
}

UserRepository:
  save (userCategories: ICreateUserCategoryDTO[]): Promise<void> {
    try {
      return this.repository.insert(userCategories)
    } catch (error) {
      throw new Error(error)
    }
  }

  deleteHardByUserId (userId: string): Promise<void> {
    try {
      return this.repository.delete({ userId })
    } catch (error) {
      throw new Error(error)
    }
  }

Attempt-2 (Transaction)
Below is an excerpt from UserController code that does this
if (Array.isArray(user.categories)) {
      const userCategories = []
      for (const categoryId of user.categories) {
          userCategories.push({userId: user.userId, categoryId})
      }

      await userCategoriesRepository.updateWithTransaction(userId, userCategories)
}

UserRepository:
async updateWithTransaction (userId: string, userCategories: ICreateUserCategoryDTO[]) {
    try {
      return getManager().transaction(async transaction => {
        await transaction.delete(UserCategory, { userId })
        await transaction.insert(UserCategory, userCategories)
      })
    } catch (error) {
      throw new Error(error)
    }
  }

QUERY LOGGING

*

*case: 1 request (SUCESS)
query: START TRANSACTION // REQUEST 1
query: DELETE FROM "user_category" WHERE "user_id" = $1 -- PARAMETERS: ["userId123"] // REQUEST 1
query: INSERT INTO "user_category"("user_id", "category_id") VALUES ($1, $2) -- PARAMETERS: ["userId123", "categoryId123"] // REQUEST 1
query: COMMIT // REQUEST 1

*case: 2 or more requests parallel (ERROR PK)
query: START TRANSACTION // REQUEST 1
query: DELETE FROM "user_category" WHERE "user_id" = $1 -- PARAMETERS: ["userId123"] // REQUEST 1
query: START TRANSACTION // REQUEST 2
query: DELETE FROM "user_category" WHERE "user_id" = $1 -- PARAMETERS: ["userId123"] // REQUEST 2
query: INSERT INTO "user_category"("user_id", "category_id") VALUES ($1, $2) -- PARAMETERS: ["userId123", "categoryId123"] // REQUEST 1
query: COMMIT // REQUEST 1
query: INSERT INTO "user_category"("user_id", "category_id") VALUES ($1, $2), ($3, $4) -- PARAMETERS: ["userId123", "categoryId123", "userId123", "categoryId456"] // REQUEST 2 --> PK ERROR
query: COMMIT // REQUEST 2
Details:

*

*node 16.13.1

*typeorm 4.3.2

*pg 8.4.0

*npm 8.3.0

*Postgres database 13.2


text:
Q: Approach the covariance matrix I have this problem:

Let the random vector $\binom{X}{Y}\sim
N_{2}(\binom{0}{0},\bigl(\begin{smallmatrix} 1 & \rho\\  \rho & 1 \end{smallmatrix}\bigr))$
1) Find the distribution of $Z=X+Y$.
2) Find the distribution of $W=X^2$, the mean and the variance.
3) Calculate $Cov(X,W)$ and $Cov(Z,W)$.

It's the first time that I have found myself analysing this type of function. What the covariance matrix involves? How do I manage it? Thanks in advance for any clarification!

A: It is given that $X$ and $Y$ are jointly normal, $EX=EY=0$, $EX^{2}=EY^{2}=1$ and $cov(X,Y)=\rho$ which gives $EXY=\rho$.
$X+Y$ is  normal with mean $0$ and its variance is $E(X+Y)^{2}=EX^{2}+EY^{2}+2EXY=1+1+2\rho$.
$P(W \leq w)=P-\sqrt w \leq X \leq \sqrt w)-\int_{-\sqrt w} ^{\sqrt w} f(x)dx$ where $f$ is the standard normal density.
$cov(X,W)=EX^{3}-EXEX^{2}=EX^{3}=0$ by symmetry of standard normal distribution. I will leave the calculation of $cov (Z,W)$ to you.

A: I will not post full answers, so that You can practice a bit - as it is Your first encounter of this subject. Nevertheless I will point out some crucial facts, that are needed here if one need to handle this.

$X=(X_{1},\cdots, X_{k})^{T}$ is multivariate normal distributed if and only if every linear combination of the form $$Y=a_{1}X_{1}+\cdots+a_{k}X_{k}$$ is normally distibuted (well known, one dimensional distribution).

From that we see, that $Z=X+Y$ must be normally distributed. Recall, that if $Z$ is normally distributed, then its distribution is uniquely determined by its mean $\mu$ and variance $\sigma^{2}$. Variance is basically "Covariance matrix" - which in this case is one dimensional. And here comes the second fact.

If $C$ is covariance matrix of $X=(X_{1},\cdots, X_{k})^{T}$ and $a\in \mathbb{R}^{k}$, then $$\mathrm{Cov}(a^{T}X)=a^{T}Ca.$$

Knowing this You can proceed with point a).
In b) You are asked about distribution of $W=X^{2}$, which depends only on distribution of $X\sim \mathrm{N}(0,1)$. This is a very famous distribution. This problem does not deal with any multivarious stuff.
Point c) $\mathrm{Cov}(X,W)=\mathrm{C}(X,X^{2})$. You can find it by basic calculations. From linearity of Covariance we have
$$\mathrm{Cov}(Z,W)=\mathrm{Cov}(X+Y,X^{2})=\mathrm{Cov}(X,X^{2})+\mathrm{Cov}(Y,X^{2}).$$
Only the last part $\ \mathrm{Cov}(Y,X^{2})=\mathbb{E}(YX^{2}), \ $
is a little bit tricky.
The idea is that we can (without loss of generality) express $Y$ as $$Y=c_{1}X+c_{2}V$$  where $V\sim \mathrm{N}(0,1),$ $$c_{1}^{2}+c_{2}^{2}=1$$ and $X,V$ are independent.
Ask if You will need more explanations.


text:
Q: Monitoring uptime and health of several services (web service, oracle, web app) I have several services growing in activity. I'm looking for a simple service that can monitor them (web service, oracle, web app), and send an email when one is down.
Thanks a lot :)

A: Go have a look at the xymon system. It is simple and easy youse and scales well. I used xymon at several organizations and it is awesome. The user community is also very vibrant and helpfull.
Other systems you can look at are Nagios and OpenNMS. These are more complex though and might be overkill.


text:
Q: How to convert/Play *.STR files in PC I recorded a show from my TV on Airtel DTH (in India) in a Pen drive. I can play the recorded show in my TV, however, I am unable to find any way to play the recorded video on my PC.
After searching a lot I came to know that the video is stored as STR format file. I browsed my pen drive in my PC, and found the .STR file. But now I would like to know how I will be able to play the video on my PC.


text:
Q: TYPO3 restricted page is accessible from url I am using TYPO3 and i have a restricted area for members.
If a guest knows the URL of a restricted page in the members area, he is able to see its content. That's not the way it should be.
Do you know how to fix this issue?

A: If you have a restricted area, you should have at least one FE usergroup created and this usergroup should be assigned at Access tab of your members only page. If you want subpages of this page to be restricted as well, you have to set Extend to subpages checkbox on that tab.


text:
Q: How to run a function as a child process in python? I have a function dosomething()  inside which am doing a os.chroot(). A process running chroot() cannot get out of chroot jail. So i want this dosomething() to run as a child process in the main program and i need to wait till the child process gets over . What is the simplest way to do this ?

A: Take a look at multiprocess.Process


text:
Q: Confusing database with schema I have defined db name in squelize constructor so that tables being generated by corresponding model files. Tables are successfully created in given db. I am confused with the schema which by default is public in models.So why to define schema in models if tables are properly generated in db in default postgresql server named PostgreSQL 15. if I change name of schema from public to some how ALGH it says schema doesnot exist. if it is referencing schema then what is the purpose of giving db name in sequelize constructor.

A: You can have multiple schemas in the same DB for different purposes like to divide sets of tables for different apps/services or by functionality.
You can indicate a schema in the Sequelize instance and it will be the default schema for all models that does not have an explicit schema OR you can indicate a schema for certain models only and other models will have the default public schema.
Of course, you need to create tables only after you decided and indicated all schemas (either in Sequelize instance and/or in certain models) you need otherwise you will get such errors you already mentioned in the post.


text:
Q: JQuery + Daterangepicker - current date and time? I am using the daterangepicker JQuery plugin as I have to pull some date ranges as part of a form. On the same form however, I also want to be able to automatically display the current date and time, preferably through the plugin.
I cant seem to find a way to make this possible as DRP doesn't seem to like the "YYYY/MM/DD HH:mm" format and instead only displays today's date as of midnight (eg. 2017/01/20 00:00), but never the actual time.
How can I fix this?
$(function() {
    $('input[name="incident_date"]').daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        timePicker: true,
        timePicker24Hour: true,
        timePickerIncrement: 10,
        autoUpdateInput: true,
        locale: {
            format: 'YYYY/MM/DD HH:mm',
        },
});

A: You should pass the option startDate: new Date().

$('input[name="incident_date"]').daterangepicker({
  singleDatePicker: true,
  startDate: new Date(),
  showDropdowns: true,
  timePicker: true,
  timePicker24Hour: true,
  timePickerIncrement: 10,
  autoUpdateInput: true,
  locale: {
    format: 'YYYY/MM/DD HH:mm'
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-daterangepicker/2.1.25/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-daterangepicker/2.1.25/daterangepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-daterangepicker/2.1.25/daterangepicker.css" rel="stylesheet"/>
<input type="text" name='incident_date' />


text:
Q: How to make the two textview more flexible in android? I have been searching around but didnt fine any clues about how to make the 2 textview flexible according to the space. Here is the picture. Any hint, it would great.

A: Try this.
 <LinearLayout
            android:id="@+id/contentWithBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:background="@drawable/incoming_message_bg"
            android:paddingLeft="10dp"
            android:paddingBottom="10dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:maxWidth="250dp" />

        </LinearLayout>

Note : incoming_message_bg must be Nine patch image . And you can mutiple textview in Linear layout.

A: Try this.It is working fine.
   <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

     <TextView
            android:id="@+id/mText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Text1"
            android:textSize="17sp"
            android:layout_margin="5dp"
            android:layout_gravity="right"
            android:gravity="right"/>

      <TextView
            android:id="@+id/mText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is some text"
            android:textSize="17sp"
            android:layout_margin="5dp"
            android:layout_gravity="right"
            android:gravity="right"/>

     </LinearLayout>


text:
Q: How to set the python path for the bluemix CF Python Apps I deployed a Python Flask app to IBM Cloud (Bluemix). But python files in the inner directories of my app are not found by Bluemix: [ImportError: No module named aciconsts ]
unless I modify the path using sys.path. Is it possible to set PYTHONPATH to look for files in Bluemix CF Python App. In other words, are there environment variable like PYTHONPATH that can be set to look for python files in the app?

A: You can add commands to your procfile.
Right now it most likely reads python yourappname.
Add a command before this line to add a directory to your Python path.
export PYTHONPATH="${PYTHONPATH}:/my/other/path"

Should be said though, that dependencies should be installed with requirements.txt. Otherwise you risk running into staging errors and memory limits...


text:
Q: Organising columns in pandas DataFrame I have a 2 sets of 92 columns. At the moment, all 92 columns are in one row. Is it possible to reogranise this such that the 92 columns are split into sets of 12, essentially having 8 sets of 12 data (one underneath the other). my code:
import glob
import pandas as pd
import os

os.chdir('C:/Users/peaches9/Desktop/')

Result = []

def FID_extract(filepath):

    path_pattern = filepath
    files = glob.glob(path_pattern)
    dataframes = [pd.DataFrame.from_csv(f, index_col=None) for f in files]

    new_dfa = pd.DataFrame()

    for i, df in enumerate(dataframes):
        colname = 'Run {}'.format(i+1)
        selected_data = df['Unnamed: 3'].ix[12:17]
        new_dfa[colname] = selected_data
    #print new_dfa
    #new_dfa.to_csv('FID_11169_Liquid.csv')
    Result.append(new_dfa)

def TCD_extract(filepath):

    path_pattern = filepath
    files = glob.glob(path_pattern)
    dataframes = [pd.DataFrame.from_csv(f, index_col=None) for f in files]

    new_dfb = pd.DataFrame()

    for i, df in enumerate(dataframes):
        colname = 'Run {}'.format(i+1)
        selected_data = df['Unnamed: 3'].ix[12:15]
        new_dfb[colname] = selected_data
    #print new_dfb
    #new_dfb.to_csv('TCD_11169_liquid.csv')
    Result.append(new_dfb)

FID_extract('C:/Users/peaches9/Desktop/Cryostat Verification/GC results/11169_Cryo_1bar/FID_0*') #files directory

TCD_extract('C:/Users/peaches9/Desktop/Cryostat Verification/GC results/11169_Cryo_1bar/TCD_0*')

dfc = pd.concat(Result)

Out:
     Run 1.....   Run 95      Run 96
12  5193791.85  5193915.21  5194343.34
13  1460874.04  1460929.33  1461072.84
14   192701.82   192729.55   192743.99
15    156836.4   156876.97   156889.26
16    98342.84     98346.7    98374.95
17         NaN         NaN         NaN
12     3982.69     3982.16     4017.66
13  2913008.04  2913627.33   2914075.7
14   226963.37    226956.1   227106.71
15     25208.2    25173.89    25197.88

I want all 96 columns split into 8 X 12 columns all underneath each other. Many thanks in advance.
EDIT:
I have managed to seperate the dataframes into sets of 8... but I can't get each dataframe to go beneath each other. They concat to the right, always!
dfc = pd.concat(Result)

df1 = dfc.ix[:,0:12]
df2 = dfc.ix[:,12:24]
df3 = dfc.ix[:,24:36]
df4 = dfc.ix[:,36:48]
df5 = dfc.ix[:,48:60]
df6 = dfc.ix[:,60:72]
df7 = dfc.ix[:,72:84]
df8 = dfc.ix[:,84:96]

pieces = [df1,df2,df3,df4,df5,df6,df7,df8]

df_final = pd.concat([df1, df2], levels = 1, axis = 3)

A: Assuming you are trying to take your 96 columns, and create a single 2-dimensional DataFrame with 12 columns and 8 times as many rows, then you want:
df_final = pd.concat( pieces, axis=0, ignore_index=True )

If you are trying to make a 3-dimensional DataFrame, with your new dimension having 8 values, you aren't trying to make a DataFrame, but a Panel.


text:
Q: sqlite mark duplicates with true or false I need to create a new column in my dataset (duplicate_name) that contains TRUE if there are more than one record for someone or FALSE otherwise. I found this code (I am working with sqlite):
SELECT *,
CASE
WHEN ROW NUMBER() OVER (PARTITION BY
first_name, last_name) > 1) THEN 'TRUE'
ELSE 'FALSE'
END AS duplicate_name
FROM users;
But when I ran it it gives me something like this (ONLY THE SECOND RECORD IS MARKED AS TRUE):
Carlo  Thomas    male  FALSE
Carlo  Thomas    male  TRUE
Don    Scallion  male  FALSE
Tania  Lopes     female  FALSE
What I need is a table like this (both records with the same name are marked as TRUE):
Carlo  Thomas    male  TRUE
Carlo  Thomas    male  TRUE
Don    Scallion  male  FALSE
Tania  Lopes     female  FALSE
Can someone help me, please.
Thanks

A: Instead of ROW_NUMBER() use COUNT(*) window function:
SELECT *,
       CASE WHEN COUNT(*) OVER (PARTITION BY first_name, last_name) > 1 THEN 'TRUE' ELSE 'FALSE' END AS duplicate_name
FROM users;

or simpler with a 1 for true and 0 for false:
SELECT *,
       COUNT(*) OVER (PARTITION BY first_name, last_name) > 1 AS duplicate_name
FROM users;


text:
Q: Display Image when beacon is detected I'm trying to make an image appear on the screen of my app, when a beacon is detected. I have currently created a dictionary by assigning an image to each beacon using the minor value, however I'm not sure how to display the image.
{   let lookupTable = [12754: "phone-icon", 22279: " StoreLocation"]

}
Here is an image of how I want the image to appear on the screen
I need assistance of how to display the image like shown above in the attachment, when a beacon is detected.
Thanks


text:
Q: Build fails on Jenkins for my Android project due to config I am trying to setup Jenkins Job for my android project. The Project is getting built successfully on my local machine but fails on Jenkins with following error:

A problem occurred configuring project ':app'  Cannot evaluate module
  volley : Configuration with name 'default' not found.

.gitmodules
[submodule "volley"]
    path = volley
    url = https://android.googlesource.com/platform/frameworks/volley

app: build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    signingConfigs {
        release {
            storeFile file('my-release-key.keystore')
            storePassword "******"
            keyAlias "release-key"
            keyPassword "*******"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def outputFile = output.outputFile
            if (outputFile != null && outputFile.name.endsWith('.apk')) {
                def fileName = outputFile.name.replace('app-release.apk', "myproject.apk")
                output.outputFile = new File(outputFile.parent, fileName)
            }
        }
    }

    lintOptions {
        abortOnError false
    }

    configurations.all {
        resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
    }

    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "com.myproject.****"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        signingConfig signingConfigs.release
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //setProperty("archivesBaseName", "myproject")
    }
    buildTypes {
        release {
            minifyEnabled false
            shrinkResources true
            debuggable false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    packagingOptions {
        exclude 'LICENSE.txt'
    }
    productFlavors {
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
    sourceSets { main { java.srcDirs = ['src/main/java'] } }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':volley')
    androidTestCompile 'com.android.support.test:runner:0.4'
    androidTestCompile 'com.android.support.test:rules:0.4'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile files('libs/json.jar')
    testCompile 'org.json:json:20140107'
    compile 'com.google.android.gms:play-services-identity:8.3.0'
    compile 'com.google.android.gms:play-services-plus:8.3.0'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'com.github.clans:fab:1.6.1'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    compile 'com.google.code.gson:gson:2.2.4'
}
apply plugin: 'idea'

settings.gradle
include ':app' , ':volley'

project-- build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.google.gms:google-services:1.5.0-beta2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

I have set up volley by cloning the repo
https://android.googlesource.com/platform/frameworks/volley
I have tried changing the path of volley and recloning also but it didn't worked

A: That error message looks like the volley submodule has not been cloned into the workspace.
You should not clone this manually, but let Jenkins do it for you.
Jenkins doesn't clone submodules by default (for some unknown reason), but you can enable this in your job configuration. In the Git section, choose:
Additional Behaviours > Add > Advanced sub-modules behaviours
You can additionally check the "Recursively clone submodules" option in the section that appears, but I don't think volley needs this.


text:
Q: Split window programmatically with iTerm? on my development workstation I often have to start the same commands every morning.
zeus start, zeus server (booting rails via zeus), redis-server, and like 3 others.
I know a lot of people would say have them running all the time but I do a lot of work on my own stuff and it wigs me out having all of those running while I'm working on separate rails projects.
Is there some kind of advanced alias I can make which starts all of these from one command, ideally by programmatically splitting the window (like ⌘-D).
I'm using iTerm2 with oh-my-zsh.
I wouldnt mind if they were all in the same window I suppose (somehow running as background processes) however I do need to sometimes look at the output, and work with the output from each command, so I'm not sure how that would work.
Thanks!

A: You can easily call this from iTerm2 directly to simulate pressing ⌘D:
osascript -e 'tell application "System Events" to key code 2 using command down'

For this to work you want to start the programs in background, since otherwise you cannot run osascript:
some-command &
osascript -e '…'

From there on you'll land in a new iTerm2 window, so you need to use the write text option in AppleScript to run further shell commands. See here for more: How do I set up an AppleScript to open a new iTerm2 tab and change the directory?

A: the answer here is a bit outdated.. here is an example script that does somethign similar:
tell application "iTerm"
    tell current window
        -- create a tab for background db stuff
        create tab with default profile
        tell current session
            write text "mongod &"
            write text "redis-server &"
        end tell
        close current tab

        -- create tab to run aioc server
        create tab with default profile
        tell current session
            write text "title server"
            write text "aactivate"
            write text "arunserver"
            -- split tab vertically to run scheduler
            split vertically with default profile
        end tell

        -- run scheduler
        tell last session of last tab
            write text "title scheduler"
            write text "aactivate"
            write text "ascheduler"
            -- split tab vertically to run main controller
            split vertically with default profile
        end tell

        -- run main_controller
        tell last session of last tab
            write text "title main_controller"
            write text "aactivate"
            write text "amain_controller"
            -- split tab vertically to run aggregator
            split vertically with default profile
        end tell

        tell last session of last tab
            write text "title aggregator"
            write text "aactivate"
            write text "aggregator"
        end tell

    end tell
end tell


text:
Q: How to get a programmer to apply nice design touches? We have a small webdesign firm, and count with one designer. We can currently not afford too much expansion in the design area, so that means that the designer creates the main design of a website (which often means: the homepage), and the programmers then work with this to make it into a website. In general, this works for us. However, I have noticed a big difference between the abilities of different programmers to apply 'nice design touches' to a website. Given that we only have the homepage design, we often need to structure internal sections ourselves. Nothing major, no design program needed, but CSS skills come into play. So let's say we need to show a list of different sections in the website. I will have the content and assign this to two programmers. One will come up with this:

And another will do very much his best - and has the same CSS knowledge - but can only come up with something like this:

NOTE: sample image taken from MailChimp website.
The second programmer is aware that his 'design' lacks style and that it needs improvement, but he is just not able to create something nice without having it all drawn up by somebody else. He wants to work on this, but I do not know what a good approach would be. Any tips? Anybody with similar experiences?

A:
However, I have noticed a big difference between the abilities of different programmers to apply 'nice design touches' to a website.

And you will notice big differences between the abilities of different programmers to play guitar. nice design touches are outside the job description for a developer. You should hire developers with design experience (or more designers) and not try to squeeze skills out of people.
And of course you could invest in formal design training for your developers. We always like learning new things. But it should be formal training, on the company's time and dime.
Half measures will lead to failure, sooner than later.

A: It's very rare to find a programmer who can design to a good standard. Design can be very hard for some programmers while programming can be very hard for some designers. If it was easy for programmers you wouldn't need designers.
Let the programmer create the initial layouts from the home page then let the designer review each (and perhaps tweak) before it goes live. Also, why doesn't the designer create a design brief on how elements should look that the programmers can follow? You would still need the designer to review it all though.

A: This is what stuck out to me:

and has the same CSS knowledge

Having the same knowledge of CSS doesn't mean they have the same skill or experience to manipulate it, or fully understand how different styles can interact.
In addition, it's difficult to say anyone has the same knowledge in something like CSS, where every attribute and possible values are pure memorization.
For example, I'd been using CSS on and off for years, and near-continuously at work for perhaps 7 months, before I found out what absolute positioning does when inside a relative-positioned DIV.  And that's just one simple thing that I'd overlooked for so long.


text:
Q: How can I set the size of edit controls in ASP.NET Dynamic Data details views? How can I, if I can, set the size of textboxes generated in the details and edit views of a Dynamic Data application, without resorting to custom page templates?

A: If you want to change ALL textboxes in the app, you should modify Text.ascx in the Fieldtemplates folder.  If you want to modify some text boxes, you should create a custom field template, and assign that control to the field in metadata like so :
[UIHint("TextWide")]
public object Description { get; set; }


text:
Q: Arch Linux in Qemu : Failed to access perfctr msr error I got the Arch Linux (march build) iso file through bittorrent lately.
I tried to run it in VM, but it only gets up to the main screen (The screen where you select what you want to do) shown below:

But when I select first option, it shows a black screen which goes nowhere. The Hardware Information option seems to work, but it's out of my intellectual capacity so I ignored it.
I then tried qemu with a simple qemu-system-x86_64 ./location to file command. It shows a slightly different image:

On selecting x64-86 I get errors:

I am a Ubuntu user, so I don't get anything of this, but the first error seems to be:
failed to access perctr msr(msr coo1ooo4 is 0)

A: I get this message (failed to access perctr msr) on boot with a functioning Arch guest in Virtualbox.  This issue has been discussed on the Arch forum (link below) and apparently is related to a cpu feature that does not exist on the system giving the error message, but the feature is unimportant, thus the message may be ignored.
https://bbs.archlinux.org/viewtopic.php?pid=1279852
In the last post:

2013-07-07 09:24:35
endle
     Member
     Registered: 2013-07-07
     Posts: 1
Re: kernel error on QEMU VM boot: Failed to access perfctr msr
  mich41 wrote:
Probably something unrelated, maybe booting without "quiet" would reveal what exactly is happening before it hangs.
Thank you! After booting without 'quiet', I found where the problem is.