text:
Q: iOS-Xcode: ProgressHUD at the beginning of the app First of all sorry about my english, it´s not my native language.
I am developing an iOS app that collects data from a JSON and displays them in a table. Everything works correctly . My problem is that JSON has many data and the app takes several seconds until it show the data. So , I need to put a charge indicator to alert the user to wait until the application has loaded the data. To use the charging indicator I downloaded Seller SVProgressHUD :
https://github.com/samvermette/SVProgressHUD
I've integrated SVProgressHUD into my application but I can not make it work as I want.
In my application I have a class AppDelegate and a class MasterViewController (where I load JSON data , populate the tableView and show the tableView)
What I want is when the application starts his executions it shows the SVProgressHUD with the text "Loading" and when the tableView with all the data appears, the SVProgressHUD dissapears.
For this, I added this line of code in my class AppDelegate in the method didFinishLaunchingWithOptions:
[SVProgressHUD showWithStatus:@"Cargando" maskType:SVProgressHUDMaskTypeBlack];

And in my class MasterViewController, in the viewDidLoad method I have added this line of code:
[SVProgressHUD dismiss];

After adding these lines of code, my application runs as ever and doesn't show charging indicator.
I think it may be because in the didFinishLaunching still no loaded view where you can show charging indicator but I don´t know what is the code that I have to add to make it works.
A greeting and thanks for the help .

A: Place this code before you send your json request for fetching data
[SVProgressHUD showWithStatus:@"Updating" maskType:SVProgressHUDMaskTypeBlack];

I have used afnetworking in my application. So when it returns success, i dismiss the SVProgressHUD.
[client postPath:@"xyz.com/abcd" parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD dismiss];
   }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD dismiss];
 }];

Hope it is helpful to you.
Thanks


text:
Q: What is the negation of ((If G, then B) or D)? I was wondering the answer to the negation of the conditional ((If G, then B) or D). Preferably, the answer would be in English/conditional format.

A: Hint: Show that (If G, then B) is equivalent to (not G or B). This implies that your statement is equivalent to ((not G or B) or D). What's the negation of a disjunction?

A: The answer is the following:
$$\neg((G\rightarrow B)\vee D)=\neg(G\rightarrow B)\wedge \neg D=(G\wedge \neg B)\wedge \neg D.$$
First equality is De Morgan's law, second is just a little theorem that you can prove with a truth table: $\neg(A\rightarrow B)=A\wedge\neg B$.
In english the answer is:
$$G \,\,\text{and}\,\, (\text{not} \,\,B) \,\,\text{and}\,\, (\text{not} \,\,D).$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to ORDER BY an unaggregated column in subquery? I'm trying to create a function in Hasura that queries the posts near a user. I got that working but I would also like to order the posts. I get a Postgres error that says:

"postgres-error : column "b.Volume" must appear in the GROUP BY clause
or be used in an aggregate function"

I'm new to Hasura and Postgres and I'm not sure if you are allowed to do something like this or not.
Here is my code:
CREATE OR REPLACE FUNCTION public.search_posts_near_user(id uuid, distance_kms integer, volume integer)
 RETURNS SETOF user_posts
 LANGUAGE sql
 STABLE
AS $function$
  SELECT  A.id, A.location,
  (SELECT json_agg(row_to_json(B)) FROM "Posts" B
   WHERE (
     ST_Distance(
       ST_Transform(B.location::Geometry, 3857),
       ST_Transform(A.location::Geometry, 3857)
     ) /1000) < distance_kms AND B."Volume" < volume
    ORDER BY B."Volume" Desc
   ) AS nearby_Posts
  FROM users A where A.id = id
$function$

A: This should work:
CREATE OR REPLACE FUNCTION public.search_posts_near_user(
      _id uuid
    , _distance_kms integer
    , _volume integer)
  RETURNS SETOF user_posts
  LANGUAGE sql STABLE AS
$func$
SELECT  A.id, A.location
     , (SELECT json_agg(B.* ORDER BY B."Volume" DESC)
        FROM   "Posts" B
        WHERE  ST_Distance(ST_Transform(B.location::Geometry, 3857)
                         , ST_Transform(A.location::Geometry, 3857))
               < _distance_kms * 1000
        AND    B."Volume" < _volume
      ) AS nearby_Posts
FROM    users A
WHERE   A.id = _id
$func$;

Make sure that function parameters (and variables) do not collide with table column names. I prefixed with _. Not strictly necessary, but a good habit.
Note how I multiply _distance_kms * 1000 instead of ST_Distance() / 1000 like you had it. That's better for multiple reasons. Multiplication is cheaper to begin with, and it avoids rounding errors. And it is substantially cheaper to manipulate the constant value once than the computed values for every row. Finally, your original expression might prevent index support (if available), being non-"sargable", which would be the strongest reason to fix it.
Basically, this is a KNN (k nearest neighbors) type of problem, that can benefit a lot from the right query technique in combination with the right index, typically a GiST index. See:

*

*Unique assignment of closest points between two tables
Also, while ORDER BY attached to the aggregate expression works conveniently, it is typically faster to sort in a subquery with ORDER BY, and then aggregate. See:

*

*How to apply ORDER BY and LIMIT in combination with an aggregate function?
Aside:
My standing advice is to use legal, lower-case, unquoted names in Postgres exclusively. See:

*

*Are PostgreSQL column names case-sensitive?


text:
Q: Random characteres at end of string I made a function to encrypt a string in C (with GCC) but I'm getting random characters at end of the decrypted string.
The function will save the length of input string at first character and the key used (first character -1) at second. All strings to be encrypted have a length between 10 and 30 so I hope there is no problem when converting to storing as char.
Whole code here:
#include <stdio.h> //printf
#include <stdlib.h> //malloc
#include <string.h> //strlen

char* x(const char* toEncrypt);
char* y(const char* toDecrypt);

int main() {
    const char *secret = "hellohello";
    printf("original: %s\n", secret);

    const char* crypted = x(secret);
    printf("crypted: %s\n", crypted);

    const char* decrypted = y(crypted);
    printf("decrypted: %s\n", decrypted);

    return 0;
}

char* x(const char* toEncrypt) {
    printf("x->toEncrypt = %s\n", toEncrypt);

    int offset = 0, i = 0;
    int length = strlen(toEncrypt);
    printf("\tx->length = %d\n", length);

    char key = ((char)(*toEncrypt))-1;
    printf("\tx->key = %c\n", key);

    char* output = (char*)malloc(length+3); //toEncrypt length + (length + key + null)

    output[offset++] = (char)length;
    output[offset++] = key;

    for (i = 0; i < length; i++) {
        printf("i = %d\toffset = %d\tchar = %c\n", i, offset, toEncrypt[i]);
        output[offset++] = toEncrypt[i] ^ key;
    }
    output[offset] = '\0';

    printf("\tx->output = %s\n", output);
    return output;
}

char* y(const char* toDecrypt) {
    printf("y->toDecrypt = %s\n", toDecrypt);

    int offset = 0, i = 0;
    int length = (int)toDecrypt[offset++] ;
    printf("\tx->length = %d\n", length);

    char key = (char)toDecrypt[offset++];
    printf("\ty->key = %c\n", key);

    char* output = (char*)malloc(length+1);

    for (i = 0; i < length; i++) {
        printf("i = %d\toffset = %d\tchar = %c\n", i, offset, (char)toDecrypt[offset] ^key);
        output[i] = toDecrypt[offset++] ^ key;
    }

    output[offset] = '\0';

    printf("\ty->output = %s\n", output);
    return output;
}

And the output:
original: hellohello
x->toEncrypt = hellohello
        x->length = 10
        x->key = g
i = 0   offset = 2      char = h
i = 1   offset = 3      char = e
i = 2   offset = 4      char = l
i = 3   offset = 5      char = l
i = 4   offset = 6      char = o
i = 5   offset = 7      char = h
i = 6   offset = 8      char = e
i = 7   offset = 9      char = l
i = 8   offset = 10     char = l
i = 9   offset = 11     char = o
        x->output =
g
crypted:
g
y->toDecrypt =
g
        x->length = 10
        y->key = g
i = 0   offset = 2      char = h
i = 1   offset = 3      char = e
i = 2   offset = 4      char = l
i = 3   offset = 5      char = l
i = 4   offset = 6      char = o
i = 5   offset = 7      char = h
i = 6   offset = 8      char = e
i = 7   offset = 9      char = l
i = 8   offset = 10     char = l
i = 9   offset = 11     char = o
        y->output = hellohellobe
decrypted: hellohellobe

A: I think the problem lies in this statement (in function y() — the same statement in function x() is OK):
output[offset] = '\0';

It should have been:
output[i] = '\0';

Changing this should work.


text:
Q: XCode 4 crashes with Git I can load, build and run my app with no errors in XCode 4, apart from Git integration that is!
If I select the master branch and create a new branch and either auto switch or manually switch to the new brach XCode 4 hangs and eventually crashes.
Than when I try to re-open my project it is corrupt!  Lucky I backed it up.
Has anyone else ha this issue?  Thinking I may stick to console git mode!
Any help gratefully received ;-)
OK:
removed git
removed xcode4
installed git
installed xcode4
opened project
in organiser the repositories are there again...cool
select master
create new branch
switch to new branch
activity indicator just spins and spins and spins?
click anywhere else in organiser....crash!
BUT....
open terminal window and git operates as usual add, commit, diff etc, all ok???

