text:
Q: C Program Segmentation Fault I am having difficulty locating a segmentation fault in a bit of code for a class project (this portion is ungraded).  I am implementing a queue for an OS class and am having trouble with a segmentation fault in the add function.
void AddQueue(QElem * head, QElem * item) {
    printf("WHERE\n");
    if(head == NULL){
        printf("THE\n");
        head = item;
        //item->next = item;
        //item->prev = item;
    }
    else{
        printf("$^&*\n");
        (head->prev)->next = item;
        printf("ARE\n");
        item->prev = (head->prev);
        printf("YOU\n");
        item->next = head;
        printf("FAILING\n");
        head->prev = item;
    }
    printf("!?!?!?\n");
}

I have a Test function which I am calling from a different class...
void TestAddQueue()
{
    printf("********************************************\n");
    printf("Begin testing the add test function\n");
    printf("********************************************\n");

    QElem * queue;
    InitQueue(queue);

    for(int i = 0; i < 10; i++)
    {
        printf("Adding element %d\n", i+1);
        QElem * newElem = NewItem();
        printf("Changing payload value\n");
        newElem->payload = i+100;
        printf("Adding to the queue\n");
        AddQueue(queue, newElem);
        printf("Item added, payload value = %d\n", queue->payload);
        printf("The previous payload = %d\n", queue->prev->payload);

    }
    for(int i = 0; i < 10; i++)
    {
        printf("Rotating list", i+1);
        RotateQ(queue);
        printf("Printing element %d\n", i+1);
        printQElem(queue);
    }
}

Here is the NewItem function...
QElem * NewItem()
{
    // just return a new QElem struct pointer on the heap
    QElem * newItem = calloc(1,sizeof(QElem));
    newItem->next = newItem;
    newItem->prev = newItem;
    newItem->payload = -1;
    return newItem;
}

...and here is the output of running the program...
********************************************
Begin testing the add test function
********************************************
Adding element 1
Changing payload value
Adding to the queue
WHERE
THE
!?!?!?
Segmentation fault

Now the head pointer which is passed into the add function should be NULL as it  sent to an initializer function which just sets the value of the pointer to NULL, so I dont think this would cause my problem.
My guess is that following line is the one causing the issue...
printf("Item added, payload value = %d\n", queue->payload);

Probably when I attempt to get the payload value, either the struct I am attempting to access doesn't exist anymore or somehow the queue pointer got moved to an invalid space. Any feedback or nudges in the right direction would be appreciated.
Side Note: This is being compiled in a Unix server environment (bash) and at the moment I do not have access to an IDE to debug and view variables.

A: In C arguments are passed by value, meaning they are copied. And changing a copy does of course not change the original.
So in the AddQueue function, the variable head is a copy that you can change as much as you want, the variable you originally passed to the function will not change at all.
To be able to change arguments you need pass by reference, which C doesn't have, but it can be emulated by using pointers. That of course means that to pass a pointer by reference, you must pass a pointer to the pointer.

So for your code it would be like
void AddQueue(QElem ** head, QElem * item) {
    if(*head == NULL){
        *head = item;
    }
    ...
}

...

AddQueue(&queue, newElem);

What the above changes do is first to make AddQueue take a pointer to a pointer to QElem, thereby making it emulate the pass-by-reference idiom. To use the original pointer you use the dereference operator * which gives you the value pointed to by a pointer (in this case the original pointer). Then to actually pass a pointer to a pointer, you have to use the address-of operator & on the pointer variable.

A: head = item does not have any effect on what goes on outside the AddQueue function. If you pass a null pointer as head to AddQueue, that pointer will still be null after AddQueue completed.

A: Thanks to @Joachim i was able to get my queue running as intended.  See below the refactored code.
First the add function...
////////////////////////////////////////////////////////////////////////////////
//
//  Add Queue
//
//      Adds a queue item, pointed to by `item`, to the end of the queue pointed
//      to by `head`.
//
//      Note: Tested 2-12-2015 using proj_1.c tests. PASSED -Dave
//
////////////////////////////////////////////////////////////////////////////////
int AddQueue(QElem ** head, QElem ** item) {

    //If the queue is empty...
    if(*head == NULL){
        //Point the head to the item.  The new item's next/prev were initialized
        //to point to itself already.
        *head = *item;
    }
    //If there are already elements in the queue...
    else{
        // insert the new element at the end of the list (just to the left
        // of the head) setting the next and previous values of the
        // appropriate nodes to the new values.
        ((*head)->prev)->next = *item;
        (*item)->prev = ((*head)->prev);
        (*item)->next = *head;
        (*head)->prev = *item;
    }
    return TRUE;
}

Next the new item function...
////////////////////////////////////////////////////////////////////////////////
//
//  New Item
//
//      Returns a pointer to a new queue element created in heap memory.
//
//      Note: Calloc is a more precise way of allocating, but is basically the
//      same as malloc, the 1 denotes how many of the item to reserve mem for.
//      -Dave
//
//      Note: Tested 2-12-2015 using proj_1.c tests. PASSED -Dave
//
////////////////////////////////////////////////////////////////////////////////
QElem * NewItem()
{
    // just return a new QElem struct pointer on the heap with values initialized
    QElem * newItem = calloc(1,sizeof(QElem));
    newItem->next = newItem;
    newItem->prev = newItem;
    newItem->payload = -1;
    return newItem;
}

And now for the test add function...
////////////////////////////////////////////////////////////////////////////////
//
//  A test function for the add function.  It will create a queue of items
//  and attempt to iterate through them and print the value of the payload
//
////////////////////////////////////////////////////////////////////////////////
void TestAddQueue(QElem ** queue){
    printf("********************************************\n");
    printf("Begin testing the add test function\n");
    printf("********************************************\n");

    InitQueue(&(*queue));

    for(int i = 0; i < 10; i++)
    {
        printf("Adding element %d\n", i+1);
        QElem * newElem = NewItem();
        printf("Changing payload value\n");
        newElem->payload = i+100;
        printf("Adding to the queue\n");
        AddQueue(&(*queue), &newElem);
        printf("Item added, payload value = %d\n", newElem->payload);
        printf("The previous payload = %d\n", (*queue)->prev->prev->payload);

    }
}


