text:
Q: Equation of the line passing through $(3,-2,-5)$ and $(3,-2,6)$
Find the Cartesian equation of the line passing through $(3,-2,-5)$ and $(3,-2,6)$ in $3$D.

The equation of the line through the points $(x_1,y_1,z_1)$ and $(x_2,y_2,z_2)$ is given by
$$
\vec{r}=\vec{a}+\lambda(\vec{b}-\vec{a})
$$
where $\vec{a}=x_1\hat{i}+y_1\hat{j}+z_1\hat{k}$ and $\vec{b}-\vec{a}=(x_2-x_1)\hat{i}+(y_2-y_1)\hat{j}+(z_2-z_1)\hat{k}$
$$
\frac{x-x_1}{x_2-x_1}=\frac{y-y_1}{y_2-y_1}=\frac{z-z_1}{z_2-z_1}
$$
For the line through the points $(3,-2,-5)$ and $(3,-2,6)$ is
$$\lambda=
\boxed{\frac{x-3}{0}=\frac{y+2}{0}=\frac{z+5}{11}}
$$
Is it the correct solution and how do I make sense of the final equation of the line through the given points ?

A: I don't think we should divide by zero.
Observe the first two coordinates of the points.
They satisfy $x=3$ and $y=-2$.
The line is the intersection of $x=3$ and $y=-2$.
The formula is only used when $x_1 \ne x_2$, $y_1 \ne y_2$, and $z_1 \ne z_2$.

A: Set $A=(3,-2,-5)$, $B=(3,-2,6)$. As  any point on the line $(AB)$ is a barycenter $\lambda A+(1-lambda)B$ of $A$ and $B$, the coordinates of a point $M$ of this line are obtained by projections on the axes of this relation:
\begin{cases}
x_M=\lambda\cdot 2+(1-\lambda)2=2, \\
y_M=\lambda(-3)+(1-\lambda)(-3)=-3,\\
z_M=-5\lambda+6(1-\lambda)=6-11\lambda.
\end{cases}
This is a parametric representation, and we see that $z_M$ can take any real value, so the cartesian equations are:
\begin{cases}
x=2, \\
y=-3.
\end{cases}

A: In $2$-D, how would you find the line passing through $(3,-5)$ and $(3,6)$? Note that the formula
$$\frac{x-x_1}{x_2-x_1}=\frac{y-y_1}{y_2-y_1} \ \ \text{or} \ \ \frac{x-x_1}{y-y_1}=\frac{x_2-x_1}{y_2-y_1}$$
shows the slope of the line. Thus:
$$\frac{x-3}{y+5}=\frac{0}{11} \Rightarrow x-3=0 \Rightarrow x=3.$$
Indeed, it is a vertical line $x=3$ ($y$ can be any value).
Similarly, the line passing through $(3,-2,-5)$ and $(3,-2,6)$ is a vertical line $x=3,y=-2$ ($z$ can be any value).

A: By your work $\vec{(0,0,1)}$ is parallel to the line, which gives the answer:
$$(x,y,z)=(3,-2,-5)+t(0,0,1).$$

A: You have $$x=3, y=-2$$
For $z$ may use parametric form $$z=-5+11t$$
Thus your equation is $$r(t) = (3,-2,-5+11t)$$

A: To make sense of the Division by 0, we have to first see the derivation of this formula to understand what the denominator actually means in this formula.

Lets say, we need to write the function for the line $l$ and we have been given that the line passes through a fixed point $A$ and is parallel to vector $\vec B$ .
Now, let $\vec a = \vec {OA}$
Put the tail of $\vec b$ on $A$
We have $\vec r = \vec a + \lambda\vec b$ such that the tip of $\vec r$ always lies on line $l$.
If we write our results in cartesian form, where
$\vec r = x \hat{i}+y \hat{j} + z\hat{k}$
$\vec a = x_1 \hat{i}+ y_1 \hat{j} + z_1\hat{k}$
$\vec b = a \hat{i}+b \hat{j} + c\hat{k}$
Here, $(x_1, y_1, z_1)$ is the given point through which $l$ passes and $(a, b, c)$ are direction ratio of $\vec b$.
Putting these in the previously derived equation,
$$
\lambda=\frac{x-x_1}{a}=\frac{y-y_1}{b}=\frac{z-z_1}{c}
$$
This formula can be modified if two points are given since the direction ratio of the line passing through $(x_1, y_1, z_1)$ and $(x_2, y_2, z_2)$ would be just the difference of respective coordinates i.e $(x_2-x_1, y_2-y_1, z_2- z_1)$. So you just replace $(a, b ,c)$ with these coordinates to get your formula.
As you can see here, the denominators are actually the direction ratio of $\vec b$. So when you get
$$\lambda=
\boxed{\frac{x-3}{0}=\frac{y+2}{0}=\frac{z+5}{11}}
$$
what it actually means is that direction ratio(or cosine) of $\vec b$ along $X$ and $Y$ axis is $0$.
Remember direction cosine is actually the cosine of the angle made by a vector with the 3 axes.

So in this case, your
$$\boxed{cos(\alpha) = cos(\beta) = 0}$$
i.e
$$\boxed{\alpha = \beta = \frac{\pi}{2}}$$
So that would mean your line $l$ would make $90°$ with $X$ and $Y$ axis respectively.
Note that this does not mean that your line would be the $Z$ axis. Your line $l$ could be any line which which is perpendicular to the $XY$ plane.
From the given points you can try to visualise that $l$ will intersect $XY$ plane perpendicularly at point $(3, -2, 0)$


text:
Q: Bind ListBox to SelectionChanged ComboBox in XAML I want to bind the selection change of the combo box to update my list box, but my xaml code is probably wrong.
This is my Collection that takes the data from the Service.
public class WorkersCollection
{
    private WorkerClient client = new WorkerClient();
    public ObservableCollection<Worker> Workers { get; set; }

    public WorkersCollection()
    {
        Workers = new ObservableCollection<Worker>();
    }

    public ICollection<Worker> GetAllWorkers()
    {
        foreach (var worker in client.GetAllWorkers())
        {
            Workers.Add(worker);
        }

        return Workers;
    }
}

My DataContext is workers:
public partial class MainWindow : Window
{
    WorkersCollection workers;

    public MainWindow()
    {
        InitializeComponent();

        workers = new WorkersCollection();
        this.DataContext = workers;

        workers.GetAllWorkers();
    }
}

and in XAML:
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ComboBoxItem Content="{Binding LastName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem}" />

How can I fix it?

A: ItemsSource property of class ListBox has type IEnumerable (msdn).
So you can't assign to it object of type Worker.
You can create converter to do that.
Converter class:
public class WorkerToListConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return new List<Worker> { value as Worker };
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML code:
...
<Window.Resources>
        <local:WorkerToListConverter x:Key="myCon" />
</Window.Resources>
...
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" ItemsSource="{Binding Workers}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ComboBoxItem Content="{Binding LastName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}"
         ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem, Converter={StaticResource myCon}}" />
...

You should also delete SelectedItem binding from ComboBox.
   ... SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}" ...

It's no sense to binding SelectedItem to the same thing as ItemsSource.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Union of finitely many closed sets
(a) Show that the union of finitely many closed sets is closed.
(b) Give an example showing that the union of infinitely many closed sets may
fail to be closed.

(a)
Given that $ \bigcup_{k=1}^{n} C_k $ is closed if $ \left[ \bigcup_{k=1}^{n} C_k \right]^c $ is open.
,and $ \left[ \bigcup_{k=1}^{n} C_k \right]^c $ is open if  $\bigcap_{k=1}^{n} C_{k}^c$ is open.
As It was shown previously that $\bigcap_{k=1}^{n} C_{k}^c$ is open (I did this in a previous post Intersection of open sets?),  $ \bigcup_{k=1}^{n} C_k $ has to be closed.
(b) any hint for this part?
Regarding (a) Is my argumentation sufficient? is there a better alternative?
Much appreciated.

A: Your proof of (a) is o.k.
(b): $ \bigcup_{k=1}^{\infty}[\frac{1}{k},1]$

A: Your proof of (a) is OK.
In order to find a counter example (for dropping a requirement) you often can see this from the proof, but in this case you have to check the proof for the theorem that you're using, the proof where the requirement is really used.
The requirement is used in that proof by picking a point in the intersection (of open sets) and see that there's a disc around that that is within each open set and a disc with radius being the minimum of these is within the intersection (in fact you need only have the radius being a lower bound).
Here the finiteness is used to ensure that a set of radii has a minimum and that is positive.
To make that step fail you need to have an infinite set of radii that will have a lower bound of zero and that's easy to find. Just take $r_j = 1/j$. That is you pick a set of open discs with radius $1/j$ then their intersection is no longer open.
Then you just take the complement of these and get a counter example. That is $F_j = \{x: x\ge 1/j\} $ and see that $\bigcup F_j = \{x\ne 0\}$ which is not closed.

A: The union of finitely many closed sets is open.
The intersection of an arbitrary collection of closed sets is closed.


text:
Q: Enable SQL Server managed backup to Azure I was trying to Enable SQL Server managed Backup to Azure.
Using SAS token to create the Credentials in SQL.
CREATE CREDENTIAL [Container_name]    WITH IDENTITY = 'Shared Access Signature',   SECRET = 'Secret_Key'

I can see the credentials been created successfully. Then executing the Backup configuration.
EXEC managed_backup.sp_backup_config_basic
      @enable_backup =   1,
      @database_name = 'DB_Name',
      @container_url = 'Container_URL',
      @retention_days =  '10'

Throwing following Error,

Msg 45207, Level 17, State 17, Procedure
managed_backup.sp_add_task_command, Line 102 [Batch Start Line 15] The
operation failed because of an internal error. The argument must not
be empty string. Parameter name: sasToken Please retry later.
at Microsoft.WindowsAzure.Storage.Core.Util.CommonUtility.AssertNotNullOrEmpty(String
paramName, String value)    at
Microsoft.WindowsAzure.Storage.Auth.StorageCredentials..ctor(String
sasToken)    at
Microsoft.SqlServer.SmartAdmin.SmartBackupAgent.FileService.VerifyContainerURL(String
containerURL, SqlConnection conn)    at
Microsoft.SqlServer.SmartAdmin.SmartBackupAgent.SmartBackup.ConfigureDbOrInstance(SmartBackupConfigParameters
config, LogBaseService jobLogger, SqlConnection conn)

Tried with Different SAS Token, and the access.  But still facing same issue.


text:
Q: Updating external DBMS tables with SAS data using PROC SQL passthrough -- is this possible? I have a MS Access database. I am required to process and update tables in this database with SAS. The tables can be very large. Some of the processing requires the use of pure SAS functions. With a SAS/ACCESS LIBREF to MS Access, you cannot update or alter tables with PROC SQL. Therefore, I see two approaches:

*

*Using LIBREF: Copy the entire table into SAS. Delete the original table in Access. Process the table in SAS. Write the table back to Access.

*Using PROC SQL passthrough: Read the rows I need into SAS. Process these rows using SAS. Update the rows in Access.