A: For now my experience with Xcode 4 tells me that anything that doesn't work is most probably the bug. So your best bet is to submit the bug report directly to Apple.

A: Try deleting the build directory and reopenning the project.
That fixed this problem for me.


text:
Q: Using "UPDATE" and "SET" in Python to Update Snowflake Table I have been using Python to read and write data to Snowflake for some time now to a table I have full update rights to using a Snowflake helper class my colleague found on the internet. Please see below for the class I have been using with my personal Snowflake connection information abstracted and a simply read query that works given you have a 'TEST' table in your schema.
from snowflake.sqlalchemy import URL
from sqlalchemy import create_engine
import keyring
import pandas as pd
from sqlalchemy import text

# Pull the username and password to be used to connect to snowflake
stored_username = keyring.get_password('my_username', 'username')
stored_password = keyring.get_password('my_password', 'password')

class SNOWDBHelper:

    def __init__(self):
        self.user = stored_username
        self.password = stored_password
        self.account = 'account'
        self.authenticator = 'authenticator'
        self.role = stored_username + '_DEV_ROLE'
        self.warehouse = 'warehouse'
        self.database = 'database'
        self.schema = 'schema'

    def __connect__(self):
        self.url = URL(
            user=stored_username,
            password=stored_password,
            account='account',
            authenticator='authenticator',
            role=stored_username + '_DEV_ROLE',
            warehouse='warehouse',
            database='database',
            schema='schema'

        )
        # =============================================================================
        self.url = URL(
            user=self.user,
            password=self.password,
            account=self.account,
            authenticator=self.authenticator,
            role=self.role,
            warehouse=self.warehouse,
            database=self.database,
            schema=self.schema

        )
        self.engine = create_engine(self.url)
        self.connection = self.engine.connect()

    def __disconnect__(self):
        self.connection.close()

    def read(self, sql):
        self.__connect__()
        result = pd.read_sql_query(sql, self.engine)
        self.__disconnect__()
        return result

    def write(self, wdf, tablename):
        self.__connect__()
        wdf.to_sql(tablename.lower(), con=self.engine, if_exists='append', index=False)
        self.__disconnect__()

# Initiate the SnowDBHelper()
SNOWDB = SNOWDBHelper()

query = """SELECT * FROM """ + 'TEST'
snow_table = SNOWDB.read(query)

I now have the need to update an existing Snowflake table and my colleague suggested I could use the read function to send the query containing the update SQL to my Snowflake table. So I adapted an update query I use successfully in the Snowflake UI to update tables and used the read function to send it to Snowflake. It actually tells me that the relevant rows in the table have been updated, but they have not. Please see below for update query I use to attempt to change a field "field" in "test" table to "X" and the success message I get back. Not thrilled with this hacky update attempt method overall (where the table update is a side effect of sorts??), but could someone please help with method to update within this framework?
# Query I actually store in file: '0-Query-Update-Effective-Dating.sql'
UPDATE "Database"."Schema"."Test" AS UP
SET UP.FIELD = 'X'

# Read the query in from file and utilize it
update_test = open('0-Query-Update-Effective-Dating.sql')
update_query = text(update_test.read())
SNOWDB.read(update_query)

# Returns message of updated rows, but no rows updated
   number of rows updated  number of multi-joined rows updated
0                     316                                    0

A: SQL2Pandas | UPDATE row(s) in pandas


text:
Q: Closed ball minus a point is connected Could someone help me to prove that if $B\subset\mathbb{R}^n$ ($n>1$) is a closed ball, then $B\setminus \{p\}$ is a connected set for all $p\in B$?

A: HINT: Let $x$ and $y$ be any two points of $B\setminus\{p\}$. If $p$ is not on the line segment $\overline{xy}$, then that line segment is a connected set in $B\setminus\{p\}$ containing both $x$ and $y$. If $p$ does lie on the line segment $\overline{xy}$, let $z$ be any point of $B$ that is not on the line through $x$ and $y$, and show that $\overline{xz}\cup\overline{zy}$ is a connected subset of $B\setminus\{p\}$ that contains both $x$ and $y$. (This actually shows that $B\setminus\{p\}$ is not just connected, but path connected.)

A: You can solve this problem by reducing to dimension $2$. Firstly, any closed ball in $R^n$ is homeomorphic to the unit closed ball in $\mathbb R^n$, so it suffices to prove that the unit closed ball has the property you mention. Now, in the $\mathbb R^2$, you can draw the argument to see that the closed unit ball minus any point is path connected.
Now, for the general case, given the closed unit ball $B$ in $\mathbb R^n$, with $n\ge 2$, a point $p$ that is removed from $B$, and two points $x,y\in B-\{p\}$, let $V$ be any plane that contains the origin as well as $x$ and $y$ (this is where $n\ge 2$ is used). The intersection $V\cap B$ is homeomorphic to the unit ball in $\mathbb R^2$. Thus, the intersection $V\cap (B-\{p\})$ is homeomorphic either to the unit ball in $\mathbb R^2$ or to the unit ball with a point removed. In either case, $x$ and $y$ can be connected by a path in the intersection (by the two-dimensional argument) and thus also in $B-\{p\}$.
This argument shows that the property is essentially two-dimensional.

A: Let $C = B \setminus \{p\}$. Let's asssume that $C$ is not connected, and show that this leads to a contradiction.
If $C$ is not connected, then we can find two closed sets $X$ and $Y$ such that $X \cap Y = \emptyset$ and $X \cup Y = C$. Let $Z = Y \cup \{p\}$. Then $Z$ is closed, $X \cap Z = \emptyset$, and $X \cup Z = B$. But this implies that $B$ is not connected, which is false, so our original assumption must have been wrong.
Caveat: the last time I wrote anything like this was about 40 years ago, so it's quite possible that I've forgotten a few things about topology. As always, you shouldn't necessarily believe the things you read on the internet.


text:
Q: Font-face shifting out of place in Google Chrome I know there are browser rendering inconsistencies between Chrome and Firefox (Windows, both). But I am seeing a weird bug involving @font-face & gooogle-fonts shifting the font down about 10px in Chrome.
Here is an image to illustrate the problem. I have highlighted the text so that you can see the shift:

Here is the CSS for clarity:
.primary-menu li a,
.primary-menu li a:visited {
    display: block;
    text-decoration: none;
    text-transform: uppercase;
    color: white;
    font-family: 'Oswald', sans-serif;
    font-weight: 700;
    padding-right: 0;
    transition: padding-right .5s;
}

I am using Google Fonts for the Oswald type face:
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Open+Sans:400,700|Oswald:400,700' type='text/css'>

I am using a CSS reset, so most properties are set to a default value. I have tried fiddling with the CSS to see if I can analyse why it is shifting, but I can not see an effect other than turning off the font-face.
Here is the source site for reference. Concept Design Ltd
Any knowledge on why this is happening would be fantastic.
Many thanks,
Neil

A: I recently had the same problem, but my font was NOT locally installed. (By the way, that would be a problem in web design, as you cant control the installed fonts on pageviewer´s computer).
The problem only occurred in Chrome 26 on Windows, and later in Firefox 19 for Windows but not on any other browser (neither Windows nor Mac OS x).
I finally found out that Chrome/Win would only render SVG Font correctly and Firefox took WOFF unhinted.
So I dirty-fixed the uncorrectly-rendered down-shifting with this-like CSS-code
/* for all browsers */
@font-face {
font-family: 'myfont';
src: url('myfont.eot');
src: url('myfont?#iefix') format('embedded-opentype'),
         url('myfont.woff') format('woff'),
         url('myfont.ttf') format('truetype'),
         url('myfont.svg#wf') format('svg');
}

/* for all webkit-browsers (Chrome, Safari and newly Opera */
@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
font-family: 'myfont';
    src: url('myfont.svg#wf') format('svg');
  }
}

/* for all mozilla-browsers (Firefox) */
@-moz-document url-prefix() {
  @font-face {
font-family: 'myfont';
    src: url('myfont_unhinted.woff') format('woff');
  }
}

Hope this helps anyone.

A: I was having the same issue, but in FireFox - I removed the Oswald fonts I had in my font directory on my computer and it fixed the issue. Maybe give that a go?


text:
Q: How to select multiple rows where a word is distinct by its letter? The title may be confusing, but so is the solution I am trying to SELECT from a table of 173k words a distinct word list by letter.
I already tried selecting distinct letters, running on a mariadb 10.1.37
SELECT DISTINCT LEFT(word, 1)

