text:
Q: Do Azure Cosmos DB consistency levels only make sense in multi-regional setup? Do I need to bother about consistency level if I'm not going to use Cosmos DB in 2 or more regions (i.e. I'm only going to use a Cosmos DB database in a single region)? Or are the consistency levels important even in a single region, because Cosmos DB maintains several replicas in every region automatically and the "consistency" is the consistency between all these automatic replicas?

A: Yes, consistency levels also make sense when you have only 1 region because, indeed, cosmos db has replicas inside each individual region (so if you have only 1 region you would have several replicas of your cosmos db inside this region).
And, for example, eventual consistency means write\read to a single replica and do not wait for acknowledgement from another replicas (faster\less RU).


text:
Q: Is $\{\emptyset\}$ a subset of $\{\{\emptyset\}\}$? $\{\emptyset\}$ is a set containing the empty set. Is $\{\emptyset\}$ a subset of $\{\{\emptyset\}\}$?
My hypothesis is yes by looking at the form of "the superset $\{\{\emptyset\}\}$" which contains "the subset $\{\emptyset\}$".

A: It's easier to just replace everything by variables, then it's clearer.
Set $a=\varnothing, b=\{\varnothing\}=\{a\}$ and $c=\{\{\varnothing\}\}=\{\{a\}\}=\{b\}$.
Now the question is whether or not $\{a\}\subseteq\{b\}$. But since $a\neq b$, it's easy to see that the answer is negative.

A: No, $\emptyset \in \{\emptyset\}$ but $\emptyset \notin \{\{\emptyset\}\}$.

A: {{∅}} has only one element, namely {∅}, it implies there are only the two trivial subsets, {{∅}} which contains all elements and ∅ which contains none.
formally all subsets of {{∅}}
{{∅}}⊆{{∅}}
∅⊆{{∅}}

A: For such abstract questions, it is important that you stick to the definitions of the involved notions.
By definition, $A$ is a subset of $B$ if every element contained in $A$ is also contained in $B$.
Now we look at $A = \{\emptyset\}$ and $B = \{\{\emptyset\}\}$.
$A$ has exactly one element, namely $\emptyset$.
This is not an element of $B$, since the only element of $B$ is $\{\emptyset\}$ and $\emptyset \neq \{\emptyset\}$ (see below).
So $A$ is not a subset of $B$.
Why $\emptyset \neq \{\emptyset\}$?
By definition, two sets are equal if they contain the same elements. However, $\emptyset$ is the empty set without any element, but $\{\emptyset\}$ is a $1$-element set with the element $\emptyset$.

A: Think of {∅} as a box containing an empty box, then
{{∅}} is a box containing a box which contains an empty box, in which case
{{∅}} is box containing {∅}, which means
{∅} is subset of {{∅}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: an inequality for non-negative scalars Let $1< p < \infty$ for non-negative scalars $x$, $y$ we have $(x+y)^p \geq x^p + y^p$
Is there a similar inequality for $ p \leq 1 $

A: Well, then from Power Means Inequality you have:
$$\frac{x+y}2 \geqslant \sqrt[p]{\frac{x^p+y^p}2} \iff (x+y)^p \geqslant \frac1{2^{1-p}}(x^p+y^p)$$

A: Does this inequation $\sqrt{1+2} \ge \sqrt{1}+\sqrt{2}$ hold?


text:
Q: Noto Sans Maths truetype font support for Unicode-maths I am looking for various unicode maths fonts to use with Arial. I have tried fira-math. But,
there are problems in it.. So, I am looking for alternatives. Google has released Noto Sans Math font available here. I tried this mwe.
\documentclass{article}
\usepackage{unicode-math}
\setmathfont{NotoSansMath-Regular.ttf}
\setmainfont{Arial}[Scale=1.1]
\begin{document}
    \(\alpha\beta,\gamma\) This is a test.
\end{document}

It compiles without errors, but it quietly substitutes latin-modern for Noto Sans Math.  There is a warning in the log file which says
Package fontspec Warning: Font "NotoSansMath-Regular" does not contain
(fontspec)                requested Script "Math".

I checked the font in microsoft word. It does have mathemtical symbols. So, what can be the problem? Curiously, the documentation for unicode-maths gives a list of fonts that support uncode-math not the other way around. Can anything be done, eg. using font forge, so that the font supports unicode-maths? How complicated is this to do?

A: Illustrating @davidcarlisle's suggestion in the comments, about the range= option:

Blue is from Noto Sans Math.
MWE
\documentclass{article}
\usepackage{xcolor}
\usepackage[nosumlimits]{amsmath}

\usepackage{halloweenmath}
\usepackage{unicode-math}
\setmathfont{Asana Math}[Colour=brown]
\setmathfont{NotoSansMath-Regular.ttf}[Colour=blue,range=it/{latin,greek}]
\setmathfont{NotoSansMath-Regular.ttf}[Colour=blue,range=up/{num}]
\setmainfont{Arial}[Scale=1.1,Colour=red]
\begin{document}
xyz
    \[x=f(y)_\alpha\beta,\gamma =\pumpkin(A)^{\mathghost}\] This is a test.
    \[\xrightflutteringbat[sin^{2}\theta]{sin\theta}\]
    \[ \overscriptrightbroom {a^{2}+b^{2}=c^{3}}\mathwitch* (\phi \minus\phi_{2}) \]
    \[ \mathcloud\greatpumpkin_{y=0}^{e^{i}} f(y_x) \]
\end{document}


text:
Q: Is there a way to search a list in a SQLite database? I am creating a health and nutrition application and I am using unity as my engine. I have a SQLite database which holds the recipes, the fields are ID (primary key), Name, Ingredients and Method. Each recipe is a record in the database and they have their own lists of ingredients. The intent is to allow the user to input ingredients and the program will filter the recipe by ingredients
I expect that when the user inputs flour (as an example) it will show all the recipes that use flour. E.g.: Apple pie, cake and so on. Instead if i want to search the ingredients the input has to be identical to the entire lest

A: the classic relational way to do that is to have an ingredients table and a relator table (ingedientrecipe) so that you can query for all the ingredients in a recipe or all recipes that contain a given ingredient

A: You need to read up on how relational databases work.  Right now, with everything in one table, your database isn't really any more useful than a simple Excel spreadsheet.
You want three tables; one for ingredients, one for recipes, and one to join them, which I'll call Ingredient_Recipe.  Ingredient_Recipe table will have two foreign keys, one from the ingredients table, one from the recipe table.  Then you can do SQL queries like this example:
select Recipes.recipeName
from Recipes
INNER JOIN Ingredient_Recipe ON recipe_ID = Ingredient_Recipe.recipe_ID
Where Ingredient_ID = "oregano"

Which should tell you every recipe that contains oregano.


text:
Q: LINQ Searching Only Allowing Equivalency I'm trying to filter a set of records based on a sub-object's criteria.  This compiles ok
recordList = recordList.Where(r => r.Areas.Where(a => a.Area == "Z").Count() > 0);

but this doesn't
recordList = recordList.Where(r => r.Areas.Where(a => a.Area <= "Z").Count() > 0);

giving these errors
Cannot convert lambda expression to type 'string' because it is not a delegate type
Delegate 'System.Func' does not take '1' arguments
Operator '<=' cannot be applied to operands of type 'string' and 'string'
!= works ok, by any sort of less than or greater than operation fails.

A: This has got nothing to do with LINQ not allowing the use of <=, but that strings cannot be compared with this operator (yet can obviously use equal or not equal).
Writing this in a console app:
string strA = "jamie";
string strB = "Z";
Console.WriteLine(strA != strB);
Console.WriteLine((bool)(strA <= strB));

Underlines the final line with (basically) the same error

Cannot apply operator '<=' with type
  'string' and 'string'

Now, you can use the <= operator on char, so the similar code below compiles and works as expected:
char charA = 'J';
char charB = 'Z';
Console.WriteLine(charA<=charB);

So maybe what you want is:
recordList = recordList.Where(r => r.Areas.Where(a => a.Area[0] <= 'Z').Count() > 0);

HTH.

A:
Operator '<=' cannot be applied to operands of type 'string' and 'string'

Well there it is. To compare for ordering, rather than for equality, use string.Compare.

A: You can do < and > on chars but not on strings ;) Use String.Compare or you can write your own comparer to compare 2 strings.


text:
Q: postgres update script using php not working i want to update rows in my table postgresql using php , i can't have my rows updated , and no error is displayed , i don't see the problem in my script  ! here is my table structure:
CREATE TABLE chercheur
(
  nomcher text,
  idfcher text NOT NULL,
  precher text,
  passcher text,
  mailcher text,
  gradcher text,
  naisscher date,
  lieucher text,
  divicher text,
  CONSTRAINT "Chercheur_pkey" PRIMARY KEY (idfcher)
)

and the program:
    $conn = pg_pconnect("dbname=postgres host=localhost port=5432 user=postgres password=postgres");

    if ($conn) {
        //print "Successfully connected to database: " . pg_dbname($conn) .
        // " on " .  pg_host($conn) . "
\n";

        $id = pg_escape_string($_POST['identif']);

        $result = pg_query($conn, "SELECT * from chercheur WHERE idfcher='" . $id . "';");
    } else {
        print pg_last_error($conn);
        exit;
    }
    if (!$result) {
        $errormessage = pg_last_error();
        echo "Error with query: " . $errormessage;
        exit();
    } else {
        while ($myrow = pg_fetch_row($result)) {

            echo '

Informations du chercheur trouvé:
';
            echo '

        Nom du chercheur
        <input value="' . $myrow[0] . '" name="nom" id="nom" type="text" />

     Prenom du chercheur

     <input value="' . $myrow[2] . '" name="prenom" id="prenom" type="text" />

        Identifiant
        <input value="' . $myrow[1] . '" name="user" id="user" type="text" />

        Mot de passe
        <input value="' . $myrow[3] . '" name="pass" id="pass" type="password" />

    Email  du chercheur
    <input value="' . $myrow[4] . '" name="mail" id="mail" type="email" />

    Grade
     <input value="' . $myrow[5] . '" name="grade" id="grade" type="text" />

        Date de naissance
        <input value="' . $myrow[6] . '" name="naiss" id="naiss" type="date" />

        Lieu de naissance
        <input value="' . $myrow[7] . '" name="lieu" id="lieu" type="text" />

        Division
        <input value="' . $myrow[8] . '" name="divis" id="divis" type="text" />

        	  <button name="submit2" id="submit2" type="submit" >Mettre à jour</button>

    <button name="annuler" id="annuler" type="reset" >Réinitialiser</button>

';
            if ((isset($_POST['submit2']))) {
                $idf = pg_escape_string($_POST['user']);
                $pass = pg_escape_string($_POST['pass']);
                $name = pg_escape_string($_POST['nom']);
                $pre = pg_escape_string($_POST['prenom']);
                $mail = pg_escape_string($_POST['mail']);
                $naissance = pg_escape_string($_POST['naiss']);
                $lieu = pg_escape_string($_POST['lieu']);
                $division = pg_escape_string($_POST['divis']);
                $gr = pg_escape_string($_POST['grade']);

                $result = pg_query($conn, "UPDATE  chercheur SET  nomcher='" . $name . "' and
precher='" . $pre . "' and passcher='" . $pass . "' and mailcher='" . $mail . "' and naisscher=date('" . $naissance . "')
and lieucher='" . $lieu . "' and divicher='" . $division . "'and gradcher='" . $gr . "'
where idfcher='" . $idf . "';");
                if (!$result) {
                    $errormessage = pg_last_error();

                    echo "Error with query: " . $errormessage;
                    exit();
                } else {
                    echo "mise à jour avec succès";
                }
            }
        }

    }
    pg_free_result($result);

    pg_close();

?>


text:
Q: Python selenium headless firefox not working with WSGI in production but working in development mode Python selenium headless firefox not working with WSGI (inside django) in production but working in development mode.

Error:- TimeoutException at / Message: connection refused


text:
Q: Getting index value when using custom Knockout mapping I'm setting up a Knockout ViewModel like this:
var Schedule = function(data, parent) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
    self.foo = 'bar';
    ...
};