My question: is number 2 even possible? With SQL functions (rather than SAS), the process outlined in number 2 is many orders of magnitude faster than number 1. I understand that this difference comes from the data being processed entirely by the DBMS, but number 2 would still have to be faster, right?

A: What I'd suggest is option 2, then use LIBREF to upload those rows to a temporary table, then use passthrough to update the bigger table.  It may be possible to update the rows directly via libref, but I'm not sufficiently familiar with SAS connection to Access to answer that part.

A: When using the LIBNAME statement to connect to an Access database, you need to add the option 'scan_text=no' in order to enable updating that databse.  You can then use MODIFY to change existing records or APPEND to add new records.  Below is some training code I wrote a while ago, this connects to Excel but the principle is the same for Access.
/* Create libname to Excel */
libname xl 'N:\SAS\Code\sas_training\sample_data\range.xls' scan_text=no; /* important to use this option */

/* Create table with updated values */
data xl_update;
input month a b c d;
cards;
200909 1 2 3 4
200910 5 6 7 8
200911 10 11 12 13
run;

/* Extract latest month from existing data */
proc sql noprint;
select max(month) into :maxmth
from xl.testdata;
quit;

/* Update existing values */
data xl.testdata;
modify xl.testdata xl_update (where=(month<=&maxmth.));
by month;
run;

/* Append new rows to exisiting data */
proc append base=xl.testdata
            data=work.xl_update (where=(month>&maxmth.));
run;

libname xl clear;

A: For future readers: I asked this question because SAS does not support a PROC SQL UPDATE statement on a MS Access library. To update an Access table, you must create a new table in the database and use a pass-through statement. My first instinct was to use an UPDATE statement assigning with a WHERE clause to update a subset of records. While I was researching this, I read some bad information that said Jet SQL did not support updating a subset of records. This is incorrect. Using an INNER JOIN, you are able to update a subset. Example code below:
/* Access database is "C:/database.mdb".
   Original table in database is "original".
   Processed table is "work.updates". */

libname mdbfile "C:/database.mdb";

proc sql;
create table mdbfile.updates as select * from work.updates;
connect to access (path="C:/database.mdb");
execute (
  update original as a inner join updates as b on a.id = b.id
  set a.variable1 = b.variable1
  where condition = 1
) by access;
execute (drop table updates) by access;
disconnect from access;
quit;


text:
Q: perl: What would cause perl to not find a file that exists? Running a perl cgi script I got the error it couldn't find the file it was trying to open. I check apache error log /var/log/apache2/error.log:
[Tue Jan 13 20:59:17 2015] [error] [client ::1] [Tue Jan 13 20:59:17 2015] submit.cgi: [Tue Jan 13 20:59:17 2015] submit.cgi:
/home/jddancks/Documents/perl/homeworks/hw13/grades4.txt: No such file or directory at /var/www/homeworks/hw13/CreateExam.pm line 48., referer: http://localhost/homeworks/hw13/test.cgi

double check:
root@debian-macbook:/var/log/apache2# ls -l /home/jddancks/Documents/perl/homeworks/hw13/grades4.txt
-rwxrwxrwx 1 jddancks jddancks 2095 Jan  7 12:25 /home/jddancks/Documents/perl/homeworks/hw13/grades4.txt

Why would this happen? This is a debian machine running apache 2.2 IDK if that helps.
There are 2 files: submit.cgi and CreateExam.pm.
submit.cgi:
use CreateExam;
...
my $path = `pwd`;
...
my $check = CreateExam->new("${path}/exam4.txt","${path}/answers4.txt","${path}/grades4.txt",$pathroot);
$check->entergrades($cookie_value,$cgi->Vars());

CreateExam.pm:
package CreateExam;

sub new {
    my ($class,$file,$answers,$grades,$script) = @_;
    #print "
in new: file: $file, grades: $grades
\n";
    return bless {'file'=>$file,'answers'=>$answers,'gradefile'=>$grades,'script'=>$script},$class;
}

sub tooktest {
    my ($self,$person) = @_;
    #print "
in tooktest: person: $person
\n";
    my $grades = $self->{'gradefile'};
    open(ANS,"< $grades") or die "$grades: $!";
    my $found = 0;
    LAST: while(my $line = <ANS>) {
        if($line =~ /\<test taker=$person/) { $found = 1; last LAST;}
    }
    return $found==1;
}

Data::Dumper:
$VAR1 = "/home/jddancks/Documents/perl/homeworks/hw13"; (in browser)

hexdump:
jddancks@debian-macbook:~/Documents/perl/homeworks/hw13$ perl -e 'print qx(pwd)' | hexdump -C
00000000  2f 68 6f 6d 65 2f 6a 64  64 61 6e 63 6b 73 2f 44  |/home/jddancks/D|
00000010  6f 63 75 6d 65 6e 74 73  2f 70 65 72 6c 2f 68 6f  |ocuments/perl/ho|
00000020  6d 65 77 6f 72 6b 73 2f  68 77 31 33 0a           |meworks/hw13.|
0000002d

A: As your hexdump shows, pwd returns the working directory followed by a newline, and that is what is you are assigning to $path.  Then you try to open "/home/jddancks/Documents/perl/homeworks/hw13\n/grades4.txt" which indeed has a directory that does not exist.
Try doing:
chomp( my $path = `pwd` );

A: If Apache is configured to run in a chroot it does not see /home on the host system at all.


text:
Q: Why does my tab don't change when clicking the button? I'm developing a new website, with a multi-step form where the steps are all in separated divs. The problem is: when i click in the first button, it shows the second page, but then it goes back to the first.
Here's my javascript code:

My html/php code for first two divs:

Olá!

Seja bem vindo(a) à empresa número 1 na pesquisa Google nesse modelo de férias. Bem como já temos mais de 11.300 inscritos no nosso canal no YouTube.

Parabéns!

Você foi pré-selecionado pelos nossos Analistas de Férias de Alto Padrão  para
                    participar de uma consultoria gratuita e exclusiva de férias onde na mesma você
                    conhecerá um método de viajar mais e melhor com sua família. Contudo o seu
                    tempo para gente vale ouro, então vamos te presentear com um brinde para que
                    você participe da consultoria. Leia até o final se você quiser saber qual é o brinde!

                <button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
                 Beleza! Quero Participar!

                </button>

Por que estou recebendo esse benefício?

Uauuuuuuuu, você é demais!!

Te parabenizamos por priorizar suas férias e novas experiências. Aliás, tudo passa e o
                    que fica são os momentos que vivemos com as pessoas que amamos. Afinal, qual é
                    a história que você vai contar?

Para começar, qual é o seu nome?

                    <input class="inputfield" style="margin-left:32%;"type="text" id="nome" name="nome">

                    <button class="btn" type="button" id="nextBtn" onclick="next(1)">

Avançar

                    </button>

I've put this online so you can see visually: https://testedeferias.000webhostapp.com/

A: You are using anchor tab and so your page is getting refreshed. The page refreshes and so the first tab by default is visible again. Try removing the a tag here:

    <button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
    Beleza! Quero Participar!

    </button>

Expected:
<button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
    Beleza! Quero Participar!

</button>


text:
Q: how to get content from external web page by php? I want get 'title'、'description'and'keywords' in a web page
I know 3 ways to implement this job:
a) use CURL
b) use fopen
c) use get_meta_data()
Strangely,each of the above does not work correctly every time.
for the same url:
Sometimes,I can get the content.
Sometimes,it return an error:'failed to open stream: HTTP request failed'
I'm confused.WHY?
help me : )

A: You can use file_get_contents("http://someurl.com"); to fetch an external website.
The result will be a string containing the entire HTML of the webpage. You can then parse that HTML using an HTML parser for PHP to get the information you need.
EDIT as noted by El Yobo, this feature can be disabled. To enable it you need to enable the fopen wrappers.

A: might be worth trying to find out what the error code is? are you trying to perform an HttpRequest on a 3rd party server - it could be that they are restricting you access, it could also be any number of other things including legitimate time-outs because your internet connection is no good so it might be worth posting some more data :-)

A: The "Sometimes" lets me think that there might be issues in your connection to the network ffrom your server. Have you tried to browse the page directly from the server, for instance using curl or wget?
Otherwise, I usually implement file_get_contents as advised by Luca.
http://www.php.net/manual/en/function.file-get-contents.php


text:
Q: Using ajax to constantly refresh php output from div I have php includes in different divs, how can i use ajax to constantly refresh the data outputted from the php file every second, I have multiple things that need to refresh, one per div

A: *

*Use the javascript function settimeout

*In the setimeout function, perform the ajax request

*Fill the div element with the results from the ajax request

*Again, use the settimeout function in the ajax response and perform the step 2 and 3.

A: send a ajax request per second.
window.setTimeout(function () {
    $.ajax({
        // param
    });
}, 1000);


text:
Q: Is it possible to read WebP images into a C# Bitmap object? I am using .NET Core 3.0 MVC app with a file upload for users. These files assumed to be an image, but for obvious reasons, I validate the image before saving it to the server.
Now I have ran into an issue, when a user tries to upload a JPEG image (which seems to be fine as he had to email it to me for further inspection) and this image seems to be a WebP image or was converted from a WebP Image.
The issue is that one of the check for each image is
using (var bitmap = new Bitmap(postedFile.OpenReadStream()))
{
}

This threw an exception "Parameter is not valid" and because of this, validation fails.
If I read the buffer of the uploaded IFromFile, it starts with RIFFڶ\0\0WEBPVP8
This is how I knew, this is not a normal image.
Any way to decode or validate this image as any other?


text:
Q: Color-charge conservation in proton decay In some extensions of the Standard Model of particle physics (Supersymmetry with R-parity violation being a prominent example), the proton is allowed to decay, e.g. via $p\to e^+\pi^0$:

While this decay is obviously violating the conservation of baryon and lepton number, I take it that color charge should still be conserved. My problem is that I don't see how this would work:
We have color-neutral objects in initial (the proton) and final state (the pion), but when I try to keep track of the color flow this fails, basically because I have to get rid of the third color charge somehow.
Is the simple picture of assigning each (anti-)quark an (anti-)color too much of a simplification to be applied here? What would be the color assignment of the intermediate particle $X$ in the proton decay?

A: It works if you assign colors like this: one red up, one green up, down is blue, $X$ takes red and green which are equivalent to antiblue ("yellow"), thus color is conserved. I didn't take into account the last fact which explains my confusion.

A: An other way to see the argument of  the answer of @fuenfundachtzig
 , is that, concerning $SU(3)$ representations, there is an equivalence between $(3*3)_\text{antisymmetrised}$ representation  ("red * green") and $3^*$ representation ("antiblue"). Why ? Well, thanks to the completely anti-symmetric Levi_Civita symbol. Using objects upon which act the representations, you could write $\psi^{rg} = \epsilon ^{rgd} \bar \psi_{d}$. This means that the representations $(3*3)_\text{antisymmetrised}$ and $3^*$, which have both dimension $3$, correspond to the same structure.