text:
Q: Refreshing and the shrinking header I've such code for shrinking header (later follows the "else" command, but it's not important). It works perfectly, but when I refresh already scrolled page, I have to scroll again to trigger the change. How to change that and display the proper shrinked version when refreshing with page already scrolled? Thanks in advance for the advice.
 var shrinkHeader = 50;
  $(window).scroll(function() {
    var scroll = getCurrentScroll();
      if ( scroll >= shrinkHeader || scrollTop() >= shrinkHeader) {
$('.pasek-mini').hide();
 $('.pasek-mini').addClass('pasek-miniu').removeClass('pasek-mini');
$('.pasek-miniu').show();
 }

A: Do your scroll position comparisons both when the page loads and after you scroll, and do your header shrinking magic.
function shrinkHeaderIfScrolled() {
    var scroll = getCurrentScroll();
    var shrinkHeader = 50;
    if ( scroll >= shrinkHeader || scrollTop() >= shrinkHeader) {
        $('.pasek-mini').hide();
        $('.pasek-mini').addClass('pasek-miniu').removeClass('pasek-mini');
        $('.pasek-miniu').show();
    }
}

$(document).ready(function() {
    shrinkHeaderIfScrolled();

    $(window).scroll(function() {
        shrinkHeaderIfScrolled();
    }
});

This is assuming you have both a getCurrentScroll() function and scrollTop() function defined somewhere since you included them in your code sample.
Otherwise you could just use:
function shrinkHeaderIfScrolled() {
    var shrinkHeader = 50;
    if ($(window).scrollTop() >= shrinkHeader) {
        $('.pasek-mini').hide();
        $('.pasek-mini').addClass('pasek-miniu').removeClass('pasek-mini');
        $('.pasek-miniu').show();
    }
}

$(document).ready(function() {
    shrinkHeaderIfScrolled();

    $(window).scroll(function() {
        shrinkHeaderIfScrolled();
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# program causes bluescreen? This is only the important stuff that the bluescreen shows. I'm on Windows 7 x64.
"A problem has been detected and Windows has been shut down to prevent damage
to your computer.
PROCESS_HAS_LOCKED_PAGES
* STOP: 0x00000076 (0x0000000000000000, 0xfffffa8009dcd060, 0x0000000000000011,
0x0000000000000000)"
I can't work on it now because every time I close it I get a bluescreen!
The program doesn't do anything yet except run the background worker below. It pings all addresses that could be part of the user's home network and attempts to connect to a certain port that another program will be listening on.
private void NetworkScanner_DoWork(object sender, DoWorkEventArgs e)
    {
        bool ExceptionEncountered = false;
        int IPsProcessed = 0;

        NetworkSearcherOutput = "Starting network scanner...";
        NetworkSearcher.ReportProgress(0);
        Thread.Sleep(1000);

        foreach (IPAddress IP in Dns.GetHostAddresses(Dns.GetHostName()))
        {
            if (IP.AddressFamily == AddressFamily.InterNetwork)
            {
                string[] Octets = IP.ToString().Split('.');
                Octets[3] = "0";

                IPAddress CurrentAddressIteration = StringArrayToIP(Octets);
                while (GetLastOctet(CurrentAddressIteration) != 255)
                {
                    PingReply Reply = new Ping().Send(CurrentAddressIteration, 5);

                    if (Reply.Status == IPStatus.Success)
                    {
                        NetworkSearcherOutput = CurrentAddressIteration.ToString() + " sent response.";
                        NetworkSearcher.ReportProgress(0);
                        Thread.Sleep(500);

                        InClient Client = new InClient(CurrentAddressIteration);

                        try
                        {
                            Client.Connect();

                            SnapshotBox.Image = Client.Receive(typeof(Image));

                            NetworkSearcherOutput = CurrentAddressIteration.ToString() + " is running program.";
                            NetworkSearcher.ReportProgress(0);
                            Thread.Sleep(1000);
                        }

                        catch (Exception E)
                        {
                            // A socket exception is expected when the client is not running the program.
                            if (E is SocketException)
                            {
                                Client.Close();

                                NetworkSearcherOutput = CurrentAddressIteration.ToString() + " is not running program.";
                                NetworkSearcher.ReportProgress(0);
                                Thread.Sleep(1000);
                            }

                            //Unhandled exception. Show messagebox and close.
                            else
                            {
                                MessageBox.Show("Network scanner encountered an unhandled exception.\n\n" + E.GetType().ToString() + ": " + E.Message, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                ExceptionEncountered = true;
                                break;
                            }
                        }
                    }

                    else
                    {
                        NetworkSearcherOutput = CurrentAddressIteration.ToString() + " did not respond.";
                        NetworkSearcher.ReportProgress(0);
                    }

                    IPsProcessed++;

                    if (IPsProcessed == 5)
                    {
                        NetworkSearcher.ReportProgress(2);
                        IPsProcessed = 0;
                    }

                    Octets = CurrentAddressIteration.ToString().Split('.');
                    Octets[3] = (Int32.Parse(Octets[3]) + 1).ToString();
                    CurrentAddressIteration = StringArrayToIP(Octets);
                }
            }
        }

        if (!ExceptionEncountered)
        {
            NetworkSearcherOutput = "Network scanning complete.";
            NetworkSearcher.ReportProgress(0);
            NetworkSearcher.ReportProgress(100);
        }

        else
        {
            NetworkSearcherOutput = "Network scanning encountered an error.";
            NetworkSearcher.ReportProgress(-1);
        }

I thought C# programs were supposed to never cause bluescreens?

A: I discovered this issue a few weeks back. It only happens when using .NET 4.
Reported at MS Connect.
Edit:
(Will*) Add this link to MS Connect bug report.
*login.live.com is going into an infinite loop again...

A: Just to be clear, there is no way for "user" mode code to forcibly create a blue screen in windows, unless it uses undocumented APIs and or forces bad data into a driver.  Your C# code is likely not be at fault here, as if you use the user mode classes (Socket) then the socket is responsible for not crashing your computer.
As @Joe has commented Microsoft Support KB Article 256010 clearly describes this stop message, but better yet has clear instructions on capturing the driver name responsible for this error.
Note that any software firewall that you have installed also is involved at kernel mode level so could also be responsible for this error.  I recommend you follow the KB articles advice and try to find out what is at fault.  But you could also ensure that you have updated your network drivers and firewall/VPN software to the latest stable versions.


text:
Q: python csv writer remove carriage returns Can somebody helps how to remove ^M end of line ?
I am using Unix system.
This is default sample script from csv python  docu, I use similar scenario in my script with same results :(
import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

A: The ^M is the carriage-return character (\r - 0x0d).
So you probably have \r or \r\n (0x0d 0x0a) at the end of each line.
Maybe you could try with:
with open('names.csv', 'w', newline='\n') as csvfile:

or:
with open('names.csv', 'w', newline='\x0a') as csvfile:


text:
Q: How to test a public/private keypair in C++? Is there a way to verify that a given private key matches a given public key? I want to check them using C++

A: It depends on the public key algorithm that uses the keys, and how those keys are encoded.  For example, an RSA public key consists of two parameters 'n' and 'e', while a private key consists of those plus 'd', and possibly 'p' and 'q' as well.  All of these params are large integers, generally represented using the internal form of some large integer library.  So to compare a public and private key you just need to check that 'n' and 'e' match.  Depending on the library and system used, you may even be able to ignore 'e', as it might be a constant.
Using OpenSSL that might look something like:
RSA *pubkey = PEM_read_RSA_PUBKEY(...);
RSA *privkey = PEM_read_RSAPrivateKey(...);

if (!BN_cmp(pubkey->n, privkey->n)) {
    // same modulus, so the keys match

A: Check out http://www.cryptopp.com/, it has the utilities for checking key pairs.
As a general rule, the private key should be able to decrypt data encrypted using the public key. That's proof that the given key pair is valid.


text:
Q: Running a python script from ArcMap running a python script from within ESRI's ArcMap and it calls another python script (or at least attempts to call it) using the subprocess module.  However, the system window that it executes in (DOS window) comes up only very briefly and enough for me to see there is an error but goes away too quickly for me to actually read it and see what the error is!
Does anyone know of a way to "pause" the DOS window or possibly pipe the output of it to a file or something using python?
Here is my code that calls the script that pops up the DOS window and has the error in it:
py_path2="C:\Python25\python.exe"
py_script2="C:\DataDownload\PythonScripts\DownloadAdministrative.py"
subprocess.call([py_path2, py_script2])
Much appreciated!
Cheers

A: Try doing a raw_input() command at the end of your script (it's input() in Python 3).
This will pause the script and wait for keyboard input. If the script raises an exception, you will need to catch it and then issue the command.
Also, there are ways to read the stdout and stderr streams of your command, try looking at subprocess.Popen arguments at http://docs.python.org/library/subprocess.html.

A: subprocess.call accepts the same arguments as Popen. See http://docs.python.org/library/subprocess.html
You are especially interested in argument stderr, I think. Perhaps something like that would help:
err = fopen('logfile', 'w')
subprocess.call([py_path2, py_script2], stderr=err)
err.close()

You could do more if you used Popen directly, without wrapping it around in call.


text:
Q: Error when compiling with webpack and babel-loader I cannot seem to compile using the babel 6 loader and webpack. It's driving me mad. Has anyone else come across this problem? I cannot for the life of me see where I am screwing up. :)
Console Log
ERROR in ./~/redux/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/redux/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/redux/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
@ ./src/js/main.js 11:13-29

ERROR in ./~/react-redux/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/react-redux/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/react-redux/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
@ ./src/js/main.js 17:18-40

ERROR in ./~/redux-router/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/redux-router/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/redux-router/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
@ ./src/js/main.js 13:19-42

webpack.config.js
var path = require('path');

module.exports = {
entry: path.resolve(__dirname + "/src/js/main.js"),
output: {
    path: path.resolve(__dirname + "/dist/js/bundle.js")
},
module: {
    loaders: [
        {
            test: /\.jsx?/,
            excludes: /(node_modules|bower_components)/,
            loader: "babel",
            query: {
                presets:['es2015']
            }
        }
    ]
}
}

main.js
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import {createStore, compose, combineReducers} from 'redux';

import {
    ReduxRouter,
    routerStateReducer,
    reduxReactRouter,
    pushState
} from 'redux-router';

import {Route, Link} from 'react-router';
import {Provider, connect} from 'react-redux';
import {createHistory} from 'history';

A: Try create a .babelrc file (root) without stage property. You can create just a empty brackets if you don't need set any property.
{}

A: According to the error it seems that redux is complaining about the stage option. It is probably because redux is still using Babel 5. This stage option has been removed from Babel 6.

Module build failed: ReferenceError: [BABEL]
  /Users/montague/Sites/redux/routing/node_modules/redux/lib/index.js:
  Unknown option:
  /Users/montague/Sites/redux/routing/node_modules/redux/.babelrc.stage

But you shouldn't be running through babel those files. Hence something in your webpack.config.js should be wrong. Probably because your exclude field has an extra s.
Change:
excludes: /(node_modules|bower_components)/,
       ^

With:
exclude: /(node_modules|bower_components)/,

A: Try installing the preset first, since babel 6 does not transform anything by default but requires a preset to define its transformation.
npm install --save-dev babel-preset-es2015

and for react:
npm install --save-dev babel-preset-react

Now add the preset to the .babelrc file:
{
  "presets": ["es2015"]
}

This should do the trick, its exactly what I had to do to solve this.

A: Forget where I saw this (lemme know if it was you so I can give credit) but this command has helped fix a multitude of babel reference errors for me.
rm $( find node_modules -name .babelrc)

A: If you exclude node_modules from your loaders, then how are you going to deal with node modules which are coded using es6?


text:
Q: Guardar varios checkbox en diferentes campos mySQL Tengo el siguiente formulario para elegir a un presidente y a dos vocales:
<form method="post" action="">

Presidente

    <input type="radio" name="president" id="president" value="<?php echo $id; ?>">
    Presidente 1

    <input type="radio" name="president" id="president" value="0">
    Voto en blanco

Vocal

Votar máximo 2 o en blanco

    <input type="checkbox" name="vocal[]" id="vocal" value="<?php echo $id; ?>">
    Vocal 1

    <input type="checkbox" name="vocal[]" id="vocal" value="<?php echo $id; ?>">
    Vocal 2

    <input type="checkbox" name="vocal[]" id="vocal" value="<?php echo $id; ?>">
    Vocal 3

    <input type="checkbox" name="vocal[]" id="vocal" value="0">
    Voto en blanco

    <button type="submit" name="submit">Send vote</button>

</form>

El valor de voto en blanco = 0.
Ahora lo que hago es limitar que se puedan solo marcar 2 checkboxes como máximo.

Y por último quiero guardar esos valores en una tabla donde almacena el id del usuario que vota,  y su voto por el presidente y por cada vocal. Lo que no sé es como hacer que los votos de los vocales vayan a dos campos diferentes de la tabla llamados "vocal1" "vocal2", y si pudiera poner otro campo que fuera "voto en blanco" sería genial.
Como no se hacerlo hice un array y almacené los checkboxes en un mismo campo separado por coma ",".
// Insert record
if(isset($_POST['submit'])) {

    $president=$_POST['president'];
    $checkBox = implode(',', $_POST['vocal']);

    if(!empty($president)){

        mysqli_query($con, "INSERT INTO vote (user_id, president, vocal) VALUES('" . $user_id . "', '" . $president . "', '" . $checkBox . "')");
    }
  }

Si hay una manera más eficiente de hacerlo para luego contar los votos me gustaría saber cómo.

A: Tu tabla de votos tiene que ser normalizada para permitirte mas flexibilidad y tambien para facilitarte luego los conteos.
Lo que podrias hacer es una tabla de votos con los siguientes campos:

Id_usuario: el usuario que vota
Id_cargo: el cargo que esta votando
Id_persona: la persona por la cual se vota.

Vas a necesitar una tabla de cargos (que contendra por ejemplo presidente, vocal, suplente, etc)
Y otra tabla con las personas que se postulan a cada cargo. Inclusive, esa tabla podra tener a la persona Voto en blanco (que lo definiras como queres) y hasta si tuvieras votos invalidos, tambien lo podrias poner como persona. De esa forma, contar cada tipo de voto es solo hacer un sum...

A: Una disculpa no había tenido tiempo de conectarme, ay tienes un ejemplo de como podrías insertar en dos campos diferentes.
 <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

<form method="post" action="" name="form" id="form">

Presidente

    <input type="radio" name="president" id="president" value="<?php echo $id; ?>">
    Presidente 1

    <input type="radio" name="president" id="president" value="0">
    Voto en blanco

Vocal

Votar máximo 2 o en blanco

    <input type="checkbox" name="vocal1" id="vocal1" value="vocal1" onchange="twoSelectionValidation('form1', this)">
    Vocal 1

    <input type="checkbox" name="vocal2" id="vocal2" value="vocal2" onchange="twoSelectionValidation('form1', this)">
    Vocal 2

    <input type="checkbox" name="vocal3" id="vocal3" value="vocal3" onchange="twoSelectionValidation('form1', this)">
    Vocal 3

    <input type="checkbox" name="votoblanco" id="votoblanco" value="0" onchange="twoSelectionValidation('form1', this)">
    Voto en blanco

    <button type="submit" name="submit">Send vote</button>

</form>

<?php
// Insert record
if(isset($_POST['submit'])) {
    $user_id  = 'user';

    $president = 0;
    if(isset($_POST['president'])){
        $president = $_POST['president'];
    }

    $vocalesArray = array(0,0,0,0);
    $v1 = 0;
    $v2 = 0;
    $v3 = 0;
    $v4 = 0;

    if(isset($_POST['vocal1'])){
        $v1=$_POST['vocal1'];
        $vocalesArray[0] = $v1;
    }

    if(isset($_POST['vocal2'])){
        $v2=$_POST['vocal2'];
        if($vocalesArray[0]=='0'){
            $vocalesArray[0] = $v2;
        }else if($vocalesArray[1]=='0'){
            $vocalesArray[1] = $v2;
        }
    }

    if(isset($_POST['vocal3'])){
        $v3=$_POST['vocal3'];
        if($vocalesArray[0]=='0'){
            $vocalesArray[0] = $v3;
        }else if($vocalesArray[1]=='0'){
            $vocalesArray[1] = $v3;
        }
    }

    if(isset($_POST['votoblanco'])){
        $v4=$_POST['votoblanco'];
        if($vocalesArray[0]=='0'){
            $vocalesArray[0] = $v4;
        }else if($vocalesArray[1]=='0'){
            $vocalesArray[1] = $v4;
        }
    }

    mysqli_query($con, "INSERT INTO vote (user_id, president, vocal1, vocal2) VALUES('" . $user_id . "', '" . $president . "', '" . $vocalesArray[0] . "', '" .$vocalesArray[1]."')");
}
  ?>

Lo único que hice es que agregue un div entonces de ahí tomo los hijos y valido que no estén chequeados más de dos, por cierto elimine el jquery ya que se puede hacer con funciones muy sencillas de JS, lo demás lo valido desde el back end con PHP y lo hago de una forma muy practica en la cual lo primero que hace el código es validad que las variables lleguen y aquí esta lo practico, las variables que no llegan sencillamente se toma como ceros es decir votos nulos, si solo marca a un vocal o si o escoge presidente se toma como nulo, luego de que se validan las variables  para que no causen problemas, al igual que tú las meto en un array y luego lo organizo para posteriormente guardarlo en la bd solo tomando como referencia las dos primeas posiciones del array.
Por cierto, debes agregar un nuevo campo en tu bd que sería el de vocale2 y editar el nombre del otro que ya tenías por vocales1.
No olvides cambiar el nombre de las variables que les puse temporalmente los candidatos por los valores que es tenías asignados.
Como lo mencionan en la parte de arriba también te recomiendo que normalices la bd, pero si te decides por hacerlo con estos ejemplos te podrás guiar un poco sobre lo que querías hacer.
Espero que te sirva de algo, si tienes alguna duda necesitas algo cométalo, saludos


text:
Q: RelativeLayout parameters programmatically align error I am trying programmatically align some elements in RelativeLayout but I am getting some problem. All my TextView elements aligned to the top left corner even when I set them deferentially. here is my screen shot:

Here is my code (this is the RelativeLayout):
        title = new TextView(context);
        date = new TextView(context);
        rating = new RatingBar(context);
        saleImage = new ImageView(context);
        arrowImage = new ImageView(context);

        RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        this.setBackgroundResource(R.drawable.list_selector);
        this.setLayoutParams(relativeLayoutParams);
        this.setClickable(true);

        relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        saleImage.setLayoutParams(relativeLayoutParams);
        saleImage.setImageResource(R.drawable.rihanna);
        this.addView(saleImage);

        relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        relativeLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        arrowImage.setImageResource(R.drawable.arrow);
        arrowImage.setLayoutParams(relativeLayoutParams);
        this.addView(arrowImage);

        relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        relativeLayoutParams.addRule(RelativeLayout.RIGHT_OF, saleImage.getId());
        title.setLayoutParams(relativeLayoutParams);
        title.setTextAppearance(context, android.R.style.TextAppearance_Medium);
        title.setText("Sale title");
        this.addView(title);

        relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        relativeLayoutParams.setMargins(0, 0, 26, 0);
        relativeLayoutParams.addRule(RelativeLayout.LEFT_OF, arrowImage.getId());
        date.setTextAppearance(context, android.R.style.TextAppearance_Small);
        date.setText("14.01.13 22:00");
        this.addView(date);

It seems that the problem is with the RelativeLayout.RIGHT_OF and RelativeLayout.LEFT_OF attributes.
here is the Activity code:
public class MainPage extends Activity {
    private LinearLayout test;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_sales);

        test = (LinearLayout)findViewById(R.id.salesConteiner);
        SaleRow row = new SaleRow(this);
        test.addView(row);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_page, menu);
        return true;
    }

}

Is there something I have missed? Thanks!!!

A: For the view.getId() function to work you first need to se an id: view.setId(1).
Thanks for the help!!!


text:
Q: How to show the data of Core Data in a UITableView I am getting the response from JSON and stored that data by using Core Data. I want to show the data always in a UITableView. Can you suggest me how to display data in a UITableView?
This is the code I'm using.
    NSManagedObject * newEntry =[[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:self.managedObjectContext];

    [newEntry setValue:[dict objectForKey:@"albumName"] forKey:@"albumName"];
    [newEntry setValue:[dict objectForKey:@"coverPhotoURL"] forKey:@"coverPhotoURL"];
    [newEntry setValue:[dict objectForKey:@"createdDate"] forKey:@"createdDate"];

    NSLog(@"Log %@", newEntry);

    NSError * error = nil;
    if ([self.managedObjectContext save:&error] == NO)
    {
        NSLog(@"CANNOT SAVE: %@ %@", error, [error localizedDescription]);
    }
    else {
        NSLog(@"SUCCES, go check the sqlite file");
    }
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"GetAlbums"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSError* error;
NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"Fetch Records %@",fetchedRecords);

A: You use below methods of table view so show your data.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  [self.arrayOfyourData count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellIdentifier";

    //you could use default cell or ur own custom cell.
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    // Now here you could pare your self.arrayOfyourData to fetch and populate your cell.

    return cell;
}

A: Even if, as suggested by walle84, you can implement the methods of UITableViewDelegate to display data in your table view, the right way is to use a UITableView in combination with NSFetchedResultsController. The latter is, as written in the doc, used

to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object.

I put the emphasis on efficiently since it provides a lot of pros. For example, it allows lazy loading of data, it allows to track changes for a specific entity (implementing NSFetchedResultsControllerDelegate), etc.
Where to start? There are a lot of tuts. Just google them and you will find a good point to start.

*

*Core Data From Scratch

*How To Use NSFetchedResultsController


text:
Q: IdentityModel Refresh token implementation on UWP I'm trying to authenticate my UWP app with an ASP.NET Core web API which implemented IdentityServer4. (geant_type is Password)
So on the app, I added the nuget IdentityModel 4.3.1 and wrote the following code to get the token and refresh token. Please note I used System.Net.Http.HttpClient here.
var policy = new DiscoveryPolicy();
        policy.ValidateIssuerName = false;

        var client = new HttpClient();

        DiscoveryDocumentResponse disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
        {
            Address = "https://maduranga-atrad.boardpac.local:8443/Auth.API",
            ClientSecret = "LTY0OTU1NzY3OTM0OTQ1NjE3NA",
            Policy = policy
        });

        TokenResponse token = await client.RequestPasswordTokenAsync(new PasswordTokenRequest()
        {
            UserName = "User786",
            Password = "Password@123",
            ClientId = "boardpac.main.uwp",
            ClientSecret = "LTY0OTU1NzY3OTM0OTQ1NjE3NA",
            GrantType = "password",
            Scope = "openid email offline_access main auth",
            Address = disco.TokenEndpoint,
            AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc6749
        });

        TokenResponse refresh = await client.RequestRefreshTokenAsync(new RefreshTokenRequest()
        {
            Address = disco.TokenEndpoint,
            RefreshToken = token.RefreshToken,
            ClientId = "boardpac.main.uwp",
            AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc6749,

        });

My problems are

*

*When to send the refresh token request? Do I have to manually handle the token expiration?
(I need to wait till HttpClient returns HTTP error 401 and then initiate the token request. But what happens to all the subsequent requests? I have to queue all the requests and then retry, etc.. seems lots of work.)

*I saw one example where RefreshTokenHandler was set to the HttpClient (System.Net.Http.HttpClient) and it says the refreshing part was automatically handled. I use Windows.Web.Http HttpClient and I can't use RefreshTokenHandler. How do I use Windows.Web.Http HttpClient to automatically handle refresh token?
Thank you for your consideration.


text:
Q: Jython, Django with Sqlite3 Now I create project by using jython 2.5.2b2 and django1.1.1 (lucid) , after download sqlitejdbc-v056.jar and do some syncdb task it's shown
"zxJDBC.Error: auth_permission.content_type_id may not be NULL [SQLCode: 0]"

but still can runserver, anyone has some great example for this situation?

A: Try to reorder django.contrib.auth in INSTALLED_APPS in settings.py
From
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    )

To
INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.auth',
    )

A: I have recreated this error on OS X with Jython 2.5.2 and Django 1.1.1. However the documentation for the 'django-jython' package (which provide the glue between Django on Jython and various databases) has the following on SQLite3 support:

SQLite3
Experimental. By now, use it only if you are working on improving it.
  Or if you are really adventurous.


text:
Q: RTEs accessibilityicons missing in TYPO3 7.6 After upgrading my project from TYPO3 4.x to TYPO3 7.6 there were many broken icons in the front-end:

  mail(at)example.com

The directory typo3/sysext/rtehtmlarea/res/accessibilityicons/img/ is not there anymore.
How to fix that?

A: As the directory structure of the extension rtehtmlarea is aligned to the Extbase structure so that the location of some directories changed (Thx to Georg Ringer). The icons are located in typo3/sysext/rtehtmlarea/Resources/Public/Images/ now.
You can easily change the whole content with this SQL snippet:
UPDATE tt_content
  SET bodytext = REPLACE(bodytext,
    'rtehtmlarea/res/accessibilityicons/img/',
    'rtehtmlarea/Resources/Public/Images/');

This rewrites all occurrences of the icons to the new path.
Sometimes also this old path is used: typo3/sysext/rtehtmlarea/htmlarea/plugins/TYPO3Browsers/img/mail.gif
You can adjust obove SQL statement for this too.
Please backup your database before.


text:
Q: Show that G/A is a symplectic manifold with $\omega(g,f)=\mathrm{tr}[g,f]\lambda$ I've never posted here and never learned much differential geometry, so sorry in advance if I'm doing something wrong.
Let $G$ be a compact Lie-group and $A$ its Cartan-subgroup. I have to show that the manifold $G/A$ is symplectic with the symplectic form $\omega(g,f)= \mathrm{tr}[g,f]\lambda$ with $[\cdot,\cdot]$ being the Lie-bracket, $f,g \in TG$ and a suitable $\lambda \in TA$.
Now my confusion already starts with the definition of ω. Isn't the trace of a commutator always zero?
I think I have to show that $d\omega = 0$ and that $\omega$ is non-degenerate, correct? Do I also have to show that $G/A$ is smooth?
$$d\omega(X,g,f)=X\mathrm{tr}[g,f]\lambda − g\mathrm{tr}[X,f]\lambda + f\mathrm{tr}[X,g]\lambda − \mathrm{tr}[[X,g],f]\lambda + \mathrm{tr}[[X,f],g]\lambda − \mathrm{tr}[[g,f],X]\lambda$$
I think I can use the Jacobi-identity for the last three terms after using that the trace is linear. But I don't know about the other terms. I also have no idea what is meant by "a suitable $\lambda$".
It would be great if someone could help me.
Kind regards


text:
Q: How do I turn off Windows 7 Firewall via script or through automation? This is in regards to working on machines before joining the machine to a domain and although I would love to rely on GPO, that isn't an option at this time.
In the environment I'm working in, the firewall policy is to use a 3rd party Firewall app from an Total Endpoint Solution, so I have to disable the default Windows Firewall top prevent conflicts. I do this using a script that I run at the end of an imagine process or manually on systems I haven't reimaged. For a while, I was able to manage this using:
netsh advfirewall set allprofiles state off

However, that stopped working for some reason. So, I found I needed to clear the local security policy (manually):
Local Security Policy MSC > Windows Firewall with Advanced Security
Right-Click Windows Firewall with Advanced Security - Local Group Policy Object
Clear Policy

This was the script I used to avoid doing it manually:
secedit /configure /db reset /cfg securityprofile

A combination of both steps was working for about a month, then, for no apparent reason, it stopped working.
I began testing a registry hack to achieve what I needed, and it is giving me mixed results.  I have two sets keys with profiles I need to change; for Local Profiles:
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile]
"EnableFirewall"=dword:00000000
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PrivateProfile]
"EnableFirewall"=dword:00000000
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PublicProfile]
"EnableFirewall"=dword:00000000

For Domain Profiles:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\DomainProfile]
"EnableFirewall"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\PublicProfile]
"EnableFirewall"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\StandardProfile]
"EnableFirewall"=dword:00000000

