text:
Q: org.bluez.Error.AuthenticationTimeout; org.bluez.Error.Failed br-connection-unknown I am trying to connect a bluetooth speaker to a near fresh install of ubuntu 22.04. I'm having several issues with this.
To try and resolve this I have moved from using the GUI to bluetoothctl.
The steps I am taking to connect to the device are as follows
power on
agent on
scan on
trust #deviceaddress
pair #deviceaddress
connect

here is the system status
bluetooth.service - Bluetooth service
     Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-08-12 20:52:25 IST; 15min ago
       Docs: man:bluetoothd(8)
   Main PID: 13854 (bluetoothd)
     Status: "Running"
      Tasks: 1 (limit: 19052)
     Memory: 836.0K
        CPU: 75ms
     CGroup: /system.slice/bluetooth.service
             `-13854 /usr/lib/bluetooth/bluetoothd

when I run pair for device address bluetoothctl registers the device as connected, but the bluetooth device itself doesnt recognise a connection (its supposed to beep). Shortly afterwards I get the authentication timeout error and the device does not get paired.
I don't know why this is, sometimes the connection works when I use the GUI, however this is inconsistent and requires multiple attempts with an indefinite length of time passing after booting into ubuntu before working.
Here is the terminal output with the bluetoothctl info for the device
[Majority Snowdon II]# info 41:42:00:CA:56:64
Device 41:42:00:CA:56:64 (public)
    Name: Majority Snowdon II
    Alias: Majority Snowdon II
    Class: 0x00240418
    Icon: audio-headphones
    Paired: no
    Trusted: yes
    Blocked: no
    Connected: yes
    LegacyPairing: yes
Failed to pair: org.bluez.Error.AuthenticationTimeout
[CHG] Device 41:42:00:CA:56:64 Connected: no

I have followed the advice given here but this has not been successful. This is the only mention of this error I can see online.
I have uninstalled, purged, reinstalled bluez. I have tried using blueman which asks for a pin for pairing, using the pin from the manual here the same error is returned. A final error is shown by blueman discussed below.
Any help on this is much appreciated. As an additional  the connect command gives the following error in which I can find very little information about.
[bluetooth]# connect 41:42:00:CA:56:64
Attempting to connect to 41:42:00:CA:56:64
[CHG] Device 41:42:00:CA:56:64 Connected: yes
[CHG] Device 41:42:00:CA:56:64 UUIDs: 0000110b-0000-1000-8000-00805f9b34fb
[CHG] Device 41:42:00:CA:56:64 UUIDs: 0000110c-0000-1000-8000-00805f9b34fb
[CHG] Device 41:42:00:CA:56:64 UUIDs: 0000110e-0000-1000-8000-00805f9b34fb
[CHG] Device 41:42:00:CA:56:64 ServicesResolved: yes
Failed to connect: org.bluez.Error.Failed br-connection-unknown
[CHG] Device 41:42:00:CA:56:64 ServicesResolved: no
[CHG] Device 41:42:00:CA:56:64 Connected: no

I have used hciconfig to enable simple pairing mode, and now I am getting a simple authentication failed error. I've had a look for solutions but cannot find any that are applicable to this.
Today after booting up the computer I was able to pair the speaker, I have no idea why. However I am now getting the error connection profile unavailable. Will keep digging.
I'm back to getting authentication timeout error :(
to try and get any audio coming from ubuntu, I ran an audio jack all the way across the room to the computer, only to find that the only output that now exists is 'dummy output' this is a known issue with intel cpu's but I am running AMD... There is nothing I can find online about this. I really don't know where to go from here. I just want audio from a fresh linux install... Over the last 4 days I've spent more time trying to get this working than I've spent at my job. I'd appreciate any help!
I've been able to get the hdmi ports to be picked up, but the audio jack is nowhere to be found :(
I gave up and did a fresh install again. Through a series of using backups after each change, experimenting with order of installations of my most used softwares... reverting when it failed or dpkg locked up during an update etc... I have got it working.
I couldnt find a direct fix for the bluetooth errors I had, but I spent less time doing the above than I did trying to fix the specific bluetooth issue.

A: I had same problem. I followed next steps to connect my device:

-scan on
-remove XX:XX:XX:XX:XX:XX, if it had already been paired
-trust XX:XX:XX:XX:XX:XX
-pair XX:XX:XX:XX:XX:XX
-connect XX:XX:XX:XX:XX:XX

A: For anyone else having this problem, I was able to find the solution here! for whatever reason when you uninstall or reinstall pulseaudio or alsa it seems to delete the a2dp module.
a2dp-sink profile connect failed


text:
Q: Using Euclid's algorithm to find Multiplicative Inverse 71 mod 53 I begin by writing out the recursion until a mod b  == 0
53 -> 71-> 53-> 18-> 17 ->1 -> 0
to get in the form $sa+tn$
starting with $1 = 18-17$ I then substitute $17 = 53-(18\cdot2)$
this gives me $18\cdot3-53$
I then substitute $18 = (71-53)$ which gives me
$$71\cdot3 - 53\cdot4$$
this has me stuck because I know I need to substitute $53$ in a form of $x\cdot53-y\cdot71$ but I am unsure how to find this form without a calculator

A: You have done almost all the work yourself. You just need to interpret what you already have.
Your arrangement in the second last line gives you $71\cdot3-53\cdot4=1$ which on rearrangement is $71\cdot3=53\cdot4 + 1$ which exactly implies by modular property that $3\cdot71=1 \pmod{53}$ i.e. in modulo group $\mathbb{Z}_{53}$, $\overline{3} \cdot \overline{71} = \overline{1}$. So your inverse is $\overline{3}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does MSBuild ignore my BeforePublish target? I must be missing something obvious here, but I have this at the end of my ASP.NET MVC web project's .csproj file:
    [...]
    <Target Name="BeforePublish">
        <Error Condition="'foo'=='foo'" Text="test publish error" />
    </Target>
</Project>

As far as I can tell, that should always cause the publish to fail with an error. Yet, if I load the project, right-click on it, and click "Publish", the thing publishes without a hitch. What am I missing?

A: Not sure if it would work in VS 2010 as I've only tested this in VS 2012, but I've found that putting the target in the (ProjectDir)/Properties/PublishProfiles/(ProfileName).pubxml file as an "AfterBuild" target works. As in, it doesn't fire when you build the project, but does fire when you publish the project.
So instead of putting
<Target Name="BeforePublish">
    <Error Condition="'foo'=='foo'" Text="test publish error" />
</Target>

in your .csproj file, try putting
<Target Name="AfterBuild">
    <Error Condition="'foo'=='foo'" Text="test publish error" />
</Target>

in your .pubxml file instead, and it should fire just before publishing.

A: The answer I finally came up with which works well for Visual Studio 2010 and Visual Studio 2012; put this just before the end of your web application's .csproj file:
<Project...
    [...]
    <!-- The following makes sure we can't accidentally publish a non-Release configuration from within Visual Studio -->
    <Target Name="PreventNonReleasePublish2010" BeforeTargets="PipelinePreDeployCopyAllFilesToOneFolder" Condition="'$(BuildingInsideVisualStudio)'=='true' AND '$(VisualStudioVersion)'=='10.0'">
        <Error Condition="'$(Configuration)'!='Release'" Text="When publishing from Visual Studio 2010, you must publish the Release configuration!" />
    </Target>
    <Target Name="PreventNonReleasePublish2012" BeforeTargets="MSDeployPublish" Condition="'$(BuildingInsideVisualStudio)'=='true' AND '$(VisualStudioVersion)'=='11.0'">
        <Error Condition="'$(Configuration)'!='Release'" Text="When publishing from Visual Studio 2012, you must publish the Release configuration!" />
    </Target>
</Project>

Read on to see my thinking behind this answer, but basically it revolves around the fact that Visual Studio 2010 defines the PipelinePreDeployCopyAllFilesToOneFolder Target to hook on to, and Visual Studio 2012 defines the more "standard" MSDeployPublish Target to hook on to.
The above code only allows deploy publishing when in a Release configuration from within Visual Studio, but it could easily be modified to prevent all deploy publishing from within Visual Studio.
AFAIR, "Publish" from Visual Studio 2010 context menu invokes webdeploy\msdeploy tool. I played with it a bit, but I didn't liked at all. If you still want to use this functionality and insert your target somewhere - you need to know the exact target and its dependency  property.
Check
c:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets
You will find two tasks - MSDeploy and VSMSDeploy. The latter one sounds right for me. The first one is not used in this file at all. But VSMSDeploy used in three different targets,
PackageUsingManifest, TestDeployPackageToLocal and MSDeployPublish. Again the latter one sounds good ;)
<Target Name="MSDeployPublish" DependsOnTargets="$(MSDeployPublishDependsOn)">

So you just need to override one property. Put this before your target and "YourTargetName" will be called right before MSDeployPublish.
<PropertyGroup>
    <MSDeployPublishDependsOn Condition="'$(MSDeployPublishDependsOn)'!=''">
        $(MSDeployPublishDependsOn);
        YourTargetName;
    </MSDeployPublishDependsOn>
  </PropertyGroup>

If you already switched to MSBuild 4.0, there is an easier way to hook your target. You just need to specify the BeforeTarget attribute. In our case it will be like this:
  <Target Name="MyTarget" BeforeTargets="MSDeployPublish">
        <Error Condition="'foo'=='foo'" Text="test publish error" />
  </Target>

I hope this helps. Ask if you have more questions.
PS: I didn't checked all that, because I don't have any MSDeploy-ready environments ;)
NB: I remember that I was discouraged from using MSDeploy for our own products because it was pretty counter-intuitive to properly configuring it for a continuous integration (CI) system. Maybe I wasn't very good at that, and your solution will work properly. But proceed with MSDeploy carefully.

A: In my project files  and  are commented out by default, and I accidentally added a new  inside the comments, and thus it wasn't called. Silly mistake.
After that I got the BeforePublish target to work in Visual Studio 2010.
<Target Name="BeforePublish">
 //insert awesome here
 </Target>

note: you must provide your own awesome :)


text:
Q: Does there exist a continuous function from [0,1] to R that has uncountably many local maxima? Does there exist a continuous function from $[0,1]$ to $R$ that has uncountably many strict local maxima?

A: If you want a local maxima that is a weak inequality, i.e. $f(x_0)\geq f(x)$ for all $x$ near $x_0$, then sure, take any constant function. If you want strict inequality, i.e. $f(x_0)>f(x)$ for all $x$ near $x_0$, then no, it is impossible. This relies on the fact that the real numbers have a countable basis.

A: A strict local maximum has a punctured neighborhood in which the values are less that that value. Every neighborhood has a rational number, so each strict local maximum is associated with a rational number. The rationals are countable, thus the strict local maxima are as well.

My previous argument is not rigorous and it does have some problems. Here is a more rigorous one.
For each strict local maximum location $a\in[0,1]$ there is a $\delta>0$ such that $0<|x-a|<\delta\implies f(x)<f(a)$. Let $\delta_a$ be the least upper bound (supremum) of such $\delta$'s for the given $a$. Then $0<\delta_a\le 1$.
If $a\ne b$ are both strict maxima, then $|a-b|$, the distance between $a$ and $b$, may be less than $\delta_a$ if $f(b)<f(a)$, but then $|a-b|$ must be at least $\delta_b$. So $|a-b|\ge\min(\delta_a,\delta_b)$. The $\delta$'s are a measure of "spread" of the strict local maxima.
So for any given $n\in\Bbb Z^+$, the number of $a$ such that $\delta_a\ge\frac 1n$ is at most $n+1$.
We can now count the strict local maxima: first list all $a$ such that $\delta_a\ge \frac 11$, then those such that $\delta_a\ge\frac 12$, and so on. Each stage gives us finitely many strict local maxima, there are countably many stages, and the union gives us all strict local maxima. Therefore there are at most countably many strict local maxima.

A: For any local maximum $x$, there are rational numbers $r<x<s$ such that $f(a)<f(x)>f(b)$ for all $r<a<x<b<s$. If $y$ is some other local maximum satisfying this condition for the same rational numbers $r,s$, then assuming WLOG that $x<y$, the condition on $x$ implies that $f(x)>f(y)$ and the condition on $y$ implies $f(x)<f(y)$, a contradiction. Thus to any pair $(r,s)\in\Bbb Q^2$ there is at most one local maximum associated with it.
This implies that there is a surjection from a subset of $\Bbb Q^2$ to the set of local maxima, so there are countably many strict local maxima. As pointed out in the other answers, it is not necessary to assume $f$ is continuous.

This proof even extends to weak local maxima, although the theorem statement needs to be tweaked since a constant function would be a trivial counterexample. Given $f:\Bbb R\to\Bbb R$, let $M$ be the set of non-strict local maxima. Then $f(M)$ is countable. To prove it, let $x\in M_{r,s}$ if $x\in(r,s)$ and $f(a)\le f(x)$ for all $a\in(r,s)$. Then if $x,y\in M_{r,s}$ then $f(x)\le f(y)$ and $f(y)\le f(x)$, so $f(M_{r,s})$ is a subsingleton. Since $M=\bigcup_{r,s\in\Bbb Q}M_{r,s}$, it follows that $f(M)=\bigcup_{r,s\in\Bbb Q}f(M_{r,s})$ is countable.


text:
Q: Find a generating polynomial. We have a cyclic code $C$ of length $n$ on a finite field $\mathbb{F}_q$ and $g$ is the generating polynomial of $C$. We define another code $\bar{C}=\{c\in C\mid\sum\limits_{i=0}^{n-1} c_i=0 \}$. We identify a word $c$ with his polynomial $c(x)=c_0+...+c_{n-1}x^{n-1}$.
We want to find a generating polynomial for $\bar{C}$ using $g$.
First I prove that $\bar{C}$ is a cyclic code. Let $(c_0,...,c_{n-1})\in \bar{C}$. Using the fact that $C$ is cyclic we have $(c_{n-1},c_0,...,c_{n-2})\in C$ and the sum is $0$ because we keep the same coefficient (just the order has changed). So $(c_{n-1},c_0,...,c_{n-2})\in \bar{C}$.
By the identification of $c$ to $c(x)$ we notice that if $c\in \bar{C}$ then $c(1)=0$ and $g$ must divide $c$ by definition of $g$. Which means that $(x-1)$ and $g$ divide $c$.
So if we have $\gcd{(x-1,g)}=1$ we take $(x-1)g$ as the generating polynomial of $\bar{C}$. But for the other case I meet difficulties.
Thanks in advance !

A: All linear binary codes $C$ have the property that either all the codewords have even Hamming weight, or half the codewords have even Hamming weight while half have odd Hamming weight. In the latter case, the codewords of even Hamming weight are a linear subcode of $C$. Note that the codewords of even Hamming weight have the property that
$\sum_{i=0}^{n-1} c_i = 0$.
If $C$ is a linear binary cyclic code of length $n$ ($n$ odd) with generator polynomial $g(x)$ and parity check polynomial $h(x)$, then
$g(x)h(x) = x^n-1$ and since $(x-1) \vert (x^n-1)$, $(x-1)$ is a divisor
of either $g(x)$ or $h(x)$ but not both. Note that since all codeword
polynomials are divisible by $g(x)$, if all the codewords of $C$ have
even Hamming weight, then it must be that $g(x)$, which is a codeword
polynomial, has even weight. Hence, $g(1) = \sum_i g_i = 0$ and
$x-1$ is a divisor of $g(x)$. If $C$ has codewords of odd Hamming weight,
then $g(1)=0$ would imply that $c(1)=0$ for all codewords, and so it must be that $g(1)=1$ and so $x-1$ is a divisor of $h(x)$.
So, if all the codewords of $C$ have even Hamming weight, then
$C^\prime = C$ and is a cyclic code with generator polynomial $g(x)$.
If $C$ has codewords of odd Hamming weight, then $C^\prime$ is the
subcode of codewords of even Hamming weight. Each $c(x)$ is divisible by $g(x)$ (which does not have $x-1$ as a factor), but $c(1)=0$ meaning that
$c(x)$ is also divisible by $x-1$. Hence, each $c(x)$ is divisible by
$(x-1)g(x)$, not $g(x)/(x-1)$ as the OP insists is correct. Let's
check dimensions. If $C$ is a $[n,k]$ code, then $\deg g(x) = n-k$.
$C^\prime$ is a $[n,k-1]$ code and its generator polynomial must have
degree $n-(k-1)=n-k+1 = \deg [(x-1)g(x)]$.


text:
Q: Cannot read property 'addRole' of undefined I setting up a addRole commands and this command works but if someone type only "!rbu" without member, bot gets error.
Maybe force a person to make the code work, they must enter the person, but how im pretty new at this

  let args = message.content.substring(PREFIX.length).split(" ");

switch(args[0]){
   case'rbu':

case'rbu':

if(!message.member.roles.find(r => r.name === "GroupI")) return message.channel.send('You cant do that')

let memberToModify = message.mentions.members.first();
var roleToAdd = message.guild.roles.find(role => role.name === "GroupII");
memberToModify.addRole(roleToAdd);

break;

    }
  }
)

I expect this to do nothing or message that member must type !rbu and user

memberToModify.addRole(roleToAdd)
               ^

TypeError: Cannot read property 'addRole' of undefined```

