text:
Q: Error in File upload using ajax and php I am writing a registration form which consists of 10 text inputs and five file input. The form posts the whole data to server using Jquery ajax. I am also using FormData for the same. PHP is the server side language.
The whole code is working properly on localhost(XAMPP). But when i upload to my webserver, the php getimagesize() function fails with ERROR: Filename cannot be empty .

*

*Php version on localhost: 5.3

*Php version on webserver:  5.2

HTML Code
<form name="drvregister" id="drvregister" action="api/driver" enctype="multipart/form-data" class="form-horizontal">

        Full Name

            <input type="text" class="form-control" id="firstname" name="firstname" value="" placeholder="First Name" required="" title="Please enter your First Name">

            <input type="text" class="form-control" id="lastname" name="lastname" value="" placeholder="Last Name" required="" title="Please enter your Last Name">

        Email Address

            <input type="text" class="form-control" id="emailid" name="emailid" value="" placeholder="Email ID" required="" title="Please enter your Email ID">

        Date of Birth

            <input type="datetime" class="form-control datepicker" id="dob" name="dob" value="" placeholder="dd/mm/yyyy" required="" title="Please enter your Date of Birth">

        Gender

                    <input type="radio" class="radio" id="gender" name="gender" value="male" required="" title="Please mention your Gender"> Male

                    <input type="radio" class="radio" id="gender" name="gender" value="female" required="" title="Please mention your Gender"> Female

        Address

            <textarea class="form-control" rows="4" id="address" name="address" value="" placeholder="Address" required="" title="Please enter your Address"></textarea>

        Vehicle Reg. Number

            <input type="text" class="form-control" id="vehiclenumber" name="vehiclenumber" value="" placeholder="Vehicle Registration Number" required="" title="Please enter your vehicle registration number">

        License Number

            <input type="text" class="form-control" id="licensenumber" name="licensenumber" value="" data-toggle="tooltip" data-placement="left" placeholder="License Number" required="" title="Please enter your License Number">

        Handset Model

            <input type="text" class="form-control" id="handset" name="handset" value="" data-toggle="tooltip" data-placement="left" placeholder="Handset Model" required="" title="Please enter your Handset Model">

    <fieldset class="docup">
        <legend class="docup">Upload Documents</legend>

            License

                <input type="file" class="form-control file" accept="image/*" id="license" name="license" value="" placeholder="License" required="" title="Please Upload your License SoftCopy">

            PAN Card

                <input type="file" class="form-control file" accept="image/*" id="pancard" name="pancard" value="" placeholder="PAN Card" required="" title="Please Upload your PAN Card SoftCopy">

            Bike Insurance Papers

                <input type="file" class="form-control file" accept="image/*" id="insurance" name="insurance" value="" placeholder="Bike Insurance Papers" required="" title="Please Upload your Bike Insurance Papers SoftCopy">

            Picture of your Bike

                <input type="file" class="form-control file" accept="image/*" id="bikepic" name="bikepic" value="" placeholder="Picture of your Bike" required="" title="Please Upload Picture of your Bike">

            Address Proof

                <input type="file" class="form-control file" accept="image/*" id="addressproof" name="addressproof" value="" placeholder="Address Proof" required="" title="Please Upload your Address Proof SoftCopy">

    </fieldset>

            <input type="text" class="form-control" name="captcha"/>

            <input type="checkbox" name="agree" id="agree"> I Agree to terms and conditions

            <button id="submit" type="submit" class="btn btn-success">Register</button>

            <button id="reset" type="reset" class="btn btn-default">Reset</button>

</form>