The problem I'm having is that the Local Profile keeps regenerating the original settings with the firewall on.  I've tried:

*

*a) Apply Both Registry Hacks

*b) Reboot

*Result on newly imaged machine) no luck

*Result on old machine used for testing) good to go

*a) Apply Local Policy Registry Hack

*b) Reboot

*Result on newly imaged machine) no luck

*Result on old machine used for testing) good to go

*a) use secedit to clear Local Security Policy

*b) Apply Both Registry Hacks

*c) Reboot

*Result on newly imaged machine) no luck

*Result on old machine used for testing) good to go

*a) use secedit to clear Local Security Policy

*b) Apply Local Policy Registry Hacks

*c) Reboot

*Result on newly imaged machine) no luck

*Result on old machine used for testing) good to go

My goal is to disable the Windows Firewall via script/automation.  Any thoughts?
Note: this is prior to joining the machines to the domain.  If I manually clear the Local Security Policy from the MSC, then the registry hacks will work.  netsh still won't work and I don't want to have to manually clear the policy for every imaged machine.

A: I'd like to preface this by saying that I strongly urge anyone that disables their Windows firewall to take the time to understand how it works and how to manipulate it via GPO instead of outright turning it off. There's no reason to turn off a host-based firewall. Microsoft makes excellent tools to manage firewall rules, you should use them.