A: First, you've got 2 case'rbu': which is weird. Then, you need to make sure that the message actually mentions, with the message.mentions propriety, like so:
let args = message.content.substring(PREFIX.length).split(" ");

switch(args[0]){
   case'rbu':

    if(!message.member.roles.find(r => r.name === "GroupI") || !message.mentions) return
message.channel.send('You cant do that')

    let memberToModify = message.mentions.members.first();
    var roleToAdd = message.guild.roles.find(role => role.name === "GroupII");
    memberToModify.addRole(roleToAdd);

break;
}


text:
Q: Is more memory in a graphic card always better? I'm building a new PC and was looking at the graphic cards here are the 2:
http://www.canadacomputers.com/product_info.php?cPath=43_557_559&item_id=039765
http://www.canadacomputers.com/product_info.php?cPath=43_557_559&item_id=038928
The cheaper has:
1536MB (4008Mhz)
The more expensive has:
3072MB GDDR5 Memory (1008MHz)
So the second one has more memory but less processing speed?
What is the benefit of having more memory?
UPDATE: didn't mean this to be a purchase recommendation explicitly, the question is more: whether the less memory 1536MB at a higher speed is better 4008Mhz or high ram with low speed: 1008MHz

A: I don't think the memory amount will count above 1024mb. At least, today ... even 512mb is sufficient (at least I never seen anything want more memory).
When you try to decide between two cards, look for Reviews, independent tests. Numbers, scores.
That's what helps you to get the better (i.e.: faster) card.
Edit: IMO since the ASUS card got some OC, thus overscoring the other card by some % in performance, is better. Memory won't help you in games or benchmarks, since 1gb is more than enough. (Still IMHO.)

A: Only a handful of applications and games are ever likely to see a consistent difference between the two.
Between more memory and faster processing, I would choose faster processing. Actually, if there was a choice, I would choose faster memory since that is the most common bottleneck. However, the exact one depends on the app but it would take a whopping amount of textures or GPU-processing on huge data to use that much memory.
At this point, the difference is so minor I would save the $30 or invest it in a better keyboard or mouse which you are much more likely to notice a difference :)

A: It depends on the architecture, I believe.
Personally, I think these cards are close enough other features that I'd go for the one with the higher memory.
From 772Mhz to 816Mhz core clock speed there's just not a whole lot of gain, while the memory is double.
UPDATE for comment:
Because the stats are layed out differently for the different cards, it took me a bit to find the different clock speeds.
Most modern GPUs, because they are purpose built for the types of calculations in graphics applications, do not need to be nearly as high frequency (Mhz, Ghz) as desktop CPUs, which are general purpose and thus not quite so "good" at one particular thing. So, the 4008Mhz right away could not have been the GPU core speed.
The 4008Mhz (effective) rate is the memory frequency. This is a bit of a misnomer though. GDDR5 is a very high bandwidth DDR (Double-Data-Rate) memory architecture that, due to it's capability of handling two instructions per clock cycle plus a wider bus is labeled or advertised at four times it's actual core speed. I may be off here. Someone please correct me if I'm wrong.
Thus, 4008Mhz is really only a more pedestrian 1Ghz with multitasking, essentially, which isn't all that great when it comes to GDDR. The fastest GDDR currently clocks in at more /than 7Ghz effective (1.75Ghz real).
You'll find the specs on the ASUS Matrix card show this:
In the specifications tab of the product page, the Memory clock is "4008Mhz (1002Mhz GDDR5)".
The EVGA only notes the first value, which is identical at 4008Mhz and adds the label "(effective)" to clarify.
In looking for the GPU speed, look for terms like "Core clock", "GPU", "Engine clock", and so forth. These will indicate the speed at which the GPU on the cards run.
In this case, the EVGA product says "772Mhz GPU" and the ASUS "Engine Clock 816Mhz".
Standardization would be great, but so long as you're careful and know what to look for it's not too hard to find out which numbers ought to be compared.


text:
Q: iOS Send sms message with location object I've been trying to figure out how to send an SMS message that includes your location. I want it to be the location object similar to when you share your position on the iphone - not just the straight address.
Is there anyway to do this? I've looked at the reference material provided by apple however I don't see any way to add special objects to the body. It looks like you can only add text.
Any information on this would be greatly appreciated!

A: SMS is just textual content (Strings) which gets transmitted over carrier airwaves, you can not embed actual objects to the body unless you send an SMS using a format your app can recognise and parse
Stuff like links in messages and addresses and times are sent via plain text and then Apple's Messages app parses it and adds the relevant contextual options (such as hyperlinking so you can open links in Safari and dates in Calendar and Addresses in Maps etc.). There is no way of adding your own contextual formatting options to the stock Messages app


text:
Q: Sending Authentication information to a web service We are designing a system where a WPF client will call both WCF services and Java web services.
What we are wondering is how we should send the authentication information such that it is compatibile with both the Microsoft and Java web services.
All user are logged into a Windows Active Directory.
Some possibilities are Kerberos, SAML, WIF ... Can anyone make a recomendation on what we should use?

A: You should look into libraries built around JAAS and LDAP.


text:
Q: how top use GET and POST simultaneusly I have a page in php that gets from the url such as this code example
<form action="welcome.php" method="get">
//some interesting code here
</form>

The issue now is that when i do the GET depending on its value I need to do a POST,
How can I use action="get" and action="post" in the same page?, I am kind of new to PHP so I am not sure if I can use two  tags ("i dont think so but please correct me if i am wrong").
PS: I am getting to the same page "welcome.php" and posting to itself again, and depending on the value I am going to show different content.
Thank you

