text:
Q: Store unique download requests in database I'm trying to get some client information and store each download file request in database. After storing all needed information, download request is being processed:
return response()->download($file_path);

The problem is that on each request, mostly by download managers, many connections are made to the same URL so application stores multiple rows on the same request by user.
I want to limit this storing on per unique client request not per connection. I thought preventing multiple connections will do it for me, so I added Accept-Ranges header:
return response()->download($file_path, null, ["Accept-Ranges" => "None"]);

Although downloads are not resume-able anymore, multiple rows are stored in database. (However it's much less than before)
What would be the best practice to avoid multiple database insertions on a user download request?
* Please do not answer or comment without considering that multiple duplicate and simultaneous requests differ from multiple unique and simultaneous requests. Otherwise there are plenty of solutions out there.
P.S. I don't want to tag my question with Laravel. Please do not add it.

A: For Understanding unique users, you need authentication system. But I see you are not able to use authentication system.
There isn't any absolute way to do this. Users can change ip address, delete or change cookies etc., because everything is on their hand.
Still you can insert ip, http_user_agent to database and also to increase quality you can set some cookie to identify unique user.
Also, you can use PHP Sessions - for user management system.
session_start();
$id = session_id();

Check current session user. If already download request is there of same user then update request, if not create one.
Update:
If you are using sessions and authentication as per your comment then store when download request comes:
+----+---------+---------+-------------+-----------------+-----------------+
| id | user_id | file_id | status      | created_at      | updated_at      |
+----+---------+---------+-------------+-----------------+-----------------+
| 1  | 1       | 1       | in_progress | 1456477761.9624 | 1456477762.9624 |
+----+---------+---------+-------------+-----------------+-----------------+

When authenticated user requests to download specific file, add row in DB specifying it's status. Whenever any new request to download file comes, you will check status with that user and file requested. If record present then you will not allow user to download file.

A: You can try storing the user agent and check with evry request if user agent if same but a user, may try downloading via different browsers / download managers at the same time so not full proof ..
BUT
Since you have mentioned in the question that you are not supporting / allowing users to resume the downloads ..
Hence after the user has started the download he may try downloading via different browsers but the possibility of user ip adress getting changed is very less ...
So you can store user browsr agent + user ip adress and check with every request if they are the same before making a new entry in your database ..
This may not be 100% proof but im guessing your problem will be solved upto a extend !

A: Have you tried checking Range header values before the insertion into the database?
For the new/unique download request, it should not be presented or start from 0.


text:
Q: Creating a square matrix from a .txt file in Python I'm about to create a program running a Hamiltonian cycle for TSP(symmetrical) problem which means that a path goes only to one point and then goes further. The distance between those points can be written as a square matrix. Because the problem is symmetrical, i only have a half of this matrix as a .txt file
I need to create a program which will allow me to insert values separated by spaces from a .txt file into an array, and create a symmetrical square matrix out of it.
URL to see present the idea  and data layout in .txt file:
https://imgur.com/4G3sXrp
I'm a newbie in Python and i don't really understand how to work with IO at this level.
I've tried using numpy function: loadtxt but did not work for me, i recieved an error message saying that i cannot convert string to float
i've also tried doing by creating loops that were supposed to split the text and create this matrix.
def createMatrix(rows):
    matrix= [[0 for col in range(int(rows[0]))] for row in range(int(rows[0]))]
    i = 0
    for w in rows[1:]:
        w = string.strip(w).split(' ')
        j = 0
        for dist in w:
            matrix[i][j] = int(dist)
            matrix[j][i] = int(dist)
            j+=1
        i+=1
 return matrix

I expected the code result to at least guide me somehow on what should i do, but as i've mentioned i'm a newbie and i don't really know how to get started with this particular problem.

A: In the picture you linked to, showing how you'd like for the matrix to look, the last column has 12 two times. Also, in the second to last column, you've got a 19. Huh? Also, the last two lines / rows of your input text file both have five numbers. I'm guessing the last line should have six numbers.
The fact that the numbers have varying numbers of digits makes it harder to visually verify that everything is correct.
If you have a text file ("stuff.txt") that looks like this (note, the leading zeros for padding):
00
01 00
02 03 00
04 05 06 00
07 08 09 10 00
11 12 13 14 00

And the code:
with open("stuff.txt", "r") as file:
    lines = list(map(str.split, file.read().splitlines()))

    missing_values = []

    for index in range(len(lines)):
        missing_values.append([line[index] for line in lines[index+1:]])

    matrix = [line + values for line, values in zip(lines, missing_values)]

    for row in matrix:
        print(row)

Output:
['00', '01', '02', '04', '07', '11']
['01', '00', '03', '05', '08', '12']
['02', '03', '00', '06', '09', '13']
['04', '05', '06', '00', '10', '14']
['07', '08', '09', '10', '00', '00']
['11', '12', '13', '14', '00']

The matrix is not square because the last two lines in your text file have five numbers (where the last line should have six).

A: You can use np.tril_indices for filling the lower triangular part of the final square matrix and then M += M.T for filling the rest (since your diagonal is zero):
import numpy as np

with open('/tmp/test.txt') as fh:
    data = np.fromstring(fh.read().replace('\n', ' '), dtype=int, sep=' ')

n = int(np.sqrt(8*data.size + 1) - 1) // 2
matrix = np.zeros((n, n), dtype=int)
matrix[np.tril_indices(len(matrix))] = data
matrix += matrix.T  # Only works if diagonal is zero.

print(matrix)

Test with the example data of the OP:
text = '''0
1 0
2 3 0
4 5 6 0
7 8 9 10 0
11 12 13 14 15 0'''

with open('/tmp/test.txt', 'w') as fh:
    fh.write(text)

We get the output:
[[ 0  1  2  4  7 11]
 [ 1  0  3  5  8 12]
 [ 2  3  0  6  9 13]
 [ 4  5  6  0 10 14]
 [ 7  8  9 10  0 15]
 [11 12 13 14 15  0]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to cast COM object (EXCEL) My application just added a new function to allow export data into Excel. It worked fine on one device but when we implement it on the second one the following error appeared:
Error Message:

System.InvalidCastException: Unable to cast COM object of type
  'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type
  'Microsoft.Office.Interop.Excel._Application'. This operation failed
  because the QueryInterface call on the COM component for the interface
  with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the
  following error: Error loading type library/DLL. (Exception from
  HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

A: The error may say it can't load a DLL but if you are trying to load Excel that is where the problem is. It can't find "EXCEL.EXE" using the registry.
For some people, doing a simple Office repair from Add\Remove programs: Modify is enough to fix the problem.
If you have already tried an Office repair then you can fix it manually by editing the registry.
Open Regedit as admin and go to:
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\

This is the location that shows where Excel is installed. At this point if you see multiple versions, "1.9", "1.8", "1.7" then you need to remove the extra entries. For example Excel 2019 is "1.9" so you would remove other versions no longer installed.
Once you have only one version you also need to check the bitness. I had moved from 32-bit to 64-bit but both keys were still present
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\1.9\0\Win32
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\1.9\0\Win64

I removed the Win32 key and everything began working again. Inside these keys the default value shows the full path to "EXCEL.EXE". Ensure that path is correct.


text:
Q: How can I work with Novell eDirectory services in J2SE? How can I work with Novell eDirectory services in J2SE?  Will JNDI work with eDirectory?  What are some resources I can use to learn about whatever library or libraries you suggest?
I just want to play around with retrieving information via LDAP for right now, and if I get things working the way I want, I will probably need to be able to modify objects later on.
Thanks!

A: JNDI should work with eDirectory.....

A: try; http://developer.novell.com/wiki/index.php/Jldap and http://developer.novell.com/wiki/index.php/Novell_LDAP_Extended_Library
Used it successfully with OpenLDAP and should suffice for eDirectory as well.

A: Any LDAP interface you want to use should work fine against eDirectory.
Be aware that the configuration of the LDAP server may not allow clear text passwords, thus a bind to port 636 via SSL (Where you have the certificate imported into the keystore already) or via TLS (retrieve the tree CA's public key on the fly).
If you have administrative access to the eDirectory server, you can easily change that, but still best to confirm that you can get it to work over SSL/TLS (aka LDAPS).
If you really need it, you can ask the admins for a server with only a replica of some test partition (and thus no real user data in its view) and test via cleartext against that.
It is very easy in eDirectory to add a new replica of a partition, carve off or merge a partition, and all can be done live.
It is similarly very easy to host replicas of many partitions on one server.  (The official limit is, no limit on the number or partitions in a tree, or replicas on a server, but it used to be 256 in older versions (before 8.x) )
If you are allowed access to the eDirectory server, you want to to ask for access to Dstrace (several versions of this, see Many Faces of Dstrace).  There is a web interface (server:8008 on Netware, 8010 on Windows, 8028 on Unix/Linux usually) or other interfaces.   If you enable the LDAP trace option (and turn off all the others) you can fairly completely debug what is going on at the server side.  See the errors, the communication, or lack thereof and so on.


text:
Q: How to queue requests in PHP? I tried the code below to queue requests, but it does not work as expected!
<?php

$Sleep_Time = "10";

if (isset($_POST["String"])){

$File = "Edit_File_Content.txt";

    while(file_exists($File . "_Locked")) {
        //wait, do nothing until "Edit_File_Content.txt_Locked" file is deleted
    }

file_put_contents($File . "_Locked", "");       //create new file with same name with "_Locked" in the end (second parameter must be specified)

$File_Content = file_get_contents($File);

$File_Content .= $_POST["String"];

sleep($Sleep_Time);       //sleep for x seconds

file_put_contents($File, $File_Content);

unlink($File . "_Locked");                  //delete the above "_Locked" file

echo "String Added";
return;
}
?>

Each request takes <?php echo $Sleep_Time ?> seconds to finish!

<input type="button"  value="Add A" onclick='Add_String("A")'>
<input type="button"  value="Add B" onclick='Add_String("B")'>

Ajax Response:

The image below shows the "Ajax Response" when "Add A" and "Add B" are both clicked 5 times at once:

After all the requests are finished, "Edit_File_Content.txt" file will only contain "AA" instead of "AAAAABBBBB" string!
Any suggestions on how to effectively queue requests in php?

A: I wrote the below "Check_File_Write_Queue()" function, so far, it seems to work ok!
When "Add A" and "Add B" are both clicked 5 times at once, when all the requests are finished, "Edit_File_Content.txt" file will contain "AAAAABBBBB" string as expected!
Anyway, better solutions are always welcome!
<?php

$Sleep_Time = "3";

if (isset($_POST["String"])){

$File = "Edit_File_Content.txt";

$File_Write_Request = Check_File_Write_Queue($File);      //add a new write request to a file and wait here until older requests are finhished

$File_Content = file_get_contents($File);

$File_Content .= $_POST["String"];

sleep($Sleep_Time);       //sleep for x seconds

file_put_contents($File, $File_Content);

Check_File_Write_Queue($File_Write_Request, "Delete");
//if the above line is not used, the "register_shutdown_function()" used in the function will ensure that the "$File_Write_Request" will be removed when script exits!

echo "String Added";
return;
}

function Check_File_Write_Queue($File, $Option = "") {        //____________________________

$Files_Write_Queue = realpath("Edit_File_Content_Check_File_Write_Queue_List.txt");

    if ($Option == "Delete" || $Option == "delete"){
    $File_Content = file_get_contents($Files_Write_Queue);
    $File_Content = str_replace($File, "", $File_Content);
    file_put_contents($Files_Write_Queue, $File_Content);
    return;
    }

$File = realpath($File);

$Request_Id = microtime() . " " . bin2hex(random_bytes(10));

$Write_Request = $File . "<<<<" . $Request_Id . ">>>>\r\n";

file_put_contents($Files_Write_Queue, $Write_Request, FILE_APPEND);

    //to prevent errors\issues, "realpath()" should be used in "register_shutdown_function()"
    register_shutdown_function(function() use ($Files_Write_Queue,$Write_Request){
    $File_Content = file_get_contents($Files_Write_Queue);
    $File_Content = str_replace($Write_Request, "", $File_Content);
    file_put_contents($Files_Write_Queue, $File_Content);
    });

    while(1) {      //1=Infinite loop
    $File_Content = file_get_contents($Files_Write_Queue);
    preg_match('/' . preg_quote($File, '/') . '<<<<(.*?)>>>>/', $File_Content, $match);

    if (@$match[1] == $Request_Id){return $Write_Request;}
    }
}

?>

Each request takes <?php echo $Sleep_Time ?> seconds to finish!

<input type="button"  value="Add A" onclick='Add_String("A")'>
<input type="button"  value="Add B" onclick='Add_String("B")'>

Ajax Response:

A: In the previous answer, I used "Check_File_Write_Queue()" function, but someone alerted me that the PHP built-in function "flock()" can be used to do the same, which is correct, but I noticed something interesting, "Check_File_Write_Queue()" is more precise than "flock()", for example, if "Add A" is clicked 5 times at once, then "Add B" is clicked 5 times at once, the output in "Edit_File_Content.txt" file from "Check_File_Write_Queue()" will always be "AAAAABBBBB" and from "flock()" will vary,"AAABBABBBA","BBAABBAABA", "ABABBBAABA","BBBBBAAAAA","AAAAABBBBB",etc, which means that "Check_File_Write_Queue()" always handles the requests in the correct order and "flock()" sometimes does and sometimes does not!
Anyway, the code below is another solution that uses PHP built-in function "flock()" instead of "Check_File_Write_Queue()" function:
<?php

$Sleep_Time = "3";

if (isset($_POST["String"])){

    $File = "Edit_File_Content.txt";
    $File_Handle = fopen("$File", "r");
    if(flock($File_Handle, LOCK_EX)){       //on success, this script execution waits here until older scripts in queue unlock the file

    $File_Content = file_get_contents($File);

    $File_Content .= $_POST["String"];

    sleep($Sleep_Time);       //sleep for x seconds

    file_put_contents($File, $File_Content);

    flock($File_Handle, LOCK_UN);       //unlock the file so new scripts in queue can continue execution

    echo "flock() success [String Added]";

    }else{echo "flock() Failed";}
    fclose($File_Handle);

return;
}

?>

Each request takes <?php echo $Sleep_Time ?> seconds to finish!

<input type="button"  value="Add A" onclick='Add_String("A")'>
<input type="button"  value="Add B" onclick='Add_String("B")'>

Ajax Response:


text:
Q: My BackgroundWorker still blocks my UI I have a time consuming method in a class that's buried in a .dll which I don't have the source for. I don't want to block the UI when I call this method. I've been trying to use a BackgroundWorker to do this. I call RunWorkerAsync from a btn_Click event handler. When I have the dllClass instance created outside of the worker thread (like below) the UI freezes until the operation is finished. The operation also blocks the timer from ever ticking.
public static dllClass dllClassInstance = new dllClass();

void worker1_DoWork(object sender, DoWorkEventArgs e)
{
    dllClassInstance.TimeConsumingMethod();
}

On the other hand if I instance the class inside the worker thread (like the next code segment) it works as intended.
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
    dllClass dllClassInstance = new dllClass();

    dllClassInstance.TimeConsumingMethod();
}

The issue with using the latter is that I need access to the class instance outside of that specific worker, since I have to call other methods before and after the time consuming method. I also tried passing the class instance into the BackgroundWorker through e.Argument but it also resulted in the UI freezing. Does anyone have suggestions how to call that method without blocking the UI?

A:
Does anyone have suggestions how to call that method without blocking the UI?

Without knowing what's happening within dllClass, it's impossible to determine.
Neither code, normally, would cause the UI to freeze.  I suspect dllClass is capturing the current SynchronizationContext within its constructor, and using it internally within TimeConsumingMethod, causing blocking.  If this is the case, you could likely construct the class within your DoWork handler, but have it scoped to the class instead, which would likely work.  However, if it is capturing the synchronization context, then the class is likely to have thread affinity and expect to be running on the UI thread.
You could try constructing the instance within the handler, like so:
public dllClass dllClassInstance;

void worker1_DoWork(object sender, DoWorkEventArgs e)
{
    dllClassInstance = new dllClass(); // Construct here
    dllClassInstance.TimeConsumingMethod();
}

This may work, though, as I said, it may have other side effects.  I would verify that dllClass doesn't have thread affinity rules which require it to run on the UI thread.

A: It's probably because of your dllClass. What you're seeing shouldn't happen, unless someone wants to make sure all calls on an instance are processed in the same thread. If dllClass takes the dispatcher in its constructor, and then TimeConsumingMethod invokes the actual processing through that dispatcher, you're going to see frozen UI.

A: As Reed pointed out, it may be hard to really resolve without knowing what the internals of that class are.  However, if you have other stuff you need to load / prepare, setup, I would have your background worker class "ReportsProgress" = true, and when it starts, immediately call a method that will grab and/or prepare other settings based on ex: a progress of 1 (starting), then, do your other element of the long process, then report progress coming out with value like 99 (end) and do some cleanup from that.
Does this sound like it would help?  You could still have it all encapsulated into a single background worker class.

A: I am working on a VB.net application and came across the same issue with the Visa Com 3.0 drivers for communication with Agilent devices.  Here is how I solved it:
Dim task = New Threading.Tasks.Task(Of dllClass)(Function()
                                                     Return New dllClass()
                                                 End Function)
task.Start()
task.Wait()

public static dllClass dllClassInstance = task.Result;

void worker1_DoWork(object sender, DoWorkEventArgs e)
{
    dllClassInstance.TimeConsumingMethod();
}

Essentially I create my dllClass instance in a new thread, but immediately discard that thread and hold on to the reference.


text:
Q: How to reset background color of UICollectionVIewCell I have created a keyboard(for a to z letter) using UICollectionView, I am able to highlight the letter which the user has pressed. Now I want the all highlighted cell should reset as user click on next button
I try to reset the background cell color, for this, I created a function as I created for highlight the tapped UICollectionViewCell
Calling this function in didSelectItemAt
 func keyboardTappedCellColor(cell: IndexPath) {
    let selectedCell: UICollectionViewCell = keyboardCollectionView.cellForItem(at: cell)!
    selectedCell.contentView.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
    selectedCell.isUserInteractionEnabled = false
}

Calling this function in cellForItemAt, as a user will click on the next button reloading the UICollectionView. Getting app crashed here
 I am not sure this is the right process or not.
    func resetKeyboardCellTappedColor(cell: IndexPath) {

    let selectedCell: UICollectionViewCell = keyboardCollectionView.cellForItem(at: cell)!
    selectedCell.contentView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    selectedCell.isUserInteractionEnabled = true
}

I want how many cells tapped in UICollectionViewCell it should change its background and user-interaction should be disabled for tapped cell, and as user click on next button it should reset the highlighted and enable the user user-interaction

A: I am assuming you are allowing multiple selections in your collectionView like this
collectionView.allowsMultipleSelection = true
To Select / Deselect cell you can override the UICollectionViewCell property isSelected
 override var isSelected: Bool{

    didSet{
        self.backgroundColor = isSelected ? SELECTEDCOLOR: UNSELECTEDCOLOR

    }
}

To Get the selected Cell indexes :

let selectedItems = self.collectionView.indexPathsForSelectedItems

To Reset the Selected cell:

 for indexPath in selectedItems {
     self.collectionView.deselectItem(at: indexPath, animated:true)
 }

A: In you custom UICollectionViewCell, you simply need to override isSelected property with the relevant code in its didSet and nothing else is needed.
class CustomCell: UICollectionViewCell {
    override var isSelected: Bool {
        didSet {
            self.backgroundColor = isSelected ? .red : .white
        }
    }

    //rest of the code...
}

Cell selection and other cells' deselection will be handled automatically.


text:
Q: Deselect previous date in jquery date picker I want to validate start date and end date.For this purpose in jquery datepicker, i want to deselect or disable the previous date from the selected start date.Any body knows please help me

A: So you have two datepicker instances and you want to restrict the second one to dates after the chosen startdate in the first one?
In that case you need to catch the selection event of the first instance and update the minDate option of the first instance via the setter method:
//setter
$('.selector').datepicker('option', 'minDate', dateFromOtherDatepickerPlusOneDay);


text:
Q: Android fragment onResume() refresh data I have a Fragment A with a RecyclerView.
Fragment A populates the RecyclerView items (a list of users) from SQLite and displays it in the onCreateView() method, and it works fine.
When i go to Fragment B and add a new user and hit done, i go back to Fragment A, now i should "Refresh" the users list.
I tried achieving that through moving the code from onCreateView() to onResume(). But, i have no access to a view like i do on the onCreateView().
What do you think is the best approach on handling this?
Thanks!

A: So, at first I suppose you should update  data on your list, which one you give to your adapter. If that won't help, try to create new adapter and bind it with recyclerview  in your onResume() method.


text:
Q: PHP better login validation for PDO My code works perfectly until the validation, When i enter wrong username it doesn't show Invaild Username or Password! but if i entered correct username but wrong password the message appears, How do i fix that?
if(isset($_POST['login'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    try {
        $sql = "SELECT * FROM users WHERE username=:username";
        $stmt = $db->prepare($sql);
        $stmt->execute(array(':username' => $username));

        while($row = $stmt->fetch()){
            $user_id = $row['user_id'];
            $username = $row['username'];
            $hash_password = $row['password'];

            if(password_verify($password, $hash_password)){
                $_SESSION['user_id'] = $user_id;
                $_SESSION['username'] = $username;
            } else {
            die("Invaild Username or Password!");
        }
        }
    }
    catch(PDOException $e)
        {
        echo "An error occurred " . $e->getMessage();
    }
}

A: if(isset($_POST['login'])){
     $username = $_POST['username'];
     $password = $_POST['password'];

     try {
        $sql = "SELECT * FROM users WHERE username=:username";
        $stmt = $db->prepare($sql);
        $res = $stmt->execute(array(':username' => $username));
        if (!$res){
           die("Invaild Username!");
        }

       while($row = $stmt->fetch()){
          $user_id = $row['user_id'];
          $username = $row['username'];
          $hash_password = $row['password'];

          if(password_verify($password, $hash_password)){
               $_SESSION['user_id'] = $user_id;
               $_SESSION['username'] = $username;
          } else {
              die("Invaild Username or Password!");
          }
     }
  } catch(PDOException $e)
    {
    echo "An error occurred " . $e->getMessage();
 }

}


text:
Q: Custom defined form Constraint throws a null pointer exception I have a problem with defining a custom Constraint on my form. This is my form:
val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply)

If I do the following:
val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying("my constraint", f => f.field == true)

then it works fine. However, if I try to use the following custom defined Constraint , then a null pointer exception is thrown and I do not knowing why:
val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying(myconstraint)

val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({
   form =>
      if(form.field == true){
          Valid
      }else {
        Invalid(Seq(ValidationError("problem")))
      }
})

I tried to use println to debug but I nothing is printed in the console.

A: Try moving myconstraint definition above the form definition like so
val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({ ...
...
val form = Form( ...

due to possible forward reference problem where we end up referencing an uninitialised value.


text:
Q: Getting SyntaxError: JSON Parse error: Expected '}' when trying to convert a string into JSON using javascript my code looks like this:
var str = "[{u'total': '54', u'value': '54', u'label': u'14 Sep'}, {u'total': '58', u'value': '4', u'label': u'15 Sep'}, {u'total': '65', u'value': '7', u'label': u'16 Sep'}]";
console.log(JSON.parse(str));

In other words, I am trying to convert the string into a list of JSON objects using Js. I believe my string's structure is solid, however, I get this error in my console:
SyntaxError: JSON Parse error: Expected '}'

Can anyone help me fix this? Why do I get this error?

A: If you cannot change this python dictionary, you can use a workaround:

var str = "[{u'total': '54', u'value': '54', u'label': u'14 Sep'}, {u'total': '58', u'value': '4', u'label': u'15 Sep'}, {u'total': '65', u'value': '7', u'label': u'16 Sep'}]";

str = str.replace(/u?'(.+?)': u?'(.+?)'/g, '"$1":"$2"');

console.log(str);

console.log(JSON.parse(str));


text:
Q: How to use for_each with the function as the overloaded operator() I have a std::vector of function objects. Each object can take an int, so I can say obj(4) and get an int result. How can I use the algorithm for_each to work on each element of the vector?

A: Which version of C++?  C++0x Lambdas make this short and sweet.
In C++03, for loop will be simpler than for_each.
To use for_each in C++03, you need to create a functor that stores all the input arguments in member variables and pass it to for_each.  Each functor in the vector will be passed to this visitor functor as an argument, you then need to call its operator() with the stored arguments.

A: You would have to create a functor 'calling' each object:
struct Caller {
  int value;
  void operator()( const YourFunctorHere& f ) const {
    f( value );
  }
} caller;
std::for_each( functors.begin(), functors.end(), caller );


text:
Q: What is wrong here? Expected expression before '=' token? I am trying to set up a structure in the C program I am writing.  However, the compiler returns that it is expecting an expression before the '=' token on line 31.  Below is a snippet of the code containing the struct and the line of code in question:
EDIT: THREAD_COUNT was defined to be
#define THREAD_COUNT = 120

struct threadInfo
{
    int threadId;
};

struct threadInfo customerIDs[THREAD_COUNT]; //offending line here

I have tried chaning it into an expression with an = sign, I tried changing the way the struct was declared, but nothing has worked so far.  Any advice?
EDIT 2: The error was resolved.  My definition of THREAD_COUNT was incorrect.

A: Don't use = in your #define statement. It should be:
#define THREAD_COUNT 120

Preprocessor definitions aren't variables, they just do simple text replacement.


text:
Q: I need some slightly basic BASH help - find + execdir + sox Ok, hello. I have some scripts that I use on the command line to rip mp3s from .wav and .aif files. Lately I've been playing with this sampler that wants only mono wav files. WAIT - I promise this is a programming question.
I want to run a command to split all wav files inside a directory to mono files with a different file name.
So, for example Drummerrolleasy.wav, would then have DrummerrolleasyL.wav in the same directory as the left mono split of the original stereo wav.
I will ensure that when the command runs, there are only stereo wav files in the directory.
I have this command:
find . -name "*.wav" -execdir echo $1    {} \;

that works as expected, and provides me the names of the files, one by one, that I would like to then put inside a call to sox.

this:
find . -type f -name "*.wav" -exec sox {} "$1" L"$1"  \;

does not work (runs but does nothing), and I'm not finding anything particularly illuminating for how to do this. I might need to spawn a new shell, but this doesn't work either because the shell just sits there:
find . -name "*.wav" -execdir sh -c 'sox "{}" "$1" "L""$1"' \;

If I have to figure this out on my own, that can work too, and when I get there I will update but if someone would like to point me in the right direction I would be much obliged.

A: Goes like this:
for file in *.wav; do sox $file L$file remix 1; done

thanks Mix .L and .R files into a stereo file using SOX in bulk
saves me a lot of time. BASH rules.


text:
Q: Saving data in Firebase in a numbered list I want to save my data like this:
- Parent
   - 1
      - Value here
      - Another value
   - 2
      - Value here
      - Another value
And so on. Right now I am using this to add an item to the Parent array:
func save() {
  let ref = AppDatabaseReference.users(uid: uid).reference()
  ref.child("parent").childByAutoId().setValue(toDictionary())
}
item.save()

This works but it saves each item under a unique string (as expected). But it makes it more difficult to reference things for me.
- Parent
   - dhsaifhafh86
      - Value here
      - Another value
   - dhsaifusfh53
      - Value here
      - Another value
I thought about adding square brackets around toDictionary() like ref.child("parent").setValue([toDictionary()]) but then it just replaces the existing children under parent rather than adding a new child:
- Parent
    - Replaced stuff
    - You'll never win!
If it helps, toDictionary() looks like this:
func toDictionary() -> [String: Any] {
   return [
      "title": title,
      "description": description,
      "stuff": stuff,
      "more stuff": moreStuff
    ]
}

A: i did something like this-
let ref=firebase().database().ref("Parent");
ref.once("value").then(snap=>{
  let length=snap.val()?Object.keys(snap.val()).length:0;
  ref.update({[length+1]:{Value here,Another value}});
});


text:
Q: Character consumption in lexical analysis If I have a subrule like the following:
.. (~']' ~']')* ...

will it only match an even number of characters?

A: (Assuming the dots are not meant as meta characters)
Not quite, it will match zero, or an even number of characters.
EDIT
To match a quote block, do something like this:
QUOTE
    :    '[[' (options {greedy=false;} : . )*  ']]'
    ;

Assuming [[ some text here ]] is a quote block.


text:
Q: Lisp program that duplicates an element of a list using a list of integers I'm working on a program that takes a list of elements and each individual element is duplicated based on an integer contained in a 2nd list of integers. for example if I had a list of
(A B C D)

being duplicated by:
(1 5 4 2)

I would have
(A B B B B B C C C C D D)

So far I have
(defun COPY (X Y)
  (if (zerop Y)
      nil
      (cons S (COPY X (1 - Y)))))

Of course this is only duplicating a single element a single number of times. Does anybody have a good idea how to go about this?

A: Use mapcan and
make-list (which is the library version of your copy):
(mapcan (lambda (letter num)
          (make-list num :initial-element letter))
        '(A B C D) '(1 5 4 2))
==> (A B B B B B C C C C D D)

or just
(mapcan #'copy '(A B C D) '(1 5 4 2))

If you are required to use simple recursion, you can also write
(defun copy-list-elements (elements counts)
  (and elements counts
       (let ((count (pop counts)))
         (if (plusp count)
             (cons (car elements)
                   (copy-list-elements elements
                                       (cons (1- count) counts)))
             (copy-list-elements (cdr elements)
                                 counts)))))
(copy-list-elements '(A B C D E) '(1 5 4 0 2))
==> (A B B B B B C C C C E E)

Note that the recursive version is longer and probably slower.

A: Loop over the two lists, call copy, and append the results.
(loop for letter in letters
      for count in counts
      nconcing (copy letter count))


text:
Q: Is there a way to display RaisedButtons in a ButtonBar lazily? I have a set of buttons I want to display on a flutter app to represent the days of the week. I currently have a widget that builds 7 RaisedButtons to represent the various days of the week. Is there a way I can do this lazily instead of having to build all 7 RaisedButtons in flutter?
Note I am using the ButtonBar widget to display the set of buttons.

A: You can declare a list like following:
List<Widget> _optionList = List<Widget>();

and add as many and any kind of widget in the list, like following:
void setupHintButtonsUI() {
    _optionList.clear();
    for (var i = 0; i < 7; i++) {
      _optionList.add(
        FlatButton(),
      );
    }
  }

A: You can make an empty list of strings and add days name in it and then iterate through it. Create a function using the for loop like
var i = "";

main() {
  final List<String> days = <String>['Sunday', 'Monday', 'Tuesday','Wednesday','Thurday','Friday'];
  days.sort();
//   print(days);

  for (i in days){
    print(i);
  }
}

and then you can loop through the code and create widgets


text:
Q: How to remove extension in eclipse through programmatically I have created an extension point, and i am trying to implement that extension in some other plugin. After certain point of time i need to remove that extension in runtime. So currentlt i am using the below to code(Reflection call)
My Code Here :
IExtensionRegistry reg = Platform.getExtensionRegistry();
Field privateStringField = ExtensionRegistry.class.getDeclaredField("masterToken"); //$NON-NLS-1$
privateStringField.setAccessible(true);
Object masterToken = privateStringField.get(reg);
IConfigurationElement[] config = reg.getConfigurationElementsFor("com.temp.rcp.product");
for (IConfigurationElement configElement : config) {
    if (configElement.getAttribute("name").equals("Temp")) {
        reg.removeExtension(configElement.getDeclaringExtension(), masterToken);
    }
}

I looked into the code and found a solution, but this is totally not acceptable, because it could/will break, when i update my eclipse target platform, because of the reflection call.
Can anyone of you help me to solve the above issue.


text:
Q: Is there any wireless NIC can support WoWLAN and arp offload In Microsoft website, "http://technet.microsoft.com/en-us/library/ee617165(v=ws.10).aspx"
it mentioned that NIC should have ARP Offload and NS Offload to prevent computer form waking up merely to maintain network presence.
But I've searched all realtek productions, it does have some wireless NIC with "Wake on Wireless LAN" featured, but none of these wireless NIC can support ARP Offload and NS Offload.
(Only some wired NIC support ARP offload).
I ask this question because i have a RTL8188CE wireless NIC, though Wake on Wireless LAN is not listed in Realtek website, it does support. I can wake up my computer by sending a magic packet. but unfortunately, it will wake up in about 0.5-2 hours by accident, i don't know why

A: All of the Broadcom and Atheros Wi-Fi chips built into Macs since probably 2009 support WoWLAN, and any of the Broadcom designs since about 2011 support ARP and Neighbor Solicitation offload. At least under OS X. I don't know if the Boot Camp Windows drivers support this.
So the 802.11ac 3-stream BCM4360 certainly supports everything you're looking for, as does whatever Broadcom chips Apple was using for the last generations of 2- and 3-stream 802.11n before that (BCM4331 maybe?).
By the way, if you have the ability to enter static ARP mappings (or IPv6 neighbor mappings) into your router, you don't need your NIC to support ARP/NS offload. Or if you know the MAC address of the machine you want to wake, and you can run something on the same [W]LAN as the sleeping machine, you don't have to bother with either static ARP mappings or ARP offload.


text:
Q: How to change the naming structure to a CSV in python I am trying to change the name that is printed out on a CSV file that I am creating from an SQL Query. I would like the file name to look like this yyyyddmm_"name". With the year day month capturing the corresponding date on the day of its creation. At the moment I am using pandas and datetime, this is not giving me the correct name structure. Can you sugest an alternative. Thank you for your help with this matter. Cheers.
df.to_csv(r datetime.now()"Name Name" + ".csv", index=False)

A: import time
file_name = time.strftime("%Y%m%d"+"_Name")
print(file_name)

for your case
import time
file_name = time.strftime("%Y%m%d"+"_Name")
save_to_path = r'C:\Users\MyPC\Desktop' #this is where your .csv file will be saved
df.to_csv(save_to_path+"\\"+file_name+ ".csv", index=False)


text:
Q: Wire heating from microwave signal How would one calculate the temperature change in a wire into which a microwave signal of a given frequency and power is applied?

A: For a wire loop, use appropriate fine gauge Litz wire for lower inductance, lower skin effects or   copper tubing for heat conduction in W/'C.
With the appropriate wavelength in copper tubing you can make into an induction heater. Or if you want it cool with lower losses, use Litz wire.
Your problem-statement is ill-defined and more complex than in comments.  There are electromagnetic and thermodynamic equations.


text:
Q: Parameterized grouping in join query in Laravel I have three tables: admins, users and  maintenances with the following structure.
admins table: (type=1)
admin_id admin_name admin_table  theme ...
1           A         ..
2           B         ..

users table (type=2):
user_id user_name
1           A
2           B
3           C

maintenances table:
maintenance_id  requester_type  requester payer_type payer
1                    2             3         2        3
1                    2             4         1        1
1                    2             1         2        1
1                    1             1         1        1

I need to get the user details and count of maintenances. Maintenances can be counted for user if either requester or payer  is that user.
SELECT u.*, COUNT(m.maintenance_id) as maintenanceCount
FROM users as u
LEFT JOIN maintenances as m ON ((m.requester_type=2 AND m.requester_id=u.user_id) OR (m.payer_type=2 AND m.payer_id=u.user_id))
GROUP BY user_id

With laravel query builder, I tried:
DB::table('users as u')
   ->leftjoin('maintenances as m', function($join){
              $join->on('m.requester_type', '=', DB::raw(2))
              ->where('m.requester_id', 'u.user_id');
    })
   ->groupby('user_id')
   ->select('u.*', DB::raw('Count(m.maintenance_id) as maintenanceCount)')->get();

but this is wrong. How can I group conditions for joining in Laravel query builder? Can someone help please

A:    DB::table('users as u')
   ->leftjoin('maintenances as m', function($join){
              $join
                  ->where(function ($on) {
                      $on->where('m.requester_type', 2)
                         ->whereRaw('m.requester_id = u.user_id');
                  })
                  ->orWhere(function ($on) {
                      $on->where('m.payer_type', 2)
                         ->whereRaw('m.payer_id = u.user_id');
                  });
    })
   ->groupby('user_id')
   ->select('u.*', DB::raw('Count(m.maintenance_id) as maintenanceCount)')->get();


text:
Q: Issue in i carousel and my custom animation i've created d app where app starts an image have to be animated and my buttons will be displayed in coverflow effect using icarousel..Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
carousel.type = iCarouselTypeInvertedWheel              ;

CGRect ChaintopFrame = Chaintop.frame;
ChaintopFrame.origin.y = self.view.bounds.size.height;
//CGRect ChainbottomFrame = Chainbottom.frame;
//ChainbottomFrame.origin.y = self.view.bounds.size.height;

[UIView animateWithDuration:0.5
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                  Chaintop.frame = ChaintopFrame;
                     //Chainbottom.frame = ChainbottomFrame;
                 }
                 completion:^(BOOL finished){
                     NSLog(@"Done!");
                 }];
}

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{

   UIImage *buttonImage=[NSArray arrayWithObjects:[UIImage imageNamed:@"Cover_0.png"],
                      [UIImage imageNamed:@"Cover_1.png"],
                      [UIImage imageNamed:@"Cover_2.png"],
                      [UIImage imageNamed:@"Cover_3.png"],
                      [UIImage imageNamed:@"Cover_4.png"],
                      [UIImage imageNamed:@"Cover_5.png"],
                      [UIImage imageNamed:@"Cover_6.png"],
                      [UIImage imageNamed:@"Cover_7.png"],nil];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 200.0f, 200.0f);

[button setImage:(UIImage*)[buttonImage objectAtIndex:index] forState:UIControlStateNormal];

[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
return button;

 }

Now when i run my simulator the image which used for animation went back and the buttons are displayed front.The good thing is animation inn image is working...and i resized my icarousel view too...
Am i missing anything?...

A: I think your adding your imageView wrong in your iCarousel view,
try this:
[self.view addSubview:Chaintop];

and try resizing your image.
hope this helps.


text:
Q: Situation of detached std::thread after parrent thread left its block I've searched but i couldnt find exact answer of this question.
For instance, if we have a code block like this:
{
  std::thread thread_1(.....);
  thread_1.detach();
  ...
}

when thread_1  still works, what happens exactly after parent thread left this code block.

A: Case 1: I am running this on a very bad operating system, or maybe very primitive, then as you have detached the thread from main thread, so it works in a independently of the main thread. So even though the main thread exits, it will keep on running as long as it is not dependent on any variables present at global scope, it will be stray thread.
Case 2: This is running on a modern opertaing system, we can say that it will behave as same as that in case 1, but modern OS on seeing a widowed thread will immediately kill it and clean it, releasing the resources captured by it.
hope this is helpful, if incorrect please suggest corrections in the comments below...thankyou


text:
Q: change apache document root to / I know this is one of the stupidest ideas you have heard of but my client, as part of his thesis project, he wants to be able to stream any media, including media on external hard disk.
proxying is an option but we finished the script and he just wants to change the document root to / after all this is just a university project.
In windows, we were able to change the document root to C: and it worked, ubuntu, no luck setting it to / so how to let apache run on all the machine/

A:
I know this is one of the stupidest ideas you have heard of but my client.

It is.
And you can't with a normal install. Apache would be needed to be run as "root" and Apache has a built-in security check on it. Error notice you will see...

Apache has not been designed to serve pages while running as root. There are known race conditions that will allow any local user to read any file on the system. If you still desire to serve pages as root then add -DBIG_SECURITY_HOLE to the CFLAGS env variable and then rebuild the server. It is strongly suggested that you instead modify the User directive in your httpd.conf file to list a non-root user.

So to do what you want to do you need to ...

*

*add -DBIG_SECURITY_HOLE to the CFLAGS env variable.

*rebuild apache server.

*setup http.conf with root as the user.

I will leave it up to you on how to do this and would suggest you to forget about this, use a normal (restricted) user as intended and store files in a sub-directory owned by that user.

A: You can accomplish a bit of what you might want with FollowSymLinks and the correct permissions on files.
This method will only create links to data where you specify, it will not give you the entire filesystem, unless you were to create symlinks for every path of course, and even then, you might run into problems with specific system paths.
By default Apache2 has FollowSymLinks on by default, so no additional apache configuration was needed.  For the sake of answering this question, I spun up an openstack instance, and did the follow steps.
I will mention, I would have assumed more would be needed as far as setting permissions, actually kind of scary.
Maybe root having a running instance of apache2 makes it work?  I don't think www-data would have access to /home/ubuntu by default.  Strange.
ubuntu@test:/home/ubuntu# sudo su
root@test:/home/ubuntu# apt-get install apache2
root@test:/home/ubuntu# ps awux | grep apache2
root     30862  0.0  0.1  71300  2572 ?        Ss   12:17   0:00 /usr/sbin/apache2 -k start
www-data 30865  0.0  0.2 360464  4252 ?        Sl   12:17   0:00 /usr/sbin/apache2 -k start
www-data 30866  0.0  0.2 557344  5024 ?        Sl   12:17   0:00 /usr/sbin/apache2 -k start
root@test:/home/ubuntu# cd /var/www/html/
root@test:/var/www/html# ls
index.html
root@test:/var/www/html# ln -s /tmp tmp-symlink
index.html  tmp-symlink
root@test:/var/www/html# cd tmp-symlink
root@test:/var/www/html/tmp-symlink# ls
hsperfdata_ubuntu
root@test:/var/www/html# ln -s /home/ubuntu/ ubuntu-user
root@test:/var/www/html# cd /home/ubuntu/
root@test:/home/ubuntu# ls
file  test  test_directory  test.sh

A: First of all here is my solution which can work with apache2-2.4.10 (as a result, you will have to replace it by the version which is in your software sources).
apt-get -y install dpkg-dev debhelper libaprutil1-dev libapr1-dev libpcre3-dev liblua5.1-0-dev autotools-dev
apt-get source apache2.2-common
cd apache2-2.4.10
export DEB_CFLAGS_SET="-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -DBIG_SECURITY_HOLE"
dpkg-buildpackage -b
cd ..
dpkg -i "name of the package apache2-bin* you generated with dpkg-buildpackage -b"
dpkg -i "name of the package apache2-common* you generated with dpkg-buildpackage -b"

Then modify httpd.conf or /etc/apache2/envvars file to set root instead of www-data (you can search www-data string and replace it by root) and restart apache.
Secondly here is the explanation:

*

*Installed dependencies to use dpkg-buildpackage and dpkg

*Got the source from the repository

*Modified environment variables CFLAGS used by dpkg-buildpackage and added -DBIG_SECURITY_HOLE to it

*Navigated to the apache generated directory and ran dbkg-buildpackage to recompile the package with the modified CFLAGS

*Returned in the parent directory to use the generated packages

*I install the packages apache2-bin and apache2-common
sudo apt-get install apache2-bin apache2-common


text:
Q: Navmenu - nav смещается со своего места Есть навигационное меню Push Jasny Bootstrap. У него есть Navbar. В Navbar я делаю navmenu-nav -  кнопка User с выпадающим меню.
Push Menu

  <button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target=".navmenu" data-canvas="body">

  </button>

            <button  id="btn_user_drop" type="button" class="btn btn-default dropdown-toggle " data-toggle="dropdown" >
                 User
            </button>

Настройки

Выйти

Я хочу, чтобы на мобильных экранах navbar прятался. Оставались только кнопки вызова меню. Для этого в css у меня указано правило:
    @media (max-width: 768px){
  body {
    padding: 0;
  }
  .navbar {
    right: auto;
    background: none;
    border: none;
  }

}

Но при скрытии navbar мое меню User смещается в левый угол экрана, при увеличении экрана и появлении navbar опять занимает свое правильное положение. Хочу понять почему такое поведение?

A: Для нормального(большого) разрешении в bootstrap есть правило:
@media (min-width: 768px)
.navbar-right {
    float: right!important;
    margin-right: -15px;
}

Поэтому Ваше меню user справа при нормальном(большом) расширении(т.е. когда min-width: 768px).
Данное правило соответственно не действует для мобильных, т.е. чтобы меню user на мобильных было справа(также как и на большом экране) просто добавьте код:
@media (max-width: 768px){
  .navbar-right {
        float: right!important;
    }
}
/*или в файле css от bootstrap уберите ограничение @media (max-width: 768px)*/

Данный ответ дан по вашему демо на jsfiddle, код в вопросе и код на jsfiddle у Вас отличаются.
UPD
Ответ для кода из Вашего вопроса:
Вы можете добавить правило .navbar{width:100%}, в данном случае меню user не будет смещаться в левую часть экрана в мобильных.


text:
Q: XSLT Choose - Trying to hide variable if empty I have created this variable in XSLT:

I want to hide it if the user does not enter content into the CMS. I have added a CHOOSE statement to the XSLT, but found out that I can't use 'style' on a variable. I'm new to XSLT.
Code below...

               <xsl:choose>
                    <xsl:when test="not($thirdBlogPost)">
                         <xsl:variable name="thirdBlogPost" style="display:none"/>

                    </xsl:when>
                    <xsl:otherwise>  </xsl:otherwise>

<xsl:value-of select="$thirdBlogPost/@Title"/>

               <xsl:value-of select="$thirdBlogPost/@Abstract" disable-output-escaping="yes"/>

               Read more...

               </xsl:choose>

A: XSLT tags are processed by whatever you are using to do the XSLT transform -- they don't show up as part of the HTML (they are not displayed).
So there should be no need for the style attribute -- the variable will not be visible on the web page.

A: The syntax for xsl:variable is
<xsl:variable
  name = QName
  select = Expression
</xsl:variable>
So, if you're trying define a variable with the value display:none, you'd write (note since the attribute contains a literal string, the string must be within quotes):
<xsl:variable
  name = "thirdBlogPost"
  select = "'display:none'"
</xsl:variable>
You could use the value like this:

this won't display


text:
Q: Dynamic checkbox events through commandbutton I am currently programming a sheet which visualizes data sets in graphs. Because the user of this sheet will not need all the graphs, I would like to let them choose the ones needed through a UserForm. Since the amount of data sets is variable, the UserForm will have the same amount of checkboxes as there are datasets.
The Userform code is as follows.
Private Sub UserForm_Initialize()

Dim chkBoxA     As MSForms.CheckBox
Dim chkBoxB     As MSForms.CheckBox
Dim lblBox      As MSForms.Label
Dim cnt         As Control

Amount = Sheet4.Range("C4").Value 'Amount of datasets

For i = 1 To Amount
    Set lblBox = Me.Controls.Add("Forms.label.1", "Label" & i)
        lblBox.Caption = "Set" & i
        lblBox.Left = 5
        lblBox.Top = 8 + ((i - 1) * 40)
    Set chkBoxA = Me.Controls.Add("Forms.CheckBox.1", "A" & i)
        chkBoxA.Caption = "Graph a"
        chkBoxA.Left = 55
        chkBoxA.Top = 5 + ((i - 1) * 40)
    Set chkBoxB = Me.Controls.Add("Forms.CheckBox.1", "B" & i)
        chkBoxB.Caption = "Graph b"
        chkBoxB.Left = 55
        chkBoxB.Top = 20 + ((i - 1) * 40)
Next

CommandButton1.Left = 20
CommandButton1.Top = 40 + ((Amount - 1) * 40)
CommandButton1.TabIndex = Amount * 3 + 1

Me.Height = 220

Me.ScrollBars = fmScrollBarsVertical
Me.ScrollWidth = Me.InsideWidth * 9
For Each cnt In Me.Controls
    If cnt.Top + cnt.Height > Me.ScrollHeight Then
        Me.ScrollHeight = cnt.Top + cnt.Height + 5
    End If
Next

End Sub

When the UserForm is filled in (graphs are chosen by clicking on the options), the user will press CommandButton1. An event should then be run to show the correct graph, but for the simplicity I am first testing if a MsgBox will show up. Unfortunately the MsgBox does not show up.
Private Sub CommandButton1_Click()
'Will fix this with a loop
If A1 = True Then
    MsgBox ("TestA1")
End If
If B1 = True then
    MsgBox ("TestB1")
End If
If A2 = True then
    MsgBox ("TestA2")
End If

Unload Me

End Sub

I am stuck on this part. The checkboxes do show up on the UserForm and they are clickable, but the commandbutton only shuts down the sub (Unload Me). I would like to see the MsgBox show up when I select the corresponding option and click the commandbutton. Any help on getting this to work is appreciated!

A: You are referencing 'A1' in the sub, but that variable does not exitst at compile time, because you add them dynamically. What you need to do is loop the controls, to check the names. Best practice is to put the checkboxes in a frame, to be able to group them.
Add a frame to the userform and name it 'checkboxframe'
And then instead of:
For i = 1 To Amount
    Set lblBox = Me.Controls.Add("Forms.label.1", "Label" & i)
        lblBox.Caption = "Set" & i
        lblBox.Left = 5
        lblBox.Top = 8 + ((i - 1) * 40)
    Set chkBoxA = Me.Controls.Add("Forms.CheckBox.1", "A" & i)
        chkBoxA.Caption = "Graph a"
        chkBoxA.Left = 55
        chkBoxA.Top = 5 + ((i - 1) * 40)
    Set chkBoxB = Me.Controls.Add("Forms.CheckBox.1", "B" & i)
        chkBoxB.Caption = "Graph b"
        chkBoxB.Left = 55
        chkBoxB.Top = 20 + ((i - 1) * 40)
Next

you would need to do:
With Me.checkboxframe
    For i = 1 To Amount
        Set lblBox = .Controls.Add("Forms.label.1", "Label" & i)
            lblBox.Caption = "Set" & i
            lblBox.Left = 5
            lblBox.Top = 8 + ((i - 1) * 40)
        Set chkBoxA = .Controls.Add("Forms.CheckBox.1", "A" & i)
            chkBoxA.Caption = "Graph a"
            chkBoxA.Left = 55
            chkBoxA.Top = 5 + ((i - 1) * 40)
        Set chkBoxB = .Controls.Add("Forms.CheckBox.1", "B" & i)
            chkBoxB.Caption = "Graph b"
            chkBoxB.Left = 55
            chkBoxB.Top = 20 + ((i - 1) * 40)
    Next
End With

And to add the checkboxes to the frame, use something like:
For Each ctr In UserForm1.frame("checkboxframe").Controls
    If TypeName(ctr) = "CheckBox" Then
        If ctr.Value = True Then
            'do something usefull here
            msgbox ctr.name
        End If
    End If
Next ctr

A: The reason nothing appears is because there is no object "A1" manually defined as a variable.
To get the value of the box you Dynamically named "A1" you would have to refer to it as such:
If Me.Controls.Item("A1").Value = True then

Hope this helps!


text:
Q: Two possibly related issues with Mission Control in MacOS Sierra 10.12.3 I've run into an annoying issue with Sierra.  I typically run four or five desktops in Mission Control (and have since Lion) to group tasks on their own screen space.  This is on a late 2012 mini, which I installed a pair of SSDs into and then did a network-install and then upgrade to Sierra before loading any apps.
If I have a window in focus and pull up Mission Control, and select Dashboard, it switches to the dashboard, but then almost instantly switches back to the active window I was just in.  I have to minimize the active window to get the switch to stick.  This is not limited to just trying to use Dashboard, which I admit I almost never do, usually I'm trying to switch to a different desktop space to go looking for a file in Finder for a reference.  This leads me to another annoyance that is related.
Prior to Sierra, if I had minimized an application, and later used CMD-TAB to switch back to it, it would pull it back up to the desktop space it was minimized from, show the application and switch to it.  Now, it accepts the selection, but does not restore the window.  It does bring it up on the ribbon, but I usually end up going to the dock to restore the application to where I can see it.
Question is this, where are the settings for these behaviors?  Hopefully its a trick setting somewhere I can toy with, but so far I've not found anything that seems to tame these issues.  I'm about ready to nuke the drive from orbit and roll back to El Cap or Yosemite, as these two issues are fouling up several years of work flow habits.
I've seen several posts like this one on Finder loosing focus or this one about strange Mission Control behavior with the Dock that seem in the same neighborhood as my issues.  For that matter this one about auto-swoosh is close too.
I've had my issue strike with Firefox, PHPStorm, Atom (GitHub's text editor) and the GitHub app too, TextWrangler, iTunes (12.5.5.5), Facetime, Messaging, and Launchpad.  I wonder if its not a fouled system hook for the little magic bar thingie on the new MacBookPro.

A: This sounds like it is a MacOS issue. My 1st recommendation would normally be to update MacOS but I would recommend that you backup your Mac and then reinstall MacOS.


text:
Q: How to pass data between routes in express.js hope someone can help me. Can't find a solution. Maybe I'm also just on the wrong way?
It's a simple express setup and I'm quite new.
I get a response from a request and want to pass a variable/the data from the response to the next route into the URL.
So one parameter in the next URL should be dynamical depending on the response of the first call.
here my whole code:
My problem is where you can see the const sendoutID
const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
const port = 3001;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Create Sendout
app.post("/createSendout", (req, res, next) => {
  request.post(
    {
      url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results.CreateSendoutResult.SendoutId); // View Results

// I want this data "results.CreateSendoutResult.SendoutId" passing to the next route

      }
    }
  );
});

/* here the variable is just hard coded for now but
I want to pass it in the URL from my previous route
to the next route see below at + sendoutID +..*/

const sendoutId = 389125;

// Add Respondent
app.post("/addRespondent", (req, res, next) => {
  request.post(
    {
      url:
        "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
        sendoutId +
        "/respondents",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response);
      //console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results); // View Results
      }
    }
  );
});

app.listen(port, () => {
  console.log(`app listening at http://localhost:${port}`);
});

A: *

*To pass to the next route you can assign results.CreateSendoutResult.SendoutId to  req.body
req.body.SendoutId = results.CreateSendoutResult.SendoutId;
Then you can use that SendoutId in next route.

*You can pass that variable inside next()
next(results.CreateSendoutResult.SendoutId);
In the next route you can access it by calling:
function nextRoute(SenderId, req, res, next)

Edited:
const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
const port = 3001;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Create Sendout
app.post("/createSendout", (req, res, next) => {
  request.post(
    {
      url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results.CreateSendoutResult.SendoutId); // View Results

// I want this data "results.CreateSendoutResult.SendoutId" passing to the next route

      req.SendoutId = results.CreateSendoutResult.SendoutId;

      }
    }
  );
}, addRespondent);

/* here the variable is just hard coded for now but
I want to pass it in the URL from my previous route
to the next route see below at + sendoutID +..*/

const sendoutId = 389125;

// Add Respondent
app.post("/addRespondent", addRespondent);

function addRespondent(req, res, next) => {
  request.post(
    {
      url:
        "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
        req.sendoutId +
        "/respondents",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response);
      //console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results); // View Results
      }
    }
  );
}