var ScheduleViewModelMapping = {
    'schedules': {
        create: function(options) {
            return new Schedule(options.data, options.parent);
        }
    }
};

ko.mapping.fromJS(data, ScheduleViewModelMapping, self);

$(document).ready(function() {
    var ViewModel = new ScheduleViewModel;
    ko.applyBindings(ViewModel);
});

Schedules is an array, and i would like to be able to fetch the index of the current schedule somewhere so i'll be able pass it to the Schedule object along with options.data and options.parent.

A: I suggest changing your mapping handler so it can store some state:
var ScheduleViewModelMapping = new (function(){
    var counter = 0;

    this.schedules = {
        create: function(options) {
            //use counter as index as required
            var s = new Schedule(options.data, options.parent);
            counter++;
            return s;
        }
    }

    this.resetCounter = function() {
        counter = 0;
    }
})();

ScheduleViewModelMapping.resetCounter();
ko.mapping.fromJS(data, ScheduleViewModelMapping, self);


text:
Q: useradd: cannot create directory A CentOS 7 server needs to have a new user created with a specific home directory and shell defined as follows, taken from the instructions at this link:
sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket

However, when that command is run on a CentOS 7 server, the command fails with the following error:
useradd: cannot create directory /opt/atlassian/bitbucket

Similarly, creating the /opt/atlassian/bitbucket directory before-hand results in the following error:
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.