A: Your question is a little unclear, but if I'm understanding it correctly, you can certainly pass GET variables via the form's action:
<form action="welcome.php?these=are&get=variables" method="post">
//some interesting code here
</form>

A: You may access both through $_REQUEST if necessary. So no matter what your method type is, $_REQUEST will contain all of your submitted values. This way you don't need to determine whether it was by post, or by get that the data was submitted.

A: You will have to trap the $_GET value as a hidden var, so when the post is submitted again, your $_GET value will be available:
if (array_key_exists('myVar', $_GET)) {
    echo '<input type="hidden" name="myVar" value="' . $_GET['myVar'] .'" />
}

// Now when you resubmit the form you should have access to 'myVar'

echo $_REQUEST['myVar'];

You could also add the get value to the session super global:
if (array_key_exists('myVar', $_GET)) {
    $_SESSION['myVar'] = $_GET['myVar'];
}

// Now when you resubmit the form you should have access to 'myVar'

echo $_SESSION['myVar'];


text:
Q: Delete specific rows based on certain conditions in pandas I want to clean my data, basically I have my data -
dataframe -
d = {'User': ['Mansi kinney', 'Mansi kinney', 'Mansi kinney', 'Alley Huff', 'Alley Huff', 'Alley Huff',  Raedden Grip', 'Raedden Grip',  'S.Sarkar',
                              'S.Sarkar', 'S.Sarkar'],
                      'Work': ['', '', '', 'College', 'College', 'College', '', '', 'Business', 'Business', 'Business'],
                      'Country': ['Aus', 'Aus', 'Australia', 'US','US', 'US', 'Ban', 'Ban',
                                 'Ind', 'Ind', 'Ind'],
                      'Dept': ['Safety', 'Safety', 'Safety', '', '', '', '', '', '', '', ''],
                      'Training': ['', 'Internal', '', '', 'External', '', '', '', '', 'Internal', ''],
                      'Status': ['', '', 'Active', '', '', 'Active', '', 'Active', '', '', '']
        }
    df = pd.DataFrame(data=d)
    df

Here I want to delete the rows where the more no. Of cells are blank and the data is scattered so I want it to be in a single row and delete the unnecessary repitition of rows
My output should be-
d = {'User':['Mansi kinney','Alley Huff','Raedden Grip', 'S.Sarkar'],
'Work': ['', 'College', '', 'Business'],
'Country': ['Aus', 'US', 'Ban',  'Ind'],
'Dept': ['Safety', '', '', ''],
                      'Training':['Internal','External', '', 'Internal'],
'Status':['Active','Active','Active', 'Active']
        }
    df = pd.DataFrame(data=d)
    df

I have typed the whole thing in my smartphone so please let me know if the question is clear or not. Please help me to clean the data and get the desired output. Thanks in advance!!!

A: You can groupby 'User' and aggregate with ' '.join and remove duplicates with unique():
df = df.groupby('User').agg(lambda x: ''.join(x.unique()))
df.reset_index(inplace=True)

print(df)
#output:
           User      Work       Country    Dept  Training  Status
0    Alley Huff   College            US          External  Active
1  Mansi kinney            AusAustralia  Safety  Internal  Active
2  Raedden Grip                     Ban                    Active
3      S.Sarkar  Business           Ind          Internal

UPDATE: Here it is with your full data
import pandas as pd
df = pd.read_excel('your_data.xls')
df = df.groupby('user').agg(lambda x: ''.join(x.unique()))
df.reset_index(inplace=True)
pd.set_option('display.max_columns', None)
print(df)

#output:
                   user                                              works  \
0        Abhishek Mitra  Director & CEO | INDIAN CYBER SECURITY SOLUTIO...
1         Anandita Kaul       HR Associate - Recruitments at Pulp Strategy
2         Glam Sorvey.B    Data Science & Analytics with Python Consultant
3   Madhurima S. Sarkar  MBA in Business Analytics and Finance || The S...
4         Mansi Makhija                                    Works at Amazon
5       NanaoSana Singh  DevOps | AWS | Docker | Kubernetes | Git | Jen...
6         Neeraj Mishra                               DGM at Pulp Strategy
7       Niral Shahpatel  Scale and Strategy Lead - Global Partner Marke...
8      Sandhya Ramagiri     Technical Program Manager at Intel Corporation
9         Sarthak Ahuja         Associate Account Manager at Pulp Strategy
10         UDIT NARAYAN          Student at Narula Institute Of Technology

                             country
0        Kolkata, West Bengal, India
1          South Delhi, Delhi, India
2    Portland, Oregon, United States
3        Kolkata, West Bengal, India
4        Noida, Uttar Pradesh, India
5           Pune, Maharashtra, India
6                              India
7   Hillsboro, Oregon, United States
8    Austin, Texas Metropolitan Area
9                       Delhi, India
10       Domchanch, Jharkhand, India


text:
Q: Basic Class Inheritance I have two files:
answer.rb
class Answer
  def decision(string)
    if string == 'Richard'
      puts "Hello"
    else
      puts "I dont know you"
    end
  end
end

question.rb
require './answer'

class Question < Answer
  puts "What is your name?"
  response = gets.chomp
  puts decision("#{response}")
end

How do I access the method in class Answer from class Question given the file is not enough? If I remove the the class Answer, then everything works.

A: To make your example work you need to call your code. For instance you can amend your Question class with the following code :
#question.rb

require './answer'

class Question < Answer

  def ask
    puts "What is your name?"
    response = gets.chomp

    puts decision(response)
  end
end

Question.new.ask

The inheritance will be that your instance of question (i.e. Question.new) will be inherited from Answer => it will have both methods (in your case 'ask' and 'decision').

A: Just do
puts self.new.decision(response) # no need for string interpolation.

#decision is an instance method of Answer class, so it will be available as an instance method of the class Question. Now inside the class, self is set to the class itself, thus the bare method call like your, will throw error as no method found. Thus you have to create an instance of the class Answer or Question, and on that instance you have to call the method.
Complete code :
class Answer
  def decision(string)
    if string == 'Richard'
      puts "Hello"
    else
      puts "I dont know you"
    end
  end
end

class Question < Answer
  puts "What is your name?"
  response = gets.chomp
  puts self.new.decision(response)
end

Run the code:
(arup~>Ruby)$ ruby so.rb
What is your name?
arup
I dont know you

(arup~>Ruby)$


text:
Q: Ionic 3 BUILD FAILED with Cordova: cordova\node_modules\cordova-common\src\superspawn.js:169:23 In Ionic 3 with Cordova when I give the command:
ionic cordova run android --device

i have already installed and set the path in system environment
JDK
SDK
Node js
I have researched a lot on the internet and I can not solve it. What can I be doing wrong?
Even formatting the computer already formatted. I do not know what to do. Neither messages from other forums with the "supposed" same error, did not work out.
It gives me the following errors:
`E:\NAB\ionic\new\myApp>ionic cordova run android
Running app-scripts build: --platform android --target cordova
[12:54:42]  build dev started ...
[12:54:43]  clean started ...
[12:54:43]  clean finished in 16 ms
[12:54:43]  copy started ...
[12:54:44]  deeplinks started ...
[12:54:44]  deeplinks finished in 203 ms
[12:54:44]  transpile started ...
[12:54:58]  transpile finished in 14.50 s
[12:54:58]  preprocess started ...
[12:54:58]  preprocess finished in less than 1 ms
[12:54:59]  webpack started ...
[12:54:59]  copy finished in 15.94 s
[12:55:32]  webpack finished in 33.82 s
[12:55:32]  sass started ...
[12:55:38]  sass finished in 5.26 s
[12:55:38]  postprocess started ...
[12:55:38]  postprocess finished in 78 ms
[12:55:38]  lint started ...
[12:55:38]  build dev finished in 55.31 s
> cordova run android
Android Studio project detected

ANDROID_HOME=C:\Users\Sohail Akbar\AppData\Local\Android\Sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_171
studio
Subproject Path: CordovaLib
Subproject Path: app

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find gradle-core.jar (com.android.tools.build:gradle-core:3.0.0).

     Searched in the following locations:
         https://jcenter.bintray.com/com/android/tools/build/gradle-core/3.0.0/g
radle-core-3.0.0.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
[12:55:47]  lint finished in 9.31 s
(node:2132) UnhandledPromiseRejectionWarning: Error: cmd: Command failed with ex
it code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find gradle-core.jar (com.android.tools.build:gradle-core:3.0.0).

     Searched in the following locations:
         https://jcenter.bintray.com/com/android/tools/build/gradle-core/3.0.0/g
radle-core-3.0.0.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
    at ChildProcess.whenDone (E:\NAB\ionic\new\myApp\platforms\android\cordova\n
ode_modules\cordova-common\src\superspawn.js:169:23)
    at emitTwo (events.js:126:13)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
(node:2132) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
 id: 1)
(node:2132) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.`

thanks in advance

A: Sorry for my bad English, I will try my best to present the answer in easy way.
I just spend my two days and nights on solving the same issue and finally I found one.
The main problem is with the Android-NDK.
Ionic framework is looking for mips64el-linux-android package in the ndk-bundle folder of Android SDK.
If You visit Your Android-SDK folder, You will find a folder with name ndk-bundle, inside this open the folder name toolchains You will see that toolchains doesn't contains the package mips64el-linux-android.
You have to download it manually.
You can download the latest version of Android-NDK here, but unfortunately this latest version doesn't contain the package we need.
At the bottom of this page You will find a link to download the older versions of Android-NDK, follow that link and download Android NDK, Revision 14b (March 2017). That's the NDK version Ionic looking for.
Now go to Your Android-SDK path, then NDK-Bundle and delete everything from that folder. And extract the downloaded file in NDK-Bundle folder, You will see the package mips64el-linux-android.
Everything is good to go now.
Hope so it will work.

A: Below is a summation of my experience installing cordova on ionic-4. See in particular the section on mips64el-linux-android error. Just follow along and create the dummy folder and subfolders as explained.
Cordova expects to see the path to C:\Users\myusernamehere\AppData\Local\Android\Sdk\ndk-bundle\toolchains\mips64el-linux-android-4.9\prebuilt\windows-x86_64\bin\mips64el-linux-android-strip but does not require it (in my case) and will throw an error if absent.
Ionic Cordova Installation experience.
• Re- install Java JDK 8 to the latest update.
• Add ANDROID_SDK_ROOT variable to point to existing installation of Android Studio SDK
• Add Java JDK\bin to the environment PATH variable on user and system
• Download Gradle 5.2 and create folder C:\Gradle and extract the contents inside. Your
The path should look like this

C:\Gradle\gradle-5.2\bin\gradle.bat

*

*Add "C:\Gradle\gradle-5.2\bin" to PATH variable on System
From the command line do the following ..

*

*export ANDROID_SDK_ROOT=$HOME/Library/Android/sdk

*export PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin

*export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools

*export PATH=$PATH:$ANDROID_SDK_ROOT/emulator

• Using a previously installed edition of Android Studio go to Tools => SDK Tools
And check the NDK checkbox for download, click apply and ok.
• In the project terminal - Enter

ionic cordova prepare android

to build Cordova.
    If there are errors delete the platforms\android project directory and rebuild.
If there is a Gradle error looking for NDK "mips64el-linux-android-version"
Do the following ..