Js Code
.on('success.form.bv', function(e) {
    e.preventDefault();
    $('#progress').modal({
        backdrop: 'static',
        keyboard: false
    });
    $('#progress').modal('show');
    var $form = $(e.target);
    var bv = $form.data('bootstrapValidator');
    var formdata = new FormData(e.target);

    $.ajax({
        url: $form.attr('action'),
        type: 'POST',
        data: formdata,
        async: false,
        xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) { // check if upload property exists
                myXhr.upload.addEventListener('progress', updateProgress, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        success: function(xml) {
            var message = $(xml).find('message').text();
            $('#returnmsg').html(message);
            $('#progress').modal('hide');
            $('#message').modal('show');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var message = $(xml).find('error').text();
            $('#returnmsg').html(message);
            $('#progress').modal('hide');
            $('#message').modal('show');
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

Php Code
public function registerdriver() {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $emailid = $_POST['emailid'];
    $dob = $_POST['dob'];
    $gender = $_POST['gender'];
    $address = $_POST['address'];
    $vehiclenumber = $_POST['vehiclenumber'];
    $licensenumber = $_POST['licensenumber'];
    $handset = $_POST['handset'];

    $parts = explode('/', $dob);
    $date = "$parts[2]-$parts[1]-$parts[0]";

    $licensefile_ext = strrchr($_FILES["license"]["name"], '.');
    $pancardfile_ext = strrchr($_FILES["pancard"]["name"], '.');
    $insurancefile_ext = strrchr($_FILES["insurance"]["name"], '.');
    $bikepicfile_ext = strrchr($_FILES["bikepic"]["name"], '.');
    $addressprooffile_ext = strrchr($_FILES["addressproof"]["name"], '.');

    $licensefile = $content_path . date("Y-m-d") . '/' . md5(basename($_FILES["license"]["name"])) . $licensefile_ext;
    $pancardfile = $content_path . date("Y-m-d") . '/' . md5(basename($_FILES["pancard"]["name"])) . $pancardfile_ext;
    $insurancefile = $content_path . date("Y-m-d") . '/' . md5(basename($_FILES["insurance"]["name"])) . $insurancefile_ext;
    $bikepicfile = $content_path . date("Y-m-d") . '/' . md5(basename($_FILES["bikepic"]["name"])) . $bikepicfile_ext;
    $addressprooffile = $content_path . date("Y-m-d") . '/' . md5(basename($_FILES["addressproof"]["name"])) . $addressprooffile_ext;

    $this->verifyimage(); //Error Line
}

private function verifyimage() {

    $imageflag = getimagesize($_FILES["license"]["tmp_name"]); //Function breaks here "Filename cannot be empty"
    if ($imageflag === false)
        $this->returnerror("Invalid Image");
    $imageflag = getimagesize($_FILES["pancard"]["tmp_name"]);
    if ($imageflag === false)
        $this->returnerror("Invalid Image");
    $imageflag = getimagesize($_FILES["insurance"]["tmp_name"]);
    if ($imageflag === false)
        $this->returnerror("Invalid Image");
    $imageflag = getimagesize($_FILES["bikepic"]["tmp_name"]);
    if ($imageflag === false)
        $this->returnerror("Invalid Image");
    $imageflag = getimagesize($_FILES["addressproof"]["tmp_name"]);
    if ($imageflag === false)
        $this->returnerror("Invalid Image");
}

printf($_FILES) gives following output
Array
(
    [license] => Array
        (
            [name] => 603842_893248767384667_7569544565024956810_n.jpg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

    [pancard] => Array
        (
            [name] => 603842_893248767384667_7569544565024956810_n.jpg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

    [insurance] => Array
        (
            [name] => 603842_893248767384667_7569544565024956810_n.jpg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

    [bikepic] => Array
        (
            [name] => 603842_893248767384667_7569544565024956810_n.jpg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

    [addressproof] => Array
        (
            [name] => 603842_893248767384667_7569544565024956810_n.jpg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

)


text:
Q: how to make title in TOCropViewController CocoaPod? I need to add a title bar named "Crop Image" in this Cocoapod.

Please help me

A: I'm the developer of TOCropViewController. :)
There's no feature in the library at the moment to display text above the cropping content right now. But it would be fairly trivial to add a UILabel to the view and position it near the top of the view.
The challenge is that you'd then need to account for it when the device is rotated sideways. At the moment, the cropping content will fill the entire height of a horizontal device, so you'd need to override that to account for the text.
It's been a while since I wrote it, but I did include a property in the vertical layout code to add padding to the top of the view controller, so it SHOULD be relatively easy.
I sadly don't have time to add it myself, but I made an issue on the repo and added the pr requested tag. Hopefully someone with more free time than I do can add it. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does fractional part converge in distribution to a uniform random variable? Let $X$ be a continuous random variable with a density function $f(x).$ Let $\{x\}$ denote the fractional part of a real number. I am tryng to prove that
$$
\mathbb{P}[\{nX\}\leq z] \rightarrow z, \ \ \forall z \in [0,1]
$$
Can anyone help me in this ?
My attempt:
If $g_n(z)$ is the density of $\{nX\}$, I got $g_n(z)=\sum_{m \in \mathbb{Z}}\frac{1}{n}f(\frac{m}{n}+\frac{z}{n})$. Can I justify from here ?
One can assume nice properties on $f$ if needed but I want to keep those assumptions as minimal as possible.

A: The obvious counterexample is the constant case $f(x) = \delta_{1/2}$ (for the Dirac $\delta$).  More generally, I doubt this is true of pathological continuous densities constructed, say, with peaks at all dyadic rational numbers.
If you specify extra smoothness then it may be true.


text:
Q: consisten (un)capitalization of labels in rendering of form fields My graphic design requires all fields in HTML forms to be lowercase. Example:

pressure Hg	<input
id="id_pressure_Hg" type="text" name="pressure_Hg" />

Django forms, however, per default make my labels with capital first letter. Since I have a lot of fields and many forms are created from a model (through a modelform), the "label" attribute is not a viable solution.
Is there a way to modify the function which translates field names into field labels?

A: you can try this.
example..
in your forms.py
value = forms.CharField(label=u'', widget=forms.TextInput())

in your HTML file.

value Value : {{form.value}}

you can modify the form.value in your CSS or JQuery. i has this attribute as an input in html.. id=id_value and name=value


text:
Q: Windows 7 - No Primary Partition - Is This Wrong? My laptop has only one physical disk - but I'm looking at it in 'Disk Management' and I see that all of the partitions are 'Simple volumes'
System (no drive letter) 199MB
Main (C:) 222GB
Ubuntu (H:) 58.59GB
Recovery (D:) 18GB
HP_TOOLS (E:) 103MB
Is this 'bad'?  I don't remember it being this way in the past (they are color-coded in the Computer Management screen and I don't remember ever seeing this shade of green on my drive - I swear it was blue).
Is there any reason I should be concerned about this?  I'm trying to use wubi.exe to install Linux on my H: partition - is that possibly the cause of this?  The install is failing and the opinion on the Ubuntu forums seems to be that there is something wrong with my disk.
EDIT:  It appears my /boot folder and /$Recycle.BIN folders are in the 'System' partition that currently has no letter to it.

A: Your disk uses Microsoft's Logical Disk Manager ("Dynamic Disks") on top of the legacy MBR partitioning scheme. "Dynamic disks" only use a single MBR partition, subdivided by Windows into volumes, which can span multiple physical drives and do not have the "four primaries" limitation of bare MBR.
This is not 'bad' in itself – it makes partitioning much easier when Windows is the only OS on the computer. Linux can access dynamic disks as well (as of 2.4.7). However, the GRUB boot manager commonly used by Linux (including grub4dos, which Wubi uses) does not support booting from a LDM disk. (It should, soon, but I wouldn't count on it reaching grub4dos anytime this year.)
In other words, to install Ubuntu (even Wubi), you will need to use 'basic' MBR or GPT partitioning. Windows doesn't provide a function to convert "back", but people have written tutorials on it. (Be careful.)


text: Q: Using command blocks, how can I automatically place mined blocks into the inventory of the player who mined them? Is it possible to make it so that each time you mine a block, you get the block, using command blocks in MCPE? It doesn't matter what tool you use, or just your fist, it just appears in your inventory. The block doesn't drop onto the floor.


text:
Q: Effect of a ground in a circuit From the picture, the switch can be considered 'closed'. Could someone explain what effect the 'ground' has on the different currents (I1, I2...)? If I had the exact same diagram, except WITHOUT the ground, what would be different? What about when the switch is opened after a long time?

A: If the ground was removed and replaced with its own voltage node, and analyzed the voltages relative to each other they would not be different from the circuit with ground, however you would not know how the value of the nodes relative to anything outside the circuit.
You could move ground to any point in the circuit and the relative voltages would be the same, but only because the ground node has no current flowing through it to another point in the circuit.

A: This image is from a circuit analysis exercise problem. The ground symbol has no effect on the currents and voltages in the circuit. One can well take an eraser and wipe it off. If the writer of the problem asked some node voltages, the ground symbol would show the reference node and that makes it important in exercices.
In real schematics of electronic equipment the ground symbol states that this is the wire that needs no shielding against the disturbing fields.  The shieldings would be connected to this. Different parts of the circuit can have their own grounds that have one connection between each other.
In schematics the ground symbol is widely used also to make the drawing easier to read. Much long lines can be replaced by a well known symbol.
In electric power systems the grounding is physical - a wire inside the soil, It is extremely important for the safety. Electric equipment often have a metal case. It should be connected to real earth for safety until double insulation is applied.


text:
Q: Tray Icon animation I know how to place a icon in the Windows notification area (system tray).
What is the best method to have an icon animate? Can you use an animated gif, or do you have to rely on a timer?
I'm using C# and WPF, but WinForms accepted too.

A: I think the best way to do this is to have multiple small icons which you can continue to change the systray object to the new picture based on the speed and the time.

A: Abhinaba Basu's blog post Animation and Text in System tray using C# explains.
It comes down to:

*

*making an array of icons each of which represent an animation frame.

*switching the icons in the tray on timer events

*create a bitmap strip. Each frame is 16x16 pixels

*use SysTray.cs
e.g.

private void button1_Click(object sender, System.EventArgs e)
{
    m_sysTray.StopAnimation();
    Bitmap bmp = new Bitmap("tick.bmp");
    // the color from the left bottom pixel will be made transparent
    bmp.MakeTransparent();
    m_sysTray.SetAnimationClip(bmp);
    m_sysTray.StartAnimation(150, 5);
}

SetAnimationClip uses the following code to create the animation frame
public void SetAnimationClip (Bitmap bitmapStrip)
{
    m_animationIcons = new Icon[bitmapStrip.Width / 16];
    for (int i = 0; i < m_animationIcons.Length; i++)
    {
        Rectangle rect = new Rectangle(i*16, 0, 16, 16);
        Bitmap bmp = bitmapStrip.Clone(rect, bitmapStrip.PixelFormat);
        m_animationIcons[i] = Icon.FromHandle(bmp.GetHicon());
    }
}

To animate the frame StartAnimation starts a timer and in the timer the icons are changed to animate the whole sequence.
public void StartAnimation(int interval, int loopCount)
{
    if(m_animationIcons == null)
        throw new ApplicationException("Animation clip not set with
                                        SetAnimationClip");

    m_loopCount = loopCount;
    m_timer.Interval = interval;
    m_timer.Start();
}

private void m_timer_Tick(object sender, EventArgs e)
{
    if(m_currIndex < m_animationIcons.Length)
    {
        m_notifyIcon.Icon = m_animationIcons[m_currIndex];
        m_currIndex++;
    }
    ....
}

Using SysTray
Create and wire up your menu
ContextMenu m_menu = new ContextMenu();
m_menu.MenuItems.Add(0, new MenuItem("Show",new
                     System.EventHandler(Show_Click)));

Get an icon you want to show statically in the tray.
Create a SysTray object with all the required information
m_sysTray = new SysTray("Right click for context menu",
            new Icon(GetType(),"TrayIcon.ico"), m_menu);

Create image strips with the animation frames. For 6 frame strip the image will have a width of 6*16 and height as 16 pixels
Bitmap bmp = new Bitmap("tick.bmp");
// the color from the left bottom pixel will be made transparent
bmp.MakeTransparent();
m_sysTray.SetAnimationClip(bmp);

Start animation indicating how many times you need to loop the animation and the frame delay
m_sysTray.StartAnimation(150, 5);

To stop animation call
m_sysTray.StopAnimation();


text:
Q: Is it counter-intuitive to have the property "id" be part of a composite key to uniquely identify an entity? Struggling with a bit of naming conventions here.
I have an object which is uniquely identifiable through two properties: the UUID of its parent and an auto-incremented count.
Example:
Parent object has an UUID of 04305eb6-cccb-498c-8fab-95e7d933672d
I add a child object to the parent. Its Id is 1.
I add a second child object to the parent. Its Id is 2.
I delete the child with Id of 1.
I add a third child. Its Id is 3.
I delete the child with Id of 3.
I add a fourth child. Its Id is (3 or 4? Not sure which would make more sense)
My questions:

*

*Is using the property Id here going to be confusing? Should I name it something like countAutoIncrement instead?

*My algorithm would mean that the countAutoIncrement would be 1 + the largest count for the playlist. Is this an OK algorithm? Or should it just always be 1 + the last generated count?


text:
Q: Create an array of strings by selecting anchor's text for all the anchors element present in DOM I need to create an array of anchor text like below:
$(currentNode).find('input:checkbox').next('a')

From above line of code I will get an object array of anchor elements, however I want an array of the text in the anchor elements.
My anchor tags are as below:
<a class="rightCaret" href="#subMenuSelect"> SelectMe </a>

and I need to create an array which contains it's text - i.e SelectMe
Any help would be appreciated

A: You can use map() to build an array populated with the required properties. Try this:
var aTexts = $(currentNode).find('input:checkbox').next('a').map(function() {
    return $(this).text();
}).get();

console.log(aTexts);

A: Use .map() function:
$(currentNode).find('input:checkbox').next('a').map(function(){
   return $(this).text()
}).get();

A: Use .map()
var array = $(currentNode).find('input:checkbox').next('a').map(function () {
    return $(this).text();
}).get()

A: Using jQuery each() you can do
var anchorTextA = [];
$(currentNode).find('input:checkbox').next('a').each(function(){
    anchorTextA.push($(this).text());
});


text:
Q: Transfinite Recursion Theorem - Particular case - Enderton I have the following theorem for any formula $\gamma(x,y)$:

Theorem of Transfinite Recursion: Given a well-ordered set $A$ such that for any $f$ there is a unique $y$ such that $\gamma(f,y)$ holds, then there is a unique function $F$ with domain $A$ such that $\gamma\big(F\upharpoonright\text{seg }t,F(t)\big)$ holds for all $t\in A$.

Now I'm reading through the proof of Well-Ordering Theorem $\implies$ Zorn's Lemma, for which the author has considered an arbitrary set $\mathscr A$, which can be endowed with some well-order $<$.
Then he says that the Transfinite Recursion Theorem give us the function $F:\mathscr A\to 2$ such that for every $A\in \mathscr A$
$$F(A)=\begin{cases}
1&\text{if for every } B<A \text{ such that } F(B)=1 \text{ we have } B\subseteq A\\
0 & \text{otherwise}
\end{cases}$$
How can I see that the Theorem of Transfinite Recursion permit this? What would $\gamma(x,y)$ be?
Thanks in advance.

A: Could it be the following?:
$\gamma(x,y)= \big(y=1 \land \varphi(x)\big)\lor\big(y=0\land \lnot\varphi(x)\big)$
where $\varphi(x)=\forall\,z\;\big(z\in\text{dom}(f)\to z\subseteq h(z)\big)$
where $h:\mathscr A\to\mathscr A$, so $h(z)=\text{the least element of }\mathscr A \text{ such that it's strictly greater than every element of }z$.
I've defined $h$ in such a way so we get $h(\text{seg }t)=t.$


text:
Q: Weird jquery problem when upgrade to Wordpress 3.1 After installed Wordpress 3.1, a jquery plugin selectbox i'm using not work 100 percent any more
I use this plugin in wordpress backend to replace my <select></select> with custom html codes on which i can apply css, but with wordpress 3.1, a lot of <select> don't get replaced 100%, <option> are missing in the replaced codes, for example
<select>
  <option (some attributes...)>text</option>
  <option (some attributes...)>text</option>
</select>

is supposed to be replaced with (actually not replace, the original <select> will be hide)

  text /* option 1 */
  text /* option 2 */

text of selected option

while actual result is

  /* nothing here */

nothing here

weird thing is there are still quite a few <select> do get 100% replaced.
i tried rollbacked to wordpress 3.0 and reinstall wordpress 3.1 twice, the script works perfectly once rollback to 3.0 and as long as 3.1 is intalled, the issue occurs.
there are no wp plugins in my test site and the jquery library is loaded completely first, my other scripts all works well. Seached a lot and no luck, but i found where the issue happens, have no idea why it goes that way though.
return this.each(function() { // for each <select>
    var _this = jQuery(this);
        ... // I added an alert here, alert(_this.attr('id')), to print <select> id, and all <select> id are catched
        jQuery('option', _this).each(function(k,v){
            ... // I added a same alert at first line this function, only replaced 100% <select> id are catched
        });
        ...
    });

this is the plugin codes do replacement, for all not get 100% replaced <select>, the line i commented above doesn't get implemented, looks like just be jumped.
Any ideas?

[Update]
I removed all other scripts and the plugin, here is the only codes left in my script
jQuery(document).ready(function() {
  jQuery('#myadmin select').each(function() {
      jQuery(this).find('option').addClass('huh?');
  });
 });

All options in those were not replaced 100% <select> do not get the class 'huh?'

[Update 2]
I changed the script in Update 1 to
jQuery(document).ready(function() {
  jQuery('select option').addClass('huh?');
 });

Guess what? All <option> got this class 'huh?'. It turns out like something about jQuery, but why WP 3.1?

[Resolved]
WP 3.1 upgrade jQuery version to 1.4.4, i deregistered it and bring back jQuery 1.4.2 on my page, everything is ok now, all <select> get replaced 100%
last question is how do i mark this question as resolved?

A: Fount this:

As for an answer to your question,
  nested eaches don't work in jQuery if
  you use the this variable. To fix your
  problem, try using the full style of
  each.

in an answer here.


text:
Q: Current carrying wire and charge invariance paradox I'm reading Purcell's Electricity and Magnetism book (5.9 "Interaction between a moving charge and other moving charges") where he explains how due to relativistic effects (length contraction) a magnetic force acting on a particle that moves near the wire in the lab frame (where the wire is stationary) is the result of an electric force that acts on the particle in its rest frame.
He starts with an uncharged wire (the charge densities of the electrons and the protons are equal in magnitude). Then he shows that in the frame of reference of the moving particle the linear densities of the electrons and protons are different and thus the wire looks charged. I have two questions:

*

*If the wire is neutral in the lab frame, how can it become charged in the moving frame? Isn't it a contradiction of the principle of charge invariance? I understand that the linear densities must change, but the total charge should not change.

*Let's examine a simpler setup. Suppose we have a neutral wire with protons and electrons both at rest in the lab frame (protons' and electrons' linear densities are $\lambda_0$ and $-\lambda_0$ respectively). Suppose we also have a charged particle at rest (also in the lab frame) near the wire. Suppose that all the electrons suddenly acquire some constant speed $v$ in the lab frame (for example, we turn on the electric field). So now we have stationary ions, moving electrons and a stationary charged particle (still, in the lab frame). Then we can use the same length contraction argument and claim that after acquiring the speed, the electron's density is now $-\gamma\lambda_0$. But then, using Purcell's argument we can claim that the total linear density of charge in the wire in the lab frame is $\lambda'=\lambda_0-\gamma\lambda_0=\lambda_0(1-\gamma)\neq 0$ therefore the wire becomes charged (again, using the same argument as Purcell). Therefore the stationary particle (we're still in the lab frame) will feel an electric force. However this seems to be wrong. What's wrong with this reasoning?

A: This is a classic problem in relativity and you can find it treated in any book which discusses the application of relativity to electromagnetism.
To understand charge invariance, we don't need an integral over all space (but it is true that if one part of the wire acquired a charge density, then another part of the wire acquired an opposite net charge density). Invariance (with respect to change of frame) in this case means that each entity with a given charge (e.g. an electron, a proton) has that same charge no matter what reference frame you pick. As you say, the densities can change from one frame to another because distance measures can change.
If you put your charges in a box (I mean a real box made out of something such as copper) then the number of charges in the box stays fixed, as you change from one frame to another, but the size of the box does not.
However, in the case of a current-carrying neutral wire, you can't simply imagine that all the electrons and protons are fixed in the same given box, because the electrons are moving relative to the protons.
I think a good insight into the situation is obtained by drawing worldlines on a spacetime diagram. e.g. draw lots of vertical straight worldlines representing protons, then lots of sloping mutually parallel worldlines representing electrons. Make this second set have the same spacing as the proton ones in the frame where the latter are vertical. These lines represent the charges, and charge invariance is the fact that each line represents the same amount of charge no matter what frame you pick. Now take a look at the situation in the frame where the electrons are at rest. To do this, don't draw a new diagram. Just draw a line of simultaneity for the electrons:

I have made part of the line of simultaneity bold in order to make it easy to see the result. There are 7 proton worldlines but only 5 electron worldlines intersecting the bold part. This means there is a net positive charge density on the wire, when the wire is observed in the rest frame of these electrons. It is because when changing frames from proton rest frame to electron rest frame, the protons here get closer together and the electrons get further apart.
Elsewhere in the circuit the flow of current is in the reverse direction. I leave you to figure out what that implies. You can also, I hope, answer your own further questions by adopting this sort of spacetime approach.

A: Short answer:

*

*It can become charged in the moving frame; however, the principle of charge invariance is indeed not violated. Hint: what else is affected by the Lorentz boost?

*The flaws in your reasoning start here. Can you figure them out?

Suppose that all the electrons suddenly acquire some constant speed $v$ in the lab frame (for example, we turn on the electric field) [...] Then we can use the same length contraction argument and claim that after acquiring the speed, the electron's density is now $−γλ_0$.

Long answer:

1.) The current-carrying wire itself is length-contracted, and in fact length contraction is the reason why the charge density of the protons increases, so even though the new charge density for the protons is $\lambda_p' = \gamma\lambda_0$, the length of the wire measured in the moving frame is $L_p' = L_0/\gamma$, giving a total charge of $$q = \lambda_p' L_p' = \frac{\gamma\lambda_0L_0}{\gamma} = \lambda_0 L_0$$ The case with the electrons is similar, but instead they experience a "length dilation" of $L_e' = \gamma L_0$, since they were moving in the lab frame but are now at rest in the comoving frame. Their charge density is now $\lambda_e' = -\lambda_0/\gamma$.The other way to convince yourself that a net nonzero charge density must develop is to simply transform the electromagnetic fields into the new frame, which will ultimately yield the following: $$\mathbf E' = \gamma\mathbf v \times \mathbf B$$ $$\mathbf B' = \gamma\mathbf B$$ Since $\mathbf E'$ is a nonzero static field that diverges away from the wire, that must mean there is now a net nonzero charge density being observed.2.) There are three things fundamentally wrong in those two sentence.First is the implicit assumption that when the electric field is turned on, every part of the wire will experience its effects, despite the fact that one of the fundamental tenets of special relativity is that the effects of electromagnetism (and pretty much everything else) have a fundamental finite propagation speed.The second is the statement that the electrons will suddenly acquire infinite velocity, which would require an unphysical infinite acceleration.The third incorrect assumption is your naive application of the idea of length contraction, a phenomenon associated with a Lorentz boost between reference frames; the development of the current in the wire is not a mere mathematical transformation between reference frames, but rather a real, physical process involving accelerating charges, the effects of which must be considered when determining the worldlines of each electron.

A:
If the wire is neutral in the lab frame, how can it become charged in the moving frame? Isn't it a contradiction of the principle of charge invariance?

Remember that the principle of charge invariance requires an integration over all of space. This means that the fact of charge invariance and the fact of the non-neutral wire in the moving frame can be combined to determine that the wire's surroundings must have an equal and opposite charge. In the case of a narrow rectangular loop of wire it is easy to see that the return wire has an equal and opposite charge.

Therefore the stationary particle (we're still in the lab frame) will feel an electric force. However this seems to be wrong. What's wrong with this reasoning?

Your reasoning is correct as far as you go, but you need to continue and finish the analysis. The charge has a non-zero velocity in the moving frame and there is a non-zero current density in the moving frame. Therefore, there is also a magnetic force on the charge. Taking the fact that there is an electric force in the moving frame and the fact that there is no force in the lab frame, you can easily see that the magnetic force in the moving frame must be equal and opposite to the electric force. Indeed, careful math can demonstrate that is the case, which is an exercise left for the reader.

A: Remember that the protons are at rest so by contraction of electrons their distance with each other will increase too. This will lead to the same amount of charge density.

A: It is not becoming charged in the moving reference . Your source is wrong .
Only if the carrier is conducting current , then it becomes electrically charged


text:
Q: Find a positive simple s-t Path on a Graph is NP-Complete? I'm trying to find something on the literature to help me to solve this problem:
Given a graph with non negative edge weights, find a simple s-t positive path of any size, i.e., a path that goes from s to t with length greater than 0. I was trying to use dijkstra algorithm to find a positive shortest path by avoiding relax the edges that have cost zero, but this is wrong. I don't want to believe that this problem is NP-Complete =/. Sometimes it seems to be NP-Complete, because there may be a case where the only positive path is the longest path. But this is such a specific case. I think that on this kind of instance the longest path problem is polynomially solvable.
Can someone help me identifying this problem or showing that it is NP-Complete ?
Observations: The only requirement is to be some positive path (not necessarily the lowest or longest). In case of multiple positive paths it can be anyone. In case of non existence of such path, the algorithm should flag that the graph has no positive path.

A: Dijkstra's algorithm produces an answer in polynomial time (so in P rather than NP) and provides a shortest path between any 2 points on the graph.
Please refer to Dijkstra's Algorithm Wiki for further details.
You don't really need any more proof.
I'm not quite sure how "relax the edges that have cost 0" has any impact on this question at all.

A: The problem is NP-complete even with only one single edge having value 1, and all the others having value 0.  Reduce from Two Directed Paths:
Two Directed Paths
Input: A directed graph G and two pairs of vertices (s1, t1) and (s2, t2)
Output: Two vertex-disjoint paths, one from s1 to t1 and from from s2 to t2.
Create a new instance with all edges having weight 0, and create an edge from t1 to s2 with weight 1.


text:
Q: AJAX .load url and postback not working I am bringing in a particular div (.source_div) from one part of my website into another div (.destination_div) on another part of my website using the following code:
<script type="text/javascript">
$(document).ready(function(){
$('.destination_div').load('http://myurl.mypage.com/something.aspx .source_div');
});
</script>

However, the .source_div contains links that go to other parts of my website. When I click on these links, I would like for those pages to continue displaying within my same .destination_div that I am on, and not taking me away to another page (which is what it currently does). On another slightly related note, I also have a form within my .source_div that that performs a postback which also appends the html. This does not work within my .load either. I have looked around and cannot figure out how to do either one of these things correctly. Could someone please help with one or both of these issues?

A: Delegate an event to all anchor tags within the destination_div element that performs the same .load, just with the href of the given link.
http://api.jquery.com/on
http://api.jquery.com/delegate

A: Implementation could be something like this.
$(document).ready(function(){
   $('.destination_div').load('http://myurl.mypage.com/something.aspx .source_div'); // your page is loaded first
   $('.destination_div').on('click','a',function() {
       var url = $(this).attr("href");
       $('.destination_div').load(url);
       return false;
   });
});

EDIT: added your previous code


text:
Q: UITableViewCell editingAccessory too far right Today I observed, that my editingAccessory (UITableViewCellAccessoryDetailButton) is too far on the right side, when the my tableView is in editing mode.
When toggling editing on and off I can see the icon move from their regular position to where they are in editing.
In my implementation I'm using
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

EDIT
There is no more code. It's just a plain UITableViewController and the edit button runs noting but the default -setEditing:animated: behind the scenes (as far as I can tell).
EDIT II
Find the complete ViewController implementation here


text:
Q: How to get an array of Element objects with javascript I am using a javascript plugin for gauges (http://bernii.github.io/gauge.js/).
The plugin works perfectly, but I can only make it work by using (getElementById)
I want to be able to have several instances of this plugin on the same page (without repeating the code for each one), but all other javascript selectors (getElementByClass), (querySelectorAll), etc, return a list of NODE OBJECTS, instead of "ELEMENT OBJECTS" as the (getElementById) method does.

var opts ={
  lines: 12,
  angle: 0.15,
  lineWidth: 0.44,
  pointer: {
    length: 0.9,
    strokeWidth: 0.035,
    color: '#000000'
  },
  limitMax: 'false',
  colorStart: '#6FADCF',
  colorStop: '#8FC0DA',
  strokeColor: '#E0E0E0',
  generateGradient: true
};

// this works
/*
var target = document.getElementById('gauge1');
var value = target.getAttribute('data-level');
var gauge = new Gauge(target).setOptions(opts);
gauge.maxValue = 1000;
gauge.animationSpeed = 32;
gauge.set(value);

*/

// this does not work
var target = document.getElementsByClassName('gauge');
for(var i=0; i<target.length; i++)
{
  var value = target[i].getAttribute('data-level');
  var gauge = new Gauge(target[i]).setOptions(opts);
  gauge.maxValue = 1000;
  gauge.animationSpeed = 32;
  gauge.set(value);
}
<script src="http://bernii.github.io/gauge.js/dist/gauge.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <canvas class='gauge' id="gauge1" data-level='900'></canvas>
    <canvas class='gauge' id="gauge2" data-level='800'></canvas>
    <canvas class='gauge' id="gauge3" data-level='700'></canvas>
  </body>
</html>

So my question is:
Is there a way to get an array of "ELEMENT OBJECTS" without using Id ?

A: The answer to this question is very simple and didn't have anything to do with nodes and elements.

*

*I was writing "getelementbyclass" instead of "getelementbyclassname" (syntax error)

*"value" was entered as a string into the plugin and therefore, the plugin was not correctly entered. I needed to add parseInt and it worked.

A: In your case you can also use:
var target = document.getElementsByTagName('canvas');


text:
Q: C# Webform resize image In WebForm, I use a control Image or ImageButton; is possible to resize an image, according to the ratio, t ? to fit the size of the control, the property Stretch is non-applicable.
If not possible in C# other ways as well JQuery, or javascript?
Ex. the pictures is 1635px x 2048 and the control 332px x 420 ratio 0.79


text:
Q: Heroku Toggle between sso and standard email login I work for a web development company that uses SSO for one client and standard email login for another.
After logging in with SSO I am now automatically routed to SSO login each time I go to Heroku.
How do I toggle back to standard login?


text:
Q: Palindromes with distinct palindromic prime factors Imagine the sequence of palindromic numbers where each term is defined as the smallest square-free palindromic number with no other prime factors but the n distinct palindromic prime factors. The sequence begins:

*

*$2$

*$6=2\cdot3$

*$66=2\cdot3\cdot11$

*$6666=2\cdot3\cdot11\cdot101$
What is the next term? Does the next term exist? I know that if there are infinitely many primes of the form $100000....000001$,then this sequence is definitely infinite, but it doesn't mean the infinitude of this sequence depends entirely on the infinitude of primes of the form $100000....000001$. I've checked palindromes up to $10^{10}$ now. So,what is the next term ?

A: I am not sure I understood the definition of the sequence, but
$$
334\,826\,628\,433=11\cdot101\cdot353\cdot919\cdot929
$$
seems to be the next term.


text:
Q: Is $\mathrm{Top}$ a coexact category? The question in the title reduces to:
Is it true that equivalence relations are effective in $Top^{op}$?
Here is some information in this direction:
The category $Top^{op}$ is regular, and therefore $Top^{op}$ is Barr exact if and only if equivalence relations are effective.
Note also the category of compact Hausdorff spaces is coexact (see Borceux)


text:
Q: Is there a ReSharper shortcut to find all instantiations of a certain type? For example:
... new MyClass();

... new MyClass { ... };

If I'm lucky:
... Activator.CreateInstance<MyClass>();

etc.
Any thoughts?

A: Right click the constructor, "Find Usages". I often create a constructor for classes even if I don't need it because of this feature.
Another way, right click on class and click "Find usages". Then click "Filter usages" (in the icon bar), "Show invocation usages". If it's grayed out, there are no invocation usages, which will probably be the case if you use
Activator.CreateInstance<MyClass>();

I found this question because I'm currently looking for a better way of doing this. No luck so far.

A: Select the constructor and press Shift+Alt+F12. This will show you all explicit calls to the constructor, which should include any factory methods. You can then use the same shortcut to see where they are called from.

A: Find Usages menu available on any member and type shows all usages, including instantiation.
I'm not aware of any way to filter the results to instantiation only.

A: Your first two are both calls to the same constructor. Simply doing a Find Usages will locate them (ALT+F7).

A: The Find Usages Feature is able to find all occurrences of any symbol. ReSharper is able to find all explicit references and the references created by using Reflection. See http://www.jetbrains.com/resharper/features/navigation_search.html#Find_Usages


text:
Q: Sed issue (regex syntax) I'm trying this sed to replace strings:
find . -type f -name "*.php" -exec sed -i "s|\!preg_match(\"\!modules\.php\!\", \\\$_SERVER\['PHP_SELF'\]) \{|\!preg_match(\"\!modules\\\.php\!\", \\\$_SERVER\['PHP_SELF'\])) \{|g" {} ";"

But I've an error message (error in pairing {)
I can't find the good syntax to do that. I just want to add a round bracket at the end on all files...
[edit]
Ok found it...
find . -type f -name "*.php" -exec sed -i "s|\!preg_match(\"\!modules\\\.php\!\", \\\$_SERVER\['PHP_SELF'\]) {|\!preg_match(\"\!modules\\\.php\!\", \\\$_SERVER\['PHP_SELF'\])) {|g" {} ";"

A: Use single quotes rather than double quotes to escape regexes and other programming language constructs that you pass on the command line from bash...

A: with simple quote and assuminf $SERVER is litteral
sed -i 's|!preg_match("!modules\.php!", \$_SERVER\['"'"'PHP_SELF'"'"'\]) {|!preg_match("!modules\.php!", \$_SERVER\['"'"'PHP_SELF'"'"'\])) {|g'

I remove the !, normaly ! should pass without escape
i propose also the simplification
sed -i 's|\(!preg_match("!modules\.php!", \$_SERVER\['"'"'PHP_SELF'"'"'\])\) {|\1) {|g'


text:
Q: How to filter and group data into 2 categories (class variables)? So I have this method:
getProducts() {
this.productService.getProducts().subscribe(products => {
  this.products = products;
});

Everything works great, so these are the 'products':

*

*0: {code: 'Product1', order: 1, description: 'Description', category: 'categoryone', price: 1500, …}

*1: {code: 'Product1', order: 2, description: 'Description', category: 'categoryone', price: 1000, …}

*2: {code: 'Product2', order: 1, description: '', category: 'categorytwo', price: 1199, …}

*3: {code: 'Product2', order: 2, description: '', category: 'categorytwo', price: 2999, …}

*4: {code: 'Product2', order: 3, description: '', category: 'categorytwo', price: 7999, …}

So what I'm trying is to filter and group that products into two class variables, for example categoryOne and categoryTwo and then display that data, but I don't know how.

A: If you know the category names and products is an array you can just loop over the array and use if conditions to assign the product to their respective variables
categoryoneProducts = []
categorytwoProducts = []

getProducts() {
  this.productService.getProducts().subscribe(products => {
    this.products = products;

    this.categoryoneProducts = []
    this.categorytwoProducts = []

    this.products.forEach(product => {

      if (product.category === 'categoryone') {
        categoryoneProducts.push(product)
      } else if (product.category === 'categorytwo') {
        categorytwoProducts.push(product)
      }
    })
  });
}


text:
Q: Problem with php-cs-fixer after upgrade php to version 8 After upgrade to php8 I have a problem with php-cs-fixer which I installed globally via composer. Right now I can not use php-cs-fixer because every time I get:
PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 7.4.*.
To ignore this requirement please set `PHP_CS_FIXER_IGNORE_ENV`.

For php upgrade and usage different version of php I use https://github.com/shivammathur/homebrew-php
For previous version of php (7.4) everything works fine.

A: The first version of php-cs-fixer to support PHP 8 was Version 2.18 released on 18th Jan 2021.

A: https://cs.symfony.com/doc/usage.html#environment-options
PHP_CS_FIXER_IGNORE_ENV=1 php php-cs-fixer.phar fix /path/to/dir

A: In the file: ./vendor/bin/php-cs-fixer
Remove the code below (starting at line 26):
elseif (!defined('PHP_VERSION_ID') || \PHP_VERSION_ID < 50600 || \PHP_VERSION_ID >= 70500) {
    fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 7.4.*.\n");

    if (getenv('PHP_CS_FIXER_IGNORE_ENV')) {
        fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n");
    } else {
        exit(1);
    }
}

It's a quick fix, but it will get you back up and running.


text:
Q: TypeError: {'name:busi,group:1'} is not JSON serializable when constructing a json in python by scratch How can we dynamically create a json file in python by using the csv data or the data provided as a list
data.csv looks like this
busi,biz
thank,pump
thank,such
thank,merri

which shows the links/edges between nodes in a graph.
I am trying to construct a json of nodes and arrays but I am getting json serialisation error.
nodes = []
nodes_dict = {}
counter = 0
edges = open(edges_file)
    for line in edges:
        line = line.replace("\n","")
        source =  line.split(",")[0]
        target = line.split(",")[1]
        if source not in nodes_dict:
            node_arr = {"name:" + source  + "," + "group:1"}
            nodes.append(node_arr)
            nodes_dict[source] = counter
            counter += 1

        if target not in nodes_dict:
            node_arr = {"name:"+ target + "," + "group:1"}
            nodes.append(node_arr)
            nodes_dict[target] = counter
            counter += 1
 json.dumps(nodes,outputfile)

But I am getting this error

TypeError: {'name:busi,group:1'} is not JSON serializable

My desired output
 "nodes":[
    {"name":"Myriel","group":1},
        {"name":"Napoleon","group":1},
{"name":"Mme.Hucheloup","group":8}],
"links":
            [{"source":1,"target":0,"value":1},{"source":2,"target":0,"value":8},
                {"source":3,"target":0,"value":10},{"source":3,"target":2,"value":6}}
}

A: You're building your dict wrong.
Try something like this
nodes = []
nodes_dict = {}
counter = 0
edges = open(edges_file)
    for line in edges:
        line = line.replace("\n","")
        source =  line.split(",")[0]
        target = line.split(",")[1]
        if source not in nodes_dict:
            node_arr = dict(
                name=source,
                group=1
            )
            nodes.append(node_arr)
            nodes_dict[source] = counter
            counter += 1

        if target not in nodes_dict:
            node_arr = dict(
                name=target,
                group=1
            )
            nodes.append(node_arr)
            nodes_dict[target] = counter
            counter += 1
 json.dumps(nodes,outputfile)


text:
Q: setInterval() speeding/slowing function propagation after a few cycles Using setInterval() and clearInterval() to cycle through a carousel of 4 images. On initial page load, the functions seem to work as expected. However, after a few cycles and hovers, focusing out of the page, the cycle starts speeding up between a couple of images and remains fine within the other. Sometimes, it starts skipping images all together in the cycle. At times it also autocorrects and starts working fine again. Here's what I have:
jQuery(document).ready(function($) {
var count = -1;
var maxCount = $('.hero-blocks .block').length;
var colors = new Array('yellow', 'blue', 'promo', 'purple');
var autopager, timer = false;
var desktop = false,
    mobile = false;

function carousel() {
    if(count < maxCount - 1) {
        count++;
    } else {
        count = 0;
    }

    $('.hero-blocks .block.active').removeClass('active');
    $('.hero-blocks .block.' + colors[count] + '').addClass('active');

};

function startAutopager() {
    autopager = window.setInterval(carousel, 4000);

    timer = true;
}

function stopAutopager() {
    window.clearInterval(autopager);
    $('.hero-blocks .block').removeClass('active');

    timer = false;
}

function triggerCarousel() {
    if (Modernizr.mq('only screen and (min-width: 1024px)')) {
        // This stuff stops the carousel if the user goes to a different tab
        if(!desktop) {
            startAutopager();
            window.addEventListener('focus', startAutopager);
            window.addEventListener('blur', stopAutopager);

            desktop = true;
            mobile = false;

            $('.hero-blocks .block').hover(function() {
                stopAutopager();
            }, function() {
                startAutopager();
            });
        }
    } else if(!mobile) {
        stopAutopager();

        mobile = true;
        desktop = false;
    }
}
triggerCarousel();

$(window).resize(function() {
    triggerCarousel();
});
});

A: I think the problem here is that it's possible to call window.setInterval(carousel, 4000) multiple times, since it's triggered during a couple of different events, and the code doesn't check if it's already running.
I suggest checking the value of timer before calling setInterval
function startAutopager() {
    if (!timer) {
        autopager = window.setInterval(carousel, 4000);

        timer = true;
    }
}

function stopAutopager() {
    if (timer) {
        window.clearInterval(autopager);
        $('.hero-blocks .block').removeClass('active');

        timer = false;
    }
}

Another minor point - setInterval doesn't guarantee perfect timing, so it's still possible that carousel will be triggered with different intervals.


text:
Q: Shuffling array properties in JavaScript I have a data dictionary like this:
var data = {
    'text1': 1,
    'text2': 2,
    'text3': 3,
    ...
    'text20': 20
];

I need to pick a random selection of those keys and then shuffle it's values. In the example, it should write something like this:
> console.log(choose(data, 5));
[ { key: 'text15', value: 8 },
{ key: 'text6', value: 3 },
{ key: 'text3', value: 15 },
{ key: 'text19', value: 6 },
{ key: 'text8', value: 19 } ]

For now I'm extracting the keys into another array and sorting by Math.random() but I'm stuck at swaping the values because no key should have the same value it initially had.
How would you swap key/values here?
Thanks

A: I put together a possible solution using underscore.js to simplify traversing the object and arrays in a cross browser manner:
var data = {
    text1: 1,
    text2: 2,
    text3: 3,
    text4: 4,
    text5: 5,
    text6: 6,
    text7: 7,
    text8: 8,
    text9: 9,
    text10: 10
};

function choose(data, num)
{
    var keys = _.sortBy(
                    _.keys(data),
                    function(k)
                    {
                        return (Math.random() * 3) - 1;
                    }
                ),
        results = [],
        k1, k2;
    if (num > keys.length) {
        throw new Error('Impossible to retrieve more values than exist');
    }
    while (results.length < num) {
        k1 = k2 || keys.pop();
        k2 = keys.pop();
        results.push({key:k1, value: data[k2]});
    }
    return results;
}

console.log(choose(data, 5));

This isn't necessarily an optimal approach but it seems to meet your requirements. I first grab all of the keys and sort them randomly. I then loop through the random keys creating a new object with one key and the following keys value. That way you'll always end up with a different value associated with each key. If you need it to work when the value of num passed in to the function == the number of keys in the data then you'll have to add a little more code - I'll leave that as an exercise for the reader :)
You can have a play with this code on jsfiddle:
http://jsfiddle.net/zVyQW/1/

A: You could do this:

*

*collect names and corresponding values in two arrays names and values

*shuffle both arrays independently of each other

*take the first n items of both arrays and combine them

Here's an example implementation:
Array.prototype.shuffle = function() {
    for (var i=this.length-1, j, tmp; i>0; i--) {
        j = Math.round(Math.random()*i);
        tmp = this[i], this[i] = this[j], this[j] = tmp;
    }
    return this;
};

function choose(data, number) {
    var names = [], values = [], pick = [];
    for (var name in data) {
        if (data.hasOwnProperty(name)) {
            names.push(name);
            values.push(data[name]);
        }
    }
    names = names.shuffle(), values = values.shuffle();
    for (var i=Math.min(number >>> 0, names.length-1); i>=0; i--) {
        pick.push({key: names[i], value: values[i]});
    }
    return pick;
}

A: Use an implementation of random that randomizes a discrete set of values, such as Math.rand seen here. For each index, randomize Math.rand(index, length-1) to get a list of random indexes, the location off all indices will change.

A: Been a while since this was answered, but I was working on shuffling and found the following to be by far the fastest implementation with an evenly random distribution.
It's fast because it only makes one call to Math.random on each iteration, all the rest is done by property access. It doesn't modify the array, just reassigns values.
  function shuffle(a) {
    var t, j, i=a.length, rand=Math.random;

    // For each element in the array, swap it with a random
    // element (which might be itself)
    while (i--) {
      k = rand()*(i+1)|0;
      t = a[k];
      a[k]=a[i];
      a[i]=t;
    }
    return a;
  }

A: It uses a combination of three functions (including the Array shuffle prototype method).
Here is the complete code:
var obj = {
    "red":"RED",
    "blue":"BLUE",
    "green":"GREEN",
    "yellow":"YELLOW",
    "purple":"PURPLE"
};

Array.prototype.shuffle = function(){
    for (var i = 0; i < this.length; i++){
        var a = this[i];
        var b = Math.floor(Math.random() * this.length);
        this[i] = this[b];
        this[b] = a;
    }
}

obj = shuffleProperties(obj); // run shuffle

function shuffleProperties(obj) {
    var new_obj = {};
    var keys = getKeys(obj);
    keys.shuffle();
    for (var key in keys){
        if (key == "shuffle") continue; // skip our prototype method
        new_obj[keys[key]] = obj[keys[key]];
    }
    return new_obj;
}

function getKeys(obj){
    var arr = new Array();
    for (var key in obj)
        arr.push(key);
    return arr;
}

for(key in obj){
   alert(key);
}

Check all post,
Best Regards.


text:
Q: popup box in bootstrap not working properly I have a layout where on a click of a button a box should appear and on click of the same link the box should disappear
My complete code is here at JS Fiddle
The problem is that after opening the box on a click of a link, i change the content inside it by clicking on login/register, after that i am not able to close the box by clicking on the Main Link again, can anyone tell how it can be done
HTML CODE
Main Link

                <form>
                    Login form
                </form>
                Register

                <form>
                    Register form
                </form>

                Login

CSS
#signupbtn
{
  display:none;
}

SCRIPT
$(document).ready(function(){
        $("#register").click(function(e){
            e.preventDefault();
            $('#loginbtn').hide();
            $('#signupbtn').show();
            return false;
        });
    });

    $(document).ready(function(){
        $("#login").click(function(e){
            e.preventDefault();
            $('#loginbtn').show();
            $('#signupbtn').hide();
            return false;
        });
    });

A: One way should be with the use of hidden class instead.
JsFiddle: https://jsfiddle.net/p1a0v6kj/
HTML:
Login

                <form>
                    Login form
                </form>
                Register

                <form>
                    Register form
                </form>

                Login

Js:
$(document).ready(function(){
        $("#register").click(function(e){
            e.preventDefault();
            $('#loginbtn').addClass('hidden');
            $('#signupbtn').removeClass('hidden');
            return false;
        });
    });

    $(document).ready(function(){
        $("#login").click(function(e){
            e.preventDefault();
            $('#loginbtn').removeClass('hidden');
            $('#signupbtn').addClass('hidden');
            return false;
        });
    });


text:
Q: How do I restrict access to a broadcast message in NodeJS? I understand routing (I think), but what's to stop User A from looking at User B's client-side  source to discover the socket.io URL specific to each user and then build their own script to start listening for broadcast messages on that particular channel?

A: You would need to use something to determine who the client is. Once you do that, you could for example use the rooms feature, and only broadcast to the specific room where you put all your authorized users.
To identify the client, you could pass in cookies from the browser in a socket.io request, and compare that to any session data you have stored in Express/Connect/Whatever.


text:
Q: KnockoutMVC Foreach Lambda filter (or any filter) I have been able to create a display that loops a list of pages.  This will display all pages in the DB table like the following.
@using (var page = ko.Foreach(m => m.PageList))
{
    @page.Html.TextBox(p => p.PageErrorMessage)
    @page.Html.TextBox(p => p.PageSuccessMessage)
    @page.Html.TextBox(p => p.Title)
    @page.Html.TextBox(p => p.Content)
}

I am would like to be able to filter what displays by a lambda expression on the Foreach.  Currently that returns the type IEnumerable, even with a ToList() at the end the following does not work.
//Note: I have tried .Where pl.Title == "string" with the same results
@using (var page = ko.Foreach(m => m.PageList.Where(pl => pl.Title.Contains("Page01")))
{
    @page.Html.TextBox(p => p.PageErrorMessage)
    @page.Html.TextBox(p => p.PageSuccessMessage)
    @page.Html.TextBox(p => p.Title)
    @page.Html.TextBox(p => p.Content)
}

I can get the results that I want, but it seems cumbersome to do this.  If I add a visible check to each field with the same check I only see the fields I want.
//Note: p.Title.Contains("string") does not work for me in the Visible here
@using (var page = ko.Foreach(m => m.PageList))
{
    @page.Html.TextBox(p => p.PageErrorMessage).Visible(p => p.Title == "Page01!")
    @page.Html.TextBox(p => p.PageSuccessMessage).Visible(p => p.Title == "Page01!")
    @page.Html.TextBox(p => p.Title).Visible(p => p.Title == "Page01!")
    @page.Html.TextBox(p => p.Content).Visible(p => p.Title == "Page01!")
}

Is there a better way to work with foreach to filter down the list or is this currently designed to always return the full set?

A: You cannot use C# code in razor to modify your viewmodel. To bind against something it needs a representation in the viewmodel. If you want to filter the full list, a computed property on the viewmodel should do the trick.
[Computed]
public List<Page> FilteredList
{
  get { return PageList.Where(pl => pl.Title.Contains("Page01")); }
}


text:
Q: Using PyWinAuto to reconnect to the main window? I reach open browser, click in the button on the screen and click in the button of the pop up window without problems. The only problem is, when I close pop up window clicking the button "Close Tor Browser", I can't reconnect with my previous window (the main and first window). Any tips??
from pywinauto.application import Application
import time

for i in range(0,2):
    try:
        for i in range(0,1):
            try:
                app=Application(backend='uia').start('\...\firefox.exe')
                app=Application(backend='uia').connect(title='Connect to Tor — Tor Browser',timeout=40)
                time.sleep(5)
                app.window(best_match='Dialog', top_level_only=True).child_window(best_match='Ver todos los servicios').click()

            except Exception:
                time.sleep(1)
                app2=Application(backend='uia').connect(title='Close Tor Browser',timeout=40)
                app2.window(best_match='Dialog', top_level_only=True).child_window(best_match='Cancel').click()

        time.sleep(5)
        app=Application(backend='uia').connect(title='Connect to Tor — Tor Browser',timeout=40)
        top_level_only=True).child_window(best_match='Ver todos los servicios').click()
        time.sleep(10)
        app.kill()
        time.sleep(1)

    except Exception:
        pass

[enter image description here]
[1]: https://i.stack.imgur.com/4v29M.png


text:
Q: OIDC client redirect to specific login provider at IdentityServer4 So I have a basic Setup. IdentityServer with 3 login options. Username/Password, Google login and an External Login provider. As it is right now when I run the following code:
var config = {
    authority: "https://example.com",
    client_id: "js",
    redirect_uri: "https://example.com/callback.html",
    response_type: "code",
    scope: "openid profile api1",
    post_logout_redirect_uri: "https://example.com/index.html",
};
var mgr = new Oidc.UserManager(config);

function login() {
    mgr.signinRedirect();
}

I get redirected to the following page.

When I press login I get redirected to my login page:

This is all fine. But now I have a new requirement for the login process. They want a specific login button on the javascript client to start login with google and a specific button to login with OpenIDConnect login provider from the javascript Client.
So I could have some subpage eg. /GoogleIntegrations.html or whatever. And there I would like to have a button "Try google login", that should start loginflow with google, by redirect to the IdentityServer and then make the google redirect instantly afterwards.
Has anyone had similar usecase?
Edit1:
Account controller can be found here:
https://github.com/TopSwagCode/Dotnet.IdentityServer/blob/master/src/IdentityServerAspNetIdentity/Controllers/Account/AccountController.cs
Edit2:
I have tried the solution by abdusco, but I am stuck on the identity server. I don't get redirected back to my Javascript client.
eg: If I have button with:
https://localhost:5001/External/Challenge?scheme=OpenIdConnect
I do get redirected to the external login provider. But when I login I am stuck on the Identity Server page.
I have also tried to login with the following link:
https://localhost:5001/External/Challenge?returnurl=/connect/authorize/callback?client_id=js&redirect_uri=https%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=code&scope=openid%20profile%20api1&scheme=OpenIdConnect
GIF of how it looks with normal flow:

Edit3:
using the following code from comment:
var returnUrl = location.href;
var url = "https://localhost:5001/External/Challenge?returnurl=" + returnUrl + "&scheme=OpenIdConnect"
location.href = url;

throws exception. See code screenshot below

Edit4:
I was looking into another aproach, but still not entirely working as I want. On the login page on Identity, you can bypass username/password login. If I comment out that code and just redirect to my OpenIdConnect login. I get login and redirect back to client as I want, but this will then not allow me to use google or username password login.
Code looks like the following:
    ///
    /// Entry point into the login workflow
    ///
    [HttpGet]
    public async Task<IActionResult> Login(string returnUrl)
    {
        // build a model so we know what to show on the login page
        var vm = await BuildLoginViewModelAsync(returnUrl);

        var context = HttpContext;

        //if (vm.IsExternalLoginOnly)
        //{
            // we only have one option for logging in and it's an external provider
            return RedirectToAction("Challenge", "External",
                new { scheme = "OpenIdConnect", provider = vm.ExternalLoginScheme, returnUrl });
        //}

        return View(vm);
    }

A: I found a solution myself.
So first off I created a new Callback URL for the OpenIDConnect Users. Eg. /admincallback.html
Then I can use the OIDC Usermanger javascript like so:
mgr.signinRedirect({ redirect_uri: 'https://localhost:5003/admincallback.html' });

While normal login button just use the default /callback.html
This will let me check on the Identity backend what callback is being used and based on that what login page to show. Default or instant challenge external providers. Like so:
    ///
    /// Entry point into the login workflow
    ///
    [HttpGet]
    public async Task<IActionResult> Login(string returnUrl)
    {
        // build a model so we know what to show on the login page
        var vm = await BuildLoginViewModelAsync(returnUrl);

        if (returnUrl.Contains("admincallback"))
        {
            // we only have one option for logging in and it's an external provider
            return RedirectToAction("Challenge", "External",
                new { scheme = "OpenIdConnect", provider = vm.ExternalLoginScheme, returnUrl });
        }

        return View(vm);
    }

You could create your callback url's to contain provider name like: /callback/google, /callback/oidc, /callback/azure, etc. This would let you dynamically decide which button was pressed. Instead of having a bunch of if statements for each supported provider.
This approach requires you to remember to add these new callback url's to the database. All code can be found here:
https://github.com/TopSwagCode/Dotnet.IdentityServer
This is just a project where I share all IdentityServer related stuff I learn.

A: As you already have ExternalController.Challenge method in your app,
create a URL that specifies the scheme, and you won't have to change anything.
///
/// initiate roundtrip to external authentication provider
///
[HttpGet]
public IActionResult Challenge(string scheme, string returnUrl)
{
    if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";

    // validate returnUrl - either it is a valid OIDC URL or back to a local page
    if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
    {
        // user might have clicked on a malicious link - should be logged
        throw new Exception("invalid return URL");
    }

    // start challenge and roundtrip the return URL and scheme
    var props = new AuthenticationProperties
    {
        RedirectUri = Url.Action(nameof(Callback)),
        Items =
        {
            { "returnUrl", returnUrl },
            { "scheme", scheme },
        }
    };

    return Challenge(props, scheme);

}

login with google

Create an endpoint in your app, and issue a challenge for Google auth.
public class AccountController : ControllerBase
{
    [AllowAnonymous]
    [HttpGet("/login-google")]
    public ActionResult LoginGoogle()
    {
        return Challenge(
            new AuthenticationProperties
            {
                RedirectUri = Url.Action("ExternalCallback"),
                // RedirectUri = Url.Page("LoginCallback"),
            }, GoogleDefaults.AuthenticationScheme
        );
    }
}

Add a button, when clicked, redirect the user to this endpoint.
User will be forced to sign in to his Google account directly without showing the login view of your app.
<button onclick="location.href='/login-google'">login with google</button>

login with google

Note that this the most basic setup. You must have an AccountController or Login razor page that contains the logic for what to do when the user returns from Google, so try setting the redirect URL to that action.


text:
Q: Uniform consistency of a sum of functions with random weights? Suppose that for $k = 1,2,...$ we have $f_k(\theta)$ a known function of the $p \times 1$ vector $\theta$, and $w_k$ a random variable with $E[w_k] = 1$.
Assume that for  $\theta \in \Theta$ where $\Theta$ is a compact set, we have
$$n^{-1}\sum^n_{k=1} w_k f_k(\theta) - n^{-1}\sum^n_{k=1}f_k(\theta)   \xrightarrow{p}\ 0 $$

Question: Under which conditions do we also have that
$$ \sup_{\theta \in \Theta}  \left| n^{-1}\sum^n_{k=1} w_k f_k(\theta) - n^{-1}\sum^n_{k=1}f_k(\theta)   \right| \xrightarrow{p}\ 0 $$

that is, that the convergence in probability is uniform in $\theta$ over the compact $\Theta$?
The assumption of uniform convergence comes up often, especially for the theory of M-estimators, but I don't know how to prove it.

A: More generally, consider function $G_n(\theta)$. Assume the following:

(A1) $\Theta$ is compact
(A2) $G_n(\theta) \xrightarrow{p}\ 0,  \forall \theta \in \Theta $
(A3) $G_n(\theta)$ is stochastically equicontinuous
Theorem. Under conditions A1-A3, we have
$$  \sup_{\theta \in \Theta} \left| G_n(\theta) \right| \xrightarrow{p}\ 0 $$

Proof. From the stochastic equicontinuity assumption, for any set $\epsilon > 0$, there exists a $\delta > 0$ such that
$$\limsup_{N \rightarrow \infty}
 P\left( \sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)} | G_n(\theta) - G_n(\theta') | > \epsilon\right)
= 0$$
From $A1$, a finite set $\{\theta_k\}$ exists such that the balls $B(\theta_k, \delta$) cover $\Theta$.
Now, we have
$$ \begin{align}P( \sup_{\theta \in \Theta} | G_n(\theta)  | > 2\epsilon)
&= P( \max_k \sup_{\theta \in B(\theta_k, \delta)} |G_n(\theta) - G_n(\theta_k) + G_n(\theta_k)| > 2\epsilon) \\
&\le
 P( \max_k \sup_{\theta \in B(\theta_k, \delta)} |G_n(\theta) - G_n(\theta_k)| + |G_n(\theta_k)| > 2\epsilon) \\
&\le
 P( \max_k \sup_{\theta \in B(\theta_k, \delta)} |G_n(\theta) - G_n(\theta_k)| > \epsilon) +  P( \max_k |G_n(\theta_k)| > \epsilon)
 \\
&\le
P(  \sup_{\theta \in \Theta}\sup_{\theta' \in B(\theta,\delta)} | G_n(\theta) - G_n(\theta') |  > \epsilon) +  P( \max_k |G_n(\theta_k)| > \epsilon)
\end{align}$$
The first term on the last line converges to zero by stochastic equicontinuity. Because of $A2$ and the fact that the set $k$ is finite, the second term also converges to zero. Because $\epsilon$ is arbitrary, the theorem is proven.
In the original problem, we may take

$$G_n(\theta) =  n^{-1}\sum^n_{k=1} (w_k - 1) f_k(\theta)$$

Conditions $A1$ and $A2$ are already satisfied by assumptions. However, we would have to prove $A3$. In this case, we need that for any $\epsilon > 0$ we have a $\delta >0 $ such that

$$\limsup_{N \rightarrow \infty}
 P\left( \sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)}
 \left| n^{-1}\sum^n_{k=1} (w_k - 1) [f_k(\theta) - f_k(\theta')] \right| > \epsilon\right)
< \epsilon$$

If we suppose

(A4) $f_k(\theta)$ are pointwise equicontinuous in $\theta \in \Theta$
(A5) $ n^{-1}\sum^n_{k=1} |w_k| = Op(1)$
Theorem. Under $A1$, $A4$ and $A5$, $G_n(\theta)$ is stochastic equicontinuous

Proof. We can write,

$$\begin{align} \sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)}
 \left| \sum^n_{k=1} \frac{w_k - 1}{n} [f_k(\theta) - f_k(\theta')] \right|
&\le
 \sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)}
\sum^n_{k=1} \frac{|w_k| + 1}{n} \left|f_k(\theta) - f_k(\theta') \right|
\\
&\le
\sum^n_{k=1} \frac{|w_k| + 1}{n}
\left(\sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)} \max_h
\left|f_h(\theta) - f_h(\theta') \right| \right)
\end{align} $$

From $A5$, there exists a $M > 0$ and $N$ such that for $n > N$,
$$P\left( \sum^n_{k=1} \frac{|w_k| + 1}{n}  > M \right) < \epsilon$$
From $A1$ and $A4$, the $f_k(\theta)$ are uniformly equicontinuous. Hence, there exists a $\delta > 0$ such that
$$ \sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)} \max_h
M \left|f_h(\theta) - f_h(\theta')\right| < \epsilon$$
Hence, for $n > N$,

$$\begin{align}
P\left(\sup_{\theta \in \Theta} \sup_{\theta' \in B(\theta,\delta)}
 \left| \sum^n_{k=1} \frac{w_k - 1}{n} [f_k(\theta) - f_k(\theta')] \right|
> \epsilon \right)
\le P\left( \sum^n_{k=1} \frac{|w_k| + 1}{n}  > M \right) < \epsilon
\end{align}$$

which proves the result.


text:
Q: What is the difference between assembly on mac and assembly on linux? I've been trying to get familiar with assembly on mac, and from what I can tell, the documentation is really sparse, and most books on the subject are for windows or linux. I thought I would be able to translate from linux to mac pretty easily, however this (linux)
.file   "simple.c"
.text
.globl simple
.type   simple, @function
simple:
      pushl   %ebp
      movl    %esp, %ebp
      movl    8(%ebp), %edx
      movl    12(%ebp), %eax
      addl    (%edx), %eax
      movl    %eax, (%edx)
      popl    %ebp
      ret
.size   simple, .-simple
.ident  "GCC: (Ubuntu 4.3.2-1ubuntu11) 4.3.2"
.section        .note.GNU-stack,"",@progbits

seems pretty different from this (mac)
.section    __TEXT,__text,regular,pure_instructions
.globl  _simple
.align  4, 0x90
_simple:                                ## @simple
    .cfi_startproc
## BB#0:
pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    addl    (%rdi), %esi
    movl    %esi, (%rdi)
    movl    %esi, %eax
    popq    %rbp
    ret
    .cfi_endproc

.subsections_via_symbols

The "normal" (for lack of a better word) instructions and registers such as pushq %rbp don't worry me. But the "weird" ones like .cfi_startproc and Ltmp2: which are smack dab in the middle of the machine instructions don't make any sense.
I have no idea where to go to find out what these are and what they mean. I'm about to pull my hair out as I've been trying to find a good resource for beginners for months. Any suggestions?

A: To begin with, you're comparing 32-bit x86 assembly with 64-bit x86-64. While the OS X Mach-O ABI supports 32-bit IA32, I suspect you want the x86-64 SysV ABI. (Thankfully, the x86-64.org site seems to be up again). The Mach-O x86-64 model is essentially a variant of the ELF / SysV ABI, so the differences are relatively minor for user-space code, even with different assemblers.
The .cfi directives are DWARF debugging directives that you don't strictly need for assembly - they are used for call frame information, etc. Here are some minimal examples:
ELF x64-64 assembler:
    .text
    .p2align 4

    .globl  my_function
    .type   my_function,@function

my_function:
    ...
.L__some_address:

    .size    my_function,[.-my_function]

Mach-O x86-64 assembler:
    .text
    .p2align 4

    .globl  _my_function

_my_function:
    ...
L__some_address:

Short of writing an asm tutorial, the main differences between the assemblers are: leading underscores for Mach-O functions names, .L vs L for labels (destinations). The assembler with OS X understands the '.p2align' directive. .align 4, 0x90 essentially does the same thing.
Not all the directives in compiler-generated code are essential for the assembler to generate valid object code. They are required to generate stack frame (debugging) and exception handling data. Refer to the links for more information.

A: Obviously the Linux code is 32-bit Linux code. Note that 64-bit Linux can run both 32- and 64-bit code!
The Mac code is definitely 64-bit code.
This is the main difference.
The ".cfi_xxx" lines are only information used for the Mac specific file format.


text:
Q: JQuery append method multiple parent elements append same element As the API document declared:

If an element selected this way is inserted into a single location
  elsewhere in the DOM, it will be moved into the target (not cloned).
  Important: If there is more than one target element, however, cloned
  copies of the inserted element will be created for each target except
  for the last one.

var div = $("

").addClass("divCells"),
    tdName = $("	").addClass("tdName"),
    tdAge = $("	").addClass("tdAge"),
    tdGender = $("	").addClass("tdGender"),
    tds = [tdName, tdAge, tdGender],
    tr = $("

"),
    tbody = $("#peopleList tbody");
    tds.append(div);
    tr.append(tdName).append(tdAge).append(tdTimetdGenderstamp);
    tbody.append(tr);

As above code represents, I try to include the 3 tds in to an Array, so that I could append div into all of them, but it is not working.

A: You're trying to use jQuery .append on a vanilla JavaScript Array.  .append only works on jQuery/DOM elements, not JavaScript types such as Arrays.
Your tds array contains jQuery/DOM elements, but the Array itself isn't 'appendable' in the manner you're attempting.
Using an Array, you'll have to iterate through your array, and manually append the div to each element in it.  Furthermore, since you will be appending to 3 separate elements individually (i.e. 1 per iteration, not all 3 at the same time) you'll have to manually .clone the div yourself, otherwise you'll just be appending the one div to the 1st item in the Array, and then moving the same div to the 2nd, and again to the 3rd. So...
// tds.append(div); // Change this to...
for (var i=0; i< tds.length; i++) {
   tds[i].append(div.clone())
}

OR...
You could forget about using the Array altogether, and have jQuery clone and append the div for you (as your original question implied).  Here's how...
// Remove the following lines...
// tds = [tdName, tdAge, tdGender],
// tds.append(div);

// Then, after you add the td's to your row here...
tr.append(tdName).append(tdAge).append(tdGender);

// ...have jQuery find all the td's and clone+append your div to them in one hit:
tr.find('td').append(div)


text:
Q: Implementing Nullable Types in Generic Interface So in a previous question I asked about implementing a generic interface with a public class and bingo, it works. However, one of the types I'm looking to pass in is one of the built in nullable types such as: int, Guid, String, etc.
Here's my Interface:
public interface IOurTemplate<T, U>
    where T : class
    where U : class
{
    IEnumerable<T> List();
    T Get(U id);
}

So when I implement this like so:
public class TestInterface : IOurTemplate<MyCustomClass, Int32>
{
    public IEnumerable<MyCustomClass> List()
    {
        throw new NotImplementedException();
    }

    public MyCustomClass Get(Int32 testID)
    {
        throw new NotImplementedException();
    }
}

I receive the error message: The type 'int' must be a reference type in order to use it as parameter 'U' in the generic type or method 'TestApp.IOurTemplate'
I've tried to infer the type Int32?, but same error. Any ideas?

A: Nullable types don't satisfy class or struct constraints:

C# Language Specification v3.0 (Section §10.1.5: Type parameter constraints):
The reference type constraint specifies that a type argument used for the type parameter must be a reference type. All class types, interface types, delegate types, array types, and type parameters known to be a reference type (as defined below) satisfy this constraint.
  The value type constraint specifies that a type argument used for the type parameter must be a non-nullable value type.
All non-nullable struct types, enum types, and type parameters having the value type constraint satisfy this constraint. Note that although classified as a value type, a nullable type (§4.1.10) does not satisfy the value type constraint. A type parameter having the value type constraint cannot also have the constructor-constraint.

A: I wouldn't really do this but it's probably the only way to get it to work.
public class MyWrapperClass<T> where T : struct
{
    public Nullable<T> Item { get; set; }
}

public class MyClass<T> where T : class
{

}

A: Any reason why you need to restrict type U to class?
public interface IOurTemplate<T, U>
    where T : class
{
    IEnumerable<T> List();
    T Get(U id);
}

public class TestInterface : IOurTemplate<MyCustomClass, Int32?>
{
    public IEnumerable<MyCustomClass> List()
    {
        throw new NotImplementedException();
    }

    public MyCustomClass Get(Int32? testID)
    {
        throw new NotImplementedException();
    }
}

FYI: int? is the C# shorthand for Nullable<int>.


text:
Q: Counting problems 1) A businessman has 10 suits. He needs to pack 3 of them to go on a trip. How many can he do this?
2) A multiple choice test has 8 questions, each with 3 possible answers. how many can the test be filled?
3) I order a dozen bagels. there are poppy seed, onion and sesame bagels available today. in how many different ways can I fill my order?
4) A bag contains 26 scrabble tiles, each with a different letter on it. i draw 3 tiles and arrange them on the tray in front of me. How many "words" can I form this way?
Attempt:
1) 10 choose 3
2) 8 choose 3
3)$3^{12}$
4) $5!$
Is my thinking correct?

A: *

*Your answer is correct.

*Each answer can independently be chosen in 3 ways. So the total number of ways is $3^8$.

*Your answer is incorrect. (See the comment below.)

*Three tiles could be drawn in $\binom{26}{3}$ ways, and there are $3!$ ways to permute them after drawing. So total no. of ways is $3!\binom{26}{3}$.


text:
Q: Why can't Node resolve this filename? I'm getting the following error with an app I'm building in node.
Error: Cannot find module '/Users/bryce/repos/wudu/requester'
This occurs when I try to access a module (requester/requests.js) from this file (main.js):
main.js
var r = require('./requester/requests');

r.updateDB();

I am perplexed as to why the error message cuts off the filename, and refers to the directory containing the file.
I am also perplexed because I get the same error when I try to execute the file (requester/requests.js) on its own.
Here is a simplified version of what is contained in the file, if that helps.
requester/requests.js
var $ = require('cheerio');
var request = require('request');
var q = require('q');
var dbStatus = require('./dbStatus');

function updateDB() {
    // n/a
}

module.exports = {
    updateDB: updateDB
};

The app's folder contains main.js and requester both. So I'm fairly certain my path declarations are correct. But I am fairly new to Node, so it's possible that I'm misunderstanding how modules work.
Thanks in advance!

A: The only way I can recreate your error is if the main.js is in the same directory as the requestor.js.  In order for your require call to work properly, your directory structure should look like so:
computer@computer:~/node_test$ tree
.
├── main.js
└── requester
  └── requests.js

1 directory, 2 files

If your directory looks like this:
computer@computer:~/node_test$ tree
.
└── requester
  └── main.js
  └── requests.js

or like this:
computer@computer:~/node_test$ tree
.
└── main.js
└── requests.js

then you would need to modify your main.js to look like so:
var r = require('./requests');

r.updateDB();

Hopefully this solves your problem, if not I'll be happy to take another look at it.  If you could edit your OP with the tree printout of your directory that would be helpful.
-----  Edit -----
It was asked if a file permission error could cause this same type of problem.  Here's an example of that:
@computer:~/node_test$ sudo chown root:root requester/requests.js
@computer:~/node_test$ sudo chmod 700 requester/requests.js
@computer:~/node_test$ node main.js

fs.js:338
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
             ^
Error: EACCES, permission denied './node_test/requester/requests.js'

So in that case where the file itself has a permission problem it throws a different error; however, if we make the folder only accessible to root then you'd have this going on:
@computer:~/node_test$ sudo chown root:root requester/
@computer:~/node_test$ sudo chmod 700 requester/
@computer:~/node_test$ node main.js

module.js:340
  throw err;
      ^
Error: Cannot find module './requester/requests'

So as @akaphenom correctly pointed out, you may have a permission problem with the ./requester folder.  You can view the permissions with the following:
@computer:~/node_test$ ls -l

Good luck resolving your problem.


text:
Q: Setting environment variables package.json in Windows 10 UPDATE: As it is explained in the question, this is not a duplicate because I have already tried adding the set keyword before the environment variable and that did not solve the problem.

I am in the process of learning node and typing examples from a book. The first examples deal with showing how the "http" module works and how to create a server to listen to requests. At some point the book asks to add the following line to the scripts section of the package.json file:

"server": "SERVERPORT=3002 node ./fiboserver"

When I try to run the example with npm run server I get the following error message:

'SERVERPORT' is not recognized as an internal or external command

I haven't been able to find any answer on the internet, at most I found that I could try:

"server": "set SERVERPORT=3002 node ./fiboserver"

But that doesn't help either, the only difference is that instead of the error message I get the command prompt again so apparently the server is never run.
I believe the author used a Linux machine, I am using a Windows 10 laptop.
I am really committed to learn Node and my line of work is on Windows environments. I believe that setting environment variables on package.json is important so I could really use some help in figuring this out.
Thank you.

A: Make it cross-platform by using cross-env:
"server": "cross-env SERVERPORT=3002 node ./fiboserver"

A: I've gone through the same problem and used one of the following methods.

Method 1
If I run (without using the npm wrapper script)
HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start

it works fine. As Quentin says,

Must be something to do with how npm shells out then

To fix it, I've gone to package.json and changed the "start" script to
"start": "./node_modules/.bin/react-scripts start",

Then npm start works fine.

Method 2
Use the cross-env package.
For that install it using the following command
npm i cross-env

then go to package.json and change it to
"start": "cross-env ./node_modules/.bin/react-scripts start",

And then running npm start will also work fine:

A: On Windows you have to separate the command of setting a variable from the one which runs the server with the && operator.
That being said, you have to do something like this:
"server": "set SERVERPORT=3002 && node ./fiboserver"

A: You can set bash as package.json scripts runner and it's will work in windows and linux.
Just set it once:

*

*for yarn yarn config set script-shell /bin/bash

*for npm npm config set script-shell /bin/bash
Or "C:\\Program Files\\git\\bin\\bash.exe" instead /bin/bash
It's will allow you to run npm script cross-platform:
"server": "SERVERPORT=3002 node ./fiboserver"


text:
Q: insert doesn't permanently change map? I have a member variable of this class that is set<pair<string,map<string,int> > > setLabelsWords; which is a little convoluted but bear with me. In a member function of the same class, I have the following code:
pair<map<string,int>::iterator,bool> ret;

for (auto j:setLabelsWords) {
  if (j.first == label) {
    for (auto k:words) {
      ret = j.second.insert(make_pair(k,1));
      if (ret.second == false) {
        j.second[k]++;
      }
    }
  }
}

"words" is a set of strings and "label" is a string. So basically it's supposed to insert "k" (a string) and if k is already in the map, it increments the int by 1. The problem is it works until the outermost for loop is over. If I print j.second's size right before the last bracket, it will give me a size I expect like 13, but right outside the last bracket the size goes back to 7, which is what the size of the map is initially before this code block runs. I am super confused why this is happening and any help would be much appreciated.

A: for (auto j:setLabelsWords) {

This iterates over the container by value. This is the same thing as if you did:
class Whatever { /* something in here */ };

void changeWhatever(Whatever w);

// ...

{
   Whatever w;

   changewhatever(w);
}

Whatever changewhatever does to w, whatever modifications are made, are made to a copy of w, because it gets passed by value, to the function.
In order to correctly update your container, you must iterate by reference:
for (auto &j:setLabelsWords) {

A:
for (auto j:setLabelsWords) {

This creates a copy of each element. All the operations you perform on j affect that copy, not the original element in setLabelsWords.
Normally, you would just use a reference:
for (auto&& j:setLabelsWords) {

However, due to the nature of a std::set, this won't get you far, because a std::set's elements cannot be modified freely via iterators or references to elements, because that would allow you to create a set with duplicates in it. The compiler will not allow that.
Here's a pragmatic solution: Use a std::vector instead of a std::set:
std::vector<std::pair<std::string, std::map<std::string,int>>> setLabelsWords;

You will then be able to use the reference approach explained above.

If you need std::set's uniqueness and sorting capabilities later on, you can either apply std::sort and/or std::unique on the std::vector, or create a new std::set from the std::vector's elements.


text:
Q: Unable to authenticate google drive api using python I have downloaded the client_secrets.json file and I am using this redirect_uri: http://localhost:8080/.
This is the code:
from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

This is the error:
"C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\Scripts\python.exe" "C:/Users/thisi/Downloads/Bot Tales/Python Script/venv/bot tales scripts/google drive access"
Traceback (most recent call last):
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\pydrive\auth.py", line 386, in LoadClientConfigFile
    client_type, client_info = clientsecrets.loadfile(client_config_file)
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\oauth2client\clientsecrets.py", line 165, in loadfile
    return _loadfile(filename)
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\oauth2client\clientsecrets.py", line 126, in _loadfile
    return _validate_clientsecrets(obj)
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\oauth2client\clientsecrets.py", line 99, in _validate_clientsecrets
    raise InvalidClientSecretsError(
oauth2client.clientsecrets.InvalidClientSecretsError: Missing property "client_secret" in a client type of "web".

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\bot tales scripts\google drive access", line 4, in <module>
    gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\pydrive\auth.py", line 113, in _decorated
    self.GetFlow()
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\pydrive\auth.py", line 443, in GetFlow
    self.LoadClientConfig()
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\pydrive\auth.py", line 366, in LoadClientConfig
    self.LoadClientConfigFile()
  File "C:\Users\thisi\Downloads\Bot Tales\Python Script\venv\lib\site-packages\pydrive\auth.py", line 388, in LoadClientConfigFile
    raise InvalidConfigError('Invalid client secrets file %s' % error)
pydrive.settings.InvalidConfigError: Invalid client secrets file Missing property "client_secret" in a client type of "web".

Process finished with exit code 1

Before the above error was not happening I was getting redirect_uri mismatch error in google authentication window, but now I am not getting even there.

A: Looks like you may have created the wrong type of credentials.   Try creating installed app.  rather than a web app.
#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'C:\YouTube\dev\credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('drive', 'v3', credentials=creds)

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()


text:
Q: Iterate over a java map and change values I have a map of <CheckBox, ImageButton>.
I want to be able to iterate over this map and change the image of each ImageButton. Is there any way I can do this? getValue() doesn't seem to let me use the methods associated with each ImageButton.

A: // support you define your hash map like this
HashMap<CheckBox,ImageButton> hs = new HashMap<CheckBox,ImageButton>();
// then
for(Map.Entry<CheckBox, ImageButton> e : hs.entrySet())
{
    ImageButton imgBtn = e.getValue();
    // do whatever you like to imgBtn
}

A: A HashMap?
Use HashMap.values() to get a Collection of the saved Values.
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()

A: You can iterate over the keys of a Map using keySet, and get the value associated with each individual key:
for (CheckBox cb : checkBoxes.keySet()) {
    ImageButton btn = checkBoxes.get(cb);
}

A: Taken from this answer
You have to cast the result of getValue to an ImageButton to use its functions.
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    ((ImageButton)pair.getValue()).setImageBitmap(bitmap);
}


text:
Q: Arma 2, Arma 2 OA, and Combined Ops So I have both Arma 2 and Arma 2 OA, and, on my old PC, I had them both installed and had run arma 2 once. I then launched from Arma 2 OA and had access to everything available in both games.
Now, my old PC was destroyed, and on my new PC, I have something of a unique space situation where my Windows partition only has around 15 GB available (not including space taken by the OS). So what I do is move games I've downloaded to my Ubuntu partition using Steam mover, which creates a shortcut in the common folder, then move them back when I want to play.
My question is, do I need to download both Arma 2 and Arma 2 OA having run  arma 2 once before on another PC, and if so, can Arma 2 be on another partition  and still give me access to the correct things in OA? Thanks.

A:
Do I need to download both Arma 2 and Arma 2 OA having run arma 2 once before on another PC?

You do need the games to run atleast once, not sure in what machine matters or not but it shouldn't.

Can Arma 2 be on another partition and still give me access to the correct things in OA

It should be no problem at all aslong as you link them properly with SteamMover.