This TechNet article outlines the proper way to disable the Windows Firewall. Don't turn off the service like others have told you, that will put your server into an unsupported configuration and cause flakiness in various scenarios that are hard to troubleshoot.
From the TechNet article, the netsh syntax is

netsh advfirewall set profiles state off

where valid values for profiles are: AllProfiles, CurrentProfile, DomainProfile, PrivateProfile, or PublicProfile.
It appears that you've already tried this exact command and it's not working. You've also pushed the registry keys that this command manipulates. Based on the fact that it used to work and now doesn't, and that these machines are not domain-joined at the time that you are doing this, there is only one conclusion:
There is something in your image that is overriding this. End of story. Since we don't have your image to look at, there's really no way we can give you a specific fix, other than "you're doing it right and if it doesn't work, something in your image is misconfigured"
Honestly, if you're having to run secedit /configure /db reset /cfg securityprofile on your images along with all of this other stuff, you might just be better off making a new image with everything the way you want it.

A: Errr, tidy up your GPOs, and disable it there.  Or, at the very least, create a new GPO at the top of the stack (highest precedence) and disable the firewall.  Then go back and tidy your other GPOs later.  Local Security policy gets overridden by GPOs, and the first area of the registry you're writing to is specifically for GPO processing.
Short answer... Group Policy.  Long answer... Group Policy.  (sorry!)

A: Found the problem.  MDT was applying a Local Group Policy at the end of it's task sequence after installing my image, which was disabling access to any changes to the local security policy, even by administrators (via command prompt commands, registry, etc...).  This is odd, since it's a default policy that comes with MDT.  Regardless, removing this task sequence allows me to turn off the firewall using netseh:
netsh advfirewall set allprofiles state off

As a note; I agree with everyone that you shouldn't disable your firewall service and you shouldn't turn off your firewall.


text:
Q: How do I send a DHCP request to find DHCP server IP address? Is this possible? Is it possible to write a small script that will send out a DHCP broadcast request and find the DHCP server address?
I need this for a project, but my research led me to believe that you cannot do this on Windows? I would need a small script for OSX, Linux and Windows.

A: Okay, I'm going to make the assumption that your default gateway is configured to point at your DHCP server. I found the following package and was able to get my default gateway:
#!/usr/bin/env python
import netifaces

gateway_info = netifaces.gateways()
print(gateway_info)

I of course first had to install the netifaces module via pip:
$> pip install --user netifaces
Code returns the following:
$> ./test3.py
{'default': {2: ('192.168.0.1', 'en0')}, 2: [('192.168.0.1', 'en0', True)]}
I hope this helps.
Best regards,
Aaron C.

A: I think you're asking an XY Problem: You want to know how to find the DHCP IP address on windows, via python?
There is a solution on SuperUser for obtaining DHCP server ip from the command line. You can wrap ipconfig /all with subprocess and then parse the output:
import subprocess  # Runs a command on the cmd line

res = subprocess.check_output("ipconfig /all")


text:
Q: Clone the first two text box values of a current row? I have a requirement that for a table has the add row button and delete row button which I show in the following code.
For adding a row I want to clone the first two values "who" and "Location" of the current row  to get the next row when I click on add row. In case I have different details on "who" and "Location" on third row when I click on "Add row" it has to take the same details of the third row and add the fourth row with the details of "who" and "location" in third row.
Hope you understand this scenario.
Html Table:

        Name
        Location
        From
        To
        Add

        <input type="text"  placeholder="who" name="who" />
        <input type="text"  placeholder="location" name="location" />
        <input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"/>
        <input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"/>
        <input type="button" name="add" value="Add" class="tr_clone_add"/>
        <input type="button" value="Delete" onclick="deleteRow(this)"/>

Jquery:

Javascript:

A: Your problem: Trying to change input value before adding it in HTML markup.
Solution: Change value after adding element to HTML.
Also, using class selector .datepicker would be better in this case.
This will work,
$("input.tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    console.log($tr);
    var $clone = $tr.clone();
    $tr.after($clone);
    $($clone).find(".datepicker").val('');
});

DEMO

A: Update: I had miss understood the question, since you need not require the dates, here is your answer and an update fiddle
Code Snippet:
$("input.tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var $clone = $tr.clone();
    $clone.find('.datepicker').val('');
    $tr.after($clone);
});

A: Working JS Fiddle Demo http://jsfiddle.net/D36ZL/1/
Your HTML:

        Name
        Location
        From
        To
        Add

            <input type="text" placeholder="who" name="who" />

            <input type="text" placeholder="location" name="location" />

            <input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker" />

            <input type="text" placeholder="End Date" name="datepicker_end" class="datepicker" />

            <input type="button" name="add" value="Add" class="tr_clone_add" />

            <input type="button" value="Delete" onclick="deleteRow(this)" />