• Open the NDK bundle\toolchains folder within Android SDK eg C:\Users\Shay\AppData\Local\Android\sdk\ndk-bundle\toolchains
• And using command line create a folder "mips64el-linux-android-4.9" ( same version number (4.9) as other folders) inside create folder "prebuilt" .. then folder "windows-x86_64" and inside place and empty text file for contents.
The created path should look like .. "C:\Users\Shay\AppData\Local\Android\sdk\ndk-bundle\toolchains\mips64el-linux-android-4.9\prebuilt\windows-x86_64\dummy file"  is not required by Cordova but is expected to be in its path .. otherwise it will throw an error and fail to build.

Alternatively, download an older build such as https://developer.android.com/ndk/downloads/older_releases/android-ndk-r16b-windows-x86_64.zip and extract the required folder to the new ndk folder in the same location as above.
• Finally, once again enter

ionic cordova prepare android

to build Cordova
The Ionic build order (as I observed it) is a follows ..

1. It looks for all the relevant Java and Android SDK paths ..
2. Then uses Gradle as the build system ..
3. Check for NDK bundle ..
4. Build project

The above took me two days to figure out. Hope it helps and saves you the headache.


text:
Q: select record after interval of at least 1 minute I have an application that logs data after around 1 second if the packet is healthy which means the logging is not guaranteed. Now the client wants to see the log data only with the gap of at least 1 minute.
For example, this the sample schema and data
declare @mytable as table(ID int, tm DATETIME, Val int)

insert into @mytable values
(1,     convert(DATETIME, N'2018-12-24 17:45:25.000', 21), 1),
(2,     convert(DATETIME, N'2018-12-24 17:45:35.000', 21), 2),
(3,     convert(DATETIME, N'2018-12-24 17:45:55.000', 21), 1),
(4,     convert(DATETIME, N'2018-12-24 17:46:05.000', 21), 5),
(5,     convert(DATETIME, N'2018-12-24 17:47:25.000', 21), 2),
(6,     convert(DATETIME, N'2018-12-24 17:47:55.000', 21), 7),
(7,     convert(DATETIME, N'2018-12-24 17:48:25.000', 21), 9),
(8,     convert(DATETIME, N'2018-12-24 17:48:50.000', 21), 1),
(9,     convert(DATETIME, N'2018-12-24 17:49:25.000', 21), 1),
(10,    convert(DATETIME, N'2018-12-24 17:50:05.000', 21), 5),
(11,    convert(DATETIME, N'2018-12-24 17:50:50.000', 21), 4),
(12,    convert(DATETIME, N'2018-12-24 17:51:25.000', 21), 8),
(13,    convert(DATETIME, N'2018-12-24 17:55:25.000', 21), 4),
(14,    convert(DATETIME, N'2018-12-24 17:56:58.000', 21), 4),
(15,    convert(DATETIME, N'2018-12-24 17:58:15.000', 21), 5),
(16,    convert(DATETIME, N'2018-12-24 18:10:25.000', 21), 8);

The output should be
1,     convert(DATETIME, N'2018-12-24 17:45:25.000', 21), 1
5,     convert(DATETIME, N'2018-12-24 17:47:25.000', 21), 2
7,     convert(DATETIME, N'2018-12-24 17:48:25.000', 21), 9
9,     convert(DATETIME, N'2018-12-24 17:49:25.000', 21), 1
11,    convert(DATETIME, N'2018-12-24 17:50:50.000', 21), 4
13,    convert(DATETIME, N'2018-12-24 17:55:25.000', 21), 4
14,    convert(DATETIME, N'2018-12-24 17:56:58.000', 21), 4
15,    convert(DATETIME, N'2018-12-24 17:58:15.000', 21), 5
16,    convert(DATETIME, N'2018-12-24 18:10:25.000', 21), 8

Here, after a qualified entry, next entry to qualify is to have at least 1 minute gap. However, I have to log all the healthy entries as in some other procedure I'll have to return all records. So skipping during logging is not an option.
Also, I know I can achieve it using a cursor but given the amount of data, this is not an acceptable solution.

A: Using recursive common table expression:
;WITH CTE (Id, tm, val)
AS
(
    SELECT TOP 1 *
    FROM @mytable m
    WHERE m.ID = 1

    UNION ALL

    SELECT
        p.Id,
        p.tm,
        p.val
    FROM
    (
        SELECT
            m.*,
            ROW_NUMBER() OVER(ORDER BY c.Id) AS row_num
        FROM CTE c
        INNER JOIN @mytable m ON c.Id < m.ID AND DATEADD(MINUTE, 1, c.tm) <= m.tm
    ) AS p
    WHERE p.row_num = 1

)
SELECT *
FROM CTE c

Id          tm                      val
----------- ----------------------- -----------
1           2018-12-24 17:45:25.000 1
5           2018-12-24 17:47:25.000 2
7           2018-12-24 17:48:25.000 9
9           2018-12-24 17:49:25.000 1
11          2018-12-24 17:50:50.000 4
13          2018-12-24 17:55:25.000 4
14          2018-12-24 17:56:58.000 4
15          2018-12-24 17:58:15.000 5
16          2018-12-24 18:10:25.000 8

But, I'm not sure, this solution will work on big tables with many records. Maybe, you need some kind of post-processing after inserting in log table.


text:
Q: JavaScript getElementByID - error in JavaScript code (field is left blank but not turning red on click) I have the following JavaScript code, it appears to be correct.
I simply want, on button Click, for the background of the textbox to turn 'red', if the textbox is left blank.
Can someone point out the error in the below code.

function validate(){
  if (document.getElementById("textbox_1").value==' '){
    document.getElementById("textbox_1").style.backgroundColor='red';
  }
}
<body>
   NAME:<INPUT TYPE="Text" SIZE="15" VALUE="" ID="textbox_1" />
   <INPUT TYPE="Button" VALUE="SEND" onClick="Validate()" />
</body>

A: Uppercase/Lowercase matters (in function name). You also should compare against empty string not blank space:

<script>
  function validate(){
    var el = document.getElementById("textbox_1");
    if (el.value.trim()==''){
      el.style.backgroundColor='red';
    }
    else{
      el.style.backgroundColor='';
    }
  }
</script>
NAME:<INPUT TYPE="Text" SIZE="15" VALUE="" ID="textbox_1">
<INPUT TYPE="Button" VALUE="SEND" onClick="validate()">

A: You have written he function name wrong

function validate(){
if (document.getElementById("textbox_1").value=='')
    document.getElementById("textbox_1").style.backgroundColor='red';
}
NAME:<input type="Text" size="15" value="" id="textbox_1">
<input type="Button" value="SEND" onClick="validate()">

A: function name will be validated not Validate.Html Uppercase function name Validate/Lower case in validate JS

function validate(){
if (document.getElementById("textbox_1").value==''){
    document.getElementById("textbox_1").style.backgroundColor='red';
}

}
<!DOCTYPE HTML>
<HTML>
<head>

</head>
<body>
NAME:<INPUT TYPE="Text" SIZE="15" VALUE="" ID="textbox_1">
<INPUT TYPE="Button" VALUE="SEND" onClick="validate()">
</body>
</html>


text:
Q: Multiple controls on same line in SwiftUI macOS form I am making a UI to change the 3D coordinates of an object, and I thought it would make sense to put all three on the same line with a label beforehand, sort of like System Preferences does for number separators :

However, doing so messes up the alignment of the whole form, and I'm not sure how to resolve this (except by adding VStacks and HStacks everywhere, which I really hope is not the best available solution) :

Here is the code driving the view :
struct ObjectSettingsView: View {
    @State var object : Object

    var body : some View {
        Form {
            TextField("Name:", text: $object.name, prompt : Text("New Object"))
            Toggle(
                "Visible",
                isOn: $object.visible
            )
            Divider()
            HStack {
                Text("Coordinates:")
                NumberView(label : "X:", number : object.coordinates.x)
                NumberView(label : "Y:", number : object.coordinates.y)
                NumberView(label : "Z:", number : object.coordinates.z)
            }
        }
    }
}

struct NumberView : View{
    var label : String
    @State var number : Int32

    var body : some View {
        HStack {
            TextField(
                self.label,
                value: self.$number,
                formatter: NumberFormatter()
            )
            Stepper("", value: self.$number, in: 1...8)
                .labelsHidden()
        }
    }
}