For example a SELECT shouldnt contain more than 1 word beginning with an "A".
Example Table (Because it's hard to understand)
╔═══════════╦═════════╗
║    Word   ║  Result ║
╠═══════════╣   ----  ║
║  Charlie  ║   Ava   ║
╠═══════════╣  Bianca ║
║   Caddie  ║ Charlie ║
╠═══════════╣         ║
║ Brooklynn ║         ║
╠═══════════╣         ║
║    Ava    ║         ║
╠═══════════╣         ║
║ Alexander ║         ║
╠═══════════╣         ║
║   Bianca  ║         ║
╚═══════════╩═════════╝

A: You can use the following solution using a GROUP BY on the first character:
SELECT MIN(word) FROM table_name GROUP BY LEFT(word, 1)

You can use MIN or MAX to get the first or last word on every group.

demo un dbfiddle.uk


text:
Q: populate dropdown menu on html page from database using php I am trying to populate a dropdown menu from database, however when i run the code i get no error but the output shows a part of my code with no proper result.
The code on index.html page is

                            <?php
                                $servername = "localhost";
                                $username = "username";
                                $password = "pwd";
                                $dbname = "db";

                                // Create connection
                                $con = mysqli_connect($servername, $username, $password, $dbname);
                                // Check connection
                                if (!$con) {
                                    die("Connection failed: " . mysqli_connect_error());
                                }

                                $sql = "SELECT treatment_type FROM treatment_type";
                                $result = $con->query($sql);
                                echo "Treatment Type: ";
                                echo "<select name='treatment_type' id='treatment_type' class='form-control'>";
                                while($row = $result->fetch_assoc()) {
                                echo "<option value='" . $row['treatment_type'] . "'>" . $row['treatment_type'] . "</option>";
                                }
                                echo "</select>";
                            ?>

output that i get along with the box is query($sql); echo "Treatment Type: "; echo " and the place where the dropdown menu should get displayed shows ".$row['treatment_type']."

A: Then, as i mentioned in my comment: "but the output shows a part of my code with no proper result" Is it mean, you see your code? Then you need to replace you .html to .php or set your configuration to parse .html as php.
This is for users whom comes later to this question.

A: First you should change the file type to .php
then as kern said you should look in to an MVC frame work, for now what i would do is move the connection to a function in a class
This example is using an ODBC connection but the points are the same just change it to mysqli or look in to using PDO
public static function functionName($variableToPassToQuery) {

   //Change this part so you are connecting to your database

    $conn = odbc_connect('SomeDatabase', '', '');
    if (!$conn) {
        exit("Connection Failed: " . $conn);
    }

   // Change to the SQL you need

    $sql = "SELECT * FROM Somewhere WHERE Something = $VariableToPassToQuery)";

    $rs = odbc_exec($conn, $sql);
    if (!$rs) {
        exit("Error in SQL");
    }

   //then once the query has been run we need to get the results and put them in to an array

    while ($data = odbc_fetch_array($rs)) {
        $row[] = $data;
    }

   //And then return that array
    return $row;
}

put all that in to a class
Now in the Html file which you should change to a PHP file we can do the drop down box like this
so inside a form you would need to tell it we need a dropdown box
    <select name="dropdown">
        <?php
         //then for each of the results in the array we need to an an option
         //call the function from the class like this Classname::Functionname($variable) of course if you
         //don't need to pass a variable then dont
        foreach (Classname::functionName($variableToPassToQuery) as $a) {
            echo '<option value=' . $a["SecondRef"] . '>' . $a["Description"] . ' </option>';
        }
        ?>
    </select>


text:
Q: How do I login successfully with the code I have? How do I use this code to make the login work? When the login button is click, it didn't login at all. Not sure what is the error as it's not shown.
login() {
    var url = 'https://login.app/login';
    var postData = JSON.stringify({
      // saving it as Email and will be used at server.js
      Email: this.loginForm.value['email'],
      Password: this.loginForm.value['password'],
    });
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-AllowMethods': 'GET,HEAD,PUT,PATCH,POST,DELETE'
      })
    };
    this.http.post(url, postData, httpOptions).subscribe((data) => {
      console.log('postData:', postData)
      if (data == false) {
       this.loginfail()
      }
      else if (data == true) {
        this.loginsuccess()
        this.modalController.dismiss();
      }
    }, error => {
      console.log(error);
    });
  }

A: Currently Your App is calling below Api for login
https://skippyforvercel.vercel.app/login

Its POST method , I tested this Api in POST man getting a 405 status code, currently your server is not supporting  POST method Please raise issue to Server Team.


text:
Q: How to make child nodes ineffective to parent nodes rotation? I am trying to add SKEmitterNode to the ball SKSpriteNode as a child.But also at the same time, I am rotating my ball node. But the problem is, the rotation of the ball node causes the emitter node to rotate (as the emitter node is child to ball node). Is there anything I could do to not rotate the emitter node,but rotate the ball node?
I added the ball node as:
SKSpriteNode * ball = [SKSpriteNode spriteNodeWithImageNamed:imageName];
ball.name=name;
ball.size=size;
ball.anchorPoint=CGPointMake(0, 0);

[self addChild:ball];

and I added the emitter node as:
 SKEmitterNode *burstEmitter =
 [NSKeyedUnarchiver unarchiveObjectWithFile:_emitterNodePath];
 [ball addChild:burstEmitter];

and when ball hits the wall, I am rotating the ball:
-(void)didBeginContact:(SKPhysicsContact *)contact
{

  SKSpriteNode * firstNode = (SKSpriteNode*)contact.bodyA.node;
  SKSpriteNode *  secondNode = (SKSpriteNode *)contact.bodyB.node;
  if (firstNode.physicsBody .categoryBitMask == wallHitCategory ||  secondNode.physicsBody.categoryBitMask == wallHitCategory) {

        NSLog(@"first sound and then rotate ball");
        [self runAction:[SKAction playSoundFileNamed:@"basketBall bounce.WAV" waitForCompletion:NO]];
        secondNode.anchorPoint=CGPointMake(0.5, 0.5);
            [secondNode runAction:[SKAction rotateByAngle:degToRad(180.0f) duration:3.0]];

    }
}

Is it possible to rotate the parent node but not its child node?

A: You could rotate the child node in opposite direction of the parent node then maybe it will be smooth enough that the eye won't see the changes,
As for another approach maybe a pinJoint could help
Also a SeanG's Comment is pretty well! I would prefer this solution
because it seems to be better cpu performance - wise!
Having an invisible node as a parent node for both the ball and the emitter node, then when you will rotate the ball emitter node wouldn't be affected by rotation.

*

*Hope it's helpful

A: I'll post my comment as an answer since it sounds like there's no reason it wouldn't work.
I would personally create a main node that the emitter and sprite node would both be children of.  If all you do is add child nodes the parent node will effectively be invisible.  Then you can move the parent node around as a whole but the individual children can be rotated independently.


text:
Q: compare date from DBfield with current date I'm new to the .NET world, so pardon my newbie question.
I'm building a webapp which gets data from a database. I am using Entity Framework, database first approach. I want to compare a date field from the database with the current date. If there's 20 or less days remaining til the current date, i want it to be shown in my view.
If there's more that 20 days remaining, it should not be shown in my view.
Right now i am presenting everything.
Controller:
        [StandardUserAuthorize]
    public ActionResult Index()
    {
        var model = new HomeVM
        {
            Offerter = db.AH_AVTAL_HUVUD.ToList(),
            Kallelser = db.AS_AVTAL_SCHEMA.ToList()
            //This is where the datefield is, in Kallelser.

        };
        return View(model);
    }

ViewModel:
    public class HomeVM
{
    public IEnumerable<AH_AVTAL_HUVUD> Offerter { get; set; }
    public IEnumerable<AS_AVTAL_SCHEMA> Kallelser { get; set; }
}

View:
 @foreach (var item in Model.Kallelser)
                    {

                                @Html.DisplayFor(modelItem => item.AS_SC_DAT)

                                @Html.DisplayFor(modelItem => item.AS_SC_VECKA)

                                @Html.DisplayFor(modelItem => item.AS_SC_OP_TXT)

                    }

How can i do this kind of logic? And where? I assume the it should be done in the controller.
Best Regards.

A: I Hope I Fully Understood You
//this is the after 20 days
 var ComparingDay = DateTime.Now.AddDays(20);

//this linq expression to get days between today and the comparing day
var ListOfNextDays = YouContextClass.YourDBSet.Where(D => D.Date > DateTime.Now && D.Date < ComparingDay).ToList();

Now You Have List Of Days That You Can Pass To You View
if you want the other days that dosn't match your condition u can use the except operator

A: I assume you wrote a sql somewhere in your application. Just add a where clause to it to retrieve only those you want to show.
SELECT t.*
FROM   Table t
WHERE  DATEDIFF(DAY, t.Date, GETDATE()) <= 20


text:
Q: 3D Pucker as user's location mapbox ios I am using Mapbox Maps iOS to create a custom 3d pucker and use that to display the user's location.
Everything seems to be working, the camera redirects to the user's location, the pucker successfully loads. However, I am having trouble setting the pucker's location to the user's location.
You can see that I am required to set the location of the pucker in the Model instance in the loadCharacter() function. But I am unsure of how to link that to the user's current location.
Please help!!!
// ViewController.swift

import UIKit
import MapboxMaps