Some jQuery:
$("table").on('click', 'input.tr_clone_add', function () {
    var $tr = $(this).closest('.tr_clone');
    var $clone = $tr.clone();
    $tr.after($clone);
    $clone.find('.datepicker').val('');
});

Using $("table").on('click', 'input.tr_clone_add', function () { is a better way, since you are generating the HTML dynamically.
Cheers!
Update:
As mentioned, there is no need to put class datepicker in loop, hence altered the solution.


text:
Q: Axon: How to configure amqp publishing for single events? I have a simple spring-driven service which publishes events via amqp.
The configuration is based on bootiful-axon.
Now I want the service to maintain some private state. It is a simple use case that can be realized with 3 extra events. Those events have no meaning outside the service's scope so I don't want them to "leave".
How can I specify which events should be published via amqp and which not?

A: This is how I solved it:
Custom SpringAMQPPublisher that intercepts the send method:
public class SelectiveAmqpPublisher extends SpringAMQPPublisher {

    static boolean shouldSend (Class<?> pt) {
        return PublicEvent.class.isAssignableFrom(pt);
    }

    public SelectiveAmqpPublisher (
            SubscribableMessageSource<EventMessage<?>> messageSource) {

        super(messageSource);

    }

    @Override
    protected void send (List<? extends EventMessage<?>> events) {

        super.send(events.stream()
                        .filter(e -> shouldSend(e.getPayloadType()))
                        .collect(Collectors.toList()));

    }

}

Configuration:
@Autowired
private AMQPProperties amqpProperties;

@Autowired
private RoutingKeyResolver routingKeyResolver;

@Autowired
private AMQPMessageConverter aMQPMessageConverter;

@Bean(initMethod = "start", destroyMethod = "shutDown")
public SpringAMQPPublisher amqpBridge(
             EventBus eventBus,
             ConnectionFactory connectionFactory,
             AMQPMessageConverter amqpMessageConverter) {

    SpringAMQPPublisher publisher = new SelectiveAmqpPublisher(eventBus);

    // The rest is from axon-spring-autoconfigure...

    publisher.setExchangeName(amqpProperties.getExchange());
    publisher.setConnectionFactory(connectionFactory);
    publisher.setMessageConverter(amqpMessageConverter);
    switch (amqpProperties.getTransactionMode()) {

        case TRANSACTIONAL:
            publisher.setTransactional(true);
            break;
        case PUBLISHER_ACK:
            publisher.setWaitForPublisherAck(true);
            break;
        case NONE:
            break;
        default:
            throw new IllegalStateException("....");
    }

    return publisher;

}


text:
Q: Rewrite by lua : Match host I have this lua script that redirect the user based on his browser laungage.
location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
            if string.sub(lang, 0, 2) == "en" then
                ngx.redirect("/en/index.html")
            end
            if string.sub(lang, 0, 2) == "nl" then
                ngx.redirect("/nl/index.html")
            end
            if string.sub(lang, 0, 2) == "de" then
                ngx.redirect("/de/index.html")
            end
        end
        ngx.redirect("/en/index.html")
    ';
}

I only want to match url that ends with mysite.org
Any idea how I can add the criteria?
the result sould be something like this:
if string.sub(lang, 0, 2) == "nl" and host == "mysite.org" then
                    ngx.redirect("/nl")
                end

A: Without having full details of your exact input, I think the below should work:
location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
          lang = lang:sub(1, 2)
          if host:match("mysite%.org$") then
            if lang == "en" then ngx.redirect("/en/index.html")
            elseif lang == "nl" then ngx.redirect("/nl/index.html")
            elseif lang == "de" then ngx.redirect("/de/index.html")
            end
          end
        end
        ngx.redirect("/en/index.html")
    ';
}

Also note the use of elseif to make code shorter.  On another note, explicit checking for 'en' language could be omitted as it is the default fall-through case.


text:
Q: TelemetryClient.Flush() takes about 2 minutes to run during application exit I have a .NET Core 3.1 console application running as a hosted service. When the application shuts down, it hangs for about 2 minutes. When breaking in I can see that it is hanging on TelemetryClient.Flush(), specifically inside InMemoryChannel.Flush().
So I watch the result in Fiddler and I can see the application is making a request out to https://dc.services.visualstudio.com/v2/track to report the telemetry, but that service doesn't respond. Eventually after 2 minutes the response fails with 500 and in the web response: "IIS 10.0 Detailed Error - 500.1013 - Internal Server Error".
I cannot tell if this is something I am doing wrong or not. So I shortened the application to the bare minimum.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace DotNetCoreConsoleAppTest
{
    public class Program
    {
        public static async Task Main()
        {
            await Host.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    services
                        .Configure<TelemetryConfiguration>(options =>
                        {
                            options.InstrumentationKey = "<put your key here>";
                        })
                        .AddSingleton<TelemetryWriter>()
                        .AddHostedService<ProgramHost>();
                })
                .RunConsoleAsync()
                .ConfigureAwait(false);
        }
    }

    public class TelemetryWriter : IDisposable
    {
        private readonly TelemetryClient _telemetryClient;

        public TelemetryWriter(IOptions<TelemetryConfiguration> telemetryConfiguration)
        {
            _telemetryClient = new TelemetryClient(telemetryConfiguration.Value);
        }

        public void WriteEvent() => _telemetryClient.TrackEvent("test");

        public void Dispose() => _telemetryClient.Flush();
    }

    public class ProgramHost : IHostedService
    {
        private readonly TelemetryWriter _telemetryWriter;
        private readonly IHostApplicationLifetime _hostApplicationLifetime;

        public ProgramHost(
            TelemetryWriter telemetryWriter,
            IHostApplicationLifetime hostApplicationLifetime)
        {
            _telemetryWriter = telemetryWriter;
            _hostApplicationLifetime = hostApplicationLifetime;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _telemetryWriter.WriteEvent();
            _hostApplicationLifetime.StopApplication();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}

Some content from the web response:

 <fieldset>
Detailed Error Information:

Module	   iisnode

Notification	   ExecuteRequestHandler

Handler	   iisnode

Error Code	   0x0000006d

Requested URL	   https://dc.services.visualstudio.com:443/InputServer.js

Physical Path	   E:\sitesroot\0\InputServer.js

Logon Method	   Anonymous

Logon User	   Anonymous

Request Tracing Directory	   C:\Resources\directory\f3eec886680f474eb56deb0e59f20036.Breeze.DiagnosticStore\FailedReqLogFiles\Web

 </fieldset>

The hanging stack trace is:
System.Private.CoreLib.dll!System.Threading.ManualResetEventSlim.Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken)    Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.Task.SpinThenBlockingWait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken)  Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.Task.InternalWaitCore(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken)  Unknown
System.Private.CoreLib.dll!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task task)    Unknown
System.Private.CoreLib.dll!System.Runtime.CompilerServices.TaskAwaiter.GetResult()  Unknown
Microsoft.ApplicationInsights.dll!Microsoft.ApplicationInsights.Channel.InMemoryTransmitter.DequeueAndSend(System.TimeSpan timeout) Unknown
Microsoft.ApplicationInsights.dll!Microsoft.ApplicationInsights.Channel.InMemoryTransmitter.Flush(System.TimeSpan timeout)  Unknown
Microsoft.ApplicationInsights.dll!Microsoft.ApplicationInsights.Channel.InMemoryChannel.Flush(System.TimeSpan timeout)  Unknown
Microsoft.ApplicationInsights.dll!Microsoft.ApplicationInsights.Channel.InMemoryChannel.Flush() Unknown
Microsoft.ApplicationInsights.dll!Microsoft.ApplicationInsights.TelemetryClient.Flush() Unknown
DotNetCoreConsoleAppTest.dll!DotNetCoreConsoleAppTest.TelemetryWriter.Dispose() Line 43 C#
Microsoft.Extensions.DependencyInjection.dll!Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.DisposeAsync()   Unknown
Microsoft.Extensions.Hosting.dll!Microsoft.Extensions.Hosting.Internal.Host.DisposeAsync()  Unknown
Microsoft.Extensions.Hosting.Abstractions.dll!Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(Microsoft.Extensions.Hosting.IHost host, System.Threading.CancellationToken token)    Unknown
Microsoft.Extensions.Hosting.dll!Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.RunConsoleAsync(Microsoft.Extensions.Hosting.IHostBuilder hostBuilder, System.Threading.CancellationToken cancellationToken) Unknown
DotNetCoreConsoleAppTest.dll!DotNetCoreConsoleAppTest.Program.Main() Line 16    C#
DotNetCoreConsoleAppTest.dll!DotNetCoreConsoleAppTest.Program.()  Unknown

Despite all of this, the events DO appear in the logs inside of Application Insights. The only problem is my host application hangs. Is this a problem with the way I am trying to Flush()? Or is this an Application Insights service problem?

A: ZakiMa answered my question -- App Insights was having an outage.


text:
Q: Concatenating multiple arrays in ruby I'm trying to make a method that accepts a nested array. From that nested array, I need to return all possible combinations that can be made by the sub-arrays. I have been working on it for hours now and I still can't get it to work.
It's like concatenating each element of a sub_array with each element from the other sub_arrays.
example:
mega_array = [["a","b"],["c","d"],["e","f"]]

my_method(mega_array)

=> ["ace","acf","ade","adf","bce","bcf","bde","bdf"]

This would have been accomplished by the following code:
mega_array[0].each do |first|
    mega_array[1].each do |second|
        mega_array[2].each do |third|
            puts first + second + third
        end
    end
end

Unfortunately, the number of subarrays can vary. This is where I'm stuck. Tried to do some recursive techniques but I still don't get it right.
Help will be greatly appreciated. I need to make this work with the vanilla Ruby that comes with Leopard and up. It's 1.8.7, right?
Thanks.

A: >> mega_array[0].product(*mega_array[1..-1]).map(&:join)
=> ["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"]


text:
Q: EditText field displaying data on different tabs I'm having some pretty strange issues with my app. I have an EditText element, lets call it display, in a reused fragment for each tab. Every time I launch the app I see the following initial behaviour when I click a button that sends text to the output display. I do not use the system keyboard, only my buttons send to the display.
The best way to think of this is like a web browser with tabs, you can edit the URL in each tab independently, and the buttons, that live below in the other two sections, supply the input. It's not a web browser, but the analogy works.