( I know this really should be using a ViewModel, I'm just trying to figure out how forms work right now )

A: I add @Binding and LazyVGrid to your Code.
Maybe this helps:
struct ObjectData {
    var name: String = "New Object"
    var visible: Bool = true
    var coordinates_x: Int32 = 0
    var coordinates_y: Int32 = 0
    var coordinates_z: Int32 = 0
}

struct ContentView: View {
    @State var data = ObjectData()

    let columns = [
        GridItem(alignment: .trailing),
        GridItem(alignment: .leading),
    ]

    var form: some View {
        LazyVGrid(columns: columns) {
            Text("Name:")
            TextField("", text: $data.name)
            Text("blind").opacity(0)
            Toggle("Visible:", isOn: $data.visible)
            Text("Coordinates:")
            HStack {
                NumberView(label : "X:", number : $data.coordinates_x)
                NumberView(label : "Y:", number : $data.coordinates_y)
                NumberView(label : "Z:", number : $data.coordinates_z)
            }
        }
    }

    var body : some View {
        VStack() {
            form
            Text(" --- Check --- ")
            Text(String(describing: data))
        }
        .frame(width: 400.0)
    }

}

struct NumberView : View{
    var label : String
    @Binding var number : Int32

    var body : some View {
        HStack {
            TextField(
                self.label,
                value: self.$number,
                formatter: NumberFormatter()
            )
            Stepper("", value: self.$number, in: 1...8)
                .labelsHidden()
        }
    }
}

A: Separating things into two Forms almost does the trick, although labels are still not exactly aligned as in system Preferences :

struct ObjectSettingsView: View {
    @State var object : Object

    var body : some View {
        VStack {
            Form {
                TextField("Name:", text: $object.name, prompt : Text("New Object"))
                Toggle("Visible", isOn: $object.visible)
            }
            Divider()
            Form {
                HStack {
                    Text("Coordinates:")
                    NumberView(label : "X:", number : object.coordinates.x)
                    NumberView(label : "Y:", number : object.coordinates.y)
                    NumberView(label : "Z:", number : object.coordinates.z)
                }
            }
        }
        .padding()
    }
}

A: // static let left = GridItem.Size.flexible(minimum: 10, maximum: .infinity)
static let left = GridItem.Size.flexible(minimum: 40, maximum: 100)
static let right = GridItem.Size.flexible(minimum: 40, maximum: 200)
let columns = [
    GridItem(left, alignment: .trailing),
    GridItem(right, alignment: .leading),
]

The problem is that the size structs are set to .infinity
I changed the column settings like above with fixed max values.
To get all infos see Apple Docs about GridItem.


text:
Q: Compiling a kernel module, header problems, makefile problems ok I'm trying to compile a simple kernel module, when I point to any of the below that contain includes, it complains about all kinds of stuff.
linux-headers-2.6.31-21              linux-headers-2.6.31-22
linux-headers-2.6.31-21-generic      linux-headers-2.6.31-22-generic
linux-headers-2.6.31-21-generic-pae  linux-headers-2.6.31-22-generic-pae

I'm attempting to follow the instructions on the following site:
http://www.faqs.org/docs/kernel/x145.html
I updated the make file to look like this:
TARGET  := hello_world
WARN    := -W -Wall -Wstrict-prototypes -Wmissing-prototypes
INCLUDE := -isystem /usr/src/linux-headers-2.6.31-22-generic/include
CFLAGS  := -O2 -DMODULE -D__KERNEL__ ${WARN} ${INCLUDE}
CC      := gcc

${TARGET}.o: ${TARGET}.c

.PHONY: clean

clean:
    rm -rf ${TARGET}.o

for example when I type in make I get the following error as well as many more, investigating the folders I see that the processor and cache files are in asm-generic, how in the world am I supposed to compile this if it's not pointing at the right locations of the files?
/usr/src/linux-headers-2.6.31-22-generic/include/linux/prefetch.h:14:27: error: asm/processor.h: No such file or directory
/usr/src/linux-headers-2.6.31-22-generic/include/linux/prefetch.h:15:23: error: asm/cache.h: No such file or directory

The ultimate goal (scary) is building a virtual file system, by thursday....(yea I know it's pretty unlikely)
I understand some of the make file, but oddly enough I expected that I should see something like ${CC} ${INCLUDE}, things like this, but I don't see that at all,
Can someone explain and/all of the following questions?

*

*What do I need to update my include to so it knows the right directory (and if it's something like what kernel I'm using etc, please explain how I can figure this out).

*Can someone explain how the makefile knows to call gcc and compile?

*Is there anything else I need to know to get this thing to compile?
-- Bonus question

*Anyone know any REALLY detailed tutorials about how to build a VFS, I have a project we were assigned that another school did, http://oslab.info/index.php/Labs/HW4, and based on the limited programming we've done before this, it is appearing to be a monumental task.

A: With 2.6 kernel, you should use the kernel build system. Here is an example for a module built outside of the kernel tree :
ifneq ($(KERNELRELEASE),)
# We were called by kbuild

obj-m += target.o

else  # We were called from command line

KDIR := /lib/modules/$(shell uname -r)/build
#KDIR := /home/cynove/src/kernel/linux-source-2.6.31
PWD  := $(shell pwd)

default:
    @echo '    Building target module 2.6 kernel.'
    @echo '    PLEASE IGNORE THE "Overriding SUBDIRS" WARNING'
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

install:
    ./do_install.sh *.ko

endif  # End kbuild check
######################### Version independent targets ##########################

clean:
    rm -f -r *.o *.ko .*cmd .tmp* core *.i

By calling make -C ($KDIR) etc..., the kernel build system gets involved, and does the job for you.

A: Example 2.2 of your link has the following line instead of the one you listed:
INCLUDE := -isystem /lib/modules/`uname -r`/build/include

That looks like the probable cause of your compile issues.  Any particular reason you changed it?

A: Looking at a couple of source trees (2.6.32 is the oldest I have on hand) there are no instances of processor.h which are in a generic directory, all are architecture specific. For example
/usr/src/linux-headers-2.6.32-24/arch/x86/include/asm/processor.h

So I'm guessing you are missing an include directory in your Makefile.


text:
Q: Filter DataFrame of dtype object using pandas I'm required to parse data using the following operations.
data=[{'a': 1,
       'b': {1: 1,
             2: 2},
       'c': ['q', 'w', 'e', 'r', 't', 'y']},
      {'a': 2,
       'b': {1: 2,
             2: 3},
       'c': ['q', 't', 'a', 'v', 'o', 'l']}]

df = pd.DataFrame(data)

I want to get data that satisfy a condition as follows:
print(df['q' in df.c].head())

However, I get an error:
File "pandas/hashtable.pyx", line 676, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216)
KeyError: False

Why wouldn't this work?
I'm confused as the following code would work unlike when parsing through the object dtype:
print(df[df.a == 1].head())

A: You can use apply on the column to generate a boolean mask describing the desired columns, and then filter the DataFrame by this mask:
>>> df[df.c.apply(lambda val: 'q' in val)]
   a             b                   c
0  1  {1: 1, 2: 2}  [q, w, e, r, t, y]
1  2  {1: 2, 2: 3}  [q, t, a, v, o, l]

A: in is used for index checking. For values you can use str.contains():
df.c.str.contains("q", regex=False)


text:
Q: Is temperature of 1 Kelvin equivalent to 1 eV in natural unit? We know that the Boltzmann's constant, $k_B$=8.617 $\times$ $10^{-5}$ eV/K. Now in the natural unit, $k_B=1$.
So can I say, in the natural unit, 1 K temperature is equivalent to 1 eV in energy? 300 K is equivalent to 300 eV?
Or am I missing something?

A: No.  The situation is similar to the situation in special relativity where we use units in which $c = 1$ instead of $c = 3.00 \times 10^8 \text{ m/s}$.  Using $c = 1$ does not mean that 1 meter is now equivalent to 1 second.  It means that we are defining our unit for distance to be the distance traveled by light in 1 second.  In other words, "1 second of distance" is the distance traveled by light in 1 second of time.
In the case you're interested in, where we use "natural units" in which $k_B = 1$, temperatures are measured in units of energy.  In other words, we could say that a system has a temperature of 1 eV, or 300 eV;  but these are not equivalent to 1 K or 300 K any more than "1 second of distance" is equivalent to 1 meter.  Rather, we are defining our temperature scale as something like, "if the average KE of an atom in a monatomic ideal gas is 3 eV, then the temperature of the gas is defined to be 2 eV."  The change from 2 to 3 is because of the $\frac32$ factor in the equipartition theorem for the ideal gas:
$$
\langle E \rangle = \frac{3}{2} T
$$
if $k = 1$.
(Finally, a nitpick on your question:  in conventional units, $k_B = 8.617 \times 10^{-5} \text{ eV/K}$, not $8.617 \times 10^{-5} \text{ eV}$.  This may have been a typo, but note that the correct units make it clearer that Boltzmann's constant is a "conversion factor" between temperature and energy.)


text:
Q: Mass of Antiparticles Why do the mass of anti-particles have to be exactly equal to the particles ?
What I learnt from Srednicki Chapter 23 is that to support charge conjugation symmetry (C-symm) of Lagrangian, mass of particle and anti-particle must be same.
My question is "Is charge conjugation symmetry a universal truth -- proven by experiments, or we still can have some Lagrangians (L) which doesn't support C-symm., where changing + charged particles to - charged in L will not mean m+ = m- ?" What would existence of such a theory mean to our world ?


text:
Q: Hide rows based on offset value I've a problem hiding rows based on other row's value.
I've tried to do some For Next loops and c.offsets, but can't target the right rows.
Original structure:

Desired structure:

I want to hide the rows that only contain the subtitles or is completely blank, but keep the titles.

A: Try the next code, please. It will hide the rows having a blank cell in column A:A and the ones having "Sub title" in A:A and nothing else in the following cells:
Sub testHiddingSubTtlRows()
 Dim sh As Worksheet, lastR As Long, lastCol As Long, arrA, i As Long, rngH As Range, boolH As Boolean

 Set sh = ActiveSheet  'use here your necessary sheet
 lastCol = sh.UsedRange.Columns.count  'last column
 lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row (in A:A)
 arrA = sh.Range("A1:A" & lastR).value 'put the range in an array (for speed)

 For i = 1 To UBound(arrA)
    boolH = False
    If arrA(i, 1) = "Sub title" Then
        If WorksheetFunction.CountA(sh.Range("B" & i, sh.cells(i, lastCol))) = 0 Then boolH = True
    ElseIf arrA(i, 1) = "" Then
        boolH = True
    End If
    If boolH Then
        If rngH Is Nothing Then
            Set rngH = sh.Range("A" & i)
        Else
            Set rngH = Union(rngH, sh.Range("A" & i))
        End If
    End If
 Next i
 If Not rngH Is Nothing Then rngH.EntireRow.Hidden = True
End Sub

The code should be very fast, building a Union range for the matching criteria cells and hiding the rows at once, at the end of the code.
Please, test it and send some feedback.
Edited:
Please, test the next adapted code, able to hide any sub titles, without previously keeping them somehow (in an array, collection, dictionary etc.):
Sub testHiddingSubTtlRows()
 Dim sh As Worksheet, lastR As Long, lastCol As Long, arrA, i As Long, rngH As Range, boolH As Boolean, boolT As Boolean

 Set sh = ActiveSheet
 lastCol = sh.UsedRange.Columns.count
 lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
 arrA = sh.Range("A1:A" & lastR).value

 For i = 1 To UBound(arrA)
    boolH = False: boolT = False
    If arrA(i, 1) = "Title" Then
        If WorksheetFunction.CountA(sh.Range("B" & i + 1, sh.cells(i + 1, lastCol))) = 0 Then boolH = True: boolT = True
    ElseIf arrA(i, 1) = "" Then
        boolH = True
    End If
    If boolH Then
        If rngH Is Nothing Then
            Set rngH = sh.Range("A" & IIf(boolT, i + 1, i))
        Else
            Set rngH = Union(rngH, sh.Range("A" & IIf(boolT, i + 1, i)))
        End If
    End If
 Next i
 If Not rngH Is Nothing Then rngH.EntireRow.Hidden = True
End Sub

A: Hide Rows

*

*Adjust the values in the constants section.

Option Explicit

Sub hideEmptyAndSub()

    Const wsName As String = "Sheet1"
    Const cCol As String = "A"
    Const FirstRow As Long = 1
    Const Crit As String = "*Sub title*"

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
    Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, cCol).End(xlUp).Row

    Dim hrg As Range
    Dim hcell As Range
    Dim cValue As Variant
    Dim i As Long

    For i = FirstRow To LastRow
        Set hcell = ws.Cells(i, cCol)
        cValue = CStr(hcell.Value)
        If Len(cValue) = 0 Or UCase(cValue) Like UCase(Crit) Then
            If hrg Is Nothing Then
                Set hrg = hcell
            Else
                Set hrg = Union(hrg, hcell)
            End If
        End If
    Next i

    If Not hrg Is Nothing Then
        hrg.EntireRow.Hidden = True
    End If

End Sub


text:
Q: lm() within mutate() in group_by() I'm looking for a way to add a column to my data table that consists of residuals from a lm(a~b) function computed separately for different levels of c
I've been suggested to look into sort_by(c) function but that doesn't seem to work with lm(a~b)
My working example data looks like this:

Columns subject, trial and rt are within a data.frame, my goal is to compute Zre_SPSS (that I originally made in SPSS) but from a R function.
I've tried
data %<>% group_by (subject) %>%
  mutate(Zre=residuals(lm(log(rt)~trial)))

but it doesn't work - Zre gets computed but not within each subject separately, rather for the entire data frame.
Anyone could please help me? I'm a complete R (and coding in general) newbie, so please forgive me if this question is stupid or a duplicate, chances are I didn't understand other solutions or they where not solutions I looked for. Best regards.
As per Ben Bolker request here is R code to generate data from excel screen shot
#generate data
  subject<-c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3)
  subject<-factor(subject)
  trial<-c(1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6)
  rt<-c(300,305,290,315,320,320,350,355,330,365,370,370,560,565,570,575,560,570)

#Following variable is what I would get after using SPSS code
  ZreSPSS<-c(0.4207,0.44871,-1.7779,0.47787,0.47958,-0.04897,0.45954,0.45487,-1.7962,0.43034,0.41075,0.0407,-0.6037,0.0113,0.61928,1.22038,-1.32533,0.07806)

#make data frame
  sym<-data.frame(subject, trial, rt, ZreSPSS)

A: It looks like a bug in dplyr 0.5's mutate, where lm within a group will still try to use the full dataset. You can use do instead:
sym %>% group_by(subject) %>% do(
{
    r <- resid(lm(log(rt) ~ trial, data = .))
    data.frame(., r)
})