app.listen(port, () => {
  console.log(`app listening at http://localhost:${port}`);
});

A: *

*You should be using a middleware function.

What is a middleware function?
-> it's just a function that runs in the middle that is (before a request hits the route and ends before a request completes.Express Documentation for writing middlewares.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function.NOTE middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging..
Advantage of using a middleware function -> "you can use this function for any other request too in the future", use it in other modules".
2)
const captureSendOutIDMiddleware = async (req, res, next) => {
    try {
         req.SendOutID=results.CreateSendoutResult.SendoutId; //changed "const req" to just req.
             next();

    } catch (error) {
        res.status(401).send({
            error: 'NO SEND OUT ID'
        })
    }
app.post("/CreateSendOut",captureSendOutIDMIddleware,async(req, res) =>{
//do your operation

});

app.post("/addRespondent",async(req,res)=>{

const capturedSendoutID=req.SendoutID;
console.log(capturedSendoutID);
//do you operations

});

A: Thanks for your help.
I found now another solution which works as well as I found another issue. Don't know if it was also a cause for why it didn't work, or why your solutions didn't work. But I used app.set() and app.get to pass the data.
The other issue was, that now, with app.set() and app.get() it sometimes worked, sometimes not. So I set a timeout on the call in the frontend, which executes the api requests. Just to have a bit time between.
here is my new code
// Create Sendout
app.post("/createSendout", (req, res, next) => {
  request.post(
    {
      url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxxxx-xxx-xx-xxxx-xxxxx",
      },
    },
    function (error, response, body) {
      console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results.CreateSendoutResult.SendoutId); // View Results
        app.set("surveyId", results.CreateSendoutResult.SendoutId);    // new added line
      }
    }
  );
});