*

*Don't click on anything -> Text drawn in B tab

*Click on B -> Text drawn in C tab

*Click on C -> Text drawn in C tab

*Click on B -> Click on C -> App Crashes

I might be running into a fencepost error but I'm not sure. I can get text to draw in A's output but only after a click or two.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.container);

    midPager = (ViewPager) findViewById(R.id.function_container);
    topPager = (ViewPager) findViewById(R.id.top_container);
    midPagerAdapter = new midPageAdapter(getFragmentManager());
    midPager.setAdapter(midPagerAdapter);

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

    TabsAdapter topTabsAdapter = new TabsAdapter(this,topPager);
    topTabsAdapter.addTab(actionBar.newTab().setText("1"),
                          TopFragment.class, null);
    topTabsAdapter.addTab(actionBar.newTab().setText("2"),
                          TopFragment.class, null);
    topTabsAdapter.addTab(actionBar.newTab().setText("3"),
                          TopFragment.class, null);

    if (savedInstanceState != null) {
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab",0));
    }
}

And in my function that manages the tabs this is what I have:
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final ActionBar mActionBar;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    static final class TabInfo {
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(Class<?> _class, Bundle _args) {
            clss = _class;
            args = _args;
        }
    }

    public TabsAdapter(Activity activity, ViewPager pager) {
        super(activity.getFragmentManager());
        mContext = activity;
        mActionBar = activity.getActionBar();
        mViewPager = pager;
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
        TabInfo info = new TabInfo(clss, args);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        mActionBar.addTab(tab);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    @Override
    public Fragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        mActionBar.setSelectedNavigationItem(position);
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        Object tag = tab.getTag();

        for (int i = 0; i < mTabs.size(); i++)
        {
            if (mTabs.get(i) == tag)
            {
                setActiveMap(i);
                mViewPager.setCurrentItem(i);
            }
        }
    }
}

In my reusable fragment I have this for my OnCreate function.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.top_fragment, container, false);
    Foobar active = Container.getActiveMap();
    active.editLine = (EditText) v.findViewById(R.id.display);
    active.editLine.setCursorVisible(false);
    active.editLine.addTextChangedListener((TextWatcher) this);
    ((EditText) v.findViewById(R.id.display)).setOnClickListener(this);
    return v;
}

One question that would help me debug this is how can I debug EditText within a reused fragment in tabs? What data does an EditText widget use to distinguish itself from tab to tab? I've tried various .tostring()'s of functions without success.
The more ideal solution is a simple error you spot in this code. Thanks for your help.
We could have 3 separate fragments but they all are of the same configuration however that seems unnecessarily ugly.


text:
Q: Are there any cons to buying a used iPhone 4S unlocked by a Gevey sim? In comparison to a factory unlocked iPhone, are there any cons to buying a used iPhone 4S unlocked by a Gevey sim?

A: The big downside is that the phone isn't really unlocked.
Apple could patch the exploit that allows it to work in a firmware update. Also, you may have to re-unlock it every time you power off your phone or lose signal for more than a couple of seconds. Some people also report poor signal and battery performance with it. Theres some more info here or just google "disadvantages of Gevey Sim."


text:
Q: Push new widget to DOJO attach point not replace I have the following
    postCreate: function() {
        this.items.forEach(lang.hitch(this, function(item) {
            new SideNavigationItem({
                name: item.name
            }, this.container);
        }));
    }

Which adds a new li item to a ul, the ul template has an attach point that I want to built all of the lis into - however doing the above just replaces the attach point's content with the next li being created upon iteration
Any ideas how I can go about achieving this?

A: Try this instead.  The key is to use _WidgetBase placeAt() method which functions similar to domConstruct place() method
Example
// place a new button as the first element of some div
var button = new Button({ label:"click" }).placeAt("wrapper","first");

If you omit the third parameter, like I did in the solution below, the default position is 'last' which is what you want.
Template

existing list item

JavaScript
    this.items.forEach(lang.hitch(this, function(item) {

         var listItem = new SideNavigationItem({name: item.name});
         listItem.placeAt(this.myAttachPoint);

         //if that doesn't work try it just with plain
 item
         //var listItem = domConstruct.toDom("

");
         //domConstruct.place(listItem, this.myAttachPoint);
    }));


text:
Q: Convert OrderBy Predicate to Where Predicate based on the current object I am new to LINQ and creating a generic function that will get the next object based on the current object and the OrderBy predicate. I need to take the property being ordered by and create a where property > currentObject.property.
Is this possible or is there a better way to do this?
GetNextArticle(IArticle current, Func<IArticle, bool> where, Func<IArticle, IComparable> orderBy)
    {
        return Articles.Where(where && x => x.[orderByIComparable] > current.[orderByIComparable]).OrderBy(orderBy)
    }

I hope this make sense
Solution
    public IArticle GetNextArticle(IArticle current, Func<IArticle, bool> where, Func<IArticle, IComparable> orderBy)
    {
        var articles = NewsItems
            .Where(where)
            .OrderBy(orderBy)
            .SkipWhile(a => a.PageId != current.PageId);

        return articles.Count() > 1 ? articles.Skip(1).Take(1).First() : null;
    }

A: I don't completely understand what I mean, but I think you want the next article in the passed order, so one way would be this:

*

*Order the articles

*Find the current one

*Return the next one

This assumes an Id property exists:
return Articles
   .Where(where)
   .OrderBy(orderBy)
   .SkipWhile(a => a.Id != current.Id)
   .Skip(1)
   .Take(1);


text:
Q: redirect to https://my-site/wp-admin/ instead of https://my-site/wordpress/wp-admin/ after options updating I installed my plugin for one of my clients but I got a bug.
In my plugin settings page using the wordpress settings system, when I click on the submit button to activate a license key, the reditection is https://my-site/wp-admin/options-general.php?page=settings-my-plugin&tab=premium&action=activate
instead of https://my-site/wordpress/wp-admin/options-general.php?page=settings-my-plugin&tab=premium&action=activate
I searched the problem and this is the result :
echo '<form method="post" action="options.php">'; //initial code - wrong redirection

<input type="hidden" name="_wp_http_referer" value="/wordpress/wp-admin/options-general.php?page=settings-my-plugin&tab=premium">//seems to be correct

admin_url(); //write https://my-site/wordpress/wp-admin/

printf( '<form method="post" action="%soptions.php">', admin_url() ); //same redirection error

.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

wordpress/.htaccess
# BEGIN s2Member GZIP exclusions
<IfModule rewrite_module>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteCond %{QUERY_STRING} (^|\?|&)s2member_file_download\=.+ [OR]
    RewriteCond %{QUERY_STRING} (^|\?|&)no-gzip\=1
    RewriteRule .* - [E=no-gzip:1]
</IfModule>
# END s2Member GZIP exclusions
# BEGIN WordPress

# END WordPress

[root]index.php
<?php //include_once("wordpress/index.php"); ?>

So, how can I resolved this problem to match with any admin url ?

A: The solution was :

*

*not use the index.php to include the folder /wordpress/

*not use wordpress/.htaccess

*use only .htaccess to point to subfolder
<IfModule mod_rewrite.c>
    RewriteEngine On
    #https
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP_HOST} ^(www.)?my-site.com$
    #point to subfolder
    RewriteCond %{REQUEST_URI} !^/wordpress/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /wordpress/$1
    RewriteCond %{HTTP_HOST} ^(www.)?my-site.com$
    RewriteRule ^(/)?$ wordpress/index.php [L]
</IfModule>


text:
Q: Error-2 : End kernel Panic while booting After running sudo apt-get -f install command at terminal and downloaded about 351 MB of fixes, I restarted Ubuntu 16.04 OS but after selecting "Ubuntu" From Windows Boot Menu (Default OS : Windows 10) and then selecting ubuntu from GRUB menu, screen hanged at purple-orange wallpaper - one which is shown in GRUB menu, something like this image:Grub Boot loader Menu and caps lock key was continuously blinking .
I restarted by holding power key for 5 Seconds and then again selected "Ubuntu" from Windows Boot Loader and selected Advanced Options from GRUB Menu and then recovery mode (I don't know  what's written after that) and after in DOS like screen after all the commands were loaded automatically, an error was shown :

end Kernel Panic - not synced Requested init/sbin/upstart failed (error-2)

Please Help

PC Specs:
Operating systems installed:
Windows 10 64 bit ,Windows 8.1 64 bit , Ubuntu 16.04 LTS 64 bit
Laptop has BIOS, not UEFI.
More Info: PC Specs screenshot taken from windows 8.1

Thanks in advance


text:
Q: ubuntu server not seeing ethernet port i am trying to setup ubuntu server on a normal desktop computer. the install went fine (even though it didnt connect to the internet) i figured i would have to change some network config settings. but i cant find anything wrong with the file.
auto eth0
iface etho inet6 dhcp

no attempt to connect works. any ideas?
i would think it would have something to do with it not being mounted or morthing of that nature. a kind of secondary question is, if everythin in linux is a file, where do i see all of the hardware? and would that be a good place to start looking?

A: Had this problem myself.
Sources Here and here
In your installation did it say "Network autoconfiguration failed
Your network is probably not using the DHCP protocol. Alternatively,
the DHCP server may be slow or some network hardware is not working
properly."
In the terminal try:
sudo lshw -class network

it will give you a list of hardware and should give you an output that looks something like this:
*- network DISABLED
       description: Ethernet interface
       product: BCM4401-B0 100Base-TX
       vendor: Broadcom Corporation
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: eth0
       version: 02
       serial: 00:15:c5:4a:16:5a
       size: 10MB/s
       capacity: 100MB/s
       width: 32 bits
       clock: 33MHz
       capabilities: (snipped for brevity)
       configuration: (snipped for brevity)
       resources: irq:17 memory:ef9fe000-ef9fffff

If you return nothing your hardware may be faulty.
If your network is disabled try one of these three commands too bring it up:
your logistical name will be listed in your first output.

*

*ip link set dev <logistical name> up