public class ViewController: UIViewController {
    internal var mapView: MapView!
    internal var cameraLocationConsumer: CameraLocationConsumer!

    override public func viewDidLoad() {
        super.viewDidLoad()

        let options = MapInitOptions(cameraOptions: CameraOptions(zoom: 16))

        mapView = MapView(frame: view.bounds, mapInitOptions: options)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(mapView)

        mapView.mapboxMap.onNext(.styleLoaded) { _ in
            self.loadCharacter()
        }

        cameraLocationConsumer = CameraLocationConsumer(mapView: mapView)

        mapView.mapboxMap.onNext(.mapLoaded) { _ in
            self.mapView.location.addLocationConsumer(newConsumer: self.cameraLocationConsumer)
        }
    }

    internal func loadCharacter() {

        let uri = Bundle.main.url(forResource: "race_car_model",
                                  withExtension: "gltf")

        // Instantiate the model
        let myModel = Model(uri: uri,
                            position: [-77.150925, 39.085006],
                            orientation: [0, 0, 180])

        // Setting an expression to  scale the model based on camera zoom
        let scalingExpression = Exp(.interpolate) {
            Exp(.linear)
            Exp(.zoom)
            0
            Exp(.literal) {
                [256000.0, 256000.0, 256000.0]
            }
            4
            Exp(.literal) {
                [40000.0, 40000.0, 40000.0]
            }
            8
            Exp(.literal) {
                [2000.0, 2000.0, 2000.0]
            }
            12
            Exp(.literal) {
                [100.0, 100.0, 100.0]
            }
            16
            Exp(.literal) {
                [7.0, 7.0, 7.0]
            }
            20
            Exp(.literal) {
                [1.0, 1.0, 1.0]
            }
        }

        let configuration = Puck3DConfiguration(model: myModel, modelScale: .expression(scalingExpression))
        mapView.location.options.puckType = .puck3D(configuration)

    }
}

// Create class which conforms to LocationConsumer, update the camera's centerCoordinate when a locationUpdate is received
public class CameraLocationConsumer: LocationConsumer {
    weak var mapView: MapView?

    init(mapView: MapView) {
        self.mapView = mapView
    }

    public func locationUpdate(newLocation: Location) {

        mapView?.camera.ease(
            to: CameraOptions(center: newLocation.coordinate, zoom: 16, pitch: 50.0),
            duration: 1.3)

    }
}

A: Mapbox has a repo with examples of navigation use cases that you can try, including 3D puck sample.
Note that this sample uses API from Navigation SDK, which in turn uses Maps SDK API internally. Fortunately, Navigation SDK is open-sourced, you can always look at how it draws current user location here.


text:
Q: How does mongodb handle a machine that drops out of the shard process How does mongodb handle a machine that drops out of the shard group?
The reason i am asking this, I have several small machines, and one of them likes to power cycle at random times.
so if i put a shard on this machine, will mongodb be able to handle it dropping out for a little while, then popping back up and coming online?
Is there anything I, as an administration level user will need to do in regards to mongodb?
thank you

A: Sharding will not give you redundancy.
In mongodb, High availavility is achieved by creating replica sets. Every part of the shard SHOULD be composed by at least 3 machines forming a replica set. If one of them fails, the two other will reelect a primary, and will continue serving data. When failed machine recovers, oplog is applied, and data is recovered without losing service.
But if you don't use replica set, accesing data through mongos will fail when one of your any of your nodes goes down.
So, if you want HA, use replica sets

A:
if i put a shard on this machine, will mongodb be able to handle it dropping out for a little while, then popping back up and coming online?
Is there anything I, as an administration level user will need to do in regards to mongodb?

This depends on a number of factors, which I've tried to summarise with some context :)
Development or non-critical deployment
If this isn't a production or critical environment, you can wait for the machine to recover and no specific admin intervention should be required unless the machine has other errors due to unclean shutdown. Your application will have to handle any networking or timeout exceptions until the cluster is "normal" again, so you may want to intervene to minimise the noise.
Production deployment
Sharding alone does not provide for high availability or data redundancy so ideally you want each shard backed by a replica set.  In this case a downed machine (with a single mongod instance) should have a minimal impact because a correctly considered Replica Set Deployment Architecture can automatically failover without any administrative intervention.
Assuming a more dire case where an entire shard is unavailable .. you will want to take some administrative action to minimise the impact.  The MongoDB logs will be very noisy with networking errors while your shard is unavailable, and some actions such as chunk migrations will fail to/from the downed shard.
At a minimum you should Disable the Balancer until all shards are back online.  There are a few other considerations below.
Impact of a "down" shard on your queries/updates through mongos
From your application's point of view, the impact of a downed shard will depend on the type of queries and updates you are doing as well as the shard key you have chosen.

*

*directed queries or updates (those that are routed to a single shard) can still succeed if the shard is available.  If a query/update is directed to a "down" shard, your driver will get an exception.

*targeted queries (those that are routed to some but not all shards) can still succeed if the downed shard does not need to be contacted.

*scatter/gather queries (those that are routed to all shards) will return an exception if one or more shards is down.
If you are okay with receiving incomplete query results from a mongos if one or more shards are down, there is a partial flag you can set on a query to allow this. Generally you would not want to use this option as your results will be inconsistent, but it can be helpful in emergency situations or ones where you can identify the impact of the downed shard based on your choice of shard key.
Impacts from your choice of shard key
One of the goals with choosing a shard key is to provide a reasonable distribution of reads & writes to suit your use case.
For example, a shard key with a large amount of randomness (such as a hashed shard key) distributes documents across all shards and maximizes write throughput. As a consequence, this also makes the impact of a downed shard generally affect all queries/updates.
You can also create a shard key with some data locality (for example, combining a coarse attribute like customer_id with a finer-grained attribute like a timestamp) in order to get better read performance with targeted queries for a given customer. With a more targeted shard key you may be able to identify a range of users affected (or unaffected) by a down shard.
Further Reading
There is much more detail on Sharding in the MongoDB manual.


text:
Q: Hide Top Bar in Gnome (Workspaces) Is there any way to eliminate the top bar for all workspaces which are not the first/main one?
I mean, a tweak or files to edit so only the main workspace shows a top bar on top.


text:
Q: VB.NET common server controls and Attach the Main.css and Request.css style sheets to the Request web page. Make sure
that the link element for the Main.css sheet precedes the one for the Request.css sheet
so rules in the Request sheet can override rules in the Main sheet.


text:
Q: Multiple http requests with cancel request I'm creating an android app, which needs make some parallel HTTP/HTTPS requests (exactly 10).
First step
How can I make this parallel requests in android?
Is it possible to use HTTP and HTTPS at the same time?
Obs: Searching in google, I found ExecutorService. Can i use this in android? (Does someone have an example?)
Second step
If someone helps with the 1st question, I will have the following scenario:
1 request one started   -- (working) --> cloud
2 request two started   -- (working) --> cloud
3 request three started -- (working) --> cloud

After some seconds the thread 2 is the 1st one to say 'i finished my work, here is the response of the page', threads 1 and 3 are working.
How can i stop/kill thread 1 and 3?

A: *

*yes you can use ExecutorService
ExecutorService executorService = Executors.newFixedThreadPool(n);
then use the submit function to execute the task
executorService.submit(Runnable task);

but there is no guarantee that all of the task will executed at the same time, it's depend on the available resources.
2.
you can shutdown the pool;
executorService.shutdown();

but There are no guarantees beyond best-effort attempts to stop processing actively executing tasks.
if you want to use asyncTask notice that :
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
so the tasks executed on single thread not several threads


text:
Q: Irreducible Polynomials over $\mathbb{R}$ or $\mathbb{Q}$ I am interested in generating irreducible polynomials of a given, arbitrary degree over either the reals or rationals using integer coefficients. They don't necessarily have to be arbitrary polynomials (i.e. random coefficients), but I would prefer not to simply use $F(x)=x^n+a_n$ (for the case of $\mathbb{R}$.
If a general algorithm for generating arbitrary irreducible polynomials does not exist, I am open to using several "families" of polynomials of arbitrary degree which are known to be irreducible, in which case I would like to be able to generate several different such families.

A: Over the rationals, use the Eisenstein Irreducibility Criterion.
Over the reals is not interesting, no polynomial of degree $\ge 3$ is irreducible.


text:
Q: Spinner in Toolbar Example in Xamarin for Android I am trying to implement a spinner in the toolbar of my navigation drawer.
My initial toolbar layout included the following xml code:
  <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/languagetoolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        android:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

      <Spinner
        android:id="@+id/toolbar_languageSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/array_languageSelect"
        android:gravity="right" />

    </android.support.v7.widget.Toolbar>

The thing is that there does not seem to exist to be an example that seem to show the implementation method using Xamarin. I have tried to use the following resources :
  https://dabx.io/2015/01/02/material-design-spinner-toolbar-style-fix/  &
  http://android-pratap.blogspot.co.za/2015/01/spinner-in-toolbar-example-in-android.html
x
  The short comings of the two examples is that using Xamarin I have found that I cannot use .setAdapter as it only exists as an interface