A: Realize that the independent conservation of 3 colors r,g,b that we are familiar with from QCD, i.e., the possibility of drawing continuous red, green and blue lines throughout the Feynman diagrams, is a consequence of both $SU(3)_c$ gauge symmetry and $U(1)_B$ baryon number global symmetry at the same time. For a more detailed explanation, look, e.g. here.
As you have written, in the BSM theory under your consideration the baryon number is not conserved, and hence drawing lines of 3 independent colors does not make a good sense.
Instead on counting numbers of red, green and blue fields in the initial and final state and, you can only look at the mutually commuting generators of $SU(3)$, which are, e.g., $\lambda_3$ and $\lambda_8$. It can be easily seen that both proton and pion are simultaneous eigenstates of both  $\lambda_3$ and $\lambda_8$ with both eigenvalues $0$ which is the precise meaning of being colorless. In this sense, color is conserved in the process on the picture.


text:
Q: CodeIgniter making the date helper output 12 hour format Using the Ci date helper, how would I turn '06/08/2012 17:10pm' into 12 hour format?
date('m/d/Y H:ia ', strtotime($row->entryCreationDateTime))

A: That code has nothing to do with CodeIgniter, it's simply PHP functions. For information on the date function, see the manual page.
The small chatacter h puts the hour in 12-hour format and capital chatacter H puts the hour in 24-hour format.
Change the code to this:
date('m/d/Y h:ia ', strtotime($row->entryCreationDateTime))


text:
Q: Implement different functions for different groupby objects pandas After doing some research, I found the following (Apply different functions to different items in group object: Python pandas). This is perhaps the exact same thing that I want, but I am unable to make sense of the answers that are being proposed. Let me try and explain with a simple example what I want:
import pandas as pd
import numpy as np

df = pd.DataFrame({'B': ['one', 'one', 'two', 'three',
                         'two', 'two', 'one', 'three'],
                   'C': np.random.randn(8),
                   'D': np.random.randn(8)})
grouped = df.groupby(['B'])

Let us say we have the simple data set built from the above that looks like this:
       B         C         D
0    one -1.758565 -1.544788
1    one -0.309472  2.289912
2    two -1.885911  0.384215
3  three  0.444186  0.551217
4    two -0.502636  2.125921
5    two -2.247551 -0.188705
6    one -0.575756  1.473056
7  three  0.640316 -0.410318

Upon grouping them on column 'B', there were 3 groups created

*

*one

*two

*three

Now, how can I apply different functions on these groups, but still have them as part of the same data frame. For e.g. if I wanted to check if elements were < 0.5 in group 1, divisible by 2 in group 2 and -ve  in group 3. These functions are for illustrative purposes only, the point I want to stress on is that they should be different custom functions that should be applied on each group, but the result should be something we can look at in one data frame. Any advice is appreciated.

A: You can use np.where to define whatever logic you want:
df['Flag'] = np.where((df['B'] == 'one') & (df['C'] < 0.5), True, False)
df['Flag'] = np.where((df['B'] == 'two') & (df['C'] >= 0.5), True, df['Flag'])
df['Flag'] = np.where((df['B'] == 'three') & (df['C'] < 0.5), True, df['Flag'])

Out[85]:
       B         C         D   Flag
0    one -1.758565 -1.544788   True
1    one -0.309472  2.289912   True
2    two -1.885911  0.384215  False
3  three  0.444186  0.551217   True
4    two -0.502636  2.125921  False
5    two -2.247551 -0.188705  False
6    one -0.575756  1.473056   True
7  three  0.640316 -0.410318  False

From there, let's say you then want to groupby the total that are True:
df = df.groupby('B')['Flag'].sum().reset_index()

       B    Flag
0    one     3.0
1  three     1.0
2    two     0.0

To implement as an adjustable custom function (per comment), you can do:
def flag(one, two, three):
    df['Flag'] = np.where((df['B'] == 'one') & (one), True, False)
    df['Flag'] = np.where((df['B'] == 'two') & (two), True, df['Flag'])
    df['Flag'] = np.where((df['B'] == 'three') & (three), True, df['Flag'])

flag(one=df['C'] < 0.5, two=df['C'] >= 0.5, three=df['C'] < 0.5)
df

B         C         D   Flag
0    one -1.758565 -1.544788   True
1    one -0.309472  2.289912   True
2    two -1.885911  0.384215  False
3  three  0.444186  0.551217   True
4    two -0.502636  2.125921  False
5    two -2.247551 -0.188705  False
6    one -0.575756  1.473056   True
7  three  0.640316 -0.410318  False


text:
Q: field validation in atk4 I remember a post from Romans pointing out different methods (3) of field validation in agile toolkit forms. Desperately searching but can't find it anywhere.
Anybody how can help me ?
Tks a lot
Clemens

A: Here are the 3 methods:
http://agiletoolkit.org/doc/form/validation


text:
Q: Populate a ComboBox with the Result of a Text Box I have a form in my Access database called:

*

*formAcademyRegister

Inside this form I have a combo box called:

*

*EmployeeCode

This combo box retrieves its data from a table called:

*

*Employees

The primary key on this field is EmployeeID
To make it easier for the user I created a form called formsEmployeeSearch. In this form use some text fields to make it easier to search for the employee using a first name or last name, returing the values to a list box on this form. This list box has three fields:

*

*EmployeeID

*FirstName

*LastName

All these fields are also populated using the Employees table so there won't be any data type issues.
Below the list box on the search form I have a button called

*

*butUpdateEmployeeID

When the button is clicked, I want the following to happen:

*

*The EmployeeCode combo box in the formAcademyRegister be updated with the employeeID as selected in the list in the formsEmployeeSearch form

*The formsEmployeeSearch to be closed

I am comfortable with the process of closing the form, I am however struggling with the code to populate that combo box with the value selected in the list box.
I tried the following:
Me.Form!formAcademyRegister!EmployeeCode = Me!lstEmpSearchResult.Value

But this is not working.

A: Try the below.
Forms.formAcademyRegister.EmployeeCode.Value = lstEmpSearchResult.Value
DoCmd.Close acForm, Me.Name, acSavePrompt

A couple of notes.

*

*The keyword Me is not required when the code is behind the form itself, but in some situations it makes the code more readable.

*The .Value property is default property (where applicable) thus can be omitted. It's best practice to keep it for clarity.

A: Me.Form is reference to current Form (where code is).
Forms is collection. Assignement to collection item "Collection(ItemNameOrItemIndex)
Forms("formAcademyRegister").cmbEmployeeCode.Value = Me.lstEmpSearchResult


text:
Q: Comparing Dates from custom field I am trying to compare dates from a custom field. I have them stored as something like "20121125". If the date has expired, a placeholder image will be used, if not, the default thumbnail will be used. Any advice is appreciated.
<?php
$html = "";
$key = get_post_meta($post->ID, 'Due', true);
$date = date('ymd');
if ($key >= $date) {
     the_post_thumbnail('medium');
} else {
    $html .= '';
}
return $html;
?>

A: Well, the exact server time/timestamp can be retrieve with current_time function. And comparing your date format, it would need to be Ymd. So combining these two thing, the proper comparison for you should be -
$key = get_post_meta( $post->ID, 'Due', true );
$date = date('Ymd', current_time('timestamp') );

if( $key >= $date )
{
    // note to retrive the post thumbnail, you need to use get_the_post_thumbnail,
    // as the_post_thumbnail function actually echo the output
    $html .= get_the_post_thumbnail(null, 'medium');
}
else
{
    $html .= '';
}
return $html;

Now, there could be one question in which timezone you are saving the date in the post meta. If the value is sanitized with the server time (as the post_date value is saved), then this is perfect comparison.

A: You can try this:
<?php
$html = "";
$key = get_post_meta($post->ID, 'Due', true);
date_default_timezone_set('Africa/Lagos'); //Only if needed. Change this for your timezone
if (strtotime($key) >= time()) {
     the_post_thumbnail('medium');
} else {
    $html .= '';
}
return $html;
?>

Here we are using the strtotime function to help us compare these two dates.
You can find more information here:

*

*Comparing dates in PHP

*Change the default timezone
Hope it helps.

A: You can store the date after coonverting to timestamp using custom fields(i.e. in post_meta table). By doing so you will be able to compare dates easily. Then you can use your code as follows:
<?php
$html = "";
$stored_timestamp = get_post_meta($post->ID, 'Due', true);
$current_timestamp = strtotime(date('Y-m-d'));
if ($stored_timestamp >= $current_timestamp) {
    the_post_thumbnail('medium');
} else {
    $html .= '';
}
return $html;
?>

Store timestamp as:
update_post_meta($post->ID,'Due',strtotime(date('Y-m-d'));


text:
Q: post custom form request I need to insert a form into one tab contained into product page.
you can see an example in this page
I created a static block that contain the form, the action is a cms page.
so, I need to insert a php function that send me the data insert into the form.
How can I do this action?

A: Set your action of form as
<form action="<?php echo $this->getUrl('module/controller/method'); ?>" >

Then create a controller with the corresponding method.
function Name(){
if ($data = $this->getRequest()->getPost()) {

    $model = Mage::getModel('module/model_name');
    $model->setData($data);
    try {
        $model->save();
    }catch (Exception $e) {
        $this->_forward('NoRoute');
    }
}

To send email do following
$translate = Mage::getSingleton('core/translate');

            /* @var $translate Mage_Core_Model_Translate */

            $translate->setTranslateInline(false);

            try {

                $postObject = new Varien_Object();

                $postObject->setData($data);

                $mailTemplate = Mage::getModel('core/email_template');

                /* @var $mailTemplate Mage_Core_Model_Email_Template */

                $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                    ->sendTransactional(
                        'test_email_template',
                        'general',
                        'receiver_email_id', null, array('data' => $postObject)
                    );

                $translate->setTranslateInline(true);

            } catch (Exception $e) {

                $translate->setTranslateInline(true);

            }

A: Try this
try{
    $mail = new Zend_Mail();
    $mail->setFrom("fromemail","fromname");
    $mail->addTo("toemail","toname");
    $mail->setSubject("subject");
    $mail->setBodyHtml(" body text");
    $mail->send();
}catch(Exception $e){
    echo $e->getMassage();
}

Hope,It may work for you..


text:
Q: Getting "Bad System Call" working with seccomp filters I have just started learning about seccomp filters and I am using libseccomp v2.4.4. I tried to write a basic whitelisting filter that will only allow writing to the file named file1 but I am getting a "Bad system call" message in STDOUT. Here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <seccomp.h>
#include <stdlib.h>
#include <errno.h>

int main(void)
{
        FILE *fil = fopen("file1", "w");
        scmp_filter_ctx filter = seccomp_init(SCMP_ACT_KILL);

        if (filter==NULL || NULL==fil)
                goto End1;

        int chk1 = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,
                                    SCMP_A0(SCMP_CMP_EQ, fileno(fil)));
        int chk2 = seccomp_load(filter);
        if (chk1<0 || chk2<0)
                goto End;

        fprintf(stdout,"Filter did not work correctly\n");
        fprintf(fil,"Filter worked correctly\n");

End:
        seccomp_release(filter); //releasing filter before closing file
        fclose(fil);

End1:
        return 0;
}

Additionally, I see no output in file1. I am just a beginner and unsure about a lot of things here as I have written the code from my understanding, not from some reference. What seems to be the issue?

Edit: I removed the filter completely and simply executed
int main(void)
{
        FILE *fil = fopen("file1", "w");

        fprintf(stdout,"Filter did not work correctly\n");
        fprintf(fil,"Filter worked correctly\n");

End:
        fclose(fil);

End1:
        return 0;
}

Stracing this I observed that syscalls fstat,close as mentioned in the answer below by @pchaigno and additionally mmap,munmap were being called. So I must allow these syscalls for the expected behaviour.

A: Debugging
Stracing your application will reveal the issue:
$ strace ./test
[...]
seccomp(SECCOMP_SET_MODE_FILTER, 0, {len=12, filter=0x55ace60a6600}) = 0
fstat(1,  <unfinished ...>)             = ?
+++ killed by SIGSYS (core dumped) +++
Bad system call (core dumped)

Allow minimum set of syscalls
You need to allow a lot more syscalls than just write(2) for the end of your program to proceed without errors.
You'll need fstat(2) for fprintf(), close(2) for fclose(), and exit_group(2) to end the process.
Deny syscall instead of killing process
In addition, if you want your program to continue running after an unauthorized syscall, you shouldn't kill it with SCMP_ACT_KILL. SCMP_ACT_ERRNO(EPERM) is probably more appropriate in this context.
Result
int main(void) {
        FILE *fil = fopen("file1", "w");
        scmp_filter_ctx filter = seccomp_init(SCMP_ACT_ERRNO(EPERM));
        if (filter == NULL || NULL == fil)
                return 1;
        if (seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(write), 1, SCMP_A0(SCMP_CMP_EQ,fileno(fil))) < 0)
                goto err;
        if (seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(fstat), 0) < 0)
                goto err;
        if (seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(close), 0) < 0)
                goto err;
        if (seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0) < 0)
                goto err;
        if (seccomp_load(filter) < 0)
                goto err;
        fprintf(stdout, "Filter did not work correctly\n");
        fprintf(fil, "Filter worked correctly\n");