// Add Respondent
app.post("/addRespondent", (req, res, next) => {
  const surveyId = app.get("surveyId");        // new added line
  request.post(
    {
      url:
        "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
        surveyId +
        "/respondents",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxxxx-xxx-xxxx-xxxx-xxxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response);
      //console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results); // View Results
      }
    }
  );
});


text:
Q: Best way to bind a dropdown at client side what is the best way to bind a dropdown at client side using JQuery

A: Assuming you are asking how to bind an event to a select element...
$('select').change(function() {
   ...
});


text:
Q: Can a lookup be done by fbid? (Instagram API)? I was wondering if it is possible to look up a user using the fbid that gets shown when using the Instagram API to look up a user. For example, I used the following URL to look up the official Instagram account:
https://www.instagram.com/instagram/?__a=1

This URL returns a JSON object and within that there is a fbid key like so:
"fbid" : "17841400039600391"

Is there anything useful that can be done with this fbid such as looking up a user?


text:
Q: Run time polymorphism Concept of OOPS According to the concept of oops. In case of up casting reference variable of parent class can not execute the personal method of child class but when i run the following program-
interface My
{
}
class my1 implements My
{
    public String toString()
    {
        return "hello";
    }
    public static void main(String... s)
    {
        My m=new my1();
        System.out.println(m.toString());
    }
}