The look that i want in the tool bar is similar to the image in the first link but having the spinner to the extreme right.

A: The solution that I finally found is explained perfectly by prathap in http://android-pratap.blogspot.co.za/2015/01/spinner-in-toolbar-example-in-android.html. The solution involves adding the spinner to the toolbar layout like below:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/languagetoolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <Spinner
      android:id="@+id/toolbar_languageSpinner"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:entries="@array/array_languageSelect"
      style="@style/MyTheme"
      android:gravity="right" />

</android.support.v7.widget.Toolbar>

Then the code that follows will require the user to populate the spinner in the code from their activity.


text:
Q: How to find an user on a LDAP server When trying to find an User on a LDAP Server, I get the following error "Unknown error (0x8000500c)"
This is the code I'm using:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "gandalf.intrafg");
UserPrincipal p = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Consultor1");

Indidentally, the following piece of code seems to work (no exception is generated), but the samAccountName comes through as a byte array. Anybody knows why?
DirectoryEntry entry = new DirectoryEntry("LDAP://gandalf.intrafg");

DirectorySearcher searcher = new DirectorySearcher(entry);

//searcher.PropertiesToLoad.Add("givenName");
//searcher.PropertiesToLoad.Add("sn");
searcher.PropertiesToLoad.Add("samAccountName");

searcher.Filter = "(&(objectCategory=person)(samAccountName=Consultor1))";

SearchResult result = searcher.FindOne();

A: Your second code block works just fine, I however did not pass the domain name in the DirectoryEntry initializer.
    Directory entry = new DirectoryEntry();
//other code
result.Properties["samAccountName"][0].ToString();

A: The code you have should be fine - it works for me, no problem at all.
However: you're not telling us what you fill in for domain_name here:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "domain_name");

or userId here:
UserPrincipal p = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, UserId);

The domain_name must be in the "old" NetBIOS style, e.g. FABRIKAM - no DNS-style like fabrikam.com or AD-style like dc=fabrikom,dc=com or even a full LDAP path.
The userId must be a valid SAM account name, e.g. max. of 20 chars, letters and numerics only (except for a few valid special chars).
Are you complying with these requirements??


text:
Q: IIS ASP.NET Core application not starting I have created an ASP.NET Core web api that has been tested on many PC's but when deploying to client's IIS server, the application does not start or produce any error, as checked in Application Event logs.
Running the executable directly, the application works and you can browse to the ASP.NET Core website.
I navigated to the web.config file to find the dll to run:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MY_API.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: c1c1b8d5-abcd-479f-9e7a-abcdefghijkl-->

running dotnet MY_API.dll produces the following:

The port is not bound to any other application, as when i run the executable, it binds to the port successfully and i can navigate to localhost:port and the api swagger interface is displayed.
The dotnet command successfully runs the application on my development PC.
I can confirm that IIS is running the same modules that i am running on my dev PC and the same .net runtime hosting bundle is installed on the server as is installed on my dev PC.
I feel that this is just a permissions issue, that the security policy perhaps is preventing me from binding ports using the dotnet command, which i have read that is what IIS uses to launch the application in the background.
My knowledge on service accounts and ApplicationPoolIdentities are very limited. What is the permissions that would prevent the application to bind the port using the dotnet command, where running the executable allows me to bind to the port? How do i change these permissions?


text:
Q: Passing Method as a Character String I need to allow the user to create an object with one of several classes. The object will require further analysis so will be passed to one of numerous S3 methods downstream.
My thought is to have them provide the class as a character string on the creation function call, but I'm not sure the best way to use useMethod to select the proper S3 method, since the different objects will be created with different algorithms.
The create_thing() function will return an object with class set, so graph_thing() and report_thing() will take the output of create_thing() and have a class to work with.
create_thing <- function(model = 'strange', foo, bar){
  tmp <- ""
  class(tmp)<-model
  UseMethod("create_thing", tmp)
}

create_thing.strange <- function(model, foo = 1, bar = 2){
  ## stuff
  print("strange")
  return(structure(list(data=runif(5)), class = c("list", "strange")))
}

create_thing.normal <- function(model, foo = 3, bar = 4){
  ## stuff
  print("normal")
  return(structure(list(data=rnorm(5)), class = c("list", "normal")))
}

graph_thing <- function(athing){
  UseMethod("graph_thing")
}

graph_thing.normal <- function(athing){
  print("normal")
  plot(athing$data)
}

graph_thing.strange <- function(athing){
  print("strange")
  plot(athing$data)
}

report_thing <- function(athing){
  UseMethod("report_thing")
}

report_thing.normal <- function(athing){
  print("normal")
  print(mean(athing$data))
}

report_thing.strange <- function(athing){
  print("strange")
  print(median(athing$data))
}

A: The UseMethod function looks up the call stack to see what was passed in to the original function. Any modifications or new objects created will not influence how dispatching works.
If you are using the create_thing functions to initilize the object, then you should create a separate generic function for that
create_thing <- function(model = 'strange', foo, bar){
  tmp <- ""
  class(tmp)<-model
  init_thing(tmp, foo, bar)
}

init_thing <- function(model, foo=0, bar=0) {
    UseMethod("init_thing")
}
init_thing.strange <- function(model, foo = 1, bar = 2){
  ## stuff
  print("strange")
  return(structure(list(data=runif(5)), class = c("list", "strange")))
}

init_thing.normal <- function(model, foo = 3, bar = 4){
  ## stuff
  print("normal")
  return(structure(list(data=rnorm(5)), class = c("list", "normal")))
}


text:
Q: Unable to set state after fetch request on React Native I'm facing a weird issue when trying to change a value of the state object after performing a GET request with either fetch or axios (not working with both).
My code is pretty basic and I tried a lot of solutions that I found online but none of them is working.
This is the code I have so far ...
class FilterScreen extends React.Component {

    state = {
        selectedCity: null,
        cities: [],
        selectedSpecialty: null,
        specialties: [],
    };

    componentWillMount() {
        this.fetchCities();
    }

    fetchCities = () => {

        fetch(`http://127.0.0.1:8000/app/cities`)
            .then(res => res.json())
            .then(e => {
                this.setState({
                    results: e.data.map(item => ({
                        label: item.name,
                        value: item.id
                    }))
                });
            })
            .catch(
                () => (
                    alert('There was an issue while fetching the doctors.')
                )
                );
        };

    render() {
        return (
          ... the body of the component...
            )}
}

export default FilterScreen;

I really can't understand what I'm doing wrong here.
I'm pretty new to React Native and maybe this has something to do with the lifecycles but I'm sure that componentWillMount is the right way to do it.
Maybe I'm wrong ...
Any kinda help is appreciated :D

A: You should make async calls in componentDidMount. Please see this.


text:
Q: Multiplying matrices Java I've been have some problems multiplying the matrices for this code, when I do it by hand and with a calculation tool I get something completely different than what my code is giving me.
Code:
public class mult1 {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    double[][] colaO = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//orginal
    double[][] colaD = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//copy
    double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
    mult1 test = new mult1();
    test.output(colaC);
    test.Alg1(colaO, colaD, colaC);
    test.output(colaC);
  }
  public void Alg1(double colaO[][], double colaD[][], double colaC[][]) {
    for (int i = 0; i < colaO.length; i++) {
      for (int j = 0; j < colaO.length; j++) {
        for (int k = 0; k < colaO.length; k++) {
          colaC[i][j] += colaO[i][k] * colaD[k][j];
        }
      }
    }
  }
  public void output(double colaC[][]) {
    for (int i = 0; i < colaC.length; i++) {
      for (int j = 0; j < colaC.length; j++) {
        System.out.printf("%.3f", colaC[i][j]);
        System.out.print(" ");
      }
      System.out.println();
    }
  }
}

Results:
 ---original-----
 0.900 0.050 0.050
 0.050 0.900 0.050
 0.050 0.050 0.900
 ---what i'm getting------
 1.715 0.143 0.143
 0.143 1.715 0.143
 0.143 0.143 1.715
 ---should be-----
 0.815 0.092 0.092
 0.092 0.815 0.092
 0.092 0.092 0.815

I don't quite see where I'm messing up the equation

A: Well the first thing I would do is 0-initialise colaC since you're using += on its entries. The way you're doing it now can't lead to the correct result.

A: double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
should be
double[][] colaC = {{0,0,0},{0,0,0},{0,0,0}};//for algs


text:
Q: cakephp 3 how to change the custom rule validation message in fly I have created a custom rule, and i need to change the message on fly.
For example consider the following code. In this i need to show the appropriate message instead of rule message(Error Number) based on the constraints
public function validationDefault(Validator $validator)
{
           $validator->add(
                    'number_field',
                    [
                        'custom' => [
                            'rule' => function ($value, $context) {
                                if ($value < 10) {
                                    //need to change the error message as its less than 10
                                } else if ($value > 10 && $value <20) {
                                    //need change the error message its between 10 and 20
                                }
                                return true;
                            },
                            'message' => 'Error number'
                        ]
                    ]
                );
     return $validator;
}