This still doesn't match your SPSS column, but it's the correct result for the data you've given. You can verify this by fitting the model manually for each subject and checking the residuals.
(Other flavours of residuals include rstandard for standardized and rstudent for studentized residuals. They still don't match your SPSS numbers, but might be what you're looking for.)

A: Later version of dplyr seems able to handle this (tested with dplyr 0.7.4):
sym %>% group_by(subject) %>% do(
{
    r <- resid(lm(log(rt) ~ trial, data = .))
    data.frame(., r)
}) ->a

sym %>% group_by(subject) %>% mutate(

    r =  resid(lm(log(rt) ~ trial))
) ->b

all(a$r==b$r)  #->TRUE

another independent test
# https://stackoverflow.com/a/40061201/2292993
# https://stackoverflow.com/q/24766450/2292993
# https://github.com/tidyverse/dplyr/issues/2177

# tested with dplyr 0.7.4

# 1) do
df = group_by(iris,Species) %>% do({
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width, data=.) )
data.frame(., res)
})

# 2) group_by + mutate
# cannot have "data=." in lm
df2 = group_by(iris,Species) %>% mutate(
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width) )
)

# 3) filter + mutate
df3 = filter(iris,Species=='setosa') %>% mutate(
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width, data=.) )
)
df3 = bind_rows(df3,
filter(iris,Species=='versicolor') %>% mutate(
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width, data=.) )
))
df3 = bind_rows(df3,
filter(iris,Species=='virginica') %>% mutate(
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width, data=.) )
))

# 4) across all rows (should not be the same)
df4 = mutate(iris,
res = resid( lm(Sepal.Length~Petal.Length+Petal.Width, data=iris) )
)

# conclusion: all the same, except df4
all(df$res==df2$res)
all(df$res==df3$res)
df$res==df4$res


text:
Q: Biztalk Server 2006 HTML Email with inline images I m quite new in Biztalk Server 2006 and I have a problem regarding sending HTML Email with inline images. What I have do so far is sending HTML emails (or text emails) in BizTalk without embedded images which works.
Could somebody help me with this?
Thank you very much for your efforts!
Br, Toan

A: If you're sending an HTML message, then it is just the case of adding the
The issue then is that you need to save the image on a public internet address (assuming that the message goes outside the firewall) or on a server in your intranet that everyone can access.
An example of the image tag would be:
 This is the internal server example

or
 This is the external server example

Hopefuly this helps.