it executes successfully and print "hello."
Can anyone explain how this is happening...??
for to be more clear the following program gives compile time error
interface My
{
}
class my1 implements My
{
    public String toString1()
    {
        return "hello";
    }
    public static void main(String... s)
    {
       My m=new my1();
       System.out.println(m.toString1());
    }
}


text:
Q: Why does count(DOMNode->childNodes) return an incorrect number of children? (PHP and XML) I have a PHP function called processDeleteForm() designed to remove a specified node from an xml document named structure.xml. The only problem I'm having with it so far is that in processDeleteForm(), it searches for the node to be removed by looping through each child node of the parent node, and matches it by the "name" attribute, but I haven't been able to get the correct number of child nodes for the loop, so it stops before it reaches the correct node. Relevant code:
function processDeleteForm($dir, $filename)
{
  echo "Processing delete request.
";
  echo "Request to delete ".$filename." from ".$dir.".
";
  $xmlDoc = new DOMDocument();

  $xmlDoc->load("structure.xml");
  $node = dirDOMNodeWritable($dir, $xmlDoc);

  $target;
  echo "Working directory has ".count($node->childNodes)." child(ren).
";
  for($x = 0; $x < count($node->childNodes); $x++)
  {
    if($node->childNodes->item($x)->getAttribute("name") == $filename)
    {
      $target = $node->childNodes->item($x);
      echo "Target found.
";
    }
    else
    {
      echo "Searching for target...
";
    }
  }

  if($target->getAttribute("type") != "directory")
  {
    $fstored = "uploads/".$target->childNodes->item(0)->wholeText;
    unlink($fstored);
  }

  $node->removeChild($target);

  $file = fopen("structure.xml", "w");
  fwrite($file, $xmlDoc->saveXML());

}