A: Validation rule methods can return either a boolean that defines whether the validation succeeded, or a string which means that the validation failed, and that the string should be used as the error message instead of the one defined in the message option.
'rule' => function ($value, $context) {
    if ($value < 10) {
        return __('Error message for value < 10');
    } else if ($value > 10 && $value <20) {
        return __('Error message for value between 10 and 20');
    }

    return true;
},

See also

*

*API > \Cake\Validation\ValidationRule::process()

A:    $validator
        ->add("number_field", "length", [
            "rule" => [ "minLength", 20],
            "message" =>__("{Your message}"),//Error message
            'on' => function ($context) {
                return !empty($context['data']['number_field']);
            }
        ])

When defining validation rules, you can use the on key to define when a validation rule should be applied.


text:
Q: How to solve this type of integration? I had the following integration: $$\int_0^z w^{m-1}K_0(2\frac{m}{\Omega}\sqrt{w})dw.\tag{1}$$
Can i use the following formula from Table of integrals to solve the integral in eq. $(1)$
$$\int_0^{\infty}x^{\mu}K_v(ax)dx=2^{\mu-1}a^{-\mu-1}\Gamma\left(\frac{1+\mu+v}{2}\right)\Gamma\left(\frac{1+\mu-v}{2}\right).$$
Any help in this regard is highly appreciated.

A: It is much more complicated for finite values of $z$ since it will be (assuming $m>0$).
Let $w=\frac{ \Omega ^2}{4 m^2}t^2$ to face
$$I=2 \left(\frac{\Omega ^2}{4m^2}\right)^m\int  t^{2 m-1} K_0(t)\,dt$$
$$\int  t^{2 m-1} K_0(t)\,dt=$$ $$\frac{t^{2 m} \left(2 m K_0(t) \, _1F_2\left(1;m,m+1;\frac{t^2}{4}\right)+t K_1(t)
   \, _1F_2\left(1;m+1,m+1;\frac{t^2}{4}\right)\right)}{4 m^2}$$
For $t=0$ the value is zero.


text:
Q: problems converting ISO date in mongo using php I have the following data in my mongo document:
"last_assigned" : ISODate("2016-11-10T20:34:36.000Z")

When i query the database for documents that include dates like the above, after my attempt to convert it, this is what my var_dump shows:
object(DateTime)[22]
  public 'date' => string '1970-01-01 00:00:00.000000' (length=26)
  public 'timezone_type' => int 1
  public 'timezone' => string '+00:00' (length=6)

And this is what my code looks like - "$value['last_assigned']" is what I get back from the db...
            if (!empty($value['last_assigned'])) {
                $tempdate = new MongoDate(strtoTime($value['last_assigned']));
                var_dump($tempdate->toDateTime());
            }

How can i write my code such that it will display the proper value for the date?
EDIT 1
I tried to change the code like this:
                $tempdate = (string)$value['last_assigned']->sec;
                $tempdate = new MongoDate(strtotime($tempdate));
                var_dump($tempdate->toDateTime());

This is what the vardump shows:
object(DateTime)[22]
  public 'date' => string '1970-01-01 00:00:00.000000' (length=26)
  public 'timezone_type' => int 1
  public 'timezone' => string '+00:00' (length=6)

A: As per this: http://php.net/manual/en/class.mongodate.php, I had to do something like this:
$tempdate =date('Y-M-d h:i:s', $value['last_assigned']->sec);
$did_details['last_assigned'] = $tempdate;


text:
Q: How to save a report directly to .doc? I have a report and i want to save it directly without a dialog.
Here is my code until now
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = @"C:\temp";
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "Browse Text Files";
            saveFileDialog.DefaultExt = "doc";
            saveFileDialog.Filter = "Word Doc (*.doc)|*.doc|PDF (*.pdf)| *.pdf";
            saveFileDialog.CheckFileExists = false;
            saveFileDialog.CheckPathExists = true;

            Warning[] warnings;
            string[] streams;
            string mimeType;
            string encoding;
            string extension;

            byte[] bytes = reportTest.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streams, out warnings);

            //if (saveFileDialog.ShowDialog() == DialogResult.OK)
            //{
                saveFileDialog.FileName = "123.doc";
                var filename = saveFileDialog.FileName;
                System.IO.FileStream file = new FileStream(filename, FileMode.Create);
                file.Write(bytes, 0, bytes.Length);
                file.Close();
            //}

Can someone help me how to save the file directly to c:\temp\123.doc (without dialog in the explorer).
Thanks a lot!

A: You can directly save this with path and file name
filename="PATH" + "test.doc";
System.IO.FileStream file = new FileStream(filename, FileMode.Create);


text:
Q: Set size, bgcolor, and editable to false on cshtml Html.TextAreaFor element Inside a cshtml file I'm trying to configure a @Html.TextAreaFor element
As I want a vertical scroller for a text content. The area should be

*

*fixed size  (no rezise)

*not allow for user editing  (editing of model.HTMLbody is allowed but not on this page)

*just list the content with a vertical scrol bar

*and set a background color to it

I tried a few variations on below, but so far i'm out of luck
What should the syntax be for this?
@Html.TextAreaFor(model => model.HTMLbody, new { @class = "whatever-class", @cols = 30, @rows = 5 ,@ResizingMode = none})
@Html.TextAreaFor(model => model.HTMLbody, new { style = "cols:80;rows:8;resize:none;" })

(ps in above i dont want to render model.HTMLbody as html )


text:
Q: PySpark, Graph, and Spark data frames foreach I am working on using spark sql context data frames to parallelize the operations. Briefly, I read in a CSV into a data frame df then call df.foreachPartition(testFunc) to do a get-or-create operation on the graph (this is in testFunc).
I am not sure if the cluster and session need to be defined in the function that is passed to the data frame (testFunc) in this instance, as I'm having a bit of trouble locating an example of a graph traversal being done this way.
I can run the graph traversal manually just fine. I can also print out the values in the rows when I call df.foreachPartition(testFunc) if I omit the session.execute_graph("g.V()....") portion.
On top of that, if I just explicitly call testFunc and pass a list of rows (say, testFunc(df.collect())) it will run successfully and get or create the appropriate vertices in the graph.
So I assume it has something to do with the way the graph traversal is being called within the function as it's passed to the different threads ?
test_sc_CSV.py:
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

from dse.cluster import Cluster, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT
from dse.cluster import GraphOptions

conf = SparkConf().set("spark.cassandra.connection.host", "*.*.*.*")
#set("spark.cassandra.connection.native.port","9042")
#set('spark.cores.max', 2).set('spark.executor.memory', '8g')
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)

# Loading data
print '\n--- Loading data...'
df = (sqlContext.read.format("com.databricks.spark.csv").
      options(header="true").
      load("file:/home/centos/datacube/notebooks/animals.csv"))

def testFunc(rows):

    graph_name = 'toy_data'
    ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name=graph_name))
    cluster = Cluster(['*.*.*.*'],execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep})
    session = cluster.connect()

    for row in rows:
        values = [int(row.app_id),int(row.id),str(row.name),str(row.contact)]
        print values

        session.execute_graph("g.inject(1).coalesce(V().has('name','n_val',n_val),\
            addV('name').property('n_val',n_val))",{'n_val':row.name})

df.foreachPartition(testFunc)
# df.rdd.repartition(2).foreachPartition(testFunc)

error logs:
--- Loading data...
[1001, 1, 'dog', 'monkey']
ERROR 2016-12-08 14:35:48,130 org.apache.spark.executor.Executor: Exception in task 0.0 in stage 1.0 (TID 1)
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 317, in func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 759, in func
  File "/home/centos/datacube/spark_graph/test_sc_CSV.py", line 31, in testFunc
    addV('name').property('n_val',n_val))",{'n_val':row.name})
  File "/home/centos/anaconda/lib/python2.7/site-packages/dse/cluster.py", line 177, in execute_graph
    return self.execute_graph_async(query, parameters, trace, execution_profile).result()
  File "/home/centos/anaconda/lib/python2.7/site-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
InvalidRequest: Error from server: code=2200 [Invalid query] message="No such property: g for class: Script10549"

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.scheduler.Task.run(Task.scala:89) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227) ~[spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_101]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_101]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101]
WARN  2016-12-08 14:35:48,142 org.apache.spark.scheduler.TaskSetManager: Lost task 0.0 in stage 1.0 (TID 1, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 317, in func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 759, in func
  File "/home/centos/datacube/spark_graph/test_sc_CSV.py", line 31, in testFunc
    addV('name').property('n_val',n_val))",{'n_val':row.name})
  File "/home/centos/anaconda/lib/python2.7/site-packages/dse/cluster.py", line 177, in execute_graph
    return self.execute_graph_async(query, parameters, trace, execution_profile).result()
  File "/home/centos/anaconda/lib/python2.7/site-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
InvalidRequest: Error from server: code=2200 [Invalid query] message="No such property: g for class: Script10549"

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