err:
        seccomp_release(filter); //releasing filter before closing file
        fclose(fil);
        return 0;
}

gives us:
$ ./test; echo file1
Filter worked correctly


text:
Q: In C++, when an element of an array is used multiple times in a loop, is it better to assign it to an other element? Let's say I have a loop that will do some math on an array x. Is it better to assign a temporary double inside the loop at each iteration or should I use the array[i] every time?
By better I mean performance-wise using C++. I wonder if C++ has some vectorization or cash optimization that I'm ruining?
Also what if I call a function using this array and I might need values of a function multiple times, so I usually do the same with functions. I assume this would be better than calling the function many times.
How about if the loop uses omp parallel, I assume this should be safe, correct?
for(int i=0; i<N; i++){
    double xi = X[i];
    double fi = f(xi);
    t[i] = xi*xi + fi + xi/fi;
}

A: elcuco is correct. Any compiler worth it's salt will be able to optimise out something this trivial. What matters here is code readability, personally i find X[i] to be a little easier to look at in this situation.
I will note that if you are repeatedly making very long statements i.e X.something.something.darkside[i][j] it might make sense to use a clearly named reference i.e auto & the_emperor = X.something.something.darkside[i][j].

A: Modern compilers (last 10 years) will optimise it out. Don't worry about it.
EDIT:
This has been discussed in StackOverflow a few times:
Will compiler optimize and reuse variable
In C++, should I bother to cache variables, or let the compiler do the optimization? (Aliasing)
This official documentation explains it, IMHO it is
-fmerge-all-constants -fivopts and maybe -ftree-coalesce-vars clang and MSCV have similar options, feel free to research them yourself or link them here.
In practice, when a compiler sees a memory read (a variable, or array value) it will read it into a register, and unless that not marked as volatile, the compiler can assume it did not change, and will not issue instructions to re-read it.
Having said the magical volatile word: It should not be used for threading. It should be used for hardware mapped memory (for example, video card memory or external ports).


text:
Q: ¿Cómo crear una lista, la cual sus valores están relacionados con otras listas? Quisiera hacer una lista población , la cual arranca con población[0] = 100000 y luego quiero ir agregando items dependiendo de otras listas, nac[] y mort[].
Por ejemplo:
nac[0] = poblacion[0] * n_t
mort[0] = poblacion[0] * m_t

para el poblacion[1] = poblacion[0] + nac[1] + mort[1]
pop = 100000
t = 50 # tiempo
t_m = 0.008
t_n = 0.01

poblacion = []
aux = []
nac = []
mort = []

a = pop * t_n
b = pop * t_m

poblacion.append(pop)
nac.append(b)
mort.append(a)

print(poblacion,nac,mort)

for i in range(t):

    #poblacion.clear()
    i = pop
    poblacion.append(i)

    i = a
    nac.append(i)

    i = b
    mort.append(i)

for j, v, x in zip(range(t), range(t), range(t)):

    j = poblacion[j]+nac[t]-mort[j]
    poblacion.append(j)

    v = poblacion[v]*t_n
    #nac.clear()
    nac.append(v)

    x = poblacion[x]*t_m
    mort.append(x)

print(poblacion)
print(nac)
print(mort)
print(aux)
print(len(poblacion))
print(len(nac))
print(len(mort))
print(len(aux))

No se si alguien tuviera un ejemplo de como hacerlo, había pensado en hacerlo con recursividad pero la verdad que no tengo mucha experiencia.

A: Si lo he entendido, no necesitas complicarte demasiado, simplemente debes desplazar el cálculo de la población:
pop = 100000
t = 5 # tiempo
t_m = 0.008
t_n = 0.01

población = []
nac = []
mort = []

for _ in range(t + 1):
    población.append(pop)
    nacimientos = int(round(pop * t_n))
    muertes = int(round(pop * t_m))
    pop = pop + nacimientos - muertes
    mort.append(muertes)
    nac.append(nacimientos)

print(población)
print(nac)
print(mort)

[100000, 100200, 100400, 100601, 100802, 101004]
[1000, 1002, 1004, 1006, 1008, 1010]
[800, 802, 803, 805, 806, 808]

El cálculo en este caso es:
    población[0] = pop
    poblacion[1] = poblacion[0] + nac[0] - mort[0]
    poblacion[2] = poblacion[1] + nac[1] - mort[1]
    ...

Otra opción sería que fuera:
    población[0] = pop
    poblacion[1] = poblacion[0] + nac[1] - mort[1]
    poblacion[2] = poblacion[1] + nac[2] - mort[2]
    ...

pero en este caso lo apropiado es que mort[0] y nac[0] sean ambos 0:
pop = 100000
t = 5 # tiempo
t_m = 0.008
t_n = 0.01

población = [pop]
nac = [0]
mot = [0]

for _ in range(t):
    nacimientos = int(round(pop * t_n))
    muertes = int(round(pop * t_m))
    pop = pop + nacimientos - muertes
    población.append(pop)
    mot.append(muertes)
    nac.append(nacimientos)

print(población)
print(nac)
print(mot)

[100000, 100200, 100400, 100601, 100802, 101004]
[0, 1000, 1002, 1004, 1006, 1008]
[0, 800, 802, 803, 805, 806]

Asumo que estás trabajando con una población, tasa de natalidad y tasa de mortalidad, por eso he redondeado al entero más cercano dado que en principio no existen individuos medio nacidos o medio muertos ni poblaciones con una fracción de un individuo :). Además resto mort en vez de sumarlo a la población.

A: Son varias lineas a corregir, por ejemplo, el primer for no es necesario, pues estás llenando con 50 elementos iguales las 3 listas. En el segundo for vuelves y agregas otros 50 elementos mas. No es necesario iterar por las 3 listas.
Yo lo dejaría así:
pop = 100000
t = 50 # tiempo
t_m = 0.008
t_n = 0.01

poblacion = [pop]
nac = [0]
mort = [0]

print(poblacion)
print(nac)
print(mort)

for i in range(t):
    nac.append(poblacion[i] * t_n)
    mort.append(poblacion[i] * t_m)
    poblacion.append(poblacion[i] + nac[i-1] - mort[i-1])

    print("{0:d}: Pob: {1:.0f} - Nac: {2:.0f} - Mort: {3:.0f}".format(i, poblacion[i], nac[i], mort[i]))

print(len(poblacion), len(nac), len(mort))


text:
Q: iOS blur shadow effect with image color What is the best way to achieve the desired effect in Swift?
I want to have a shadow of the same color as image card.
I've tried using UIVisualEffectView below UIImageView but without success.

A: just found this library, see if this one helps.
ShadowImageView


text:
Q: Is it OK to have Microsoft Visual C++ Redistribuable installed several time (same year / CPU / version)? If I go to Programs > Programs and features on my computer, I have Microsoft Visual C++ Redistribuable item installed several times, for the same year and for the same CPU target (x86 or x64). Sometimes, even version is the same (only install date is different).

Is this OK or, should I uninstall the duplicates (and only keep latest version ?)

A: There is no need for having multiple copies of same versions of VC++ Redistributables, they provide same libraries for the programs which use them.
However, It's okay to install multiple versions of VC++ as their libraries are different and many programs need specific version of those.
You can uninstall the duplicate copies of same version.
Note: It is possible that there is one copy of actual libraries on your system and there are two entries in programs' list (The latest entry might have replace the old files). If you like, you can uninstall all version of VC++, and install the fresh copy of those (all versions 2005, 2008, 2010, 2012, 2013 & 2015; both x64 & x86).


text:
Q: why there is a difference between calling (call) on a method and calling the method on the obj sorry I really should of asked why there is a differnce ,
`Object.prototype.toString.call(o).slice(x,y);`

and this?
o.toString().slice(x.y);

// why those are different , call should change the 'this' value for the called method
// and toString is already inherited ,
var x = 44 ;

`Object.prototype.toString.call(x)`; //"[object Number]"

x.toString(); // '44'

A: You're not calling .call on the method here:

Object.prototype.toString(o).slice(x,y);

Instead, you just call the method (on the prototype object) with o  as an argument.
To get an equivalent method to call to

o.toString().slice(x.y);

(which calls the method on the o object, with no arguments), you will need to use
o.toString.call(o).slice(x.y);

Why is x.toString() different from Object.prototype.toString.call(x)?

Because x = 44 is a number, and when you access x.toString you get the Number.prototype.toString method not the Object.prototype.toString method. You could also write
Number.prototype.toString.call(x)

to get "44".

A: Use second one and check the difference between a class (your first case) and an instance of that class (second case).
http://en.wikipedia.org/wiki/Instance_(computer_science)
Its a general object oriented programming issue common for all languages.

*

*First is the general definition of the type (without any specific data) - you call it wrong

*The second one is a particular instance with own data (can be multiple)

Anyway:
Object.prototype.toString(o) returns "Object object" so it's not working for you well.

A: The first one (Object.prototype.toString) calls the built in or default toString function for objects, the second calls the toString function of o, which may or may not have been overwritten
var o = {};
o.toString();
    // "[object Object]"
o.toString = function(){};
o.toString();
    // undefined
Object.prototype.toString.call(o);
    // "[object Object]"

With a number, such as 44, the toString function is different from a objects. Calling the toString function of a variable with the value 44, will actually do Number.prototype.toString.call(). Hence the different output.
a few different types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString


text:
Q: Contiki 3.0 - Sky mote not connecting properly Running ubuntu 16.04, x64. I installed contiki 3.0 without VMware (I'm under the impression I don't need it since I am running ubuntu).
I'm trying to perform the command sudo make hello-world.upload using saved target sky. I've scoured the internet and not found a fix that has work for me yet. However, I keep getting the code below:
using saved target 'sky'
msp430-objcopy hello-world.sky -O ihex hello-world.ihex
make IHEXFILE=hello-world.ihex sky-reset sky-upload
make[1]: Entering directory '/home/liam/contiki/examples/hello-world'
using saved target 'sky'
make -k -j 20 sky-reset-sequence
make[2]: Entering directory '/home/liam/contiki/examples/hello-world'
using saved target 'sky'
../../tools/sky/msp430-bsl-linux --telosb -c /dev/ttyUSB1 -r
MSP430 Bootstrap Loader Version: 1.39-telos-7
Use -h for help
Reset device ...
Done
make[2]: Leaving directory '/home/liam/contiki/examples/hello-world'
make -j 20 sky-upload-sequence
make[2]: Entering directory '/home/liam/contiki/examples/hello-world'
using saved target 'sky'
+++++ Erasing /dev/ttyUSB1
MSP430 Bootstrap Loader Version: 1.39-telos-7
Use -h for help
Mass Erase...
Transmit default password ...
+++++ Programming /dev/ttyUSB1
MSP430 Bootstrap Loader Version: 1.39-telos-7
Invoking BSL...
Transmit default password ...
Current bootstrap loader version: 1.61 (Device ID: f16c)
Changing baudrate to 38400 ...
Program ...
42978 bytes programmed.
+++++ Resetting /dev/ttyUSB1
MSP430 Bootstrap Loader Version: 1.39-telos-7
Use -h for help
Reset device ...
Done
make[2]: Leaving directory '/home/liam/contiki/examples/hello-world'
make[1]: Leaving directory '/home/liam/contiki/examples/hello-world'
rm hello-world.ihex

To my understanding, this did not run correctly and breaks the subsequent command, make login which gives me:
using saved target 'sky'
../../tools/sky/serialdump-linux -b115200 /dev/ttyUSB1
connecting to /dev/ttyUSB1 (115200)
open: Invalid argument
../../platform/sky/Makefile.common:193: recipe for target 'login' failed
make: *** [login] Error 255

I think this means that the mote is not properly connected somehow??
With make motelist I receive back that my device is in /dev/ttyUSB1, which makes me think that it is properly connected. I've also checkmakefile against this and it seems to be fine.
Could someone advise me how to fix this?
Thank you for your time.

A: You need to change your serialdump-linux execution file in the contiki/tools/sky folder and follow the steps given in the link..
1) http://anrg.usc.edu/contiki/index.php/Hello_World
Everey thing is given clearly in the above link
The above documentation is really good as of now I am also a newbie in this area.
http://anrg.usc.edu/contiki/index.php/


text:
Q: Dynamic/Expando and JSON There's a lot of Qs on this, but I need a solution without JSON.Net, etc. - I must use the canned stuff in Asp.Net MVC.
How can I serialize a POCO with a dynamic property - and get all the static properties, too?  What I found was the dynamic only, or the static type which is easy.
e.g.
public class ReturnThisClassAsJSON {
    public int Id {get; set; }
    public string Name { get; set; }
    public ContainedClass ContainedContents { get; set; }
}

public class ContainedClass {
    public int Order { get; set; }
    public string Label { get; set; }
    public dynamic DynamicInfo { get; set; }
    public List<dynamic> DynamicList { get; set }
}

A: My own answer:
I replaced the dynamic from the DynamicInfo and DynamicList from the ContainedClass with static types.
With the dynamic, I had 1 of 2 choices.  Either serialize the dynamic to a string in its own serialization call using above SO question 5156664. (Which left me with the rest of the class I also wanted serialized and merged with it, thus this question).  Or, incur this error:
"A circular reference was detected while serializing an object of type 'System.Reflection .RuntimeModule' ".
when attempting a single serialization call on the ContainedClass.
So, I transferred the dynamics into static-typed classes:
public class ColumnValue
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class DynamicRow
{
    public List<ColumnValue> ColumnValue { get; set; }
}

and, change ContainedClass to this:
public class ContainedClass
{
    public List<ColumnValue> DynamicInfo { get; set; }
    public List<DynamicRow>  Data { get; set; }
}

And, it serializes using out-of-the-box Asp.Net MVC:
 return Json(ReturnThisClassAsJSON, JsonRequestBehaviour.AllowGet);


text:
Q: Why doesn't the memory being used by a program change, when more memory allocations are done? I have the following program:
int main(int argc,char **argv){
  double*a;
  double*b;
  double*c;
  double*d;
  double*e;
  double*f;
  double*g;
  double*h;
  double*i;
  double*j;
  double*k;
  double*l;
  double*m;
  double*n;
  double*o;
  double*p;
  double*q;
  while(1){
    a=malloc(1000000*1000000000000*sizeof(double));
    b=malloc(1000000*1000000000000);
    c=malloc(1000000*1000000000000);
    d=malloc(1000000*1000000000000);
    e=malloc(1000000*1000000000000);
    f=malloc(1000000*1000000000000);
    g=malloc(1000000*1000000000000);
    h=malloc(1000000*1000000000000);
    i=malloc(1000000*1000000000000);
    j=malloc(1000000*1000000000000);
    m=malloc(1000000*1000000000000);
    n=malloc(1000000*1000000000000);
    o=malloc(1000000*1000000000000);
    p=malloc(1000000*1000000000000);
    q=malloc(1000000*1000000000000);
  }
}

and the task manager issues the following memory usage:

I, then, changed the program to
int main(int argc,char **argv){
  double*a;
  while(1){
    a=malloc(1000000*1000000000000*sizeof(double));
  }
}

compiled it, and task manager showed:

Shouldn't memory usage be higher in the first program? What am I missing here?

A: Memory allocators like the glibc memory allocator have memory limits. This means making huge allocations could end up on a failed allocation. A NULL pointer is returned in such cases.
Check out return value of those mallocs to see what is happening, tho it is obvious that the request is too long to be allocated.


text:
Q: How to create a incremental variable in a position of list on Robot Framework I'm trying to do a test that lists all of the configuration files in a folder and performs one configuration at a time, but I don't know how to insert an incremental variable at the position of the list. In my code below, only the first file of the first position is loaded. Can anyone help a robot beginner?

    ${list} =   List Files in Directory     ${input_folder}
    ${lista} =  Create List     ${list}
    ${number_files} =   BuiltIn.Get Length    ${list}

    :FOR    ${i}     IN   ${lista}
        Run Process        python     aster_scripts/setup_transform.py       --input-yaml   ${input_folder}${lista[0][0]}
        Generate plan
    END```

A: For using a list in a list content you need to use @
*** Settings ***
Library     OperatingSystem

*** Test Cases ***
List Files
    @{list}=      List Directory     ${EXECDIR}

    FOR    ${filename}     IN   @{list}
        Log To Console  ${filename}
    END

It is also possible to use a list with $. As far as I can see it is not documented but ${list} is some kind of a "reference to list" Perl's style. It is not exactly like that but it helps me understand it. So with ${list} you can pass a list to a keyword as a scalar.


text:
Q: How to center a bar button item in navigation bar in swift using storyboard? I'm trying to have 3 bar button items in my navigation bar in my swift project.
I can drag/drop the buttons in my navigation bar using storyboard but the buttons will go to the left or right of the navigation bar!
I need to have 1 of these 3 buttons to sit in the middle of the navigation bar so I can use it as a Logo.
I've tried to use the Flexible space bar item as well with no success. I have nothing else in my navigation bar other than these 3 buttons.
could someone please advice on this issue?


text:
Q: How to prevent iTerm2's Hotkey Window from changing desktop? I've configured Hotkey Window to slide down from top when global hotkey is pressed (like console). But when I do that when maximized window is active it switches to a desktop. Is there a way to prevent that? I want terminal to just slide over fullscreen window.

A: iTerm developers answered that this feature is already in a nightly build


text:
Q: VSCode + Remote - SSH + VS Code Debugger for Firefox, How? So, I'm trying to get the vscode-firefox-debug to play.
It, vscode-firefox-debug, claims to be compatible with vscode remote.
How do I configure this thing, to work with my remote?
All my development is done on a remote headless server, running Slackware64 14.2
Let's call that box www.example.com.
My local box is a Windows 8.1 x64 Pro with:
Firefox 69.0.1 (64-bit)
Visual Studio Code
Version: 1.38.1 (system setup)
Commit: b37e54c98e1a74ba89e03073e5a3761284e3ffb0
Date: 2019-09-11T13:35:15.005Z
Electron: 4.2.10
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Windows_NT x64 6.3.9600

I run firefox with "C:\Program Files\Mozilla Firefox\firefox.exe" -start-debugger-server
I've got the Remote-SSH and friends setup, and working nicely with vscode-php-debug and XDebug.
Adding to launch.json on remote server. I got a few variations I've tried:
First try
    {
      "name": "Launch localhost",
      "type": "firefox",
      "request": "launch",
      "reAttach": true,
      "url": "http://localhost/index.html",
      "webRoot": "${workspaceFolder}"
    },

Second try
    {
      "name": "Attach localhost",
      "type": "firefox",
      "request": "attach",
      "url": "http://localhost/index.html",
      "webRoot": "${workspaceFolder}"
    },

Third try
    {
      "name": "Launch index.html",
      "type": "firefox",
      "request": "launch",
      "reAttach": true,
      "port": 6000,
      "file": "${workspaceFolder}/index.html",
      "url": "https://www.example.com/index.html",
      "webRoot": "${workspaceFolder}"
    },

And I get a Notification in debug console, saying:
Firefox can't open a file in a remote workspace

Last try
    {
      "name": "Attach index.html",
      "type": "firefox",
      "request": "attach",
      "port": 6000,
      "url": "https://www.example.com/",
      "webRoot": "${workspaceFolder}"
    },

A: Follow the link to help you:
https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug
Example to run on server to start manually xdebug while debug by SSH the file on local VS code IDE is:
$ php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=127.0.0.1 -dxdebug.remote_connect_back=1 /var/www/html/teste.php


text:
Q: What's the opposite of chr() in Ruby? In many languages there's a pair of functions, chr() and ord(), which convert between numbers and character values. In some languages, ord() is called asc().
Ruby has Integer#chr, which works great:
>> 65.chr
A

Fair enough. But how do you go the other way?
"A".each_byte do |byte|
   puts byte
end

prints:
65

and that's pretty close to what I want. But I'd really rather avoid a loop -- I'm looking for something short enough to be readable when declaring a const.

A: If String#ord didn't exist in 1.9, it does in 2.0:
"A".ord #=> 65

A: Just came across this while putting together a pure Ruby version of Stringprep via RFCs.
Beware that chr fails outside [0,255], instead use 1.9.x - 2.1.x portable replacements:
[22] pry(main)> "\u0221".ord.chr
RangeError: 545 out of char range
from (pry):2:in 'chr'
[23] pry(main)> x = "\u0221".unpack('U')[0]
=> 545
[24] pry(main)> [x].pack('U')
=> "ȡ"
[25] pry(main)>

A: In Ruby up to and including the 1.8 series, the following will both produce 65 (for ASCII):
puts ?A
'A'[0]

The behavior has changed in Ruby 1.9, both of the above will produce "A" instead.  The correct way to do this in Ruby 1.9 is:
'A'[0].ord

Unfortunately, the ord method doesn't exist in Ruby 1.8.

A: Additionally, if you have the char in a string and you want to decode it without a loop:
puts 'Az'[0]
=> 65
puts 'Az'[1]
=> 122

A: How about

puts ?A

A: You can have these:
65.chr.ord
'a'.ord.chr

A: If you don't mind pulling the values out of an array, you can use "A".bytes

A: Try:
'A'.unpack('c')

A: I'd like to +1 dylanfm and AShelly's comment but add the [0]:

'A'.unpack('C')[0]

The unpack call returns an Array containing a single integer, which is not always accepted where an integer is wanted:

$ ruby -e 'printf("0x%02X\n", "A".unpack("C"))'
-e:1:in `printf': can't convert Array into Integer (TypeError)
    from -e:1