text:
Q: Can GET and POST requests from a same machine come from different IPs? I'm pretty sure I remember reading --but cannot find back the links anymore-- about this: on some ISP (including at least one big ISP in the U.S.) it is possible to have a user's GET and POST request appearing to come from different IPs.
(note that this is totally programming related, and I'll give an example below)
I'm not talking about having your IP adress dynamically change between two requests.
I'm talking about this:
IP 1:  123.45.67.89
IP 2:  101.22.33.44

The same user makes a GET, then a POST, then a GET again, then a POST again and the servers see this:
- GET  from IP 1
- POST from IP 2
- GET  from IP 1
- POST from IP 2

So altough it's the same user, the webserver sees different IPs for the GET and the POSTs.
Surely seen that HTTP is a stateless protocol this is perfectly legit right?
I'd like to find back the explanation as to how/why certain ISP have their networks configured such that this may happen.
I'm asking because someone asked me to implement the following IP filter and I'm pretty sure it is fundamentally broken code (breaking havoc for at least one major american ISP users).
Here's a Java servlet filter that is supposed to protect against some attacks.  The reasoning is that:
"For any session filter checks that IP address in the request is the same that was used when session was created. So in this case session ID could not be stolen for forming fake sessions."
http://www.servletsuite.com/servlets/protectsessionsflt.htm
However I'm pretty sure this is inherently broken because there are ISPs where you may see GET and POST coming from different IPs.

A: Some ISPs (or university networks) operate transparent proxies which relay the request from the outgoing node that is under the least network load.
It would also be possible to configure this on a local machine to use the NIC with the lowest load which could, again, result in this situation.
You are correct that this is a valid state for HTTP and, although it should occur relatively infrequently, this is why validation of a user based on IP is not an appropriate determinate of identity.

A: For a web server to be seeing this implies that the end user is behind some kind of proxy/gateway. As you say it's perfectly valid given that HTTP is stateless, but I imagine would be unusual. As far as I am aware most ISPs assign home users a real, non-translated IP (albeit usually dynamic).
Of course for corporate/institutional networks they could be doing anything. load balancing could mean that requests come from different IPs, and maybe sometimes request types get farmed out to different gateways (altho I'd be interested to know why, given that N_GET >> N_POST).


text:
Q: Making buttons disappear in Tkinter I'm doing a coding project at school and I'm trying to set up functions for my buttons
but when i run the code the buttons run the commands without being clicked and they don't dissapear because the button mentioned in the function that hides them doesn't work:
from tkinter import *
import tkinter
#Parent Window Setup
GoodChefWindow = Tk()
GoodChefWindow.title("Welcome To GoodChef")
GoodChefWindow.geometry("600x500")

#Displaying Company Logo
Logo=PhotoImage(file="LogoV2.gif")
LogoCanvas=tkinter.Canvas(GoodChefWindow,height=150, width=600)
LogoCanvas.create_image(300,75,image=Logo)
LogoCanvas.pack()

#Pickup and Delivery buttons
def Delivery_Clicked():
    Delivery=Tk()
    Delivery.title("Delivery Options")
    Delivery.geometry("400x333")
    Remove_Buttons()

def PickUp_Clicked():
    Delivery=Tk()
    Delivery.title("Pick Up Options")
    Delivery.geometry("400x333")
    Remove_Buttons()

def Remove_Buttons():
    MenuButtonsFrame.destroy()

def Buttons(MenuButtonsFrame):
    DeliveryIcon=PhotoImage(file="Delivery_Icon.gif")
    PickUpIcon=PhotoImage(file="Pick_Up_Icon.gif")
    MenuButtonsFrame = LabelFrame(GoodChefWindow, text="Order")
    MenuButtonsFrame.pack()
    DeliveryLabelFrame = LabelFrame(MenuButtonsFrame)
    DeliveryLabelFrame.pack(side=RIGHT,expand="yes")
    PickUpLabelFrame = LabelFrame(MenuButtonsFrame)
    PickUpLabelFrame.pack(side=LEFT,expand="yes")
    DeliveryButton = tkinter.Button(DeliveryLabelFrame,bg="red",
                                    fg="yellow",compound="left",
                                    image=DeliveryIcon,height=40,
                                    width=120,text="Delivery",
                                    command=Delivery_Clicked())
    PickUpButton = tkinter.Button(PickUpLabelFrame,bg="red",
                                  fg="yellow",compound="left",
                                  image=PickUpIcon,height=40,
                                  width=120,text="Pick Up",
                                  command=PickUp_Clicked())
    DeliveryButton.pack()
    PickUpButton.pack()

Buttons()

A: You really need to rethink your approach in my opinion, here is the way I would do what you have so far:
from tkinter import *

#Parent Window Setup
GoodChefWindow = Tk()
GoodChefWindow.title("Welcome To GoodChef")
GoodChefWindow.geometry("600x500")

#Displaying Company Logo
Logo=PhotoImage(file="rd.gif")
LogoCanvas=Canvas(GoodChefWindow,height=150, width=600)
LogoCanvas.create_image(300,75,image=Logo)
LogoCanvas.pack()

#Pickup and Delivery buttons
def Delivery_Clicked():
    Delivery=Toplevel()
    Delivery.title("Delivery Options")
    Delivery.geometry("400x333")
    Remove_Buttons(MenuButtonsFrame)

def PickUp_Clicked():
    Delivery=Toplevel()
    Delivery.title("Pick Up Options")
    Delivery.geometry("400x333")
    Remove_Buttons(MenuButtonsFrame)

def Remove_Buttons(MenuButtonsFrame):
    MenuButtonsFrame.destroy()

DeliveryIcon=PhotoImage(file="rd.gif")
PickUpIcon=PhotoImage(file="rd.gif")
MenuButtonsFrame = LabelFrame(GoodChefWindow, text="Order")
MenuButtonsFrame.pack()
DeliveryLabelFrame = LabelFrame(MenuButtonsFrame)
DeliveryLabelFrame.pack(side=RIGHT,expand="yes")
PickUpLabelFrame = LabelFrame(MenuButtonsFrame)
PickUpLabelFrame.pack(side=LEFT,expand="yes")
DeliveryButton = Button(DeliveryLabelFrame,bg="red",
                                fg="yellow",compound="left",
                                image=DeliveryIcon,height=40,
                                width=120,text="Delivery",
                                command=Delivery_Clicked)
PickUpButton = Button(PickUpLabelFrame,bg="red",
                              fg="yellow",compound="left",
                              image=PickUpIcon,height=40,
                              width=120,text="Pick Up",
                              command=PickUp_Clicked)
DeliveryButton.pack()
PickUpButton.pack()

mainloop()

This should help? if not speak out! you could also make more tk windows (toplevel isn't necessary).


text:
Q: How can I show that $\mathcal{F}_t^X$ is generated by sets of the form $F=\{(X_{t_1},\dots, X_{t_n}) \in \Gamma\}$ How can I show that $\mathcal{F}_t^X$ is generated by sets of the form $F={(X_{t_1},\dots, X_{t_n}) \in \Gamma}$ where $\Gamma \in\mathcal{B}(\mathbb{R}^n)$ and $0=t_1< \dots <t_n=t$.
Do I need some kind of continuity for this to hold. The question assumes that $X$ is left continuous.
I tried to use the definition of $\mathcal{F}_t^X=\sigma(X_s,0 \leq s \leq t)$ and tried to think of an application of the $\pi-\lambda$ theorem to prove this but I couldnt apply it. Any hints on how could I show this?

A: By definition, $\mathcal{F}_t^X$ is the smallest $\sigma$-algebra for which $X_s$ is measurable for any $0\leqslant s\leqslant t$.
Let
$$
\mathcal C:=\left\{ \left\{(X_{t_1},\dots, X_{t_n})\in \Gamma\right\},\Gamma \in\mathcal{B}(\mathbb{R}^n),0=t_1< \dots <t_n=t,n\geqslant 1 \right\}.
$$
Then the $\sigma$-algebra generated by $\mathcal C$, denoted by $\sigma\left(\mathcal C\right)$, is such that $X_s^{-1}(B)$ is in $\sigma\left(\mathcal C\right)$ for all $B\in\mathcal B(\mathbb R)$. This shows that $\mathcal F_t^X\subseteq \sigma\left(\mathcal C\right)$.
To see the other inclusion, let $\mathcal G$ be a $\sigma$-algebra for which $X_s$ is measurable for any $0\leqslant s\leqslant t$ and let us show that $\sigma\left(\mathcal C\right)\subseteq\mathcal G$. Since $\mathcal G$ is a $\sigma$-algebra, it suffices to establish that $\mathcal C\subseteq\mathcal G$. This follows from the fact that measurability of $X_s$ for all $s$ with respect to $\mathcal G$ is equivalent (using projections) to measurability of $(X_{t_1},\dots, X_{t_n})$ with respect to $\mathcal G$. Indeed, the mentioned measurability implies that for any Borel subset $B$ of $\mathbb R^n$, the set $\left\{\omega\mid (X_{t_1}(\omega),\dots, X_{t_n}(\omega))\in B\right\}$ is in $\mathcal G$.


text:
Q: Javascript Miscalculation and $NaN I'm confused and I've tried getting the following javascript to render a Total amount calculation but I'm having $NaN and some cell are not displaying the correct values when a dropdown list is used to pick a mailing option.
Here's the Javascript and the JSFIDDLE that I've been working on:
$(function() {
  function calcTotal() {
    var p = {
      qty: parseInt($(".prod-row .qty").text().trim()),
        costperitem: parseInt($(".prod-row .costperitem").text().trim()),
        tax: parseFloat($(".prod-row .tax").text().trim().slice(1)),
        shipcost: parseFloat($(".prod-row .shippingcost").text().trim().slice(1)),
        price: parseFloat($(".prod-row .item-cost").text().trim().slice(1))
      };
      var t = 0.00;
      if (p) {
         t = (p.qty * p.costperitem) + (p.tax) + (p.qty * p.shippingcost);
      }
      console.log(p, t);
      return t;
    }
    $("#shippingmethod").change(function(e) {
        var shipQty = parseInt($(".prod-row .qty").text());
        var shipCost = parseFloat($(this).val());
            $(".prod-row .item-cost").html("$" + shipCost.toFixed(2));
            $(".prod-row .total").html("$" + (shipQty * shipCost).toFixed(2));
        var total = calcTotal();
        $("#product-totals .total").html("$" + total.toFixed(2));
   });
});

Desired outcome
To have all the items in only 1 row and where total column shows the following math result from the calculation: (Qty. + ItemCost + Tax) + (Qty.*S&H).
Thanks for any help!

A: The issue resides in the index call. In the following function:
function calcTotal() {
  var p = {
    qty: parseInt($(".prod-row .qty").text().trim()),
    costperitem: parseInt($(".prod-row .costperitem").text().trim()),
    tax: parseFloat($(".prod-row .tax").text().trim().slice(1)),
    shipcost: parseFloat($(".prod-row .shippingcost").text().trim().slice(1)),
    price: parseFloat($(".prod-row .item-cost").text().trim().slice(1))
  };
  var t = 0.00;
  if (p) {
    t = (p.qty * p.costperitem) + (p.tax) + (p.qty * p.shippingcost);
  }
  console.log(p, t);
  return t;
}

You reference p.shippingcost which does not exist and returns undefined.
Also, you want to parseFloat() on your costperitem section. parseInt() will round to the nearest Integer.
Also you need to slice() off any preceding $ signs.
Correct like so:
function calcTotal() {
  var p = {
    qty: parseInt($(".prod-row .qty").text().trim()),
    costperitem: parseFloat($(".prod-row .costperitem").text().trim().slice(1)),
    tax: parseFloat($(".prod-row .tax").text().trim().slice(1)),
    shipcost: parseFloat($(".prod-row .shippingcost").text().trim().slice(1)),
    price: parseFloat($(".prod-row .item-cost").text().trim().slice(1))
  };
  var t = 0.00;
  if (p) {
    t = (p.qty * p.costperitem) + (p.tax) + (p.qty * p.shipcost);
  }
  console.log(p, t);
  return t;
}

Good Luck!
Update
I would suggest the following code that is fixed to perform all the various steps needed with the correct Class Names in place.
$(function() {
  function toCur(fl) {
    return "$" + parseFloat(fl).toFixed(2);
  }

  function parseCurToFloat(txt) {
    return parseFloat(txt.trim().slice(1));
  }

  function setNewShipCost($row, cost) {
    $row.find(".shipping-cost").html(toCur(cost));
    return toCur(cost);
  }

  function calcRowTotal($row) {
    var q = parseInt($row.find(".qty").text());
    var c = parseCurToFloat($row.find(".item-cost").text());
    var t = parseCurToFloat($row.find(".tax").text());
    var sh = parseCurToFloat($row.find(".shipping-cost").text());
    var ttl = (q * c) + (q * sh) + t;
    $row.find(".total").html(toCur(ttl));
    return ttl;
  }

  function calcNewTotal() {
    var t = 0.00;
    $(".prod-row").each(function(ind, el) {
      t = t + parseCurToFloat($(el).find(".total").text());
    });
    $("#product-totals .total").html(toCur(t));
    return t;
  }

  $("#shippingmethod").change(function(e) {
    var shipCost = $(this).val();
    console.log("Set Ship", setNewShipCost($(".prod-row"), shipCost));
    console.log("Calc Row Total", calcRowTotal($(".prod-row")));
    console.log("Calc total", calcNewTotal());
  });
});

Working Example: http://jsfiddle.net/Twisty/ag1u4vjc/


text:
Q: use @Bean inject a bean but could't pass check about @ConditionalOnBean When I comment out the line @ConditionalOnBean(name = "customRedisConnectionFactory"),the function is execute and the customRedisConnectionFactory is the object that I injected. But when I enabled this line, the method doesn't execute. I want to know the reason. Can someone help me answer it.
RedisConfig
@Configuration
@ConditionalOnClass(RedisOperations.class)
@AutoConfigureBefore({CacheAutoConfiguration.class})
public class RedisConfig {
    @Bean(name = "customRedisConnectionFactory")
    public RedisConnectionFactory customRedisConnectionFactory(){
        RedisStandaloneConfiguration redisStandaloneConfiguration=new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setDatabase(12);
        redisStandaloneConfiguration.setHostName("127.0.0.1");
        redisStandaloneConfiguration.setPassword("yichen");
        redisStandaloneConfiguration.setPort(6379);

        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
        return jedisConnectionFactory;
    }
}

CustomRedisCacheManagerConfiguration
@Configuration
@AutoConfigureAfter({CacheAutoConfiguration.class})
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties({RedisProperties.class, CacheProperties.class, RedisCacheExpiresProperties.class})
public class CustomRedisCacheManagerConfiguration {

    private final CacheProperties cacheProperties;

    public CustomRedisCacheManagerConfiguration(CacheProperties cacheProperties) {
        this.cacheProperties = cacheProperties;
    }
    @Bean(name = "serviceRedisCacheManager")
    @ConditionalOnBean(name = "customRedisConnectionFactory")
    public RedisCacheManager serviceRedisCacheManager(
            @Qualifier("customRedisConnectionFactory") RedisConnectionFactory customRedisConnectionFactory,
            RedisCacheExpiresProperties redisCacheExpiresProperties) {

        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.builder(customRedisConnectionFactory).cacheDefaults(determineConfigurationDefault());

        Map<String, Long> cacheConfigurations = redisCacheExpiresProperties.getCacheExpires();
        if (cacheConfigurations != null && cacheConfigurations.size() > 0) {
            Map<String, RedisCacheConfiguration> redisCacheConfigurations = new HashMap<>();
            for (String cacheName : cacheConfigurations.keySet()) {
                Assert.notNull(cacheName, "CacheName must not be null!");

                long ttl = cacheConfigurations.get(cacheName);
                Assert.isTrue(ttl > 0, "Expire must not be null!");

                RedisCacheConfiguration redisCacheConfiguration = determineConfiguration(cacheName, ttl);
                redisCacheConfigurations.put(cacheName, redisCacheConfiguration);

            }
            builder.withInitialCacheConfigurations(redisCacheConfigurations);
        }

        return builder.build();
    }

    private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfigurationDefault() {

        CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
        org.springframework.data.redis.cache.RedisCacheConfiguration config =
                org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();

        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }

    private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(String cacheName,long ttl) {
        org.springframework.data.redis.cache.RedisCacheConfiguration config =
                org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.entryTtl(Duration.ofSeconds(ttl));
        config = config.disableCachingNullValues();
        return config;
    }

}

application.properties
spring.redis.password=yichen
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=10
spring.redis.max.idle=10
spring.redis.max.total=30
spring.redis.max.wait.mills=-1

spring.cache.redis.time-to-live=60000
spring.cache.redis.key-prefix=test

spring.cache.redis.cache-expires.c3m=180
spring.cache.redis.cache-expires.c5m=300
spring.cache.redis.cache-expires.c10m=600
spring.cache.redis.cache-expires.c30m=1800
spring.cache.redis.cache-expires.c24h=86400
spring.cache.redis.cache-expires.c7d=604800
spring.cache.redis.cache-expires.c30d=2592000

RedisCacheExpiresProperties
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheExpiresProperties {
    private Map<String, Long> cacheExpires;
    public Map<String, Long> getCacheExpires() {
        return cacheExpires;
    }
    public void setCacheExpires(Map<String, Long> cacheExpires) {
        this.cacheExpires = cacheExpires;
    }
}

A: I think it's maybe a problem with the order the two configuration class (RedisConfig and CustomRedisCacheManagerConfiguration) were auto configured. Make sure you registered the class as auto configuration class and RedisConfig is auto configured before CustomRedisCacheManagerConfiguration.

A: When I try to replace @DependsOn("customRedisConnectionFactory") with @ConditionalOnBean(type = "RedisConnectionFactory"), it successfully executed.
Their differences and implementation details are to be studied.


text:
Q: Javascript - Calling two onClick functions I have this submit button on my website.
<form name="bbsform" action="<?=$PHP_SELF?>" method="post"
<input type="submit" value="Submit" onclick="this.disabled=true,this.form.submit();" />
</form>

The onClick part disables the submit button immediately after the first click, to prevent possible double submission of the form. And it perfectly works.
And I also have made this javascript function, too. Let's say it's called 'Guidance(bbsform)'.
Briefly, when a user forgot to complete one field in the form, it shows an alert message and focuses to the field.
(It work like that some invisible cursor is automatically clicking on the field, so the user can start typing right away.) This function works great too.
They both work great, well at least separately.
But when I combine them like this :
onclick="return Guidance(bbsform);this.disabled=true,this.form.submit();"

Only the Guidance function properly works.
Could you tell me what's wrong with the code?
Thank you for reading. I'm a newbie to this whole programming thing, so please be generous :)
Here is the Guidance function. Sorry none of the solutions worked.. It's really frustrating.
function Guidance(frm){

if(frm.subject.value == ""){

alert("Please complete the title field.");

frm.subject.focus();

return false;  }

try{ content.outputBodyHTML(); } catch(e){ }

 if(frm.content.value == ""){

    alert("Please complete the message field.");

frm.content.focus();    return false;  }

A: Well you will have to also post the Guidance function, but i guess all you have to do is return the guidance function with a true:
function Guidance(something){
    //do something

    return true;
}

A: Put the two JS into a single function, and then call that function onClick.

A: onclick="if (Guidance(bbsform)==true) {this.disabled=true;this.form.submit();} else {return false;}"

A: remove the 'return' in your onclick it's not getting to the second piece.
also you should look into unobtrusive javascript as a solution, then you could use an anonymous function to execute those two.

A: Solution by OP.
I couldn't find the right way to solve the problem directly, so I've found a workaround :)
I have found another function, and discarded 'onclick="this.disabled=true,this.form.submit();"'
The new JavaScript function I found is this - function SubmitOnce()
var submitted = 0;
function submitOnce() {
if(!submitted) {
  submitted ++;
  return true;
 }   else {
  return false;   }}

And I called the new function directly to the form onSubmit.
<form name="bbsform" action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data" onsubmit="return submitOnce()">

And later in the submit button code, I put in the Guidance function onClick.
<input type="submit" value="Submit" onclick="return Guidance(bbsform);" />

This works perfect! No double submission no matter what users do. (repeatedly hitting the Enter key, double - triple clicking, all of them submits only once!)


text:
Q: Theano dmatrix contains newaxis raise dimension mismatch The following is the snippet of the definition of theano variable and function for RBFNN.
# Theano Tensor Definition
    self.X = T.dmatrix('X')
    self.y = T.dmatrix('y')
    self.centers = T.dmatrix('centers')
    self.sigmas = T.dvector('sigmas')

    self.W = theano.shared(np.zeros((self.n_centers, self.n_classes)), 'W')
    self.b = theano.shared(np.zeros((self.n_classes,)), 'b')

    # Build Graph
    self.phi = T.exp(-T.sum(T.square(self.X[:, np.newaxis, :] - self.centers[np.newaxis, :, :]), axis=-1) / (
        2 * T.square(self.sigmas)))
    self.prob = T.mul(self.phi, self.W) + self.b
    self.pred = T.argmax(self.prob, axis=1)
    self.loss = T.mean(T.sum(T.square(self.y - self.prob), axis=1))
    self.W_grad = T.grad(self.loss, self.W)
    self.b_grad = T.grad(self.loss, self.b)
    self.updates = [(self.W, self.W - self.learning_rate * self.W_grad),
                    (self.b, self.b - self.learning_rate * self.b_grad)]

    # Build Function
    self.one_step = theano.function([self.X, self.y, self.centers, self.sigmas], [self.loss], updates=self.updates)
    self.compute_prob = theano.function([self.X, self.centers, self.sigmas], [self.prob])
    self.compute_pred = theano.function([self.X, self.centers, self.sigmas], [self.pred])

Then I feed the data
for i in xrange(max_iter):
    losses = []
    for batch in xrange(X.shape[0] / n_batch):
        losses.append(self.one_step(X[batch * n_batch:(batch + 1) * n_batch, :], y[batch * n_batch:(batch + 1) * n_batch, :], centers, sigmas)

where X, y is the train data and the centers and sigmas is the kmeans centers and the std of each centers.
It finally raise the error
ValueError: Input dimension mis-match. (input[0].shape[0] = 50, input[2].shape[0] = 10)
Apply node that caused the error: Elemwise{Composite{(i0 - ((i1 * i2) + i3))}}(y, Elemwise{Composite{exp(((i0 * i1) / i2))}}[(0, 1)].0, W, InplaceDimShuffle{x,0}.0)
Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix), TensorType(float64, matrix), TensorType(float64, row)]
Inputs shapes: [(50, 2), (50, 10), (10, 2), (1, 2)]
Inputs strides: [(16, 8), (80, 8), (16, 8), (16, 8)]
Inputs values: ['not shown', 'not shown', 'not shown', array([[ 0.,  0.]])]
Debugprint of the apply node:
Elemwise{Composite{(i0 - ((i1 * i2) + i3))}} [@A] <TensorType(float64, matrix)> ''
 |y [@B] <TensorType(float64, matrix)>
 |Elemwise{Composite{exp(((i0 * i1) / i2))}}[(0, 1)] [@C] <TensorType(float64, matrix)> ''
 | |TensorConstant{(1, 1) of -0.5} [@D] <TensorType(float64, (True, True))>
 | |Sum{axis=[2], acc_dtype=float64} [@E] <TensorType(float64, matrix)> ''
 | | |Elemwise{Composite{sqr((i0 - i1))}} [@F] <TensorType(float64, 3D)> ''
 | |   |InplaceDimShuffle{0,x,1} [@G] <TensorType(float64, (False, True, False))> ''
 | |   | |X [@H] <TensorType(float64, matrix)>
 | |   |InplaceDimShuffle{x,0,1} [@I] <TensorType(float64, (True, False, False))> ''
 | |     |centers [@J] <TensorType(float64, matrix)>
 | |Elemwise{sqr,no_inplace} [@K] <TensorType(float64, row)> ''
 |   |InplaceDimShuffle{x,0} [@L] <TensorType(float64, row)> ''
 |     |sigmas [@M] <TensorType(float64, vector)>
 |W [@N] <TensorType(float64, matrix)>
 |InplaceDimShuffle{x,0} [@O] <TensorType(float64, row)> ''
   |b [@P] <TensorType(float64, vector)>

Storage map footprint:
 - InplaceDimShuffle{x,0}.0, Shape: (1, 2), ElemSize: 8 Byte(s), TotalSize: 16 Byte(s)
 - TensorConstant{(1,) of 0.001}, Shape: (1,), ElemSize: 8 Byte(s), TotalSize: 8 Byte(s)
 - Elemwise{Composite{exp(((i0 * i1) / i2))}}[(0, 1)].0, Shape: (50, 10), ElemSize: 8 Byte(s), TotalSize: 4000 Byte(s)
 - X, Shape: (50, 4), ElemSize: 8 Byte(s), TotalSize: 1600 Byte(s)
 - y, Shape: (50, 2), ElemSize: 8 Byte(s), TotalSize: 800 Byte(s)
 - centers, Shape: (10, 4), ElemSize: 8 Byte(s), TotalSize: 320 Byte(s)
 - sigmas, Shape: (10,), ElemSize: 8 Byte(s), TotalSize: 80 Byte(s)
 - b, Shape: (2,), ElemSize: 8 Byte(s), TotalSize: 16 Byte(s)
 - TensorConstant{(1, 1) of -0.002}, Shape: (1, 1), ElemSize: 8 Byte(s), TotalSize: 8 Byte(s)
 - TensorConstant{(1,) of -2.0}, Shape: (1,), ElemSize: 8 Byte(s), TotalSize: 8 Byte(s)
 - TensorConstant{(1, 1) of -0.5}, Shape: (1, 1), ElemSize: 8 Byte(s), TotalSize: 8 Byte(s)
 - W, Shape: (10, 2), ElemSize: 8 Byte(s), TotalSize: 160 Byte(s)

Did self.X and self.center has the shape [50, newaxis, 4] and [newaxis, 10, 4]? Why it turns out [50, 4] and [10, 4]? Could you tell me how to solve it?

A: You can use test values to try and debug the issue while building the graph.


text:
Q: Angular refresh browser on redirect When running an angularjs application, the user access may be withdrawn from the server side. In this case, every request results in a http 302 redirect and a login html (no partial) page. Since angular does expect whatever it was requesting in case the access would still be given, it breaks as it may expect a json string but gets the html login page.
Is there anything I can do do catch this event (listen to redirects, figure out whether html is returned, etc) and do a "hard" refresh of the redirect url?

A: Since you can't interfere an ajax 302 response and redirect to an error page, you will need to be a little creative.
You can add a header or a different response code to your relevant responses and add an interceptor on the client end.
The interceptor is a module that every ajax request\response goes throught.
You can add code that will look for that header and simple perform a $window.location.href to the login page.
Read here about interceptors.
Check this example out - It handles 401 responses.

A: If I get you right you are talking about the $http Service from AngularJS.
If thats the point, you could transform the response by yourself and check if its valide JSON like this:
$http({
    url: '...',
    method: 'GET',
    transformResponse: function (reponse) {
        var ret = [];//if the return stays empty, the repsonse may be HTML
        try {
            ret = JSON.parse(reponse);
        } catch (error) {
            //here you could check for the error
        }
        return ret;
    }
}).success(function(answer){
    if(answer.length === 0){//its empty, so its probably HTML
        $window.location.reload();//refresh page here
        return;
    }
    //its JSON with content!
});


text:
Q: Boost::Asio Transferred bytes while using an async operation I'm using Boost::Asio HTTP Server 3 example (http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/examples.html)
but I need some "download information" such as number of transferred bytes in a certain amount of time in order to show a progress bar.
But how can I get this information if I'm using the boost::asio::async_write function? I know that I can access to boost::asio::placeholders::bytes_transferred in the handle_write completion handler but it is called just once asynchronous write operation has finished.
There is a way to do that?

A: You don't want to use the composed operation (boost::async_*).
Instead, roll your own composed operation that uses service_object.async_read_some repeatedly and report the progress where you want it.

*

*http://vinniefalco.github.io/beast/beast/core/tutorial.html


text:
Q: multidimensional array returns bad results with foreach I have a php class that interacts with mysql database and then fetches an array as a result.
$res = $db->getResult(); // $res is an array

I use it with print_r :
print_r($res);

and it outputs this:

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => Mohamed
            [lastname] => Kadri
        )

    [1] => Array
        (
            [id] => 2
            [firstname] => Slim
            [lastname] => Nejmaoui
        )

    [2] => Array
        (
            [id] => 3
            [firstname] => Sameh
            [lastname] => Chraiti
        )

And with foreach:
foreach ($res as $row) {
    echo $row['id'] . ' ' . $row['firstname'] . ' ' . $row['lastname'] . '
';
}

it outputs this:
1 Mohamed Kadri
2 Slim Nejmaoui
3 Sameh Chraiti

but when there is only one row, it shows this:
1 1 1
M M M
K K K

(1 is the id, M is the first letter in the firstname and K is the first letter in the lastname).
So maybe when there is more than one row the class generates a multidimensional array and the foreach will work on it, and when there is only one row it generates a simple array that will be treated as a multidimensional array by this exact foreach.
So should I make a condition to process one of two types of foreach?
Thanks.

A: Yep, it looks like that's exactly what's happening. Most likely, $db->getResult() returns the resulting row as an array (not sub-arrays within the result) when there is only one row returned from the query. So, you'll need to detect if there are nested arrays and handle appropriately:
if (isset($res[0]) && is_array($res[0])){
    foreach ($res as $row) {
        echo $row['id'] . ' ' . $row['firstname'] . ' ' . $row['lastname'] . '
';
    }
}else{
    echo $res['id'] . ' ' . $res['firstname'] . ' ' . $res['lastname'] . '
';
}

A: apparently your db object return a single array when you have only one result somthing like that:
Array
(
    [id] => 2
    [firstname] => Slim
    [lastname] => Nejmaoui
)

you can test first input and if this is not an array don't loop thrue the foreach else do a foreach
if( is_array(current($res)) ){
  // do the foreach...
}else{
  echo $res['id'] . ' ' . $res['firstname'] . ' ' . $res['lastname'] . '
';
}

I think you should change your db class to always return a nested array even on single row result to keep your results consistents.

A: Are you using CodeIgniter? Because it looks like you are. In CodeIgniter, when there is only one result, it only returns one array.
My suggestion? Create a support function (do_something_with_row below) and then call it conditionally:
if(count($res) > 1)
{
    foreach($res as $row)
    {
        do_something_with_a_row($row);
    }
}
else
{
    do_something_with_a_row($res);
}

A: You are iterating over one result-row in the case that is unclear to you.
What happens unnoticed to you is that $row then contains only scalar values:

*

*1 (int)

*Mohamed (string)

*KadriK (string)

This is the contents for $row already per each iteration (1-3).
These values are getting accessed with the substring access syntax that looks exactly like an array, making use of square brackets.
As all indezies 'id', 'firstname' and 'firstname' are interpreted as constants which are all undefined and result in 0, you're actually accessing the first character/byte in the string: 1, M and K.
With a newer version of PHP the 1 would not even be returned.
Now the important part: If you develop or you look for errors, enable the logging of notices. They warn you about such things:
PHP Notice:  Use of undefined constant Kadri - assumed 'Kadri' in ...

A quick setup can be done by adding this:
  error_reporting(-1);
  ini_set('display_errors', 1);