*/sbin/ifconfig <logistical name> up

*ifconfig <logistical name> up


text:
Q: Length of supporting ropes in a two-pulley system
Say I want to find the length of each component. I thought that in an ideal two-pulley system, each side of the supporting rope has a length 1/2 of the effort distance. So if I want to lift an object 3m in the air, I would think each supporting rope has a length of 3m and the effort distance is 6m. According to Kaplan MCAT Physics book, "If, for example, the crate must be lifted to a shelf 3 m above the ground, then both sides of the supporting rope must be shortened by 3 meters, and the only way to accomplish this is by pulling through  6 meters of rope". Why aren't the supporting ropes 3 m each?

A: The supporting ropes are not necessarily 3 metres each just because they are each shortened by 3 metres when the body is lifted through that height - they could be any length $l \geq 3$ metres and will just wind up 3 metres shorter, of length $l -3$ metres, once the action is complete. To summarise: "because the problem presented never implies it, and because that information is not needed to work out everything there is to know about the system".
This of course applies to an idealised system where we are assuming that

*

*The physical components of the pulley, wheels, rope, et cetera, don't get in the way of one another, have negligible mass, and -

*The supporting ropes are all perfectly vertical, such that the total length of rope reduced is exactly twice the displacement through which the weight is lifted.


text:
Q: Is there a way to send variable values to a python script or a way to print the value into a text file? i am trying to use take values from indicator scripts that are written in pine-script and use them to make desicions in a python, is there a way to send the values to the python script or write them into a text file so the python script can read them from there?

A: In an inherently complex way, yes, it is doable.
Pine scripts (and the Tradingview interface in general) can create Alerts where you can create an Alert message with any custom data (meaning, you can send whatever you want).
Those alerts can trigger a HTTP request with the above alert message attached so it can talk to a webserver, sending your data payload along with it. Now you just need to set up your own webserver and have your python app run under that webserver and you have just connected a Pine script with your Python code.
Why not code the logic in Pine script, or why not get that indicator value from other - easily accessible - source?


text:
Q: CSS getting extra padding inside ul I am trying to make a dropdown ul, using position:absolute;.I could successfully stick it by adding position: relative; to it's parent, and position: absolute; to itself, and right: 0; with z-index:999; so it overlaps everything.
But unfortunately, I am getting random extra padding inside the ul.

(source: gyazo.com)
A you see, the li has a red background, the ul has a green background.
You can see there is around 10 to 15px padding at the top.
When I created my CodePen, I had to copy/paste the whole container in order to get this bug to work here, it means that it's not the ul itself, but something outside of the ul causes it, but I am not really sure why, I've checked it a few times.
There's a live CodePen example: http://codepen.io/anon/pen/Dohpn
What did I do wrong?

A: You're forcing your first li element to be displayed 15px from the top of the ul element with a margin-top.
Take out
#filtersContent section ul li {
    margin-top: 5px;
}
#filtersContent section ul li:first-child {
    margin-top: 15px;
}

Updated CodePen

A: You need to remove the margin from your #filtersContent section ul li and filtersContent section ul li:first-child.
The margin-top that you have set for these is adding additional space.
Edit: Check out how to use the Chrome developer tools and Firebug for firefox. These tools will make tracking down this stuff much easier than guess and check!

A: you can remove below styles. here is working code  http://codepen.io/anon/pen/amoFh
/*#filtersContent section ul li {
    margin-top: 5px;
}
#filtersContent section ul li:first-child {
    margin-top: 5px;
}*/


text:
Q: How to wget/curl a dynamically built zip archive? I'm trying to create a script that will download a dynamically built Initializr zip archive.  Something like:
wget http://www.initializr.com/builder?mode=less&boot-hero&h5bp-htaccess&h5bp-nginx&h5bp-webconfig&h5bp-chromeframe&h5bp-analytics&h5bp-build&h5bp-iecond&h5bp-favicon&h5bp-appletouchicons&h5bp-scripts&h5bp-robots&h5bp-humans&h5bp-404&h5bp-adobecrossdomain&jquery&modernizrrespond&boot-css&boot-scripts

That url works in a browser, but not in a script.  In a script it downloads a small portion of the archive, and saves it as builder?mode=less instead of initializr-less-verekia-3.0.zip.
builder?mode=less actually unzips, so it is just a misnamed a zip file.  But it's missing probably 80% of the files it should have.
Anyone know how to script this?

A: urls contain shell metacharacters, so you'll have to quote the whole url:
wget 'your...url...here'

If the initializr website doesn't put a proper filename into the HTTP response headers, wget will use a best-guess version based on the url being requested. You can force it to write to a specific filename with
wget 'your url here' -O name_of_file.zip


text:
Q: Retrieve data from a Quartz Job I'm using Quartz Scheduler and I have a job to process accounts:
public class MyJob implements Job {

    public void execute(JobExecutionContext ctx) throws JobExecutionException {
        List<String> accounts = (List<String>) ctx.getJobDetail().getJobDataMap().get("accounts");
        for(String account : accounts) {
            // process account
        }
    }

}

This works fine, but I have a button on the webpage and when I click it, I want to see the progress logged to my website.
So on clicking the button an ajaxcall is done every second, but how can I return something from this job?
putting it on the jobDataMap didn't seem to work. Or maybe I missed something.

A: Some solutions:

*

*Store the progress somewhere externally (like database or synchronized map/coutner). JobDataMap is only updated when the job finishes. Your AJAX request can then query the global progress variable

*Similar to 1.: send some event (JMS? maybe something more leightweight) and listen for that event somewhere else in your system.

*Instead of one huge job processing all accounts schedule single job per account. Then you can monitor the progress of each individual job or see how many jobs finished.


text:
Q: Windows Azure: node.js + mongodb setup cheaply I am building a chrome extension that needs a backend to store user information. So far, we have been using Firebase, a real-time solution that we can access from the front end. Yet we will need to store approximately 200GB of data so Firebase seems less viable for a startup budget.
We were looking into transitioning  to hosting a node.js app in the cloud and then communicating with a mongodb database. We were looking into Azure for this purpose. Yet it seems the only way to do this is getting MongoLab, which is still really expensive. Isn't there a way to store a lot data in mongodb without incurring in huge costs? For some reason, the SQL databases look way cheaper, which does not make much sense to me.
some links for reference.
SQL pricing:
http://azure.microsoft.com/en-us/pricing/details/sql-database/
mongodb pricing:
https://mongolab.com/plans/pricing/

A: Sure you can get Mongo running in Azure. You would simply fire up a new Linux VM and install Mongo and you're off!
http://azure.microsoft.com/en-us/pricing/details/virtual-machines/#Linux
Your question hints that the biggest priority is disk space. Storage in Azure is pretty cheap. Let's imagine you get an A2 instance with 60 GB of space and you run out of space. You can easily attach new disks in Azure and the storage is really cheap.
The classic way to scale Mongo however is to use a replica set, in which case you'll need to pay for more nodes/machines as you add them.


text:
Q: Function for every a django-model I have django-models and I made a function, for example:
def function(django-model):
    return django-model.objects.order_by('-date')

I want execute function for all models, but I don't know how it works.
function(django-model-1())

or
function(django-model-2)

return:
AttributeError: Manager isn't accessible via django-model-1 instances

Thanks for help and sorry for my English.
Upd:
Sorry, maybe I poorly explained.
I need a universal function for manipulating models.
from django-model-1.models import django-model-1
from django-model-2.models import django-model-2

    def function(django-model):
        return django-model.objects.order_by('-date') # This is only for example

function(django-model-1)
function(django-model-2)

But it's don't work.
If I make without the function, it's work.
django-model-1.objects.order_by('-date')

A: Django Model definitions define the tables to store records and they also define what an instance of that object looks like and how it behaves. objects is a special attribute on a Model class (not on the instances) that allow you to do things to all of the instances (such as query the tables). objects is a type of ModelManager.
What you want to do is define a custom manager.
Let's say you have a model definition like so:
class SomeModel(models.Model):
     pass

Well, you can define a custom manager for your model with a custom method like so:
class SomeModelManager(models.Manager):
    def datesort(self):
        return self.order_by('-date')

Now, you can attach your manager to your model definition and give it whatever name you want:
class SomeModel(models.Model):
    sorting = SomeModelManager()

Now, you can import and use that sorting Manager:
 >>> from some_app.models import SomeModel
 >>> SomeModel.sorting.date()  # Not called on an instance!
 [sorted results]

The key thing to realize is that you do not want to work on instances of SomeModel, but the actual ModelManager itself. This is often confusing in Django because you get to them by interacting with the same class.
See the docs for more info:
https://docs.djangoproject.com/en/1.9/topics/db/managers/


text:
Q: Cosmos DB SQL API query tracing I have many collections in Cosmos DB (SQL API) and many services using the same database. 100s of query executing every minute, Sometimes I can see RU exceeding warning. I know all query is not optimized in all the application.
Is there any way to get all queries and execution time (like SQL server Profiler Trace)?
I tried to enable Cosmos DB Diagnostic Settings, but didn't get any way to trace queries

A: The way you would have to go about it is enabling PopulateQueryMetrics in the SDK.
Ones enabled your queries will have the x-ms-documentdb-query-metrics header populated. The value looks like this:
totalExecutionTimeInMs=33.67;queryCompileTimeInMs=0.06;queryLogicalPlanBuildTimeInMs=0.02;queryPhysicalPlanBuildTimeInMs=0.10;queryOptimizationTimeInMs=0.00;VMExecutionTimeInMs=32.56;indexLookupTimeInMs=0.36;documentLoadTimeInMs=9.58;systemFunctionExecuteTimeInMs=0.00;userFunctionExecuteTimeInMs=0.00;retrievedDocumentCount=2000;retrievedDocumentSize=1125600;outputDocumentCount=2000;writeOutputTimeInMs=18.10;indexUtilizationRatio=1.00

As you can see this needs be to split and parsed but it has a lot of useful info which you can log and query to see a lot of stuff about your queries and their performance.
You can read more about query metrics here: https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-query-metrics