structure.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<directory name="root" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
  <directory name="music" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
    <directory name="She" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
      <directory name="Chiptek" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
        <directory name="mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
          <file name="intro.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">intro.mp3</file>
          <file name="music.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">music.mp3</file>
          <file name="supersonic.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">supersonic.mp3</file>
          <file name="memories.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">memories.mp3</file>
          <file name="chiptek.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">chiptek.mp3</file>
          <file name="intermission.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">intermission.mp3</file>
          <file name="kicks.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">kicks.mp3</file>
          <file name="1997.mp3" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/mpeg">1997.mp3</file>
        </directory>
        <directory name="ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="directory">
          <file name="intro.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">intro.ogg</file>
          <file name="music.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">music.ogg</file>
          <file name="supersonic.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">supersonic.ogg</file>
          <file name="memories.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">memories.ogg</file>
          <file name="chiptek.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">chiptek.ogg</file>
          <file name="intermission.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">intermission.ogg</file>
          <file name="kicks.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">kicks.ogg</file>
          <file name="1997.ogg" owner="elarsen" read="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" write="aclum,ahoffman,apavlowski,bvollmer,dpotts,drichardson,epiatt,jcantrell,jreeve,kdouglas,kjab,lbrewer,lholliday,mfriedman,norty,pmoore,rlongwell,scatlett,sketcherside,tperkins" type="audio/ogg">1997.ogg</file>
        </directory>
      </directory>
    </directory>
  </directory>
  <directory name="test01" owner="elarsen" read="0" write="0" type="directory"/>
  <directory name="test02" owner="elarsen" read="0" write="0" type="directory"/>
  <directory name="test03" owner="elarsen" read="0" write="0" type="directory"/>