$ ruby -e 'printf("0x%02X\n", "A".unpack("C")[0])'
0x41
$

I'm trying to write code that works on Ruby 1.8.1, 1.8.7 and 1.9.2.
Edited to pass C to unpack in uppercase, because unpack("c") gives me -1 where ord() gives me 255 (despite running on a platform where C's char is signed).

A: I'm writing code for 1.8.6 and 1.9.3 and I couldn't get any of these solutions to work in both environments :(
However, I came across another solution:
http://smajnr.net/2009/12/ruby-1-8-nomethoderror-undefined-method-ord-for-string.html
That didn't work for me either but I adapted it for my use:

unless "".respond_to?(:ord)
  class Fixnum
    def ord
      return self
    end
  end
end

Having done that, then the following will work in both environments

'A'[0].ord


text:
Q: Removing shadows from UIWebView I use a web view to display small pdf files. In the interest of aesthetics, I'd like to remove the grey border around the PDF. Is there any way around it? I've looked at various resources none of which seem to work or the solution no longer works in iOS5.
Also, is there any way of stopping the scroll if there's only one page?
Thanks.

A: The shadows are actually UIImageView subviews of the UIScrollView (or the equivalent in iOS5 UIWebView).
So in iOS4:
for (UIView* subView in [webView subviews])
{
    if ([subView isKindOfClass:[UIScrollView class]]) {
        for (UIView* shadowView in [subView subviews])
        {
            if ([shadowView isKindOfClass:[UIImageView class]]) {
                [shadowView setHidden:YES];
            }
        }
    }
}

and in iOS5 and above:
for (UIView* shadowView in [webView.scrollView subviews])
{
    if ([shadowView isKindOfClass:[UIImageView class]]) {
        [shadowView setHidden:YES];
    }
}

A: Works great with iOS 9
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    for (UIView *object in webView.scrollView.subviews) {
        if ([NSStringFromClass([object class]) isEqualToString:@"UIWebPDFView"]) {
            UIView *pdfView = object;
            for (UIView *pdfObjectSubview in pdfView.subviews) {
                if ([NSStringFromClass([pdfObjectSubview class]) isEqualToString:@"UIPDFPageView"]) {
                    UIView *uiPDFPageView = pdfObjectSubview;
                    uiPDFPageView.layer.shadowOpacity = 0.0f;
                }
            }
        }
    }
}

A: Try to remove the border and shadow:
[[yourView layer] setBorderColor: [[UIColor clearColor] CGColor]];
[[yourView layer] setBorderWidth: 0.0f];
[[yourView layer] setShadowColor: [[UIColor clearColor] CGColor]];
[[yourView layer] setShadowOpacity: 0.0f];
[[yourView layer] setShadowOffset: CGSizeMake(0.0f, 0.0f)];

A: This is worked for me. I am using navigation Controller
I hope it will help
self.navigationController.navigationBar.translucent = NO;

One more way is there, Just go to storyboard and select Controller where the web view is present. And go to attribute inspector and uncheck the

adjust scroll view insects


text:
Q: Right aligning cell content in a datatable column I want to right align an outputText value (ie. fee.TableAmount below) and I want to keep the header for that column centered.  What parameter do I have to pass to outputText below to achieve this?
<h:dataTable>
    ...
    (other columns)
    ...
    <h:column headerClass="columnCenter">
        <f:facet id="header_agency" name="header">
            <h:outputText value="Amount"/>
        </f:facet>
        <h:outputText value="#{fee.tableAmount}">
            <f:convertNumber maxFractionDigits="2" groupingUsed="true"
                currencySymbol="$" type="currency" />
        </h:outputText>
    </h:column>
</h:dataTable>

A: As you said, if you define a float: right directly on your <h:outputText>, like this:
<h:outputText style="float: right;" value="#{fee.tableAmount}"/>

then it will nest your text in a  that will then be moved to the right.
Unfortunately, the <h:column> component does not provide a way to specify the CSS class of the column itself. However, in case you are using another component for your table, such as the Richfaces <rich:column>, there is another solution is to specify this: first, set a CSS class:
.textOnRight {
    text-align: right;
}

Then, assign this CSS class to your column:
<rich:column styleClass="textOnRight" headerClass="columnCenter">
    <f:facet name="header">
        <h:outputText value="Amount"/>
    </f:facet>
    <h:outputText value="#{fee.tableAmount}">
        <f:convertNumber maxFractionDigits="2" groupingUsed="true"
            currencySymbol="$" type="currency" />
    </h:outputText>
</rich:column>

By the way, setting an id in your <f:facet> does nothing, as this attribute is not handled by this component.

A: You can use the columnClasses attribute of <h:dataTable> to specify CSS classes on all cells of the same column. You can pass a commaseparated string of class names.
<h:dataTable columnClasses="column1,column2,column3">

The above renders  for the first column,  for the second and so on. This allows you to externalize and normalize the styles.
Imagine that you have 4 columns and the first, second and fourth column doesn't need to have a special style and that only the third column needs to be right-aligned, then do so
<h:dataTable columnClasses="none,none,right,none">

in combination with
td.right {
    text-align: right;
}

which is semantically more correct and technically more robust than a float: right;.

A: I just added style="float:right" for anyone else wanting to know.
<h:outputText style="float:right" value="#{fee.tableAmount}">
   ...
</h:outputText>


text:
Q: Trigger button when finger drag crossed it I am trying to trigger a button when I drag my finger across, instead of pressing it directly. I have tried all the events associated with buttons and none worked in any combination. I have also tried the tap gesture, swipe gesture, and the pan gesture. These didn't trigger the button when I pressed off the button and drag crossed it.
override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(frame: CGRect(x: 0, y: 49, width: 568, height: 8))
    button.backgroundColor = .greenColor()
    button.setTitle("Test Button", forState: .Normal)
    button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

    self.view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

or
@IBAction func s2(sender: AnyObject) {

print("1")

}

A: Add a UIPanGestureRecognizer to your button.
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(doSomething))
button.addGestureRecognizer(panGesture)

func doSomething() {
    //do something here
}


text:
Q: How to filter a data grid view in accordance with one or multiple drop down list selections as the title states I am trying to filter a grid view based on one or multiple selections made among 4 drop down lists.  On a button click event I populate the grid view with the broadest set of information. From here I would like to have the grid view update as I make selections in the available drop down lists (4 in total).
While I feel like I could accomplish this through a series of if statements and a modified query for each condition, I feel like there should be a more efficient way this can be done. Below I have posted any pertinent code to this problem I am having.
html/asp code

                    <asp:DropDownList ID="ddlSearchOCFamily" AutoPostBack="True" AppendDataBoundItems="True" DataTextField="FamilyLong" DataValueField="FamilyLong" runat="server"></asp:DropDownList>

                    <asp:DropDownList ID="ddlSearchOCRate" AutoPostBack="True" AppendDataBoundItems="True" DataTextField="RateLong" DataValueField="RateLong" runat="server"></asp:DropDownList>

                    <asp:DropDownList ID="ddlSearchOCTerm" AutoPostBack="True" AppendDataBoundItems="True" DataTextField="TermLong" DataValueField="TermLong" runat="server"></asp:DropDownList>

                    <asp:DropDownList ID="ddlSearchOCEnrollment" AutoPostBack="True" AppendDataBoundItems="True" DataTextField="TypeDescription" DataValueField="TypeDescription" runat="server"></asp:DropDownList>

                        <asp:GridView ID="gvReverseSearchOC" runat="server" Width="99%" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
                            BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False" PageSize="20" AutoGenerateSelectButton="True">
                            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                            <RowStyle BackColor="White" ForeColor="#330099" />
                            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                            <SortedAscendingCellStyle BackColor="#FEFCEB" />
                            <SortedAscendingHeaderStyle BackColor="#AF0101" />
                            <SortedDescendingCellStyle BackColor="#F6F0C0" />
                            <SortedDescendingHeaderStyle BackColor="#7E0000" />
                            <Columns>
                                <asp:BoundField DataField="OrderCode" HeaderText="Order Code" SortExpression="OrderCode" Visible="True" ReadOnly="True" HeaderStyle-Wrap="False" />
                                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" ItemStyle-Wrap="False" />
                                <asp:BoundField DataField="Net Price" HeaderText="Net Price" SortExpression="Net Price" HeaderStyle-Wrap="False" />
                            </Columns>
                        </asp:GridView>

page load event
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim RSQuery As String = "
        SELECT dDown.OrderCode, dDown.[Description], dDown.[Net Price]
        FROM (
              SELECT SKU.OrderCode AS OrderCode, SKU.[Description] AS [Description],
              (SELECT FORMAT(SKU.ListPrice * EnrollmentType.Multiplier, 'C')) AS [Net Price]
              FROM Enrollment
              INNER JOIN EnrollmentType ON Enrollment.EnrollmentTypeID = EnrollmentType.RecID
              INNER JOIN SKU ON EnrollmentType.TypeID = SKU.EnrollmentTypeID
              INNER JOIN SKUBuild ON SKU.SKU = SKUBuild.SKU
              WHERE (Enrollment.AccountNumber = '12345')
              AND (Enrollment.Active = 'yes')
              AND (SKU.[Description] IS NOT NULL AND NOT (SKU.[Description] = '""'))
        ) AS dDown
        "
    pnlSearchOC.Visible = False
    PopSearchOCDDLs()
    PopGVSearchOC(RSQuery)
End Sub

Procedure to populate the gridview
Protected Sub PopGVSearchOC(ByVal query As String)
    Dim dt As New DataTable
    Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
        Using cmd As New SqlCommand(query, con)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader
                If sdr.HasRows Then
                    dt.Load(sdr)
                    With gvReverseSearchOC
                        .DataSource = dt
                        .DataBind()
                        con.Close()
                    End With
                End If
            End Using
        End Using
        If con.State <> ConnectionState.Closed Then
            con.Close()
        End If
    End Using

End Sub