What specific changes need to be made to these commands, so that the new atlbitbucket user can successfully be created?
The Complete Terminal Output:
The following is the complete series of commands and responses in the CentOS 7 terminal:
Manually Creating The Directories:
login as: my_sudoer_user
my_sudoer_user@private.lan.ip.addr's password:
Last login: Mon May 15 14:00:18 2017
[my_sudoer_user@localhost ~]$ sudo mkdir /opt/atlassian/
[sudo] password for my_sudoer_user:
[my_sudoer_user@localhost ~]$ sudo mkdir /opt/atlassian/bitbucket
[my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.

[my_sudoer_user@localhost ~]$ sudo rmdir /opt/atlassian/bitbucket
[my_sudoer_user@localhost ~]$ sudo rmdir /opt/atlassian/

The Recommended useradd Syntax:
[my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket
useradd: user 'atlbitbucket' already exists

[my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucket
userdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found

[my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket
useradd: cannot create directory /opt/atlassian/bitbucket
[my_sudoer_user@localhost ~]$

adduser Instead Of useradd
I then tried @terdon's suggestion from this other posting to use adduser instead, but got the same error, as follows:
[my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucket
[sudo] password for my_sudoer_user:
userdel: atlbitbucket mail spool (/var/spool/mail/atlbitbucket) not found
userdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found
[my_sudoer_user@localhost ~]$ sudo adduser --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket
adduser: cannot create directory /opt/atlassian/bitbucket
[my_sudoer_user@localhost ~]$

Shorter Syntax:
Then I tried @rajcoumar's suggestion from the same other posting, but got the same following results:
[my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucket
userdel: atlbitbucket mail spool (/var/spool/mail/atlbitbucket) not found
userdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found
[my_sudoer_user@localhost ~]$ sudo useradd -m -d /opt/atlassian/bitbucket -s /bin/bash atlbitbucket
useradd: cannot create directory /opt/atlassian/bitbucket
[my_sudoer_user@localhost ~]$

Elevating To root:
I even upgraded to root just to see if the problem could be resolved by running the command as root, but I still got the following error:
[my_sudoer_user@localhost ~]$ su -
Password:
Last login: Mon May 15 14:07:11 PDT 2017 on ttyS0
[root@localhost ~]# /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket
useradd: cannot create directory /opt/atlassian/bitbucket
[root@localhost ~]#

A: The useradd code calls a mkdir library function to (attempt to) create the specified directory. useradd checks the return code, but only for being non-zero; in this case, I suspect that mkdir is returning ENOENT -- A directory component in pathname does not exist or is a dangling symbolic link because the parent directory (/opt/atlassian) didn't exist, or had been removed during your attempts to add the user.
As Kusalananda / roaima point out, the simplest solution here is to create the parent directory structure before calling useradd:

*

*sudo mkdir -p /opt/atlassian

*sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket

A: The commands you use to create the user and their home directory will only be able to create the home directory if the immediate parent of the home directory already exists. It will fail if it can't find the parent folder where the home directory should go, or if the home directory already exists.
This means that
$ mkdir -p /some/dir/myhome
$ useradd --home-dir /some/dir/myhome ...

will fail since /some/dir/myhome exists, whereas
$ rm -rf /some/dir
$ useradd --home-dir /some/dir/myhome ...

will fail as /some/dir does not exist.
Just make sure that the directory where in the home directory is to be created exists, i.e. in your situation,
mkdir -p /opt/atlassian


text:
Q: AVAssetRescourceLoader shouldWaitForResponseToAuthenticationChallenge only triggers using the Simulator I am using the AVARLDelegateDemo Example supplied by Apple it is suppose to stream m3u8 video. My Stream is HSL HTTPBasicAuth user and password. I added the:
- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForResponseToAuthenticationChallenge:(NSURLAuthenticationChallenge *)authenticationChallenge

on the APLCustomDelegate its seems to work great when using the simulator the videos shows up and the shouldWaitForResponseToAuthenticationChallenge is called.
the problem is when I deploy it to a device it displays a 401 ERROR
and after doing some testing it looks like the shouldWaitForResponseToAuthenticationChallenge is not being called
BTW: I have Allow Arbitrary Loads: YES
LINK TO APPLE SOURCE


text:
Q: How to rotate TickMarks in DateListPlot? Is there a way to rotate TickMarks in DateListPlot to avoid overlap, eg:

Part of the code used to generate this is:
TimelineGr[file_] :=
 DateListPlot[{{First[#], 1}, {Last[#], Length@#}} &@
   Sort@Flatten[ Last /@ I2B2[file, dateIntervals], 1],
  Epilog -> ({Text[First@#, {First@Last@#, First@#2}, {1, 0}], Blue,
       Rectangle[{First@Last@#, First@#2}, {Last@Last@#,
         First@#2 + 0.1}]} &~MapIndexed ~ I2B2[file, dateIntervals]),
  PlotRange -> All, AspectRatio -> 1/4, ImageSize -> 800,
  DateTicksFormat -> {"Year", "/", "Month", "/", "Day"},
  FrameTicks -> {{Automatic, Automatic}, {
     First[Last[#]] & /@ I2B2[file, dateIntervals], Automatic}},
  PlotLabel -> file <> ".xml"
  ]

(Note, this includes custom functions)
If not, this is just another example of why it's almost always better to write visualization from the bottom-up

A: An answer in the same vein as @Mr.Wizard's, but that works in more recent versions of Mathematica:
data = {{{2006, 10, 1}, 10}, {{2006, 10, 15}, 12}, {{2006, 10, 30}, 15}, {{2006, 11, 20}, 20}};

dlp = DateListPlot[data];

(*get x plotrange*)
xpr = First[PlotRange /. Options[dlp, PlotRange]];

(*get the frameticks that DateListPlot uses by default from the internal function*)
ticks = (Charting`DateTicksFunction[Automatic, DateTicksFormat -> {Automatic}] @@ xpr);

(* manually adjust styling (adding rotation) for ticks gathered above *)
rotatedTicks = Replace[
     ticks,
     {x_, Style[y_String, specs__], z_List, d_Directive} :> {x, Style[Rotate[y, 80 Degree], specs], z, d},
     {1}
];

(*add our "custom" ticks back into the plot*)
Show[
     dlp,
     FrameTicks -> {{Automatic, Automatic}, {rotatedTicks, Automatic}}
]

This gets the ticks manually from the internal Charting`DateTicksFunction function, and then post-processes them and plugs them back into the graphics object.
YMMV, and this uses internal functionality that may change in a future release.

A: Perhaps something like this?
data = {{{2006, 10, 1}, 10}, {{2006, 10, 15}, 12},
        {{2006, 10, 30}, 15}, {{2006, 11, 20}, 20}};

p = DateListPlot[data];

Show[p,
  Options[p, FrameTicks] /. s_String :> Rotate[s, 90 Degree]
]

If one prefers not to use Show then:
p /. x : (FrameTicks -> _) :> (x /. s_String :> Rotate[s, 90 Degree])

A: Mr.Wizard has shown you how to rotate the labels. Sometimes, it might also be useful to simply offset alternate labels so that it doesn't clash and is more readable. For example:
Block[{i = 1},
    DateListPlot[data, DateTicksFormat -> {"Day", "/", "Month", "/", "Year"}] /.
        s_String :> If[s =!= "" && OddQ[i], i += 1; s, i += 1; Column[{"", s}]]
]

A: Given that the original question already uses so many different options, I think the most obvious answer is the one that makes use of exactly these existing options. This requires no post-processing whatsoever. By post-processing, I mean the replacement rules s_String :> ...
data = {{{2006, 10, 1}, 10}, {{2006, 10, 25}, 12}, {{2006, 10, 30},
    15}, {{2006, 11, 20}, 20}};

DateListPlot[
 data,
 FrameTicks ->
  {
   {Automatic, None},
   {
    Map[
     {#,
       Framed[
        Rotate[
         DateString[#, {"Year", "/", "Month", "/", "Day"}],
         90 Degree]
        , RoundingRadius -> 5,
        FrameStyle -> None,
        Background -> LightOrange
        ],
       {0, .01}
       } &,
     data[[All, 1]]
     ],
    None}
   }
 ]

All the heavy lifting is done by the FrameTicks option. The list data contains all the information necessary to create the positions and text for the tick labels, more precisely we need only the first entries: data[[All, 1]].
The Map command uses each date entry in data[[All, 1]] to create a list that identifies a tick mark with a position and label. The label part is rotated by 90 degrees - I also chose to add a rounded rectangle background using Framed, and make the tick mark extend outside the frame toward the label, by using a tuple {0, .01} for the tick length specification.
This approach has some potential advantages, other than making full use of the existing options: in particular, making pattern replacements in a post-processing step may require more carefully crafted conditions (instead of s_String) if  some of the labels on the vertical axis happen to be customized with strings too (e.g., instead of purely numbers from 0 to 20, you could have one special tick labeled by a word like "special value" - then that word would unintentionally get rotated along with the date labels).
See also this answer to a closely related question, "Centering date labels over the year in a DateListPlot"


text:
Q: Serialization, Desiarilazation in Swift to JSON So, I've been reading a boatload of material on this topic for several days already. I've solved most of my problems except few. These are the following:
1)How do you serialize Dictionary of Custom classes to JSON,(considering that each class is serializable)
2) How to deserialize JSON, which is a contains Dictionary into actual Dictionary, provided that UserObject alone can be serialized.
For serialization I use this protocol:
https://gist.github.com/anaimi/ad336b44d718430195f8#file-serializable-swift
For deserialization I just pull values from json. It works with all the primitives and custom types, but I don't know how to deserialize collections of custom types.
For example, here is my code for serialization:
@objc var jsonProperties:Array<String> {
    get {
        return ["id","login","password","name","picture","reputation","description","gender","x","y","visibility","friendRequests","friendWeightings","interestWeightings"]
    }
}
@objc func valueForKey(key: String!) -> AnyObject! {
    if key == "id" {
        return self.id
    } else if key == "login" {
        return self.login
    } else if key == "password" {
        return self.password
    } else if key == "name" {
        return self.name
    }
}

ANd so on...
That's how I deserialize the same object:
init() {}
init(json: JSON) {
    if let i = json["id"].string {
        self.id = i
    }
    if let l = json["login"].string {
        self.login = l
    }
    if let f: Array<String> = json["someArray"].arrayObject as? [String] {
        self.friendRequests = f
    }
    if let f = json["someDictionary"].dictionaryObject as? Dictionary<String,Float> {
        self.friendWeightings = f
    }
}

The problem arises when I try to serialize or deserialize A COLLECTION(like an Array or Dictionary) of that class
Has somebody encountered that problem before?
In addition, I don't think that Serializable protocol serializes Dictionaries of NON-Primitive types correctly. I haven't looked into it yet.
Anyway, the point is:
Is there a nice library, which does all the serialization/deserialization of ANY data I send OR if there is no such thing, what is the way to serialize/deserialize collections of custom types to json.
Thank You.

A: So I finally found a solution. I bridged JSONModel to my swift project. It does all the serialization correctly from and to JSON. The only thing, which was left is to add serialization and deserialization to classes. Nothing tricky, a lot of mechanical work of writing if let code. Dictionaries were tricky, first of all I checked if the dictionary exists if so, then I wrote down each key to my dictionary but for value I needed to transform JSONModel type to my type. Anyway, I seemed to achive everything that I wanted, although Apple should get it straight and write a high-quality level json library.


text:
Q: Testing in Objective c I have the Unit Test Class named CarouselWithXmlTests.I have single test case.If i entered the data for test case failure or test case success each time it throws the message that 0 test cases tested. I have following code is there anything missing?
-(void)checkTheArrayForNull
{
    viewController.temp=@"c";
    viewController.buttonCount=1;
    [viewController goButton:self];
    STAssertNotNil(viewController.setUpArray,@"set up Array is not nil");

}

and having the following message in o/p:
Test Suite 'CarouselWithXmlTests' started at 2012-05-17 10:23:55 +0000
Test Suite 'CarouselWithXmlTests' finished at 2012-05-17 10:23:55 +0000.
 Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.000) seconds

A: Change your method name, it must start with test to run as test case
-(void)testCheckTheArrayForNull
{
    viewController.temp=@"c";
    viewController.buttonCount=1;
    [viewController goButton:self];
    STAssertNotNil(viewController.setUpArray,@"set up Array is not nil");

}


text:
Q: Stop scrolling at last image in html I have the following html-

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

   <img src="images/square.jpg" width="850" height="534" /

When I view this page in IE the horizontal scrollbar goes much further than it should, whereas I need it to stop on the last image rectangle.png.
I have tried to alter the CSS making the column width set to auto but this did not work, and also the table width. How can I get round this?

A: Your first column have a width of 3484px  and your rectangle image have a width of 1134px. So at minimun it will be 4618px even if you change the width in the CSS. ( about 4 times the width of my current screen).

A:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<img src="images/square.jpg" width="850" height="534" /

Try this and see if it helps you if you have your content contained within the screen it should help with scrolling. I have solved the same problem in the past this way. Hope it helps good luck.


text:
Q: Logon script does not run for all users We have a standalone common-use workstation running Windows XP Pro SP3 and have created a script using Javascript (scriptname.js) that is to be run for each user. The file was added as a user logon script via gpedit.msc and tested using a newly created user account as well as an existing user account. The script ran and functioned as intended on both accounts; however, a few existing users have informed us that the script is not running on their accounts.
All user accounts are members of the same groups and have identical permissions. We already have an existing script (but in this case, a batch file) that is applied in the same manner and it runs for all accounts without any problems. Furthermore, on the accounts where the new script does not run during logon, it can still be run manually and works fine.
So the question is: what would cause this script to not run during logon on certain accounts?
Thanks!


text:
Q: Pass array to async library eachSeries - expects 'Dictionary<{}>' I have the following TypeScript code:
const allDescribeBlocks: Array<ITestSuite> = suman.allDescribeBlocks;

async.eachSeries(allDescribeBlocks, function (block: ITestSuite, cb: Function) {

//....

}, cb);

this will transpile with warnings:

Argument of type ITestSuite[] is not assignable to parameter of type
  Dictionary<{}>. Index signature is missing in ITestSuite[].

How to fix?
Here is the exact warning:

A: Have you installed the latest type definition for async library?
npm install --save @types/async

I just checked their source and it should accept both array and collection:
export function each<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function each<T, E>(arr: Dictionary<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachSeries: typeof each;

I think if you install the type definition module and add the definition directory to your tsconfig.json using "typeRoots": ["node_modules/@types"], it should solve the issue.
Edit - Also, you should avoid Array<T> definition for simple types and use T[] instead.


text:
Q: Можно ли переписать условие в одну строку? if (currentPos < min) {
  currentPos = min;
} else if (currentPos > max) {
  currentPos = max;
}

делаю так
currentPos = currentPos < min ? min : (currentPos > max ? max);

получаю ошибку

Parsing error: ':' expected. eslint

A:

let number = 0;
let min = 1;
let max = 3;

console.log(Math.max(min, Math.min(number, max)));

number = 4;
min = 1;
max = 3;

console.log(Math.max(min, Math.min(number, max)));

number = 2;
min = 1;
max = 3;

console.log(Math.max(min, Math.min(number, max)));

A: Да, переписать в одну строку можно.
Проблема решения в вопросе
currentPos = currentPos < min ? min : (currentPos > max ? max);

заключается в том, что опущена обязательная else-часть вложенного тернарного оператора, и это является синтаксической ошибкой.
С соблюдением синтаксиса, можно записать решение (например) так:
currentPos = currentPos < min ? min : (currentPos > max ? max : currentPos);

«min если currentPos < min, иначе (max если currentPos > max, иначе currentPos)» - чтобы соблюсти синтаксис, мы вынуждены указать последним "иначе"-значением текущее значение переменной, при невыполнении всех указанных условий совершая "бесполезное" присваивание (которое на самом деле никак не повредит).

Оффтоп:
Более читаемым вариантом в данном случае является использование методов Math вместо тернарника, как предлагает @Алексей в своем ответе:
currentPos = Math.max(min, Math.min(max, currentPos));

Поначалу это может показаться чуть сложнее для восприятия, но на самом деле все просто: сначала вложенный вызов вернет меньшее из max и currentPos (мысленно назовем эту величину x), а затем внешний вызов вернет большее из min и x.
Это читаемее и короче по символам, но выполняется медленнее тернарного оператора. Различие их быстродействия обычно имеет значение только в циклах с большим кол-вом итераций (в остальных случаях, этим различием можно пренебречь).


text:
Q: Other approaches concerning the series $\sum_{n=1}^{\infty} \frac{\sin(n)}{n!}$ I recently saw the question What is the closed form for $S=\displaystyle\sum_{n=1}^{\infty} \dfrac{\sin ({n})}{n!}$?
I became interested in the problem and generalized the equation using the same method provided in the link.
$$\displaystyle\sum_{n=0}^{\infty} \dfrac{\sin ({kn})}{n!} = e^{\cos(k)}\sin(\sin(k)),$$
$$\displaystyle\sum_{n=0}^{\infty} \dfrac{\cos ({kn})}{n!} = e^{\cos(k)}\cos(\sin(k)),$$
$$\displaystyle\sum_{n=0}^{\infty} \dfrac{\sin^2 ({kn})}{n!} = \frac{e+e^{\cos(2k)}\cos(\sin(2k))}{2},k\in\mathbb{R}.$$
Are there any other methods besides complex analysis that can provide a closed form for $\displaystyle\sum_{n=0}^{\infty} \dfrac{\sin ({n})}{n!}$?

A: I tried alternative methods to find the bijection between complex numbers and some operation or transformation. First thing I thought about was that if we call the derivative operator $D$, we have that:
$$D^2\cos{t}=-\cos{t} $$
$$D^2\sin{t}=-\sin{t} $$
Therefore in this context we have that $D^2=-I$, so I started looking for differential equations. I called the functions:
$$y(t)=\sum_{n=0}^\infty \frac{sin{(tn)}}{n!}$$
$$x(t)=\sum_{n=0}^\infty \frac{cos{(tn)}}{n!}$$
Then I derived the functions and fount a relation. Now the problem is to solve the following system with initial conditions $x(0)=e \text{, } \space y(0)=0$ and evaluate $y(t)$ in $t=1$:
$$y'=x\cos{t}-y\sin{t}$$
$$x'=-y\cos{t}-x\sin{t}$$
Using the subs $x=R(t)\cos(\theta (t))$ and $y=R(t)\sin(\theta (t))$ we get the answer:
$$y(t)=e^{\cos{t}}\sin(\sin{t})$$
$$x(t)=e^{\cos{t}}\cos(\sin{t})$$


text:
Q: Decrypt cipher text using NodeJs createDecipheriv. What am I doing wrong? I have the following code that should decrypt an encrypted text:
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;

var iv = new Buffer('the-iv', 'binary'); //length=16
var key = new Buffer('the-secret-key', 'binary');//length=30

var encryptedText = new Buffer('base64-encoded-encrypted-data', 'base64');

var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv); //using the aes-128-cbc algorithm
decrypted = decipher.update(encryptedText, "binary", 'utf8');
decrypted += decipher.final('utf8');

When I execute the script node test-main.js, I get the following error:
node-crypto : Invalid key length 30

crypto.js:355
  this._binding.initiv(cipher, toBuf(key), toBuf(iv));
                ^
Error: DecipherInitIv error
    at new Decipheriv (crypto.js:355:17)
    at Object.Decipheriv (crypto.js:352:12)
    at Object.<anonymous> (path/to/file/test-main.js:9:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

My NodeJs version is 0.10.15
I am not sure what I am doing wrong/missing.

A: Please try using a key length of 16.
aes-128-cbc uses a 128 bit key.

A:     var crypto = require('crypto');// dont forget to include this line i am just unable to put this in the code
    var data = JSON.stringify({someKey: "someValue"});

    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = 'myVeryTopSecretK';
    var clearEncoding = 'buffer';
    var cipherEncoding = 'base64';

    var cipher = crypto.createCipheriv(algorithm, key, new Buffer(""));

    var cipherChunks = [];
    cipherChunks.push(cipher.update(new Buffer(JSON.stringify({someKey: "someValue"}), 'utf8'), clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
    var decipher = crypto.createDecipheriv(algorithm, key, new Buffer(""));
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
//// dont forget to include this line i am just unable to put this in the code
var crypto = require('crypto');


text:
Q: JavaFX applet javascript and max os x I'm writing a javafx applet. In the page I use javascript function to change some applet properties.
When I try this applet on windows or solaris or linux it works fine.
When i open the same page on mac os x it diplay an error message live app.script not found.
Any ideas?

A: JavaFX is only supported in JDK 6u10 and above. It uses the new plugin architecture. Not sure if this supported in OSX. Did you set the id attribyte on your FX applet?


text:
Q: ASP.net FileUpload corrupts uploaded files I've been using the FileUpload control to upload a large file. Everything works fine on localhost, but on the server, the file gets corrupt: the upload goes well, the file has correct size, but the contents are mixed up, some parts of the file are written over others.
E.g. like this:
Original file:
abcdef0123456789

Uploaded file:
abc1230123456789

There is about one segment like this per 10 MBs of the file, the length varies, typically 0.1-1 kB.
My code is simple:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UploadTest.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />

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

And the server side:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UploadTest
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "\\Files\\" + FileUpload1.FileName);
                Label1.Text = "Success " + FileUpload1.FileName;
            }
            else {
                Label1.Text = "No file";
            }
        }
    }
}

It does not matter what file I try to upload, the large ones (> 10 MB) get corrupted.
I think that this has no business with the code, but it is related to something else (but it does not happen on my client computer only and I need solution simple enough to explain it to the other person using it, if this is client-related). I've tried to disable the antivirus software and it had no effect. But also, there are some clients that handle the data upload correctly.
What else can mess up my post data?
Any ideas?
Thanks,
AlesP
Post edited

A: Change your <form> encoding attribute to enctype="multipart/form-data".

A: It seems that you may be exceeding the default file size limit, which is a setting I think you can change. See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx
Specifically the section on memory limitations.
Edit
This looks like it may help you:
Large POST data is corrupted when using Django/PyISAPIe/IIS


text:
Q: R How to Check if XPath Exists hoping someone more knowledgeable than me can throw some light here.
As part of a larger web-scraper I want to pull meta data out of a set of pages.  When I ran this it fell over, investigation shows this was due to one of the Xpath's being requested not existing.
I can see one potential solution is to grab ALL the meta for a page into a vector and to check if each required one exists before building a new vector of just those I want.
BUT
It would be even better if I only grabbed the bits I want if they exist in the page.
require(XML)
require(RCurl)
parsed <- htmlParse("http://www.coindesk.com/information")

meta <- list()
meta[1] <- xpathSApply(parsed, "//meta[starts-with(@property, \"og:title\")]", xmlGetAttr,"content")
meta[2] <- xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]", xmlGetAttr,"content")
meta[3] <- xpathApply(parsed, "//meta[starts-with(@property, \"og:url\")]",  xmlGetAttr,"content")
meta[4] <- xpathApply(parsed, "//meta[starts-with(@property, \"article:published_time\")]",  xmlGetAttr,"content")
meta[5] <- xpathApply(parsed, "//meta[starts-with(@property, \"article:modified_time\")]",  xmlGetAttr,"content")

This will throw an error as og:description isn't in this page.
Error in meta[2] <- xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]",  :
  replacement has length zero

Can anyone suggest a simple test that will check for its existence before trying to extract it, falling over gracefully with perhaps a NULL response?

A: Assuming the error comes when you try and process the empty list...
> parsed <- htmlParse("http://www.coindesk.com/information")
> meta <- xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]", xmlGetAttr,"content")
> meta
list()
> length(meta)==0
[1] TRUE

Then test for length(meta)==0 - which is TRUE if the element is missing. Otherwise its FALSE - as in this example of extracting the title property:
> meta <- xpathApply(parsed, "//meta[starts-with(@property, \"og:title\")]", xmlGetAttr,"content")
> meta
[[1]]
[1] "Beginner's guide to bitcoin - CoinDesk's Information Center"

> length(meta)==0
[1] FALSE

A: The answer to this has been hard to nail down.  Whilst there are a couple of custom implementations of xpathApply knocking around that handle NULL results the solution to the question posed did lay in Spacedman's suggestion.
The first part of the IF statement calls the xPath and checks to see if the return length = 0.
If it does then it applies a custom message to the list, "Title NA" or "Description NA" but
if the length isn't 0 (i.e. there is a match) then it applies the xPath to the list.
Simples.
 require(XML)
    require(RCurl)
    parsed <- htmlParse("http://www.coindesk.com/information")

    meta    <- list()
    meta[1] <- if(length(xpathSApply(parsed, "//meta[starts-with(@property, \"og:title\")]", xmlGetAttr,"content"))==0)
               {
                 "Title NA"
               }
               else
               {
                 xpathSApply(parsed, "//meta[starts-with(@property, \"og:title\")]", xmlGetAttr,"content")
               }
    meta[2] <- if(length(xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]", xmlGetAttr,"content"))==0)
               {
                 "Description NA"
               }
               else
               {
                  xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]", xmlGetAttr,"content")
               }


text:
Q: How can I include one bibtex item in the manuscript body? Can I include one bibtex item in the manuscript body? For example, I want something like:

Blah blah blah blah blah Blah blah blah blah blah Blah blah blah blah
  blah Blah blah blah blah blah Blah blah blah blah blah Blah blah blah
  blah blah Blah blah blah blah blah Blah blah blah blah blah.
[32] J. Doe, "Hello, World", Journal of Hello, 32(1), 13-24, 2009.
Blah blah blah blah blah Blah blah blah blah blah Blah blah blah blah
  blah Blah blah blah blah blah Blah blah blah blah blah Blah blah blah
  blah blah Blah blah blah blah blah Blah blah blah blah blah.
Bibliography
[1] ...
[2] ...
........
[32] J. Doe ...
[33] ...
  ....

Is this possible? How can I do this? I am using bibtex.


text:
Q: How do I downgrade Xbox 360 dashboard? I have an Xbox 360 Elite and I want to downgrade the dashboard version from 2.x to 9199. I tried putting $SystemUpdate (from the official $SystemUpdate9199.zip) folder into a FAT32 formatted USB and restarting the console with the USB stick inserted, but it didn't work. What else can I do?

A: There is no easy way of downgrading Xbox 360 Dashboard, since there are physical measures put in place to prevent just that (CPU e-Fuses blow when upgraded to prevent downgrade).
I heard there is a possibility of downgrading certain Dashboard versions by a timing attack, but that requires advanced electronics knowledge (and equipment) and definetly voids your warranty.

A: Basically what you have to do is JTAG your Xbox, then it will work. I'm no expert so double check on YouTube or something. I'm pretty sure, though!

A: Here's how you do it go to settings then click on storage then press LB RB X LB RB X And keep doing it until you get the dashboard of your likings


text:
Q: Custom inspection for PhpStorm to detect missing empty line from end of file? For git it is recommended to include empty line at the end of the file. I'd like to create custom inspection in PhpStorm IDE that detects files that are missing this empty line, however docs for those inspections are rather scarce.
It would be nice to be able to add them automatically too.


text:
Q: Ayuda con condición en PHP Saludos amigos de la comunidad tengo una duda como puedo crear una condición que los usuarios que tengan el estado ¡por asistir! no se puedan registrarse en la inscripción de un proyecto, ya que es un requisito que el usuario haya asistido a la charla para poder ser inscrito a un proyecto. Les explico el sistema funciona de esta manera los usuarios hacen una pre- inscripción en el sistema para almacenar esos datos tengo dos tablas las cuales son:
Tabla Usuarios
Id, usuario, clave, fk_nivel, correo, cedula, nombres, apellidos
Tabla pre_inscripcion
Fk_cedula, fk_idcarrera, estado
Luego de eso tengo las siguientes tablas para hacer el registro de los proyectos y saber que alumnos están inscriptos en ese proyecto
Tabla: inscripción_proyectos
Id, titulo_proyecto, fk_departamento, fk_profesor, fk_cedula
Tabla: inscripción_alumnos
Id, fk_inscripción_proyectos, fk_cedula
Ahora mi duda es como puede hacer esa condición…
código que uso para insertar en inscripción_alumnos:
<?php
if (isset ($_POST['guardar'])){

$id=$_POST['id'];
$idinscripcion_proyectos=$_POST['idinscripcion_proyectos'];
$cedula=$_POST['cedula'];
$nombres=$_POST['nombres'];
$apellidos=$_POST['apellidos'];

  $sql="SELECT * FROM inscripcion_alumnos WHERE id='$id' LIMIT 1";
  $res=mysql_query($sql,$link);
  $nrows=mysql_num_rows($res);

if($nrows==0){

for ($i = 0; $i < count($idinscripcion_proyectos); $i++) {
    foreach ($nombres as $key => $nombre) {

 if (mysql_query("INSERT INTO inscripcion_alumnos (id,idinscripcion_proyectos,cedula,nombres,apellidos) VALUES
    ('$id','$last_id','$cedula[$key]','$nombres[$key]','$apellidos[$key]')",$link));

}
}

echo "

¡ Bien Hecho: Registro Insertado Correctamente !

";
header("refresh:5;registrar_inscripcion.php");

          }
  else

echo "

¡ Ups Aviso: Disculpe Este Usuario no Puede Inscribirse en proyecto ya que no asistio a la charla !

";
header("refresh:5;registrar_inscripcion.php");

}

?>

ahora lo he editado asi pero de igual manera me brincan los mjs de alertas:
    <?php
 if (isset ($_POST['guardar'])){

$id=$_POST['id'];
$idinscripcion_proyectos=$_POST['idinscripcion_proyectos'];
$cedula=$_POST['cedula'];
$nombres=$_POST['nombres'];
$apellidos=$_POST['apellidos'];

   $sql_user="SELECT count(1) as item FROM pre_inscripcion WHERE estado IN('NO Asistio', 'Por Asistir') AND cedula='$cedula[$key]' LIMIT 1";
   $res=mysql_query($sql_user,$link);
   if (mysql_num_rows($res) > 0) {

    echo "

    ¡ Ups Aviso: Disculpe Este Usuario no Puede Inscribirse en proyecto ya que no Asistio a la Charla !

";
    //header("refresh:5;registrar_inscripcion.php");

    }

  $sql="SELECT * FROM inscripcion_alumnos WHERE id='$id' LIMIT 1";
  $res=mysql_query($sql,$link);
  $nrows=mysql_num_rows($res);

    //******** He editado esta parte (A. Cedano)
if($nrows==0)
{
    for ($i = 0; $i < count($idinscripcion_proyectos); $i++)
    {
        foreach ($nombres as $key => $nombre)
        {

            if (mysql_query("INSERT INTO inscripcion_alumnos (id,idinscripcion_proyectos,cedula,nombres,apellidos) VALUES
                ('$id','$last_id','$cedula[$key]','$nombres[$key]','$apellidos[$key]')",$link))
            {

                echo "

                    ¡ Bien Hecho: Registro Insertado Correctamente !

";
                //header("refresh:5;registrar_inscripcion.php");
            }
            else
            {

                echo "

                ¡ Ups Aviso: El Registro ya se Encuentra Insertado !

";
                //header("refresh:5;registrar_inscripcion.php");
            }
        }
    }
}

?>

A: Plantearé la solución a tu problema en dos etapas. Primero la posibilidad de verificar la asistencia (a), segundo el manejo de los datos (b).
A. Verificar la asistencia
Para ello podrías sencillamente tener una tabla auxiliar en la base de datos en la que sólo estén inscritos los alumnos que hayan asistido. Esta tabla podría incluso servir como control de asistencia, por ejemplo en ella podrías registrar las fechas en que un alumno ha asistido a un curso o taller determinado y otras cosas...
Para verificar si el alumno asistió sólo haces una consulta a dicha tabla buscando el id del estudiante, si se encuentra el id significa que asistió, si no lo encuentra, significa que no ha asistido.
B. Consultar a la Base de Datos

Esto es lo más importante. Se requiere siempre un buen manejo de nuestros datos y que el mismo sea hecho de forma eficaz.

No te asustes con la solución que te voy a dar, puede parecer larga, pero si haces algo así te vas a ahorrar muchos dolores de cabeza en el futuro.
Lo primero que quiero indicarte es que tu código es inseguro, ya que no estás usando PDO ni MySQLi, sino extensiones obsoletas e inseguras de PHP tales como mysql_query() y mysql_num_rows(), al respecto de las cuales dice el Manual de PHP:

Esta extensión fue declarada obsoleta en PHP 5.5.0 y eliminada en PHP
  7.0.0. En su lugar debería utilzarse las extensiones MySQLi o PDO_MySQL. Véase también la guía MySQL: elegir una API y sus P+F
  relacionadas para más información. Alternatives to this function
  include: mysqli_query() and PDO::query()

Estas extensiones son susceptibles de Inyección SQL.
Solución propuesta con PDO
Propongo una solución basada en PDO. Yo lo prefiero con respecto a MySQLi, aunque cualquiera de los dos es válido.
Lo ideal es tener una clase en tu PHP que se dedique a hacer la conexión, de forma que no tengas que andar preocupándote por eso cada vez que tengas que conectar. Sólo invocas a tu clase, llamada Conexion en este caso. Además la clase Conexion tendrá varios métodos o funciones que te facilitarán la vida y lo mejor de todo es que puedes agregar en ella cuantos métodos necesites. Eso sí, cuando crees un método permite que éste tenga un uso múltiple, o sea, las cosas particulares pásalas en parámetro, sea al mismo método, sea a otro de la clase.
También, este modelo de Clase podría ser útil en cualquier proyecto PHP que tengas.
Bueno, esta sería la clase Conexionque podría ser un archivo php llamado conexion.php el cual deberás incluir cada vez que necesites usar la clase.
conexion.php
<?php
    class Conexion {
        /*
         * Rellenar estos campos con tus datos *
         */

        private $host      = 'localhost';
        private $user      = '';
        private $dbname    = '';
        private $pass      = '';
        private $error;

        public function __construct(){
            // Set DSN
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname.';charset=utf8';

            // Set options
            $options = array(
                PDO::ATTR_PERSISTENT    => true,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
                );

        // Create a new PDO instance
            try{
                $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
                }
                // Catch any errors
            catch(PDOException $e){
                $this->error = $e->getMessage();
            }
        }

        public static function getInstance()
        {
            if (self::$instance == null) {
                $className = __CLASS__;
                self::$instance = new $className();
            }
            return self::$instance;
        }

        public function query($query){
            $this->stmt = $this->dbh->prepare($query);
        }

        public function execute(){
            return $this->stmt->execute();
        }

        public function resultset(){
            $this->execute();
            return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        public function lastInsertId(){
            return $this->dbh->lastInsertId();
        }

        public function bind($param, $value, $type = null){
            if (is_null($type)) {
                switch (true) {
                    case is_int($value):
                        $type = PDO::PARAM_INT;
                        break;
                    case is_bool($value):
                        $type = PDO::PARAM_BOOL;
                        break;
                    case is_null($value):
                        $type = PDO::PARAM_NULL;
                        break;
                    default:
                        $type = PDO::PARAM_STR;
                }
            }
            $this->stmt->bindValue($param, $value, $type);
        }

        public function single(){
            $this->execute();
            return $this->stmt->fetch(PDO::FETCH_ASSOC);
        }

        public function valor(){
            $this->execute();
            $valor=$this->stmt->fetch(PDO::FETCH_COLUMN);
            return (empty($valor)) ? 0 : $valor;
        }

        public function si_existe(){
            $this->execute();
            if ($this->stmt->fetch(PDO::FETCH_ASSOC)){
                return true;
            } else {
                return false;
            }
        }

}

?>

¿Cómo uso la clase `Conexion`?
Ahora viene lo bueno. En el caso del problema planteado en tu pregunta, y en cualquier otro caso que tenga que ver con bases de datos.
tuarchivo.php
include_once "conexion.php"; // esto incluirá la clase Conexion en el archivo actual

//Datos obtenidos del formulario

$id=$_POST['id'];
$idinscripcion_proyectos=$_POST['idinscripcion_proyectos'];
$cedula=$_POST['cedula'];
$nombres=$_POST['nombres'];
$apellidos=$_POST['apellidos'];

/*
 *Aquí creas una nueva instancia de la clase
 * e invocas al método que devuelve una conexión válida
 */

    $cnx = new Conexion();
    $db=$cnx->getInstance();

/*
 *Ya tendrás en la variable $db una conexión disponible a tu BD
 * Ahora envías las consultas a tu objeto de BD
 */

/*
 * Verificar que el usuario existe en la tabla de asistencias
 * Enviaremos una consulta preparada a la BD
 * Una consulta preparada protege a la BD de Inyección SQL
 * Siempre es recomendable separar la consulta y los datos
 * Por eso verás que en la consulta aparece `WHERE id=:id`
 * porque luego `id`es pasado en parámetro usando `bind`
 * El método `si_existe` nos dirá si hay alguien o no con ese id
 * devolviendo `true` o `false`según el caso
 */
    $consulta= "SELECT id_alumno FROM tabla_de_asistencias WHERE id_alumno=:id LIMIT 1";
    $db->query($consulta);
    $db->bind(':id', $id);
    $datos=$db->si_existe();

/*
 * Ahora verificamos si $datos es `true`
 * Si lo es significa que el alumno con ese id ha asistido
 * y que en consecuencia podemos insertar
 * El `INSERT`se hace también mediante consulta preparada
 * enviando los datos separados de la cadena SQL `INSERT`
 */
if ($datos)
{
    $consulta="INSERT INTO inscripcion_alumnos
               (id,idinscripcion_proyectos,cedula,nombres,apellidos)
               VALUES (:id, :idinscripcion, :cedula, :nombres, :apellidos)";
    $db->query($consulta);
    $db->bind(':id', $id);
    $db->bind(':idinscripcion', $last_id);
    $db->bind(':cedula',$cedula[$key]);
    $db->bind(':nombres',$nombres[$key]);
    $db->bind(':apellidos',$apellidos[$key]);
    $db->execute();
}
else
{
    echo "Este usuario no está inscrito en la tabla de asistencias";
}

Espero te sirva.
Si tienes dudas, las puedes plantear en comentario.

A: Yo crearia una tabla charla_proyecto que tuviera por columna :
id, fk_inscripción_proyectos, fk_usuario

Asi siempre voy a poder estar controlando que usuario presenciaron la charla de x proyecto

A: Puedes hacerlo en el momento de crear tu tabla le agregas un check
CHECK ((estado='estadoAceptado1')
       OR (estado='estadoAceptado2'))

Puedes probar CHECK (estado!='porAsistir')  pero no estoy seguro de esta forma

A: Yo pienso que sencillamente creas otra tabla que llamadas Asistencias o como dice @OmarMiranda "charla_proyecto", la cual tenga algo asi:
Asistencias
ID --- DESC

1  --- Asistio

2  --- Por Asistir

Y en el formulario de la preinscripcion colocas un SELECT con esta tabla de Asistencias.
El mostrara los dos posibles estados: Asistio - No asistio
luego al inscribir puedes verificar con una sentencia asi:
$id=$_POST["id_del_estudiante"];

SELECT * FROM estudiantes WHERE asistio_ID = 1 AND id_estudiante = $id

Si existen ambos que te diga "El estudiante puede inscribir".
Si no existe y no devuelve el resultado, te diga "este estudiante no puede ser inscrito" y borre los campos
Esto lo harias con mysql_rows
Si te parece bien asi puedo ayudarte a armar el SELECT y el formulario.
Codigo:
<?php
include 'conexion.php';
function opciones(){

global $conexion;
    $sql="SELECT * FROM asistencias";
    $resultado = $conexion->query($sql);
    while ($datos = $resultado->fetch_array(MYSQLI_ASSOC))
    {
     echo "<option value='".$datos['ID']."'>".$datos['DESC']."</option>";
    }
}
?>

    <form method="POST" action="preinscribir.php">

Sistema para preinscribir

    Ingrese id<input type="text" name="id">
    Ingrese nombre<input type="text" name="nombre">
    Seleccione la asistencia a la charla
    <select>
    <?php opciones();?>
    </select>
    <input type"submit" name="pre" value="Preinscribir">
    </form>

A: $sql_user="SELECT count(1) as item FROM pre_inscripcion WHERE estado IN('NO Asistio', 'Por Asistir') AND cedula='$cedula[$key]' LIMIT 1";
   $res=mysql_query($sql_user,$link);
   if (mysql_num_rows($res) > 0) {

    echo "

    ¡ Ups Aviso: Disculpe Este Usuario no Puede Inscribirse en proyecto ya que no Asistio a la Charla !

";
    //header("refresh:5;registrar_inscripcion.php");

    }

Esta porción de código siempre va a entrar en el if, y por ende no va a realizar el else, que es donde está tu método de inserción. Porque preguntas por la cantidad de filas devueltas que siempre va a ser mayor a cero, por más que tu cantidad contada es cero, me explico? Tienes que preguntar por el valor devuelto del COUNT()


text:
Q: Filling a dictionary with numbers from textbox and with the textboxes as keys I'm writing a code where I want to get the numbers from multiple TextBox controls into a collection. Sort it, then change the background color of the textboxes containing the top 3 highest value. This is the dictionary
Dictionary<System.Windows.Forms.TextBox, string> all_cycles = new Dictionary<System.Windows.Forms.TextBox, string>(10);
for (var i = 1; i < 5; i++)
{
    all_cycles.Add(((System.Windows.Forms.TextBox)this.Controls.Find("txtendc" + Convert.ToString(i), true)[0]),this.Text);
}

I know that with "this.text" I won't get the textboxes values so that's why I'm asking.
I also tried creating an array which only contains the values of the textboxes which I then use to fill the dictionary. But it always drops an Index was outside the bounds of the array. Or Index was out of range exception. This drops the out of range exception:
List<System.Windows.Forms.TextBox> txtendc = new List<System.Windows.Forms.TextBox>(10);
for (var i = 1; i < 5; i++)
{
    txtendc.Add((System.Windows.Forms.TextBox)this.Controls.Find("txtendc" + Convert.ToString(i), true)[0]);
}
int[] endc_content = new int[10];
for (var i = 1;i < 5; i++)
{
    endc_content[i]= int.Parse(txtendc[i].Text);
}

I don't have any problem with the coloring, just filling up the dictionary. If you have a better solution than the dictionary collection please tell me.
Thanks
EDIT: This whole code is inside a timer tick event if it matters anything

A: I would create a list of all of your TextBoxes in code behind when you instantiate your class.  Then you could use Linq to get the top 3.  Remember that you will need to confirm that all of the textboxes actually contain numbers - ensure that your program doesn't crash if you enter text into one of them.  If all of the TextBoxes in the form will be holding these numbers, you could do something like this to validate and sort in one method (not tested):
private List<TextBox> myTextBoxes { get; set; }

public Form1()
{
    InitializeComponent();
    foreach (Control c in this.Controls)
    {
        if (c.GetType() == typeof(TextBox))
            myTextBoxes.Add((TextBox)c);
    }
}

private IEnumerable<TextBox> getTop3()
{
    return myTextBoxes.Where(tb => tb.Text.AsEnumerable().All(char.IsDigit)).Select(tb => tb).OrderByDescending(tb => Double.Parse(tb.Text)).Take(3);
}

The first step of the Linq query converts the text to an enumerable of char and ensures that all characters contain digits (instead of letters).  The second selects these textboxes.  The third parses them into doubles and compares them, highest number first.  The last takes the first three in the list (the textboxes containing the highest 3 numbers)
EDIT: Based on your comments, the code could be simplified to:
public Form1()
{
    InitializeComponent();

}

private IEnumerable<TextBox> getTop3(string textboxPrefix)
{
    List<TextBox> textBoxesToSort = new List<TextBox>();
    foreach (Control c in this.Controls)
        if (c.GetType() == typeof(TextBox) && c.Name.StartsWith(textboxPrefix))
            textBoxesToSort.Add((TextBox)c);

    return textBoxesToSort.OrderByDescending(tb => Double.Parse(tb.Text)).Take(3);
}

A: You can sort those TextBox controls based on values and then select top 3 from the list:
var result = this.Controls.OfType<TextBox>().Select(x =>
                 {
                     try { return new { Key = x, Value = Convert.ToInt32(x.Text) }; }
                     catch { return null; }
                 })
                 .Where(x=>x!=null)
                 .OrderByDescending(x => x.Value)
                 .Take(3)
                 .ToDictionary(x => x.Key, x => x.Value);

To test the result, show a message box containing values:
MessageBox.Show(string.Join("\n",
    result.Select((x, i) => string.Format("{0}:{1}", i+1, x.Value))));

Above example will be applied on any list of TextBox controls and just for example I used all TextBox controls of the form.

A: Please try this, hope it helps:
List<System.Windows.Forms.TextBox> all_cycles = new List<System.Windows.Forms.TextBox>(10);
        int[] indexOfTextBox = new int[3];
        foreach(var cycle in all_cycles)
        {
            int value = Convert.ToInt16(cycle.Text);
            if (value > indexOfTextBox[0])
            {
                indexOfTextBox[0] = value;
            }
            else if (value > indexOfTextBox[1])
            {
                indexOfTextBox[1] = value;
            }
            else if (value > indexOfTextBox[2])
            {
                indexOfTextBox[2] = value;
            }
        }
        all_cycles[indexOfTextBox[0]].BackColor = ConsoleColor.Red;
        all_cycles[indexOfTextBox[1]].BackColor = ConsoleColor.Blue;
        all_cycles[indexOfTextBox[2]].BackColor = ConsoleColor.Green;


text:
Q: Process management in TempleOS: listing and killing processes? TempleOS has different processes, according to docs/Glossary.DD.Z,

There is no distinction between task, process or thread.  The Fs segment reg is kept pointing to the current task's CTask.  There is only one window per task, and only Core0 tasks can have windows.  Each task has a code and data heap so memory is returned when it dies.  Each task has a hash symbol table.
Since there is not friendly disk sharing and all tasks have the same address map, it might be accurate to call TempleOS, "multi-thread/single-process". You run a single application process on Core0 and it can create threads on the same core or others.  If you run multiple processes, it should be safe, but one process will wait until another completely finishes a long disk access

From that we can run multiple processes, and I am guessing when we run an application, such as a game, that game runs as its own process until completion and then gives back control to the terminal. How can we from the terminal get a list of processes, or kill them? I don't see any documentation on process management?
What is the TempleOS way to run ps and kill?

A: TempleOS equivalent of

*

*ps is TaskRep;

*kill is Kill(task);
You can see a screen sot of TaskRep() here, #0 is the Adam task.


text:
Q: Memory address out of bounds error in MIPS but works in a different function I am making a program in MIPS that will compare two strings but I can't seem to access the proper locations. I have a function that calculates the lenght of the strings which works fine, but when I try to use a different function (in this case its just a test to see if it works), it says that i'm acessing the wrong memory. I am using QTSpim to test it. The function that works is the duzinaStringa, the one that does not is the krajStringa. Currently it's just trying to print out the first character of the string so I can make sure it works
.text

krajStringa:

li $v0,0
li $t0,0 #brojac1

move $t2, $a0 #adresa prvog
move $t3, $a1 #adresa drugog

lb $a0,0($t2)
li $v0,4
syscall
jr $ra

duzinaStringa:
move $t1,$a0
li $t0,0
petlja:
    lb $t2,0($t1)
    beqz $t2,krajDuzine
        addi $t1,$t1,1
        addi $t0,$t0,1
        j petlja

    krajDuzine:
    addi $t0,$t0,-1
    move $v0,$t0
    jr $ra

main:

la $a0,str1
li $v0, 4
syscall

la $a0, arr
li $a1,200
li $v0, 8
syscall

la $a0,str1
li $v0, 4
syscall

la $a0, arr2
li $a1,200
li $v0, 8
syscall

la $a0,arr
jal duzinaStringa
move $a2,$v0

la $a0,arr2
jal duzinaStringa
move $a3,$v0

la $a0,arr
la $a1,arr2
jal krajStringa

li $v0,10
syscall

.data
arr: .space 200
arr2: .space 200
str1: .asciiz "Unesi string: \n"

A: As @ErikEidt pointed out, I used the wrong system call when printing the first character of a string.


text:
Q: Reducing number of static routes in VPN cluster I'm trying to set up a high availability OpenVPN cluster for worker nodes that have a fixed ip regardless of which OpenVPN server they connect to. This is a requirement, as things are bound specifically to that ip address. I was planning to have a distributed etcd on each master node where I push which master node has which worker nodes (connect/disconnect script with OpenVPN) and update then update the routing table of each master accordingly (by watching the etcd key).
Everything will be running in docker containers.
I've made a diagram of the situation I have now with 3 master nodes (M1,M2,M3), 3 worker nodes (w1,w2,w3) and "sidecar" containers (M2M1, M3M1, M3M2) to connect each master to the others masters.
With the following routing tables set up everything works fine but it requires updating the routes on both the master nodes and the sidecar containers.
Aside from the standard iptables -A FORWARD rules to ensure traffic is forwarded between interfaces I only had to add a single iptables rule on the worker nodes, e.g iptables -A POSTROUTING -o tap0 -m iprange --dst-range 5.0.0.0-5.255.255.255 -j SNAT --to-source 5.0.0.1 -t nat for w1, otherwise it would send the packets with the primary ip address.

I was wondering if it is possible to set up policy based routes on the sidecar containers to just have the rule "if it's coming from tap0 and it's from an ip in 5.0.0.0/8 then put it on eth0 towards the master node inside the same subnet" and the other way around "if it's coming from eth0 and it's in an ip in 5.0.0.0/8 then put it on tap0 towards the vpn gateway". If I could do that then I just need to manipulate the routes on the master nodes
Am I correct that I would need to mark the packets with iptables and then setup 2 route tables, one corresponding to each mark and then set up the route on that table?
I tried setting up a bridge before but I couldn't get it to work.
(And if there is a much better way of setting up a vpn cluster with fixed IPs than my rather convoluted setup do let me know)
EDIT:
With the help of the answer below I tested the following statements for M2M1, which works fine:
# Create the 2 tables to add specific routes on
echo "2     toeth" >> /etc/iproute2/rt_tables
echo "3     totap" >> /etc/iproute2/rt_tables

# Everything coming from eth0 will be going to the totap table and everything from tap0 will be going to the toeth table
ip rule add table totap iif eth0
ip rule add table toeth iif tap0

# Add the routes but on the specific table
ip r r 5.0.0.0/8 via 192.168.1.1 table totap
ip r r 5.0.0.0/8 via 172.30.2.2 table toeth

EDIT2:
In case anyone is interested playing around with it, I've set up a github repo

A: You can use ip rule (see man ip-rule) to setup specific routing tables based on source or destination IP and based on source or destination interface. It should be able to achieve what you want.
SELECTOR := [ from PREFIX ] [ to PREFIX ] [ iif STRING ] [ oif STRING ] ...


text:
Q: Getting inconsistent margins across pages
I'm getting inconsistent margins across pages. The preamble of my document is:
\documentclass[12pt,a4paper,twoside, openright]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{sectsty}
\usepackage{listings}
\usepackage{color}
\usepackage{titlesec}
\usepackage{mathptmx}
\usepackage{framed}
\usepackage{xcolor}

% Title Formats for Chapter and Section Headings
\titleformat{\section}{\normalfont\bfseries}{\thesection}{1em}{}[{\titlerule[0.8pt]}]
\titleformat{\chapter}[display]
{\normalfont\bfseries \centering}{\chaptertitlename\ \thechapter}{12pt}{}

\titlespacing*{\chapter}{0pt}{-50pt}{14pt}
\titlespacing*{\section}{0pt}{14 pt}{14pt}

I haven't used any other commands to change spacing. The margins do return to the original value on the next page.


text:
Q: attr_accessor feature not working as expected I have defined a class like below. But when I run to the format function I get an error like below. Thanks!!!
class NonAccentVietnamese
  def initialize(str)
    @str = str
  end

  def format
    str = str.downcase
    str = str.gsub(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/, "a")
    str = str.gsub(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/, "e")
    str = str.gsub(/ì|í|ị|ỉ|ĩ/, "i")
    str = str.gsub(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/, "o")
    str = str.gsub(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/, "u")
    str = str.gsub(/ỳ|ý|ỵ|ỷ|ỹ/, "y")
    str = str.gsub(/đ/, "d")
    # Some system encode vietnamese combining accent as individual utf-8 characters
    str = str.gsub(/\u0300|\u0301|\u0303|\u0309|\u0323/, "") # Huyền sắc hỏi ngã nặng
    str = str.gsub(/\u02C6|\u0306|\u031B/, "") # Â, Ê, Ă, Ơ, Ư
    str
  end

  private

  attr_accessor :str
end

[2] pry(main)> NonAccentVietnamese.new("Ruby on Rails").format
NoMethodError: undefined method `downcase' for nil:NilClass
from /app-server/app/formats/non_accent_vietnamese.rb:7:in `format'
[3] pry(main)>

enter image description here

A: You have local variable name str and an accessor method str, So the local str is being used. What you can do is:

*

*Change the name of the local variable

*Change the name of the attr_accessor

*Use @str in place of attr_accessor.

A: You can either use @str.downcase or self.str.downcase.
That being said, you should use the transliterate method:
https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate
That will let you use the transliterate methods to replace non-ascii characters with ascii alternatives:
I18n.transliterate("Über der Höhenstraße")
 => "Ueber der Hoehenstrasse"


text:
Q: Unfortunately, myApplication has stopped Every time I run my App,it stops.
It says: Unfortunately, myApplication has stopped
how can i fix it?
I am using the latest version of Android Studio (1.5.x)
I named my application DDDx, as you can see in this screenshot

This is my log (part 1)

This is my log (part 2)

A: The problem is that you are using a ListActivity.
Therefore, in the Activity layout, you must have a single ListView with a forced id of @android:id/list.


text:
Q: AutoMapper ProjectTo extension At least one object must implement IComparable I am using AutoMapper IQueryable extension ProjectTo for selecting data.
When I am trying to write unit test for this method which use this extension method I get this exception.
At least one object must implement IComparable.
I also tried to implement interface for type which is used in ProjectTo extension, but the same exception occured.
In unit test I use Moq for mocking EntityFramework DbContext
Here is the code which return exception:
freePacks = packageQuery.ProjectTo<PackageDTO>();

return new PackageQueryResult
{
  query.OldestPacks
         ? freePacks.OrderBy(p => new { p.ProdDt, p.Cert }).NoLock()
         : freePacks.OrderByDescending(p => new { p.ProdDt, p.Cert }).NoLock()
};

Where NoLock() is
static List<T> NoLock<T>(this IQueryable<T> query)
{
  var txn = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew,
            new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
            }))
        {
            List<T> toReturn = query.ToList();
            txn.Complete();
            return toReturn;
        }
}

Is any way how can I solve this problem?
Thanks for any advice

A: I think the problem is caused by the OrderBy(p => new { p.ProdDt, p.Cert }). The anynomous object you are creating does not implement IComparable, so OrderBy does not work.
Use the ThenBy method if you need to sort by multiple criteria:
query.OldestPacks
     ? freePacks.OrderBy(p => p.ProdDt).ThenBy(p => p.Cert).NoLock()
     : freePacks.OrderByDescending(p => p.ProdDt).ThenByDescending(p => p.Cert).NoLock();


text:
Q: take string input at 2-d array in c i am new in c,so i want to input string at 2-d array,but don't print string.what's wrong in this code and how can i fixed this problem.thanks in advanced
#include <stdio.h>
#include<string.h>
int main()
{
    char col[100][100];
    int i,j;
    for(i=0; i<2; i++)
    {
        for(j=0; j<2; j++)
        {
            scanf("%s",
                  &col[i][j]);

        }
    }
     for(i=0; i<2; i++)
    {
        for(j=0; j<2; j++)
        {
           printf("%s\t",col[i][j]);

        }
        printf("\n");
    }

    return 0;
}

A: You're printing a char with %s. Change instead to %c.
printf("%c\t", col[i][j]);

With %s printf will print all characters until a \0 is found and in your case there's none which will lead to unexpected behavior.

A: In a 2D character-array, each element col[i][j] is a character. But , you're taking string and printing string using the printf and scanf statements. You need to change the following:
scanf("%c",&col[i][j]);

and
printf("%c\t",col[i][j]);

A: Use %c instead of %s because %s is a identifier of String. What I found in your code is that you said you want string as input but you are taking char by char as a input. I will suggest you to use pointer to take String as a input in 2D char Array.
Taking String as a input in 2D char Array
#include <stdio.h>
#include <string.h>
int main() {
    char *s[100];
    char s1[100];
    int i;
    for(i=0;i<5;i++){
        scanf("%s", s1);
        s[i]=strdup(s1);
    }
    for(i=0;i<5;i++){
        printf("%s\n", s[i]);
    }
    return 0;
}

What I am doing is that I am taking the input from user in s1 and put that in the 2D char array. By using this method you have put each string in a each row.
Hopefully that help.


text:
Q: WSO2 - Set a property and write it in the Carbon Log I've created a Custom Proxy and added a class mediator and log Mediator in it. I'm trying to set a property's value in the java class and need to write that in the log, as the proxy gets deployed. But, so far, haven't got any success.
I've tried adding a parameter in the Log mediator and used the get-property() method but it still doesn't print it. If I use a 'Property' mediator itself, then I'm able to write the value in the log but that's not our purpose here.
I've also tried using log.debug in the java class, just to write the usual 'entering/exiting a function', but to no respite.
Could anyone please help?

A: How are you setting a property in the java class(ie: in your class mediator)?
It should be like;
synapseMesssageContext.setProperty(key,value);

Then,In the sequence flow access it as;
<property xmlns:ns="http://org.apache.synapse/xsd"   name="testing the property"
                expression="get-property('key')"   scope="default"/>

A: You can use log.info to print any log messages. Please reffer [1] which has logged messages using log.info.
[1]http://wso2.org/library/2898


text:
Q: Multiple Select onChange create dynamic fields I'm trying to accomplish when an option is selected/unselected on a multiple select the onChange event will call a function to add or remove the dynamic field that is selected/unselected.
I've been trying for a few hours to think of the best logical approach to get this to work.

$('.multi-select').on('change', function() {
  $.each($(this).val(), function() {
   /* [ Some logic to check if a dynamic input should be removed or added. ]*/
  });
});

<select class="multi-select" multiple>
  <option value="0" selected>Col 0</option>
  <option value="1">Col 2</option>
  <option value="2" selected>Col 2</option>
  ...
</select>

  <input type="text" name="option[0]" value="asc">
  <input type="text" name="option[2]" value="desc">

I just need some guidance with the best approach that I should take.

A: According to your question, every time the user select one or more elements from the selectbox a function must do:

*

*if element is selected and already present in the div area: do nothing

*if the element is  selected and not present in the div area: insert

*if the element is not selected --> remove the element from the div area

The difficulty here is to select an element by name where the name attribute contains a square bracket.

$(function () {
  $('.multi-select').on('change', function(e) {
    var cacheEle = $('.dynamic-fields');
    $(this).find('option').each(function(index, element) {
      if (element.selected) {
        if (cacheEle.find('input[name="option\\[' + element.value + '\\]"]').length == 0) {
          cacheEle.append('<input type="text" name="option[' + element.value + ']" value="' + element.text + '">')
        }
      }  else {
        cacheEle.find('input[name="option\\[' + element.value + '\\]"]').remove();
      }
    });
  });
});

<select class="multi-select" multiple>
    <option value="0" selected>Col 0</option>
    <option value="1">Col 1</option>
    <option value="2" selected>Col 2</option>
</select>

    <input type="text" name="option[0]" value="asc">
    <input type="text" name="option[2]" value="desc">


text:
Q: Escaping less than sign in paste/system command in R I would like to run head <(cat file.txt) using system within R, but escaping < is a problem.
system(paste("head <(cat file.txt)"))
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `head <(cat file.txt)'

I've tried escaping it, but its not working

system(paste("head /<(cat file.txt)"))
head: cannot open `/<(cat file.txt)' for reading: No such file or directory

Can someone suggest an alternative.
Cheers

A: The problem is not with escaping <. By default, system runs the command with /bin/sh, and your command is incorrect with this shell :
$ sh -c "head <(cat foo.txt)"
sh: 1: Syntax error: "(" unexpected

But it works with bash.
Under R, you can try something like :
system("bash -c 'head <(cat file.txt)'")


text:
Q: Logstash - match filename I have two servers. The first one hosts elastic stack. Both servers have a file /var/log/commands.log which is configured in the same way and are being shipped with filebeat to logstash.
Using grok, I tried parsing the data into custom fields using this statement:
if [log][file][path] == "/var/log/commands.log" {
grok{
match => { "message" => "*some grok stuff*"
}
}
}

Problem is, even though on both servers the file is /var/log/commands.log & they're configured the same - it skips the if statement as if it's false.
I've noticed that if I ship the logs locally (without filebeat - just do input{file{input => "/var/log/commands.log}} ) it works for the local "/var/log/commands.log" file on that machine that hosts logstash.
For reference, this is the full .conf file for logstash: https://pastebin.com/1QbnAG7G
This is how elastic sees the file path: https://i.imgur.com/5h9HXf2.png
Does anyone why it skips the "if" statement? How to make it filter by name.  Thanks ahead!

A: So, it looks like you're using =~ in your pastebin code. If that's the case, you'll be matching a regex. Is that what you meant to do?
If you're intending to use a regex, then you'd want something like this, probably:
if [log][file][path] =~ /\/var\/log\/commands\.log/
Example: https://regex101.com/r/nqGg9G/1


text:
Q: Google Static Maps API not returning any data Im trying to use the Google Static Maps API but it's not returning anything. The API key is correct and I am successfully using the Google Places API. IDK what I'm doing wrong. I've tried using only the required parameters and nothing. I've also tried using an example URL from the API Docs and nothing either.
NSString *url = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/staticmap?zoom=18&size=320x120&visual_refresh=true&markers=size:mid|color:0x00AB8B|%f,%f&key=AIzaSyDbg7wrSq-USEJWUqf5TOPepbtGRwbYtg8", [LocationController sharedSingleton].locationManager.location.coordinate.latitude, [LocationController sharedSingleton].locationManager.location.coordinate.longitude];

NSURL *googleURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

      dispatch_async(kBgQueue, ^{
           NSData* data = [NSData dataWithContentsOfURL: googleURL];
           NSLog(@"data size: %lu", (unsigned long)[data length]);
           if (data.length != 0){
               [mapViewArray addObject:data];
           }
      });

A: Figured it out. Was missing the required "sensor" param


text:
Q: Restrict all special characters except for '/' in my input text field in html I want to restrict all special characters inside my input text field, except for the character /. How do I do that?
Edit: I want my text field to be like this input text

A: This code did the trick:
var specialKeys = new Array();
specialKeys.push(8);  //Backspace
specialKeys.push(9);  //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right

function IsAlphaNumeric(e) {
    var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
    var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
    //console.log(e.keyCode);
    document.getElementById("error").style.display = ret ? "none" : "inline";
    if(e.charCode==47){
        ret=true;
        document.getElementById("error").style.display ="none";
    }
    return ret;
}


text:
Q: How can I run a function (to get side effects) when a python Mock is called? I am mocking (using python Mock) a function where I want to return a list of values, but in some of the items in the list I want a side effect to also occur (at the point where the mocked function is called).  How is this most easily done?  I'm trying something like this:
import mock
import socket

def oddConnect():
  result = mock.MagicMock()  # this is where the return value would go
  raise socket.error  # I want it assigned but also this raised

socket.create_connection = mock(spec=socket.create_connection,
  side_effect=[oddConnect, oddConnect, mock.MagicMock(),])
# what I want: call my function twice, and on the third time return normally
# what I get: two function objects returned and then the normal return

for _ in xrange(3):
  result = None
  try:
    # this is the context in which I want the oddConnect function call
    # to be called (not above when creating the list)
    result = socket.create_connection()
  except socket.error:
    if result is not None:
      # I should get here twice
      result.close()
      result = None
  if result is not None:
    # happy days we have a connection
    # I should get here the third time
    pass

The except clause (and it's internal if) I copied from the internals of socket and want to verify that I "test" that path through my copy of the code.  (I don't understand how socket can get to that code (setting the target while still raising an exception, but that isn't my concern, only the I verify that I can replicate that code path.)  That's why I want the side effect to happen when the mock is called and not when I build the list.

A: I also encountered the problem of wanting a side effect to occur for only some items in a list of values.
In my case, I wanted to call a method from freezegun the third time my mocked method was called. These answers were really helpful for me; I ended up writing up a fairly general wrapper class, which I thought I'd share here:
class DelayedSideEffect:
    """
    If DelayedSideEffect.side_effect is assigned to a mock.side_effect, allows you to
    delay the first call of callback until after a certain number of iterations.
    """
    def __init__(self, callback, delay_until_call_num: int, return_value=DEFAULT):
        self.times_called = 0
        self.delay_until_call_num = delay_until_call_num
        self.callback = callback
        self.return_value = return_value

    def side_effect(self, *args, **kwargs):
        self.times_called += 1
        if self.times_called >= self.delay_until_call_num:
            self.callback()
        return self.return_value

To then return "my_default_return_value" without calling the lambda function on the first three calls:
with freeze_time(datetime.now()) as freezer:
    se = DelayedSideEffect(callback=lambda: freezer.move_to(the_future), 3)
    my_mock = MagicMock(return_value="my_default_return_value", side_effect=se)

A: According to the unittest.mock documentation for side_effect:

If you pass in an iterable, it is used to retrieve an iterator which must
  yield a value on every call. This value can either be an exception
  instance to be raised, or a value to be returned from the call to the
  mock (DEFAULT handling is identical to the function case).

Therefore, your socket.create_connection mock will return the function oddConnect for the first two calls, then return the Mock object for the last call. From what I understand, you want to mock create_connection object to actually call those functions as side effects rather than returning them.
I find this behavior rather odd, since you'd expect side_effect, to mean side_effect in every case, not return_value. I suppose the reason this is so lies in the fact that the value of the return_value property must be interpreted as-is. For instance, if your Mock had return_value=[1, 2, 3], would your Mock return [1, 2, 3] for every call, or would it return 1 for the first call?
Solution
Fortunately, there is a solution to this problem. According to the docs, if you pass a single function to side_effect, then that function will be called (not returned) every time the mock is called.

If you pass in a function it will be called with same arguments as the
  mock and unless the function returns the DEFAULT singleton the call to
  the mock will then return whatever the function returns. If the function
  returns DEFAULT then the mock will return its normal value (from the
  return_value).

Therefore, in order to achieve the desired effect, your side_effect function must do something different every time it is called. You can easily achieve this with a counter and some conditional logic in your function. Note that in order for this to work, your counter must exist outside the scope of the function, so the counter isn't reset when the function exits.
import mock
import socket

# You may wish to encapsulate times_called and oddConnect in a class
times_called = 0
def oddConnect():
  times_called += 1
  # We only do something special the first two times oddConnect is called
  if times_called <= 2:
    result = mock.MagicMock()  # this is where the return value would go
    raise socket.error  # I want it assigned but also this raised

socket.create_connection = mock(spec=socket.create_connection,
  side_effect=oddConnect)
# what I want: call my function twice, and on the third time return normally
# what I get: two function objects returned and then the normal return

for _ in xrange(3):
  result = None
  try:
    # this is the context in which I want the oddConnect function call
    # to be called (not above when creating the list)
    result = socket.create_connection()
  except socket.error:
    if result is not None:
      # I should get here twice
      result.close()
      result = None
  if result is not None:
    # happy days we have a connection
    # I should get here the third time
    pass


text:
Q: Difference between x++ and ++x in compiler implementation I searched for x++ vs ++x and I found a great answer here, So I decide to see the assembly output of gcc to see how x++ and ++x implemented:

main() {  int s = 0;  ++s;    return 0; }

Compiling the example:

gcc mul.c -masm=intel -o mul.asm

Output of ++s:
    .file   "mul.c"
    .intel_syntax
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
    lea %ecx, [%esp+4]
    and %esp, -16
    push    DWORD PTR [%ecx-4]
    push    %ebp
    mov %ebp, %esp
    push    %ecx
    sub %esp, 16
    mov DWORD PTR [%ebp-8], 0
    add DWORD PTR [%ebp-8], 1
    mov %eax, 0
    add %esp, 16
    pop %ecx
    pop %ebp
    lea %esp, [%ecx-4]
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 4.2.1 20070719  [FreeBSD]"

Output for x++:
    .file   "mul.c"
    .intel_syntax
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
    lea %ecx, [%esp+4]
    and %esp, -16
    push    DWORD PTR [%ecx-4]
    push    %ebp
    mov %ebp, %esp
    push    %ecx
    sub %esp, 16
    mov DWORD PTR [%ebp-8], 0
    add DWORD PTR [%ebp-8], 1
    mov %eax, 0
    add %esp, 16
    pop %ecx
    pop %ebp
    lea %esp, [%ecx-4]
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 4.2.1 20070719  [FreeBSD]"

So, I am asking if x++ and ++x have different meaning, why GCC outputs the some assembly for them, shouldn't have different output?

A: This is an example of a not-well written test case. The actual result of the expression value++ or ++value is never stored, as such the compiler can handle both equivalent for basic types.
Use this examples instead:
main() { int s = 0, x; x = ++s; return 0; }

main() { int s = 0, x; x = s++; return 0; }

Post-increment:
(gdb) disas /m main
Dump of assembler code for function main():
1       int main(){
   0x0040138c :     push   %ebp
   0x0040138d :     mov    %esp,%ebp
   0x0040138f :     and    $0xfffffff0,%esp
   0x00401392 :     sub    $0x10,%esp
   0x00401395 :     call   0x4018d4

2               int s = 0;
   0x0040139a :    movl   $0x0,0xc(%esp)

3               int x;
4               x = s++;
   0x004013a2 :    mov    0xc(%esp),%eax
   0x004013a6 :    mov    %eax,0x8(%esp)
   0x004013aa :    incl   0xc(%esp)

5               return 0;
   0x004013ae :    mov    $0x0,%eax

6       }   0x004013b3 :   leave
   0x004013b4 :    ret

End of assembler dump.
(gdb)
Pre-increment:
(gdb) disas /m main
Dump of assembler code for function main():
1       int main(){
   0x0040138c :     push   %ebp
   0x0040138d :     mov    %esp,%ebp
   0x0040138f :     and    $0xfffffff0,%esp
   0x00401392 :     sub    $0x10,%esp
   0x00401395 :     call   0x4018d4

2               int s = 0;
   0x0040139a :    movl   $0x0,0xc(%esp)

3               int x;
4               x = ++s;
   0x004013a2 :    incl   0xc(%esp)
   0x004013a6 :    mov    0xc(%esp),%eax
   0x004013aa :    mov    %eax,0x8(%esp)

5               return 0;
   0x004013ae :    mov    $0x0,%eax

6       }   0x004013b3 :   leave
   0x004013b4 :    ret

End of assembler dump.
(gdb)

A: To see different output, you need to do more than just increment.

main() {  int s = 0;  int a = ++s;    return 0; }

++s and s++ do exactly the same thing if the value is not used.

A: It's called "optimization".
In your case, it doesn't matter if pre-increment or post-increment (it results in exactly the same logic flow), so the assembly output is identical.
Here's a counter-example:
/*
 * SAMPLE OUTPUT: i++=1, ++j=3
 */
#include <stdio.h>

int
main (int argc, char *argv[])
{
  int i = 1, j= 2;
  printf ("i++=%d, ++j=%d\n", i++, ++j);
  return 0;
}

Here's the Visual C++ assembler output.  You'll notice that this example increments *both "i" and "j":
; File tmp.c
; Line 5
    push    ebp
    mov ebp, esp
    sub esp, 12                 ; 0000000cH
; Line 6
    mov DWORD PTR _i$[ebp], 1
    mov DWORD PTR _j$[ebp], 2
; Line 7
    mov eax, DWORD PTR _j$[ebp]
    add eax, 1
    mov DWORD PTR _j$[ebp], eax
    mov ecx, DWORD PTR _j$[ebp]
    push    ecx
    mov edx, DWORD PTR _i$[ebp]
    mov DWORD PTR -12+[ebp], edx
    mov eax, DWORD PTR -12+[ebp]
    push    eax
    push    OFFSET FLAT:$SG342
    mov ecx, DWORD PTR _i$[ebp]
    add ecx, 1
    mov DWORD PTR _i$[ebp], ecx
    call    _printf
    add esp, 12                 ; 0000000cH
; Line 8
    xor eax, eax
; Line 9
    mov esp, ebp
    pop ebp
    ret 0
_main   ENDP

Here is gcc assembler, with -O3.  You'll notice it doesn't do any increments: the compiler just stores the final values i=1 and j=3:
.LC0:
        .string "i++=%d, ++j=%d\n"
        .text
        .p2align 4,,15
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $20, %esp
        movl    $3, 8(%esp)
        movl    $1, 4(%esp)
        movl    $.LC0, (%esp)
        call    printf
        addl    $20, %esp
        xorl    %eax, %eax
        popl    %ecx

Finally, here's the optimized Visual C++ version (with "/Ox").  You'll notice it's the shortest of these three examples:
; File tmp.c
; Line 7
    push    3
    push    1
    push    OFFSET FLAT:$SG399
    call    _printf
    add esp, 12                 ; 0000000cH
; Line 8
    xor eax, eax
; Line 9
    ret 0
_main   ENDP


text:
Q: How to validate a RSA public and private key pair in Python I generated an RSA public and private key pair using the pycryptodome module and returned the private key to the user. Now, for fetching some specific data, I need to validate the public and private key pair. I have both of them in bytes form:
public_key = b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlisb129W98LyU3caYcTr\nowqPJLUuaP9imnAOcJxzrKgK..........................qGUPMhPxVFA92mifqr9T2m5cI5/b\nCwIDAQAB\n-----END PUBLIC KEY-----'

private_key = bytes(input())

I need to create a function to check whether the private key entered by the user matches the public key stored by the program.