</directory>

*The above is supposed to be the contents of an xml file, but I can't figure out how to display it as such. If somebody with more knowledge about formatting xml on stackoverflow could fix it, I would be much obliged.
It might also be useful to see the code responsible for the creation of the directories named "test01", "test02", and "test03":
function processNewForm($dir, $dirName, $readPrivs, $writePrivs)
{
  $readString = "";
  $writeString = "";
  $dirOwner = $_SESSION["user"];

  for($x = 0; $x < count($readPrivs); $x++)
  {
    $readString += $readPrivs[$x].",";
  }
  for($x = 0; $x < count($writePrivs); $x++)
  {
    $writeString += $writePrivs[$x].",";
  }

  $xmlDoc = new DOMDocument();

  $xmlDoc->load("structure.xml");
  $node = dirDOMNodeWritable($dir, $xmlDoc);

  $newDir = $xmlDoc->createElement("directory");
  $newDir->setAttribute("name", $dirName);
  $newDir->setAttribute("owner", $dirOwner);
  $newDir->setAttribute("read", $readString);
  $newDir->setAttribute("write", $writeString);
  $newDir->setAttribute("type", "directory");

  $node->appendChild($newDir);

  $file = fopen("structure.xml", "w");
  fwrite($file, $xmlDoc->saveXML());

}