ERROR 2016-12-08 14:35:48,144 org.apache.spark.scheduler.TaskSetManager: Task 0 in stage 1.0 failed 1 times; aborting job
Traceback (most recent call last):
  File "/home/centos/datacube/spark_graph/test_sc_CSV.py", line 33, in <module>
    df.foreachPartition(testFunc)
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/sql/dataframe.py", line 370, in foreachPartition
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 764, in foreachPartition
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 1004, in count
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 995, in sum
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 869, in fold
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 771, in collect
  File "/usr/share/dse/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 45, in deco
  File "/usr/share/dse/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 1.0 failed 1 times, most recent failure: Lost task 0.0 in stage 1.0 (TID 1, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 317, in func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 759, in func
  File "/home/centos/datacube/spark_graph/test_sc_CSV.py", line 31, in testFunc
    addV('name').property('n_val',n_val))",{'n_val':row.name})
  File "/home/centos/anaconda/lib/python2.7/site-packages/dse/cluster.py", line 177, in execute_graph
    return self.execute_graph_async(query, parameters, trace, execution_profile).result()
  File "/home/centos/anaconda/lib/python2.7/site-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
InvalidRequest: Error from server: code=2200 [Invalid query] message="No such property: g for class: Script10549"

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1431)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1419)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1418)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1418)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1640)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1599)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1588)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:620)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1838)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1851)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1864)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1935)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:927)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:150)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:111)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:316)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:926)
    at org.apache.spark.api.python.PythonRDD$.collectAndServe(PythonRDD.scala:405)
    at org.apache.spark.api.python.PythonRDD.collectAndServe(PythonRDD.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 317, in func
  File "/usr/share/dse/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 759, in func
  File "/home/centos/datacube/spark_graph/test_sc_CSV.py", line 31, in testFunc
    addV('name').property('n_val',n_val))",{'n_val':row.name})
  File "/home/centos/anaconda/lib/python2.7/site-packages/dse/cluster.py", line 177, in execute_graph
    return self.execute_graph_async(query, parameters, trace, execution_profile).result()
  File "/home/centos/anaconda/lib/python2.7/site-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
InvalidRequest: Error from server: code=2200 [Invalid query] message="No such property: g for class: Script10549"

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

WARN  2016-12-08 14:35:48,346 org.apache.spark.rpc.netty.Dispatcher: Message RemoteProcessDisconnected(ip-172-31-13-58.ec2.internal:43418) dropped.
java.lang.IllegalStateException: RpcEnv already stopped.
    at org.apache.spark.rpc.netty.Dispatcher.postMessage(Dispatcher.scala:159) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rpc.netty.Dispatcher.postToAll(Dispatcher.scala:109) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rpc.netty.NettyRpcHandler.connectionTerminated(NettyRpcEnv.scala:622) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.network.server.TransportRequestHandler.channelUnregistered(TransportRequestHandler.java:94) [spark-network-common_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.network.server.TransportChannelHandler.channelUnregistered(TransportChannelHandler.java:89) [spark-network-common_2.10-1.6.2.2.jar:1.6.2.2]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelUnregistered(DefaultChannelPipeline.java:731) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:674) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:329) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.confirmShutdown(SingleThreadEventExecutor.java:628) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:362) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101]
WARN  2016-12-08 14:35:48,347 org.apache.spark.rpc.netty.Dispatcher: Message RemoteProcessDisconnected(ip-172-31-13-58.ec2.internal:43418) dropped.
java.lang.IllegalStateException: RpcEnv already stopped.
    at org.apache.spark.rpc.netty.Dispatcher.postMessage(Dispatcher.scala:159) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rpc.netty.Dispatcher.postToAll(Dispatcher.scala:109) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.rpc.netty.NettyRpcHandler.connectionTerminated(NettyRpcEnv.scala:622) [spark-core_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.network.server.TransportRequestHandler.channelUnregistered(TransportRequestHandler.java:94) [spark-network-common_2.10-1.6.2.2.jar:1.6.2.2]
    at org.apache.spark.network.server.TransportChannelHandler.channelUnregistered(TransportChannelHandler.java:89) [spark-network-common_2.10-1.6.2.2.jar:1.6.2.2]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelUnregistered(ChannelInboundHandlerAdapter.java:53) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelUnregistered(AbstractChannelHandlerContext.java:158) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelUnregistered(AbstractChannelHandlerContext.java:144) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelUnregistered(DefaultChannelPipeline.java:731) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:674) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:329) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.confirmShutdown(SingleThreadEventExecutor.java:628) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:362) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112) [netty-all-4.0.34.Final.jar:4.0.34.Final]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101]

Graph schema:
schema.propertyKey('name').Text().single().create()
schema.propertyKey('person_id').Int().single().create()
schema.propertyKey('app_id').Int().single().create()
schema.propertyKey('score').Int().single().create()
schema.propertyKey('date').Int().single().create()

schema.vertexLabel('name').properties('name').create()
schema.vertexLabel('name').index('personByName').materialized().by('name').add()

schema.vertexLabel('id').properties('person_id').create()
schema.vertexLabel('id').index('IdById').materialized().by('person_id').add()

schema.vertexLabel('application').properties('app_id').create()
schema.vertexLabel('application').index('appByName').materialized().by('app_id').add()

schema.edgeLabel('has_name').multiple().create()
schema.edgeLabel('has_name').connection('id', 'name').add()

schema.edgeLabel('has_contact').multiple().create()
schema.edgeLabel('has_contact').connection('application', 'id').add()

schema.edgeLabel('is_match').multiple().properties('score','date').create()
schema.edgeLabel('is_match').connection('id', 'id').add()

schema.edgeLabel('has_application').multiple().create()
schema.edgeLabel('has_application').connection('id', 'application').add()

schema.propertyKey('hash').Int().single().create()
schema.vertexLabel('bin').properties('hash').create()
schema.vertexLabel('bin').index('binByHash').materialized().by('hash').add()
schema.edgeLabel('has_hash').multiple().create()
schema.edgeLabel('has_hash').connection('name', 'bin').add()

CSV:
,app_id,contact,id,name
0,1001,monkey,1,dog
1,1002,monkey,2,cat
2,1003,mad gorilla,3,mad cat
3,1004,good gorilla,4,good dog
4,1005,bad monkey,5,bad dog
5,1006,dog,6,chicken
6,1007,gorilla,7,chicken
7,1008,hawk,8,cat
8,1009,monkey,9,dog
9,1010,monkey,10,dog
10,1011,monkey,11,chicken
11,1012,cat,12,cat
12,1013,monkey,13,dog
13,1014,dog,14,dog
14,1015,hawk,15,cat


text:
Q: Reactjs: How to make Users age displays on the users button instead of displaying on the page using reactjs I have five Users in the array.
The code below displays each users info from the arrays when pop up button is clicked and everything works fine.
Now I have created a form to update each user's age based on their respective person Id on form submission via call to nodejs
backend. Am actually getting the result from nodejs backend..
Here is my issue.
Each time I entered age in the input and click on submission button Eg. for user 1. Instead of the age result to
appear near that very user 's name in the space provided in the button, it will appears on the body of the page as can be seen from
screenshots provided.

If call it as props For instance  {this.props.messages.personAge}
as per below
   <button
            onClick={() => this.open(this.props.data.id, this.props.data.name)}
          >
(Age should Appear Here-- ({this.props.messages.personAge})--)
            {this.props.data.name}
          </button>

It shows error
TypeError: Cannot read property 'personAge' of undefined
    at User.render
Here is how am getting the response from nodejs server
componentDidMount(){

this.socket = io('http://localhost:8080');
this.socket.on('response message', function(data){
            addAge(data);
        });

        const addAge = data => {
            console.log(data);
            //this.setState({messages: [...this.state.messages, data]});
         this.setState({messages: [data]});
        };
}

below is how am displaying the age result for each unique user
{this.state.messages.map((message, i) => {

//if (message.personId == this.props.data.id) {
//if (message.personId == person.id) {

if (message.personId) {

          return (

 ({message.personAge}--years)

          )

  }
        })}

Here is the Entire Code
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import { Link } from 'react-router-dom';
import axios from 'axios';
import io from "socket.io-client";

class User extends React.Component {
  open = () => this.props.open(this.props.data.id, this.props.data.name);
  render() {
    return (
      <React.Fragment>

          <button
            onClick={() => this.open(this.props.data.id, this.props.data.name)}
          >
(Age should Appear Here-- ({this.props.messages})--)
            {this.props.data.name}
          </button>

      </React.Fragment>
    );
  }
}

class OpenedUser extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hidden: false,
 personId: '',
 personAge: '',
    };

  }

componentDidMount(){

this.socket = io('http://localhost:8080');

var userId= this.props.data.id;

}