text:
Q: NavigationLink not working inside a button I have added a ToolBarItemGroup with a button that should navigate to another view.
But in this case the button with navigationLink does not work
It is because I am not able to add a navigationLink to .toolbar?
VStack {
    NavigationView {
         List {

         }.toolbar {
             ToolbarItemGroup(placement: .navigationBarTrailing) {
                 Button("MyButton") {
                      NavigationLink(Destination: ContentView()) {
                          ContentView()
                      }
                 }
             }
         }

Whenever I click the MyButton, it does not navigate to my ContentView.
What I am doing wrong here? I want to use the button in the toolbar

A: NavigationLink is actually a type of button, albeit one with different constructors and default styling (for example, when you use it inside a List).
In your example code, you're putting it inside another button's action closure, which should contain code to execute rather than SwiftUI views.
Your toolbar can be more simply expressed as:
.toolbar {
  NavigationLink("MyButton") {
    ContentView()
  }
}


text:
Q: yii2 framework applying a new theme I've gone through the steps in the guide, however my request to index.php gives me "Object not found!"
I have created dirs:

*

*themes/ directory in /web/

*basic/ directory in /web/themes/

*moved all files from /web/* to /web/themes/basic/

*moved views/ directory to /web/themes/basic/

*have the web.php changed to
'components' => [
    'view' => [
        'theme' => [
            'pathMap' => ['@app/views' => '@app/themes/basic/views'],
            'baseUrl' => '@web/themes/basic/views',
        ]
    ],

and my AppAsset.php is like
public $basePath = '@webroot';
public $baseUrl = '@web';

Where I could go wrong?
Also, in cases like this, how can I use debugging?

A: The guide does not tell you to create the directory @web/themes, it tells you to create @app/themes. So you have created the theme folder in the wrong place. The reason why you should NOT have it in @web is that the entire @web folder is opened to the public, your themes are php files and should not be opened to the public.
@web is basically yourapplicationfolder/web, @app is yourapplicationfolder
In case you use the advanced template yourapplicationfolder is either frontend or backend. Also when I used the theme I configure it like this
'view' => [
            'theme' => [
                'pathMap' => [
                    '@app/views' => '@app/assets/theme/views',
                ],
                'baseUrl' => '@web/',
            ],
        ],

Notice that I still have 'baseUrl' => '@web/',


text:
Q: $\sum \limits_{k=1}^{p-1}\frac{(p-1)!}{k} \equiv 0 \ [p]$? Here's the expression :
$\frac{(p-1)!}{1}+\frac{(p-1)!}{2}...+\frac{(p-1)!}{p-1}= (p-1)\times...\times2+(p-1)\times...\times1+...+(p-2)\times...\times1=q$.
For $p=5$ we obtain : $(4.3.2)+(4.3.1)+(4.2.1)+(3.2.1)=50$
I precise that $q\in \mathbb{N}^*$, and $p\ge 3$ a prime number.
We know that there are $(p-2)$ terms of each $k\in\{1,...,p-1\}$
$p$ divides $q$ ?
I don't search for a polynomial method or an arrangement of the coefficients. Just by developing is it possible ?
Thanks in advance !

A: Method 1
For distinct $k, \ell \in \{ 1, 2, \ldots, p-1 \}$, we have
$$\frac{(p-1)!}{k} - \frac{(p-1)!}{\ell} = \frac{(p-1)!}{k\ell}(k - \ell)\tag{*1}$$
The first factor is a product of numbers relative prime to $p$. The second factor $k - \ell$ is a number with $0 < |k - \ell| < p$.  So RHS and hence LHS of $(*1)$ is relative prime to $p$. This means
$$\frac{(p-1)!}{k} \not\equiv \frac{(p-1)!}{\ell} \pmod p \quad\text{ for distinct }\quad k, \ell \in \{ 1,2,\ldots,p-1 \}$$
So under modulus $p$ arithmetic,
$\frac{(p-1)!}{k}$ is simply a relabeling of the $p-1$ equivalent classes of integers relative prime to $p$. As a result,
$$\sum_{k=1}^{p-1}\frac{(p-1)!}{k} \equiv \sum_{\ell=1}^{p-1} \ell = \frac{p(p-1)}{2} \equiv 0 \pmod p$$
Method 2
$$\sum_{k=1}^{p-1}\frac{(p-1)!}{k} = \sum_{k=1}^{\frac{p-1}{2}}\left[\frac{(p-1)!}{k} + \frac{(p-1)!}{p-k}\right]
= \sum_{k=1}^{\frac{p-1}{2}}\frac{(p-1)!}{k(p-k)}((p-k) + k)\\
= \sum_{k=1}^{\frac{p-1}{2}}\frac{p!}{k(p-k)}
= p \left[ \sum_{k=1}^{\frac{p-1}{2}}\frac{(p-1)!}{k(p-k)}\right]\tag{*2}
$$
Notice for each $1 \le k \le \frac{p-1}{2}$, $\displaystyle\;\frac{(p-1)!}{k(p-k)} = \prod_{\ell = 1, \ne k, p-k}^{p-1} \ell$ is a product of integer, so it is an integer.
This implies the sum in the square bracket on RHS of $(*2)$ is an integer.
As a result, RHS and hence LHS of $(*2)$ is a multiple of $p$.

A: Apply Wilson's Theorem:  $$(p-1)!\equiv -1 \pmod p\implies \frac {(p-1)!}k\equiv -k^{-1} \pmod p$$  For any non-zero residue $p$.
Thus the desired sum is just $$-\sum_{l=1}^{p-1}k^{-1}$$  But, up to sign, that's just the sum of the residues (as no two residues have the same inverse).  As $p$ is odd, the sum of the residues $\pmod p$ is $0$.
As a side note, OEIS A007619 gives the sequence of "Wilson's quotients", i.e. $\frac {(p-1)!+1}p$ for primes $p$. There is no reference there to any alternate expression for them.  Doesn't prove there isn't a simple expression which gives them, of course, nor does it prove that there isn't a simple expression for your quotient.


text:
Q: Every even number $2n$ can be written in the form $2n= (x+y)^2 + 3x +y $ with $ x,y$ non negative integers. Can someone give a hint for the solution of this question?
Question: Every even number $2n$ can be written in the form $2n= (x+y)^2 + 3x +y $ with $ x,y$ non negative integers.
My attempt : I have tried expanding the right hand side and it's obvious that it is even. But how do I proceed to prove that for each and every even integer there exists a value of $ x$ and $y$?  I even tried considering the expression as a quadratic in one of its variables but I still find it a bit difficult to resolve the discriminant as a perfect square. Can someone help here please?

A: By induction you have that $2=(0+1)^2+3\cdot 0+1$. Suppose now that you can write $2n=(x+y)^2+3x+y$, then $2(n+1)=2n+2=(x+y)^2+3x+y+2=((x+1)+(y-1))^2+3(x+1)+(y-1)$,so the thesis is veryfied also for $n+1$ if $y\ge 1$. But suppose $y=0$ then $2n=x^2+3x$ and $2(n+1)=x^2+3x+2=(x+1)^2+(x+1)=(0+(x+1))^2+3\cdot 0+(x+1)$ and so your thesis is true by induction.

A: Denote $x+y$ by $z$. You want $2n=z(z+1)+2x$, $z\ge x\ge 0$. So $$n=(z+1)z/2+x=1+2+...z +x.$$ Take $z$ maximal  so that $a=1+2+...z\le n$ and $x=n-a$. We only need to check that $z\ge x$. Indeed $a+z+1\ge n+1$. So $x=n-a\le z$.

A: For a given $n\ge0$, take
$$m:=\left\lfloor\frac{\sqrt{8n+1}-1}2\right\rfloor,\\x=n-\frac{m(m+1)}2,\\y=m-x,$$ which are always defined.
E.g. $n=43\to m=8,x=7,y=1; n=3\to m=2,x=0,y=2; n=1000\to m=44, x= 10, y=34\ \cdots$


text:
Q: import data in oracle I know how to use the "imp" to import the .dmp data . But I wonder if I have to create the tablespace first,for example?
Other people have a oracle database instance,and he create a user "sa_one" whose defaule tablespace is "tabspace_one",then he create some tables under this tablespace.
Then he export the objects under the user "sa_one" to a xx.dmp.
Now,in my machine,I have my own database instance,and I create a user "sa_two" whose defaule tablespace is "tabspace_two".
Now if I want import the xx.dmp to the user "sa_two". I use the cmd:
imp fromuser=sa_one touser=sa_two file=xx.dmp

But I wonder if I have to create a tablespace "tabspace_one" in my database instace?

A: Yes, I believe you have to create the tablespace AND give the sa_two user rights on it.  I usually use a group of SQL commands like this:
create tablespace my_data
datafile 'C:\Oracle\oradata\orcl\my_data.dbf' size 50m
autoextend on next 10m
/

drop user sa_two cascade
/

create user sa_two
identified by mypassword
quota unlimited on my_data
/

grant connect, resource to sa_two
/

If you use the imp full import, I believe the tablespaces are created for you.

A: hguser,
If you do what you said:
imp fromuser=sa_one touser=sa_two file=xx.dmp

Then the data will be imported into the table space that the 'sa_two' schema has set to as a default table space. Although I must admit - I can't find the oracle documentation that explicitly says this it true, but I did find this oracle wiki:
http://wiki.oracle.com/thread/1284972/EXP+%26+IMP+only+restores+to+same+tablespace(s)
Alternatively, you could just use EXPDP and IMPDP and issue remap_tablespace for the import.
All else, this is what happens when you try to import to a table space that does not exist:
C:\Users\jslowik\Desktop>impdp user/password@db_name dumpfile=datfile.dat full=y

Import: Release 11.2.0.1.0 - Production on Thu Jun 23 15:34:27 2011

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
ORA-31626: job does not exist
ORA-31633: unable to create master table "SC_BASE.SYS_IMPORT_FULL_05"
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95
ORA-06512: at "SYS.KUPV$FT", line 1020
ORA-00959: tablespace 'TABLES' does not exist


text:
Q: Django forms, integer field is converted to string when accessed from template tags In Django forms, If we submit an invalid form, The integer field is converted to string field when accessed from template tags.
(i.e): Status = forms.IntegerField( max_value=20, required=True)
Accessed on page using template tags
{% if  form.Status.value == 1 %}
do something...
{% endif %}