The current output looks like this:
Received delete request.
Validating delete request... Request is valid.
Processing delete request.
Request to delete test03/ from /.
Working directory has 1 child(ren).
Searching for target...

Notice: Undefined variable: target in E:\aepi\dev\fileshare.php on line 540

Fatal error: Call to a member function getAttribute() on a non-object in E:\aepi\dev\fileshare.php on line 540

A: From the PHP manual for count():

Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned.

DOMNode::$childNodes is a DOMNodeList object. It is not Countable. It will always return one (even if empty). Use its length property instead:
$count = $element->childNodes->length;

Update: DOMNodeList has been made Countable from PHP 7.2 onwards.

A: I'm guessing that your childNodes is including text nodes along with the XML tag nodes due to the white space in between tags.  This can result in a count of childNodes twice what you expect it to be.  You should check the nodeType to make sure it isn't a text node before attempting to get its attributes.
Possibly in here:
  for($x = 0; $x < count($node->childNodes); $x++)
  {
    // Verify that you're not working on a text node (type 3 TEXT_NODE)
    if($node->nodeType != 3 && $node->childNodes->item($x)->getAttribute("name") == $filename)
    {
      $target = $node->childNodes->item($x);
      echo "Target found.
";
    }
    else
    {
      echo "Searching for target...
";
    }
  }


text:
Q: Does Affine combination of vectors reduce dimensionality? I'm not familiar with Affine combination, but I came across this concept in a paper and tried to make sure whether I understand it correctly.
Suppose in a D-dimensional vector space we have three linearly independent vector $v_1,v_2,v_3$. The linear combination of this three vector spans a 3-dimensional subspace. Is that right to say that the affine combination of the three vectors spans a 2- dimensional subspace? Furthermore, the convex combination will just be a finite area of the span of affine combination?
I may well mess up a lot of concepts here. Please feel free to point them out. Thank you

A: Yes, you're right that the affine span of three (affinely independent) vectors will be an affine 2-dimensional plane. Note that vectors may be linearly dependent and still be affinely independent. The relevant definition is this:
$v_0,\dots,v_k$ are affinely independent if the only solution of $c_0v_0+c_1v_1+\dots+c_kv_k=0$ with $c_0+c_1+\dots+c_k=0$ is $c_0=c_1=\dots=c_k=0$.
You can check that $v_0,\dots,v_k$ are affinely independent if and only if the $k$ vectors $v_1-v_0$, $\dots$, $v_k-v_0$ are linearly independent (and this definition does not depend on your choice of which one is $v_0$).
The next thing to check is that the affine span of $v_0,\dots,v_k$ (i.e., the affine subspace they span) consists precisely of all vectors $$x=c_0v_0+c_1v_1+\dots+c_kv_k \quad\text{with}\quad c_0+c_1+\dots+c_k=1.$$
(Hint: Write such an $x$ as $v_0+\lambda_1(v_1-v_0)+\dots+\lambda_k(v_k-v_0)$ for some scalars $\lambda_1,\dots,\lambda_k$.) It's worth thinking about what subset you get in the affine span when you require, for example, all $c_i\ge 0$. (Can you interpret, then, what it means to have one particular $c_i\ge 0$?)