I have one more procedure that populates the drop down lists but I don't believe it is relevant to my problem, I may be wrong.
I am looking for an elegant solution to update/filter my grid view based on the selections made in the drop down lists, any information in this regard would be much appreciated. If I am missing any necessary code I would be happy to supply it but I am pretty sure its all here.
Thanks for you time guys.

A: Ok, you can do this two ways.
You can pull the data table, and persist the table (but, this can be a bit heavy on browser memory. (but, you could use session() to hold that resulting table - but using session() often means that if the user opens two copies of the page, then things don't work well.
So, probably best to filer against the sql you have. (I would put that sql in a sql server view - we really don't want all sql code in-line, as it hard to maintain.
So, our lodgic:
No selections - show all data. Select 1, or 2 or 3 or 4 combo or filters, then we progressive add this extra conditions. So, blank = ignore, and some value = filter with given values.
So, we kind of need a code stub and approach that works for 1, or 10 filer options. In other words, if we don't find a easy way to "add up" the filters, then we have to write code that considers all combinations. (very bad).
and in this solution, we ALSO very much do NOT want to concatenate values into the sql, since that opens up to not only sql injection, but such code tends to get very messy in a hurry.
So, this approach:
Test the given filter control - if value, then add to our criteria, but STILL use correct parameters - no concatenation of USER input values ever!!!
I don't have your data, but lets just cook up a simple grid, and add a few filters. We will have 2 combo, and say one check box (for only Active Hotels).
So, we have this markup, nothing fancy:

Filters

            <asp:Label ID="Label1" runat="server" Text="Select City"></asp:Label>

            <asp:DropDownList ID="cboCity" runat="server" Width="180px"
                DataValueField="City"
                DataTextField="City" >
            </asp:DropDownList>

            <asp:Label ID="Label2" runat="server" Text="Select Province"></asp:Label>

            <asp:DropDownList ID="cboProvince" runat="server" Width="180px"
                DataValueField="Province"
                DataTextField="Province" >
            </asp:DropDownList>

            <asp:Label ID="Label3" runat="server" Text="Must Have Description"></asp:Label>

            <asp:CheckBox ID="chkDescripiton" runat="server"  />

            <asp:Label ID="Label4" runat="server" Text="Show only Active Hotels"></asp:Label>

            <asp:CheckBox ID="chkActiveOnly" runat="server"  />

            <asp:Button ID="cmdSearch" runat="server" Text="Search" CssClass="btn"/>

            <asp:Button ID="cmdClear" runat="server" Text="Clear Fitler" CssClass="btn"/>

                <%-- this starts new line for grid --%>

        <asp:GridView ID="GridView1" runat="server"
            AutoGenerateColumns="False" DataKeyNames="ID"  CssClass="table" Width="60%">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName"  />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="Province" HeaderText="Province" />
                <asp:BoundField DataField="Description" HeaderText="Description"  />
                <asp:BoundField DataField="Active" HeaderText="Active"  />

            </Columns>
        </asp:GridView>

So, we just drop in as many "divs", float them left for the filers. You can easy add more filter controls.
So, now our code to load up this stuff, is say this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadCombos()
        Dim cmdSQL As New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName")
        LoadGrid(cmdSQL)

    End If

End Sub

Sub LoadCombos()

    Dim cmdSQL As New _
        SqlCommand("SELECT City FROM tblHotels WHERE City is not null GROUP by City")
    cboCity.DataSource = MyrstP(cmdSQL)
    cboCity.DataBind()
    cboCity.Items.Insert(0, New ListItem("All", "All"))

    cmdSQL.CommandText =
        "SELECT Province FROM tblHotels WHERE Province is not null GROUP by Province"
    cboProvince.DataSource = MyrstP(cmdSQL)
    cboProvince.DataBind()
    cboProvince.Items.Insert(0, New ListItem("All", "All"))

End Sub

Sub LoadGrid(cmdSQL As SqlCommand)

    Dim rstData As DataTable = MyrstP(cmdSQL)
    GridView1.DataSource = rstData
    GridView1.DataBind()

End Sub

Public Function MyrstP(sqlCmd As SqlCommand) As DataTable

    Dim rstData As New DataTable

    Using sqlCmd
        sqlCmd.Connection = New SqlConnection(My.Settings.TEST4)
        sqlCmd.Connection.Open()
        rstData.Load(sqlCmd.ExecuteReader)
    End Using

    Return rstData

End Function

Again, quite simple - just some clean code to load up our combo, and the grid.
So, now we have this:

Ok, so now the filter code. As noted, this can work if we have 2 or 20 filters. and you can add more over time - you don't have to change EXISTING code.
So, the code is like this - search button:
Protected Sub cmdSearch_Click(sender As Object, e As EventArgs) Handles cmdSearch.Click

    Dim strSQL As String = "SELECT * FROM tblHotels"
    Dim strOrderBy As String = " ORDER BY HotelName"
    Dim strWhere As String = ""

    Dim cmdSQL As New SqlCommand("")

    If cboCity.Text <> "All" Then
        ' city filter
        strWhere = "(City = @City)"
        cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = cboCity.Text
    End If

    If cboProvince.Text <> "All" Then
        If strWhere <> "" Then strWhere &= " AND "
        strWhere &= " (Province = @Province)"
        cmdSQL.Parameters.Add("@Province", SqlDbType.NVarChar).Value = cboProvince.Text
    End If

    ' must have description
    If chkDescripiton.Checked Then
        If strWhere <> "" Then strWhere &= " AND "
        strWhere &= " (Description is not null)"
    End If

    If chkActiveOnly.Checked Then
        If strWhere <> "" Then strWhere &= " AND "
        strWhere &= " (Active = 1)"
    End If

    If strWhere <> "" Then
        strSQL &= " WHERE " & strWhere
    End If

    strSQL &= " " & strOrderBy
    cmdSQL.CommandText = strSQL
    LoadGrid(cmdSQL)

End Sub

So, note the "pattern". For each control you add, you have a if/then block. You check existing where clause (might be none), and add " AND " to the where clause. You then add parameters to the sql command object.
MANY fail to realize, that you can add parameters to the command object, and you don't even need to have set what the sql source for the sql command object is!!! - they are separate concepts.
So, with above, we are free to check/select or whatever for the filter, and then hit search button.
the above approach works if you have 2 or 25 optional controls.
And VERY important? We NEVER in ANY case ever concatenate user input into that sql string - only ever use parmaters , so this approach is SQL injection safe.


text:
Q: jQuery Accordion and loading content through AJAX I would like to load the content under each jQuery accordion header using the jQuery load command. Currently, I have set this up as the following
$(function() {

    $("#accordion").accordion({
        header: "h2",
        active: false
    });

    $("h2", "#accordion").click(function(e) {
        var contentDiv = $(this).next("div");
        contentDiv.load($(this).find("a").attr("href"));
    });
});

and the HTML (relevant snippet)

Home

Products

Now this all works fine, but there is a problem in that loading content in this manner interrupts the slide down animation of the accordion plugin on some browsers (IE6), and on others (FF), the slide down animation does not occur.
I'm thinking that I would need to prevent the slide down animation from occurring until the content has loaded (using the load callback function) but am unsure how to hook this into the accordion plugin.
Any ideas greatly appreciated!

A: I've just done something similar, and found the trick was to load the content from an ajax request as soon as the DOM is ready, and enable to accordion in the request's callback function.
I tried doing it with jquery's load function, but had trouble, ended up using the ajax function instead.
In your case with multiple ajax calls, i guess you could nest each one in the callback function of the previous. Which is really a horribly inefficient way to do it but if they're just small text files it should be ok.
example as follows:
$.ajax({type:"get",url:"home.htm",success: function(data){
    $("#homeDiv").html(data);
    $.ajax({type:"get",url:"products.htm",success: function(data){
            $("#productsDiv").html(data);
            $("#accordion").accordion();
        }
    });
}});

that should do it...

A: I run in to same problem while trying to load accordion in to ajax tabs with Jquery UI.
The accordion cannot be initialised before you destroy it.
Here is example javascript code:
    $("#navigation").tabs({
    show: function(ui) {
        $('#browse').accordion('destroy').accordion({autoHeight: false, collapsible: true , active: false, header: 'h3'});
    }
});

A: I've done this before let me copy and paste it here.

    {section name=cat_loop loop=$cats}

                    {print id=$cats[cat_loop].subcat_title}

                {include file='include/section_profile_fields.stpl'}

    {section}

The stuff inside {} contains server-side scripting and is basically a loop to print content for multiple accordions. Here is the javascript:
jQuery('.accordion').accordion({
            changestart: function(event, ui){
                   var $activeCord = jQuery(this).find('.ui-state-active');
                   var contentDiv = $activeCord.next("div");
                contentDiv.load('ajax_member_profile_edit.aspx?cat_id='+$activeCord.attr('data-id'));
            }

});

A: Here is the simplest and easiest way to do it

    $("#accordion").accordion({
                active:false,
                change:function(event, ui) {
                    if(ui.newContent.html()==""){
                        ui.newContent.load(ui.newHeader.find('a').attr('href'));
                        }
                },
                autoHeight: false
            });

A: This should solve the problem of loading the accordion before it is activated:

Home

Products

A: Just thinking outside the box for a moment, is there any reason you're using ajax to load the content?  It looks, from your example at least, as if the content could just be loaded initially and be done with it.
As for your actually question, have you tried something like this:
var contentDiv = $(this).find("div");

or explored any other way in which your loading might be interfering with the accordian's view of the DOM tree?  (e.g., trying loading a more deeply nested div)?

A: Maybe this isnt entirely the same as whats being talked about here, but a lot of these snippets helped me to get my solution working so i thought id share it incase anyone else needs to do (exactly!) what i needed to do.
i wanted to load external content fragments into an accordion but getting it to resize properly etc was fiddley, heres my solution:
$(document).ready(function () { //All the content is loaded at page load which means you dont get screwy animations
    $('#accordion').accordion({
        autoHeight: false, // set to false incase theres loads more in one panel than the others
        create: function (event, ui) {
            $('div#accordion > div').each(function () { //for each accordion panel get the associated content from external file and load it in.
                var id = $(this).attr('id');
                $(this).load('ajax_content.html #' + id, function () {
                    $('#accordion').accordion('resize');
                });
            });
        }
    });
});

Hope this helps someone =)
Oh and i should have mentioned that obviously in the ajax_content.html file there is a  div with a the same id as each of the accordion panels so it knows what to put where!

A: This is actually much easier than you are all making out!
In your doc ready function:
$('#accordion').accordion();
$("#accordion").click(function(e) {
  $('.ui-accordion-content-active').load('/path/to/content');
});

and your html

Click me

Loading....

Or even click me!

Loading...

Etc..

Loading

A: Just a quick heads up.
None of these answers will work as expected with the latest API as since jQuery UI 1.9 the events change and changestart have been altered to 'activate' and 'beforeActivate' respectively.
Hope that saves someone a few minutes.

A: This should solve your issue:
    $('#accordion').accordion({
    changestart: function(event, ui){
        var clicked = $(this).find('.ui-state-active').attr('id');
        $('#'+clicked).load('/widgets/'+clicked);
    }
});

The trick to it is that accordion changes the classes of the live container, so you can use .find() to locate the active accordion and perform an action on it.

A: I Have been dealing with this problem, using jquery 1.4 and here is how I solved it. The "ui" object has two important propeties "newContent" and "newHeader". I used newContent and put an id on the div that will hold the content. I also a hidden input tag to hold the important data, It just felt cleaner.
 $("#accordion").accordion({
         disabled: false,
         autoHeight: false,
         collapsible: true,
         active: false,
         header: 'h2',
         animated: 'bounceslide',
         changestart: function (event, ui) {
             var location = ui.newContent.find('input:hidden[name=location]').val();
             ui.newContent.find('#data').load(location);

         }

     });

A: I believe this is the simplest answer not yet given, and meets all of the OP's requirements... loads BEFORE the div is shown, and dynamically according to the href of the a tag:
$("#accordion").accordion({

    active: false,
    clearStyle: true,
    changestart: function(event, ui){

        var href = $(ui.newHeader.find("a")).attr("href");

        $.post(href, function(data) {

            ui.newHeader.next("div").html(data);
        });

    }
});

A: $( "#accordion" ).bind( "accordionchange", function(event, ui) {
    if (ui.newHeader.text()=="LaLaLa"){
       do here ....
    }
   });

A: I was looking for an answer to the same question, and tried a couple of the examples here. However, I  was getting an undefined value using the example with ui-state-active:
var clicked = $(this).find('.ui-state-active').attr('id');

I also wanted to make sure the .load function was only called the first time each accordion panel was expanded. By combining a couple of other posters answers I got the result I wanted:
$('#accordion').accordion({
    changestart: function(event, ui){
         if(ui.newContent.html() == ""){
             var id = ui.newContent.attr("id");
             ui.newContent.load("[your url]" + id);
         }
});


text:
Q: checking if the character pointer has string literal or undeterministic value I have a question on character pointers.
Lets say I have:
char * x = malloc(len);

The above does not return a NULL also.
Now depending on a condition:
if (<condition>)
  strncpy (x,y,len);

How can I check if x contains any string literals?
Because then I need to do:
strncpy(z,x,len);

Any pointers greatly appreciated.

A:
How can i check if x contains any string literals?

In general you can't. C gives no guarantees about the addresses used here so you cannot reliably determine where they come from.
But you're probably addressing the problem the wrong way round: why does this confusion about the origin of x exist in the first place? If you simply want to ensure that the value is always malloc'd, simply always malloc it instead of storing the direct address to a string literal.
(I find it generally odd that the target of your copying should depend on the origin of a value …)

A: What I understood from your question is that you want to check if the strncpy function returned successfully. And the answer is::

strncpy does not returns any value to indicate an error

So, I think you have to printf the variable x to see exactly if it contains any string literals and strncpy was successful.
EDIT::
Try this:
int isZero ;
char * x = malloc(len);
memset(x, 0, len) ;
if (<condition>)
    strncpy ( x, y, strlen(y) + 1);

isZero = strlen(x) ; /* if not 0, you know something is copied */
if( isZero != 0 )
    strncpy( z, x, (strlen(x) + 1) );

A: Guess this is a homework question. Anyways from the manual pages of malloc,
malloc() allocates size bytes and returns a pointer to the allocated memory.  The memory is not cleared.  If size is 0, then malloc() returns either  NULL,  or  a  unique pointer value that can later be successfully passed to free().

In most of the cases, when malloc fails NULL is returned so a check can be performed.
In your question, I'm comfortably assuming that if x contains any string literals ? means that you want to check if the strncpy was successful. strncpy by default returns a pointer to the destination. So, you will surely land up in a segmentation fault if malloc had returned NULL.
One simple way can be check if strlen of x is equal to len.
strncpy is quite a dirty function and your code is prone to lot of bugs !
man is the best friend for a novice programmer. I guess you should go through them and do a little more research before posting questions.


text:
Q: What should be a Select query with SUM calculation of a column for every row? I have a Column Amount, I will get multiple rows with different values in that Amount column.
I need a select query such that I get the SUM of all these amounts as an output.
Thanks And Regards

A: Use the SUM aggregrate function:
SELECT SUM(Amount) AS Total
FROM yourtable

The result will contain a single row, containing the total sum for the column.

A: This:
SELECT SUM(t.amount)
  FROM YOUR_TABLE t

...will return a single value, the sum of all the values in the amount column.  If you want to see the sum for different groups of values, you need to add a GROUP BY clause to the query:
  SELECT SUM(t.amount)
    FROM YOUR_TABLE t
GROUP BY t.column


text:
Q: Getting bounding box of an HTML element excluding CSS transforms I realise this used to be the default behaviour of getBoundingClientRect() but it seems that I'm in the rare position of needing this feature!
I have a CSS animation that moves a div across the Y axis using translate. However, I want the finishing position of the div ...but before the animation has even begun.
Is there any (neat) way of doing this assuming I have no knowledge of the animation parameters?

A: You can use getBoundingClientRect just as is.
Here is an example:

var element = document.getElementById("move");
window.setInterval(function() {
  var structure = element.getBoundingClientRect();
  element.innerHTML = "left: " + Math.floor(structure.left) + "px
 top: " + Math.floor(structure.top) + "px";
}, 100);
body {
  background-color: #222;
  height: 450px;
}
#move {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: white;
  animation: move 5s infinite alternate;
}
@keyframes move {
  from {
    left: 0;
    top: 0;
  }
  to {
    left: calc(100% - 200px);
    top: calc(100% - 200px);
  }
}

HELLO!


text:
Q: read only TMOUT variable – workaround to disable automatically exit shell when there is no activity We have here a read only Bash variable. I am not allowed to unset that variable.
$ echo $TMOUT
1800

As a workaround I wrote those lines (that my session don't exit)
#!/usr/bin/perl

$|++;
while (1) { print "\e[0n"; sleep 120; }

Is there an official package (rpm) that does similar (like above Perl code) in a CentOS7/RHEL7 repository? I don't like to open up a vim editor, I wish a command.

A: Here is the thing,
When the session variable is "Read Only" you have to replace the current shell process with the command by "exec"
So, the Answer to your question is:
$> exec env TMOUT=0 bash

But I recommend setting a higher timeout value
$> exec env TMOUT=3600 bash

A: You can issue perl commands from the command line...
perl -e '$|++; while (1) { print "\e[0n"; sleep 120; }'
or you could do the same in shell (a sh/bash example):
while sleep 120; do printf '\33[0n'; done
Or you could use watch:
watch -n 120 printf '\33[0n'

A: I my case, it is defined in /etc/profile.d/bash_autologout.sh:
TMOUT=1800
readonly TMOUT
export TMOUT

To find it, I did:
sudo find /etc/ -name "*" | xargs sudo grep "TMOUT" 2>&1 | grep -v "filter..."

A: Add this to the start of your .bash_profile ?
if [ ! -z "$TMOUT" ]; then
  env -i bash --init-file ~/.bash_profile
fi

Beware the wrath of the sysadmins if you leave a gazillion old sessions running as a result of defeating their timeout rulings.

A: export TMOUT=0
top
You will have some activity and your session will stay and you could see how long it runs.

A: Why aren't you switching to non-interactive session?
# TMOUT=0
-bash: TMOUT: readonly variable
# unset TMOUT
-bash: unset: TMOUT: cannot unset: readonly variable
# su
# export TMOUT=10
# unset TMOUT
#


text:
Q: How to get current iterator in lambda operation How can I solve the following situation, for any container-type which can use the for_each function -> for a vector this would be easy, because I could add a variable outside the call and give it as a reference parameter and increment it in the lambda function. So how can I get the current iterator in the lambda function?
std::for_each(container.begin(), container.end(), []() {
            //do-something and get the current iterator
});

A: Just do not call std::for_each() but use loop:
auto lambda = []( auto iter ) {}
for( auto it = container.begin(); it != container.end(); ++it ) lambda( it );

if you prefer you can write an algo around it:
template< class InputIt, class UnaryFunction >
UnaryFunction for_each_iter( InputIt first, InputIt last, UnaryFunction f )
{
    while( first != last ) f(first++);
    return f;
}

A: You can write your own function:
template<class InputIt, class UnaryFunction>
UnaryFunction for_each_it(InputIt first, InputIt last, UnaryFunction f) {
    for (; first != last; ++first) (void) f(first);
    return f;
}


text:
Q: Lib for generating documentation of svelte components does anybody knows if there is a standardized way to document svelte components and a lib which would generate a markdown documentation?
I've found just this https://www.npmjs.com/package/sveltedoc-parser which looks kinda dead by now. And it generates just a JSON with bunch of data and I have to create the markdown documentation on my onw from it.


text:
Q: pandas, excel. Поиск значений 3-х столбцов в другом столбце Здраствуйте, нужно проверить имеет ли в себе строка столбца "Summary" строки столбцов 'PS Calendar Frequency','IFS Frequency','Amos..'. В столбце "Summary" между данными могут быть другие символи, могут быть пропущенные данные, так же может отличаться последний символ столбца "IFS Frequency", тоесть вместо PM00678A- PM00678B. Буду рад любой помощи. также возможно что записи будут идти не подряд.
dataframe = {
'PS Calendar Frequency': ['ELEC', 'ELEC','SAFETY','SAFETY','CARGO','CARGO'],
'IFS Frequency': ['PM00187A','PM00678A','PM00149A','PM00152f','PM05A','PM00169f'],
'AMOS Responsible Disc.': ['Electrical','Electrical','Safety','Safety','Cargo','Cargo'],
'Summary': ['eeELECPSSSSSSM00187BElectrical','ELECPSSM00678BElectrical','\'\'\'SAFETSSSSYPM00149A      Safety','','CARQSGOPM00155QCargo','CARGOPM00169fCargo'],
'Result':['False','TRUE','TRUE','False','TRUE','TRUE']
}

A: Мне не удалось добиться именно такого результата, видимо, я не до конца понял принцип. Но делается это примерно таким способом:
import pandas as pd

dataframe = {
'PS Calendar Frequency': ['ELEC', 'ELEC','SAFETY','SAFETY','CARGO','CARGO'],
'IFS Frequency': ['PM00187A','PM00678A','PM00149A','PM00152f','PM05A','PM00169f'],
'AMOS Responsible Disc.': ['Electrical','Electrical','Safety','Safety','Cargo','Cargo'],
'Summary': ['eeELECPSSSSSSM00187BElectrical','ELECPSSM00678BElectrical','\'\'\'SAFETSSSSYPM00149A      Safety','','CARQSGOPM00155QCargo','CARGOPM00169fCargo'],
'Result':['False','TRUE','TRUE','False','TRUE','TRUE']
}
df = pd.DataFrame(dataframe)

def check_df(x):
    return x['Summary'].endswith(x['AMOS Responsible Disc.']) and \
           x['PS Calendar Frequency'][:3] in x['Summary'] and \
           x['IFS Frequency'][:-1] in x['Summary']

#df['Result'] =
df.apply(check_df, axis=1)

Вывод:
0    False
1    False
2     True
3    False
4    False
5     True
dtype: bool