sendPost = (personId,personAge) => {
alert(personId);
alert(personAge);

this.socket.emit('messageUpdate', {
                personId: personId,
                personAge: personAge,

            });

         this.setState({personId: ''});
         this.setState({personAge: ''});

        }

  toggleHidden = () =>
    this.setState(prevState => ({ hidden: !prevState.hidden }));

  close = () => this.props.close(this.props.data.id);

  render() {

    return (

          <button onClick={this.close}>close</button>

user {this.props.data.id}

name {this.props.data.name}

 {this.state.hidden ? null : (

Update Age Info

<input type="text"  placeholder="personAge" value={this.state.personAge} onChange={ev => this.setState({personAge: ev.target.value})}/>

                                 this.sendPost(this.props.data.id, this.state.personAge)} className="btn btn-primary">Update Age

          )}

    );
  }
}
class App extends React.Component {
  constructor() {
    super();

    this.state = {

  showingAlert_UserTyping: false,
      shown: true,
      activeIds: [],
 messages: [],
      data: [
        { id: 1, name: "user 1" },
        { id: 2, name: "user 2" },
        { id: 3, name: "user 3" },
        { id: 4, name: "user 4" },
        { id: 5, name: "user 5" }
      ]
    };
  }

componentDidMount(){

this.socket = io('http://localhost:8080');

this.socket.on('response message', function(data){
            addAge(data);

            console.log(' am add message' +data);
        });

        const addAge = data => {
            console.log(data);
            //this.setState({messages: [...this.state.messages, data]});
         this.setState({messages: [data]});
        };

} // close component didmount

  toggle() {
    this.setState({
      shown: !this.state.shown
    });
  }

  open = (id,name) => {
    this.setState(prevState => ({
      activeIds: prevState.activeIds.find(user => user === id)
        ? prevState.activeIds
        : [...prevState.activeIds, id]
    }));
  };

  close = id => {
    this.setState(prevState => ({
      activeIds: prevState.activeIds.filter(user => user !== id)
    }));
  };

  renderUser = id => {
    const user = this.state.data.find(user => user.id === id);
    if (!user) {
      return null;
    }
    return (
      <OpenedUser  messages={this.state.messages}
        key={user.id}
        data={user}
        close={this.close}
      />
    );
  };

  renderActiveUser = () => {
    return (

        {this.state.activeIds.map(id => this.renderUser(id))}

    );
  };

  render() {

    return (

{this.state.messages.map((message, i) => {

//if (message.personId == this.props.data.id) {
//if (message.personId == person.id) {

if (message.personId) {

          return (

 ({message.personAge}--years)

          )

  }
        })}

{this.state.data.map(person => {

return (
  <User key={person.id} data={person}  open={this.open} />
);

        })}
        {this.state.activeIds.length !== 0 && this.renderActiveUser()}

    );
  }
}

A: Here is how I solved the issue:
I created a const resultdata and using map() and Filter() function.
Here is how I initialized the the variable resultdata and then pass it within state.data.map() method
const resultdata = this.state.messages.filter(res => res.personId == person.id).map(res => res.personAge));


text:
Q: Make does not run ar and make new libraries after object changes Iam trying to start project with couple of static libraries that are built on their own makefiles, like this:
LIBDIR= ../../lib/
SRC= mgui.c

-include $(SRC:%.c=%.d)

INC=-I../../inc \
    -Iinc \
    -I../../shared

EXEC= libmgui.lib

CFLAGS= -Wall -static -D$(DEBUG) -MMD -MP

ARFLAGS= rcs
AR = ar

all: $(SRC:%.c=%.o)
    $(AR) $(ARFLAGS) $(LIBDIR)$(EXEC) $<

%.o: %.c
$(CC) -c $< -o $@ $(INC) $(CFLAGS)

That makefile is run from higher level makefile.
I have globals.h file in ../../shared/ folder, which is included from mgui.c and if I make modifications to that file, this makefile does not work. It just makes new .o file, but ar and new .lib is never made , why ? Using win8 with mingw.
Generated dependency file looks like this:
mgui.o: mgui.c inc/mgui.h ../../shared/globals.h
inc/mgui.h:
../../shared/globals.h:

A: You need to move the -include down to the end of your makefile.  Make takes the first target defined (even if it's in an included file) and uses it as the default target.  Since the include comes first, it defines the mgui.o as the first target and that's the only target that will be built, unless you explicitly run make all.
Also, you shouldn't put the recipe to build the library in the all target rule.  If you do, then that library will always be rebuilt even if nothing has changed.
You should write it as:
all: $(LIBDIR)$(EXEC)

$(LIBDIR)$(EXEC): $(SRC:%.c=%.o)
        $(AR) $(ARFLAGS) $@ $<


text:
Q: Why is ProtoBuf so slow on the 1st call but very fast inside loops? Inspired from this question. I created a small benchmark program to compare ProtoBuf, BinaryFormatter and Json.NET. The benchmark itself is a small console based one at https://github.com/sidshetye/SerializersCompare .Feel free to add/improve, it's quite simple to add a new serializer to the mix. Anyway, my results are:
        Binary Formatter         ProtoBuf          Json.NET     ServiceStackJson   ServiceStackJSV
 Loop     Size:512 bytes    Size:99 bytes    Size:205 bytes      Size:205 bytes     Size:181 bytes
    1         16.1242 ms      151.6354 ms       277.2085 ms         129.8321 ms        146.3547 ms
    2          0.0673 ms        0.0349 ms         0.0727 ms           0.0343 ms          0.0370 ms
    4          0.0292 ms        0.0085 ms         0.0303 ms           0.0145 ms          0.0148 ms
    8          0.0255 ms        0.0069 ms         0.0017 ms           0.0216 ms          0.0129 ms
   16          0.0011 ms        0.0064 ms         0.0282 ms           0.0114 ms          0.0120 ms
   32          0.0164 ms        0.0061 ms         0.0334 ms           0.0112 ms          0.0120 ms
   64          0.0347 ms        0.0073 ms         0.0296 ms           0.0121 ms          0.0013 ms
  128          0.0312 ms        0.0058 ms         0.0266 ms           0.0062 ms          0.0117 ms
  256          0.0256 ms        0.0097 ms         0.0448 ms           0.0087 ms          0.0116 ms
  512          0.0261 ms        0.0058 ms         0.0307 ms           0.0127 ms          0.0116 ms
 1024          0.0258 ms        0.0057 ms         0.0309 ms           0.0113 ms          0.0122 ms
 2048          0.0257 ms        0.0059 ms         0.0297 ms           0.0125 ms          0.0121 ms
 4096          0.0247 ms        0.0060 ms         0.0290 ms           0.0119 ms          0.0120 ms
 8192          0.0247 ms        0.0060 ms         0.0286 ms           0.0115 ms          0.0121 ms

Disclaimer:

*

*The results above are from within a Windows VM - the Stopwatch/timer values for very small intervals may not be 100% accurate compared to bare-metal OSes. So ignore ultra low values in the above table.

*For ServiceStack, the Json and JSV scored were taken from two separate runs. Since they share the same underlying ServiceStack library, running one right after the other affects the "cold start" 1 loop scores for the next run (it's 'warm start' fast)
BinaryFormatter is the largest in size but also the fastest for a single serialization => deserialization loop. However, once we tight loop around the serialization => deserialization code, ProtoBuf is super fast.
Question#1: Why is ProtoBuf that much slower for a single serialization => deserialization loop?
Question#2: From a practical perspective, what can we do to get past that "cold start"? Run at least one object (of any type) through it? Run every (critical) object type through it?

A:
Question#1: Why is ProtoBuf that much slower for a single serialization => deserialization loop?

Because it does a metric ton of work to analyse the model and prepare the strategy; I've spent a lot of time making the generated strategy be as insanely fast as possible, but it could be that I've skimped on optimizations in the meta-programming layer. I'm happy to add that as an item to look at, to reduce the time on a first pass. Of course, on the other hand the meta-programming layer is still twice as fast as Json.NET's equivalent pre-processing ;p

Question#2: From a practical perspective, what can we do to get past that "cold start"? Run at least one object (of any time) through it? Run every (critical) object type through it?

Various options:

*

*use the "precompile" tool as part of your build process, to generate the compiled serializer as a separate fully-static compiled dll that you can reference and use like normal: exactly zero meta-programming then happens

*explicitly tell the model about the "root" types at startup, and store the output of Compile()
static TypeModel serializer;
...
RuntimeTypeModel.Default.Add(typeof(Foo), true);
RuntimeTypeModel.Default.Add(typeof(Bar), true);
serializer = RuntimeTypeModel.Default.Compile();

(the Compile() method will analyse from the root-types, adding in any additional types needed as it goes, returning a compiled generated instance)

*explicitly tell the model about the "root" types at startup, and call CompileInPlace() "a few times"; CompileInPlace() will not full expand the model - but calling it a few times should cover most bases, since compiling one layer will bring other types into the model
RuntimeTypeModel.Default.Add(typeof(Foo), true);
RuntimeTypeModel.Default.Add(typeof(Bar), true);
for(int i = 0 ; i < 5 ; i++) {
    RuntimeTypeModel.Default.CompileInPlace();
}

Separately, I should probably:

*

*add a method to fully expand a model for the CompileInPlace scenario

*spend some time optimizing the meta-programming layer

Final thought: the main difference between Compile and CompileInPlace here will be what happens if you've forgotten to add some types; CompileInPlace works against the existing model, so you can still add new types (implicitly or explicitly) later, and it will "just work"; Compile is more rigid: once you've generated a type via that, it is fixed and can handle only the types it could deduce at the time it was compiled.