text:
Q: How to create multiple instances of RestController in Spring boot application? I want to create different instances of Spring RestController with different instances of beans (service, dao, cache) injected.
Currently, we have implemented this with JAX-RS Restful API.
But when I try to implement the same in Spring RestController, I'm getting below error when Spring tries to create a new bean "product2RestController".
Because bean "product1RestController" is already mapped to the rest url and created.
Stacktrace:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'product2RestController' method
@Path("/products")
public class ProductLookupRestService {

    @Context
    HttpServletRequest httpServletRequest;

    @Context
    HttpServletResponse httpServletResponse;

    @Context
    UriInfo uriInfo;

    private Map<Integer, AbstractProductRestService> productServiceLoopup;

    public void setProductServiceLoopup(Map<Integer, AbstractProductRestService> productServiceLoopup) {
        this.productServiceLoopup = productServiceLoopup;
    }

    @Path("/{productId}")
    public AbstractProductRestService getReport(@PathParam("productId") int productId) {
        AbstractProductRestService productRestService = this.productServiceLoopup.get(productId);
        productRestService.setHttpServletRequest(httpServletRequest);
        productRestService.setHttpServletResponse(httpServletResponse);
        productRestService.setUriInfo(uriInfo);

        return productRestService;
    }
}

public abstract class AbstractProductRestService {

    @Context
    protected HttpServletRequest httpServletRequest;

    @Context
    protected HttpServletResponse httpServletResponse;

    @Context
    protected UriInfo uriInfo;

    protected IProductService productService;
    protected IProductCache productCache;

    public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }

    public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
        this.httpServletResponse = httpServletResponse;
    }

    public void setUriInfo(UriInfo uriInfo) {
        this.uriInfo = uriInfo;
    }

    public void setProductService(IProductService productService) {
        this.productService = productService;
    }

    public void setProductCache(IProductCache productCache) {
        this.productCache = productCache;
    }

    @POST
    @Path("/filters")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createFilters(Form filterForm) {
        //Save the filters and return uuid
        ResponseBuilder responseBuilder = Response.created(uriInfo.getAbsolutePathBuilder().path("uuid").build());

        return responseBuilder.build();
    }
}

public class ProductRestService extends AbstractProductRestService {

    @GET
    @Path("/filters/{uuid}/detail")
    public String getProductDetail(){
        // do cache check : productCache
        return this.productService.readProductDetail();
    }
}

public class ProductServiceImpl implements IProductService{

    @Override
    public String readProductDetail() {
        // Call to dao to get the data
        return null;
    }

}

<bean id="product1RestService" class="com.poc.jaxrs.rest.ProductRestService">
        <property name="productService" ref="product1Service"/>
        <property name="productCache" ref="product1Cache"/>
    </bean>

    <bean id="product2RestService" class="com.poc.jaxrs.rest.ProductRestService">
        <property name="productService" ref="product2Service"/>
        <property name="productCache" ref="product2Cache"/>
    </bean>

    <bean id="restProductLookupService" class="com.poc.jaxrs.rest.ProductLookupRestService">
        <property name="productServiceLoopup">
            <map key-type="java.lang.Integer">
                <entry key="1"><ref bean="product1RestService"/></entry>
                <entry key="2"><ref bean="product2RestService"/></entry>
            </map>
        </property>
    </bean>

I use below like urls to invoke service.
POST Call: http://localhost:8080/productservice/products/1/filters
GET Call: http://localhost:8080/productservice/products/1/filters/uuid/detail
In my spring application context xml, I'm creating multiple instances of ProductRestService class with different beans (service, cache) instances injected.
Same way I want to create multiple instances of Spring RestController, But I'm getting Ambiguous mapping error.
Thanks for your help in advance.


text:
Q: Azure table storage with loopbackJS I want to use Azure table storage with loopbackJS. Is there any library to use this or can any one please help me to how can i use this.

A: Loopback doesn't have a commercial Azure Table Storage connector available currently, and neither is there a community connector for it.
You can write a new connector yourself, but that may be overkill/difficult for you.
If you're flexible about your Azure NoSQL technology you could look at using Azure DocumentDB which has protocol support for MongoDB, so you could use the Loopback MongoDB connector.


text:
Q: CSS checking if input is checked and chaining elements I cannot make this work, guys. The problem is I no longer have idea how to (try to) make it work.

#5starcheckbox:checked+label[for="5starcheckbox"]>.col-lg-10>.progress>.progress-bar {
  opacity: 1 !important;
}

input#5starcheckbox:checked+span#5starpercentage {
  color: #0060df !important;
}

                <input type="checkbox" id="5starcheckbox" name="stars[]" value="5">

{{ $scoreInfo['percent_5_star'] }}%

Is there something wrong in my code? Why it isn't working?

A: The problem is, that your label encloses your input. The CSS selector + (in your case #5starcheckbox:checked + label[for="5starcheckbox"]) matches the followin sibling, if the selector matches it. So, #5starcheckbox:checked + label[for="5starcheckbox"] only matches the label in the following code:
<input type="checkbox" name="5starcheckbox" id="5starcheckbox">

There isn't a parent selector in CSS.

A: I resorted to jQuery to do this.
$("#form").on('change', function() {
    for(i = 1; i <= 5; i++) {
        checkbox = $("#" + i + "starcheckbox");
        checked = checkbox.is(":checked");
        if(checked == true) {
            $("#" + i + "starpercentage").removeClass('text-secondary').addClass('text-primary');
            $(".progress" + i).css('opacity', '1.0');
        } else {
            $("#" + i + "starpercentage").removeClass('text-primary').addClass('text-secondary');
            $(".progress" + i).css('opacity', '0.4');
        }
    }
});


text:
Q: How to calculate the dead time to incorporate in the complementay PWM input to an H-Bridge designed using MOSFETs? I am working on making an autonomous robot. Right now,  I am involved in designing an H-Bridge using discrete components for my robot. I am almost done with the H-Bridge design, and want to test it now. However, I am not being able to decide a dead time for the input complementary PWM I will provide as an input to the H-Bridge. I know that to prevent overshoot, you have to delay the turn-on of the low-side FET by at least as much as the turn-off time of the high-side FET. The same goes of course for the other transition, when you switch from low-side to the high-side.
I have searched about finding the dead time online and I haven't found any useful information. The information I found was for H-Bridges who have gate driver circuitry designed discretely, and use formulas to find the actual turn on and turn off times of the MOSFET. Whereas, I am using IR2112 to drive the MOSFETs (IRFZ44N in my case).
I am attaching the schematic of my H-Bridge circuit. Please view it and tell me how should I calculate the dead time. I do know the turn on/off delays of both the gate driver IC and the MOSFET. Should I add the turn off delay of both these to get my dead time?

A: Dead time is to prevent shoot through i.e. both MOSFETs conducting appreciable current at the same time.

I do know the turn on/off delays of both the gate driver IC and the
  MOSFET

That's good because you are almost there.

Should I add the turn off delay of both these to get my dead time?

No, add the turn-on time of one MOSFET/driver to the turn-off time of the other MOSFET/driver to give a conservative estimate. Calculate this for switching high and switching low and choose the highest value of combined times.
If you wanted to reduce the value a fraction it's down to how much shoot-through current you can suffer - I would probably want to simulate this on something like LTSpice.


text:
Q: Fetching ID from Select menu and saving record as one-to-many I have been trying to fetch the id of this Select helper all day, and still noting but nil's and undefined...
I just want the product_id to be set to the value in the Select which is being set fine in the template....
// Models
Amber.Consumption = DS.Model.extend({
  product: DS.belongsTo('product', {async: true}),
  quantityUsed: DS.attr('number'),
  location: DS.attr('string'),
  employeeName: DS.attr('string'),
  processed: DS.attr('boolean', {defaultValue: false})
});

Amber.Product = DS.Model.extend({
  quantityStock: DS.attr('number'),
  product: DS.attr('string'),
  consumptions: DS.hasMany('consumption', {async:true})
});

/consumption/new.hbs
<form {{action "create" on="submit"}}>

    Produkt

      {{view "select"
        content=products
        selection=products
        optionValuePath="content.id"
        optionLabelPath="content.product"
     }}

...

// controller
Amber.ConsumptionsNewController = Ember.ObjectController.extend ({
  products: function() {
    return this.store.find('product')
  }.property('product')
});

// Route + routes
Amber.Router.map(function() {
  this.resource('products', function() {
    this.route('new');
    this.route('update', { path: '/update/:product_id' });
    this.route('show', { path: '/show/:product_id' });
    this.resource('consumptions', function() {
      this.route('new');
      this.route('show', { path: '/show/:consumption_id' });
    })
  });
});

Amber.ConsumptionsNewRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('consumption', {
      processed: true,
    });
  },

actions: {
    create: function() {
      var newConsumption = this.get('currentModel');
      var self = this;

      newConsumption.save().then(
        function() { self.transitionTo('consumptions') },
        function() { }
      );
    }
  }
});

// Rails Serializers
class ConsumptionSerializer < ActiveModel::Serializer
  attributes :id, :product_id, :quantity_used, :employee_name, :processed, :location
end

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :quantity_stock, :product
end

All the other values are being saved alright... but product_id is never set. Very frustrating when I can actually see the ID being bound to the option value in the html:
<select id="ember983" class="ember-view ember-select">
  <option id="ember996" class="ember-view" value="1">A-Product</option>

I hope someone can help.. Have been stuck here for waaayyy to long now :/