text:
Q: SQL Query to generate reports I have three tables:
Emp
    EmpId   EmpName
    51894   Alex
    51899   Peter
    51901   Sam

EmpPunch
    PunchId EmpId   BusinessDate    PunchIn     PunchOut
    15896   51894   12/18/2017      7:30:00 AM  5:30:00 PM
    15897   51894   12/19/2017      7:30:00 AM  5:30:00 PM
    15898   51899   12/18/2017      7:30:00 AM  5:30:00 PM
    15899   51901   12/18/2017      7:30:00 AM  5:30:00 PM

EmpMeals
    MealID  PunchID MealStart          MealEnd
    40725   15896   12/18/2017 9:00    12/18/2017 10:00
    40726   15896   12/18/2017 11:30   12/18/2017 12:30
    40727   15897   12/19/2017 9:00    12/19/2017 10:00
    40728   15897   12/19/2017 11:30   12/19/2017 12:30
    40729   15898   12/18/2017 9:00    12/18/2017 10:00

I need to write a query to generate a report in following format:
    EmpId    EmpName BusinessDate    PunchIn       Meal 1 Start    Meal 1 End     Meal 1 Duration     Meal 2 Start   Meal 2 End    Meal 2 Duration     PunchOut
    51894    Alex    12/18/2017      7:30:00 AM    9:00:00 AM      10:00:00 AM    1.00                11:30:00 AM    12:30:00 PM   1.00                5:30:00 PM
    51894    Alex    12/19/2017      7:30:00 AM    9:00:00 AM      10:00:00 AM    1.00                11:30:00 AM    12:30:00 PM   1.00                5:30:00 PM
    51899    Peter   12/18/2017      7:30:00 AM    9:00:00 AM      10:00:00 AM    1.00                                                                 5:30:00 PM
    51901    Sam     12/18/2017      7:30:00 AM                                                                                5:30:00 PM

Points to note:
a. Employee can have any number of meals. But we are considering first two.
b. If employee has availed only one meal, then for 2nd meal start and end time, NULL will be displayed.
c. If employee has not availed any meals then his record will not appear in EmpMeals table.

Right now, the query i have written is fetching records in multiple rows. I am not very proficient in SQL, so seeking help.
Please guide.

A: Here is an approach using temporary tables.
-- First assign meal numbers per PunchID in order of MealStart time
SELECT ROW_NUMBER() OVER ( PARTITION BY EM.PunchID ORDER BY EM.MealStart ) AS MEALNUMBER
    , EM.*
    INTO #MEALS
    FROM EmployeeMeal EM;

-- Then join the first two meals of each PunchID into a single row
SELECT
    EM1.PunchID
    , EM1.MealStart MealStart1
    , EM1.MealEnd MealEnd1
    , DateDiff(MINUTE, EM1.MealStart, EM1.MealEnd)/60.0 MealDuration1
    , EM2.MealStart MealStart2
    , EM2.MealEnd MealEnd2
    , DateDiff(MINUTE, EM2.MealStart, EM2.MealEnd)/60.0 MealDuration2
INTO #PUNCHES
 FROM #MEALS EM1
         LEFT JOIN #MEALS EM2
         ON EM1.PunchID = EM2.PunchID
         AND EM2.MEALNUMBER = 2

  WHERE EM1.MEALNUMBER = 1;

-- Finally join the employee and punch details with the meal details
SELECT E.EmpID
            , E.EmpName
            , EP.BusinessDate
            , CAST(ISNULL( FORMAT(PP.MealStart1, 'h:mm tt'), '') as varchar(10))  [Meal 1 Start]
            , CAST(ISNULL( FORMAT(PP.MealEnd1, 'h:mm tt'), '') as varchar(10))  [Meal 1 End]
            , ISNULL(PP.MealDuration1, 0) [Meal 1 Duration]
            , CAST(ISNULL( FORMAT(PP.MealStart2, 'h:mm tt'), '') as varchar(10))  [Meal 2 Start]
            , CAST(ISNULL( FORMAT(PP.MealEnd2, 'h:mm tt'), '') as varchar(10))  [Meal 2 End]
            , ISNULL(PP.MealDuration2, 0) [Meal 2 Duration]

        FROM Employee E
        JOIN EmployeePunch EP
            ON E.EmpID = EP.EmpID
        LEFT JOIN #PUNCHES PP
            ON PP.PunchID = EP.Punchid
            ;

  DROP TABLE #PUNCHES;
  DROP TABLE #MEALS;

A: Below is the code which I wrote for the issue:
    SELECT
            E.EmpId EmpId,
            E.EmpName,
            EP.PunchId PunchId,
            EP.BusinessDate BusinessDate,
            FORMAT(EP.StartTime, 'hh:mm tt') InTime,
            FORMAT(EP.EndTime, 'hh:mm tt') OutTime,
            MAX(CASE WHEN EPMBTemp.DefNum = 1 THEN FORMAT(EPMB.StartTime, 'hh:mm tt') END) MealOut1,
            MAX(CASE WHEN EPMBTemp.DefNum = 1 THEN FORMAT(EPMB.EndTime, 'hh:mm tt') END) MealIn1,
            MAX(CASE WHEN EPMBTemp.DefNum = 1 THEN DATEDIFF(MINUTE,EPMB.StartTime,EPMB.EndTime)/60.0 END) Meal1Length,
            MAX(CASE WHEN EPMBTemp.DefNum = 2 THEN FORMAT(EPMB.StartTime,'hh:mm tt') END) MealOut2,
            MAX(CASE WHEN EPMBTemp.DefNum = 2 THEN FORMAT(EPMB.EndTime,'hh:mm tt') END) MealIn2,
            MAX(CASE WHEN EPMBTemp.DefNum = 2 THEN DATEDIFF(MINUTE,EPMB.StartTime,EPMB.EndTime)/60.0 END) Meal2Length
    FROM EmpPunch EP
    LEFT JOIN
    (
    SELECT ROW_NUMBER () OVER (PARTITION BY PunchId ORDER BY PunchId ) AS DefNum, PunchId, MealPunchId
    FROM
    (
            SELECT DISTINCT EPMB.PunchId, EPMB.MealPunchId
            FROM EmpMealPunch EPMB
    )Temp
    )EPMBTemp ON EPMBTemp.PunchId = EP.PunchId
    LEFT JOIN EmpMealPunch EPMB ON EPMB.MealPunchId = EPMBTemp.MealPunchId
    JOIN Emp E ON EP.EmpId = E.EmpId
    group by E.EmpId, E.EmpName, EP.BusinessDate, EP.PunchId, EP.StartTime, EP.EndTime


text:
Q: Where to place layout file in a name-spaced app's directory structure? So I have a PHP application I'm developing that's nicely name-spaced as such:
src/
    VendorName/
        Ecommerce/
            Products/
                Controllers/
                    ProductsController.php
                Models/
                    Product.php
                Views/
                    index.html
                    view.html

Straightforward. My project is an e-commerce website, with functionality broken down into sub-modules like Products, Cart, Discounts etc. Each module then has its own controllers, models, and HTML view files.
My question is, although modules have their own views, where would I put "global" template files, like a common layout?

redpajama_set_name: RedPajamaStackExchange


text:
Q: EF Codefirst AddOrUpdate with related entities as identifier I want to use AddorUpdate with setting an identifier expression using related entities.
My class:
Class Task
   property id as Integer
   property name as String
End Class

My relation class:
Class RelationTask
   property id as Integer
   property task as Task
   property parentTask as Task
End Class

now I want to add a relation like:
taskA = new Task with {.name = "A"}
taskB = new Task with {.name = "B"}
.... ' add tasks to context
context.RelationTasks.AddOrUpdate(function(r) r.task, new RelationTask with {.task = TaskB, .parentTask = TaskA})

This does not work (error "Unable to create a constant value of type 'DataModel.Task'. Only primitive types or enumeration types are supported in this context."), because I use an entity instead of a value...
How should I do this?
Also, a second question: how would I write the same but with multiple identifiers? I think something like function(r) {r.task, r.parentTask}
Thanks!

A: Since nobody answers, I tried to find a solution myself, but I can't believe that's the best way of doing it. Anyhow, I added the IDs of both related entities so I could use these as identifier:
Class Task
   property id as Integer
   property name as String
End Class

Class RelationTask
   property id as Integer
   property task as Task
   property taskId as Integer
   property parentTask as Task
   property parentTaskId as Integer
End Class

taskA = new Task with {.name = "A"}
taskB = new Task with {.name = "B"}
.... ' add tasks to context
context.RelationTasks.AddOrUpdate(function(r) New With {r.taskId, r.parentTaskId}, new RelationTask with {.task = TaskB, .parentTask = TaskA})

It is behaving as I want, but it doesn't feel good...


text:
Q: Swift 2 - Insert device token in the database using PHP EDIT:
I'm developing an iOS application, which uses a webview, that has push notification and I'm trying to pass the device token to a php file (sampleIndex.php) for database registration.
My attempt on posting the device token isn't working. Here's the code:
EDIT (2): My current code is based from @mat 's answer (same concept, but cleaner)
extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = bytes.map { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return (hexBytes).joinWithSeparator("")
  }

}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    let session = NSURLSession.sharedSession()
    let tk = deviceToken.hexString()
    let postBody = NSString(format: "token=%@", tk)
    let endBody = NSURL(string: "http://samplesite.com/subfolder/subfolder2/sampleIndex.php")
    let request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
    request.HTTPMethod = "POST";
    request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        if data != nil {

            print("data: \(response)")

        } else {

            print("failed: \(error!.localizedDescription)")

        }

    }//closure

    dataTask.resume()
}

Why can't I get the value of tk? (token device). Am I missing something? Sorry, I'm just new to this.
EDIT (3)
Here's the php code (sampleIndex.php) where the token is being requested:
<?php
  include_once("includes/myConnect.php");
  $token = $_REQUEST['token'];

if (empty($token)) {
  $sql = "UPDATE sampleDB . sampleTB SET token= '0' WHERE id='8982'";
  $result = mysqli_query($conn, $sql);
}else{
  $sql = "UPDATE sampleDB . sampleTB SET token= '1' WHERE id='8982'";
  $result = mysqli_query($conn, $sql);
}

?>

(token sets to value " 0 " which proves that the device token fails to be passed on sampleIndex.php)

A: First make sure that you don't get the following error "failed: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection" if you do, add this to your plist:

The following code works for me. I have just changed the postBody and URL to answer your question but doing that I am able to save the token to my database.
extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = bytes.map { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return (hexBytes).joinWithSeparator("")
  }

}

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    //request notification
    let type: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound];
    let setting = UIUserNotificationSettings(forTypes: type, categories: nil);
    UIApplication.sharedApplication().registerUserNotificationSettings(setting);
    //register for remote notification - push notification
    UIApplication.sharedApplication().registerForRemoteNotifications();

    return true
}

fun application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

 let session = NSURLSession.sharedSession()
 let userId = "12345" // not sure you have a userId at this point but you can remove that line and also remove it from postBody
 let tk = deviceToken.hexString()
 let postBody = NSString(format: "user=%@&token=%@", userId, tk)
 let endBody = NSURL(string: "http://www.sampleurl.com/sampleIndex.php")
 let request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
 request.HTTPMethod = "POST";
 request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
                                                    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
     let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

         if data != nil {

          print("data: \(response)")

           } else {

           print("failed: \(error!.localizedDescription)")

           }

       }//closure

       dataTask.resume()
}

To insert the token in the database I strongly suggest you to use prepare statement. I use OOP Php so I have a class Database that handle all the connections but I simplified the code:
sampleIndex.php
<?php

$userid = $_REQUEST['user'];
$token = $_REQUEST['token'];

    if (empty($userid) || empty($token)) {
    return;
}else{

    saveTokenToDatabase($userid, $token);
}

function saveTokenToDatabase($user, $token){

    $username = 'youDatabaseUsername';
    $password =  'yourPassword';

$dbh = new PDO('mysql:host=localhost;dbname=database_name', $username, $password);

// first verify if the token is already in the database
$sth = $dbh->prepare("SELECT token
        FROM user_tokens
        WHERE user_id = ?
          AND token = ? LIMIT 1");

$sth->bindParam(1, $user, PDO::PARAM_INT);
$sth->bindParam(2, $token, PDO::PARAM_STR);
$sth->execute();
$tokenExists = ($sth->fetchColumn() > 0) ? true : false;

//if token is not already there
if(!$tokenExists){

$now = date("Y-m-d H:i:s");
$query = $dbh->prepare("INSERT INTO user_tokens (user_id, token, datecreated)  VALUES(?,?,'".$now."')");
$query->bindParam(1, $user, PDO::PARAM_INT);
$query->bindParam(2, $token, PDO::PARAM_STR);
$query->execute();

// determine if token already exists
}
    //close the connection
    $dbh = null;
}


text:
Q: Spring boot maven plugin not terminating forked tomcat process I do my development cycle using mvn clean package spring-boot:run and it forked a new process to run the tomcat server so you have two: maven process and tomcat process.
The problem is when the maven process is killed, the forked tomcat process isn't dead so I have to go through my task manager each time, search the process and kill it manually.
Is there any setting to disable process forking, or automatically kill the forked process? Tried searching the plugin manual but found nothing relevant.
Edit: I'm using Spring Boot 1.1.1.RELEASE


text:
Q: Spiltting Strings into Array Lists A friend is working on some homework. He has to take account numbers from an input file, check for account duplicates, calculate the cost using piecewise formula, then add them by account to display as an itemized bill. It's essentially the same homework found here.
It's hard since it's intro to java and I'm not very good. We're getting two errors: one is there's an Array out of bounds exception and two is the file checking. Since we use a for loop to calculate the account cost per call we can't keep track of previous account numbers to check. I suggested an ArrayList to keep hold of previous accounts and to check for duplicates but we can't figure out how to split into a separate ArrayList.
We have this code:
public static void main(String[] args) throws IOException, ParseException{

    ArrayList<String> acctHolder = new ArrayList<String>();
    String tmp = "";

    File fInput = new File("input_data.txt");

    Scanner scInput = null;
    scInput = new Scanner(fInput);
    while (scInput.hasNextLine()){
        tmp = scInput.nextLine();
        acctHolder.add(tmp);
    }

    scInput.close();

    DecimalFormat twoDForm = new DecimalFormat("#.##");

    String acctNum = null;
    String timeMin = null;
    String totalTime = null;
    double feeCost = 0;
    double totalCost = 0;
    double finalTotal = 0;
    double sum = 0;

    final double DAYRATE = 0.12;
    final double NIGHTRATE = 0.05;
    final double BASEFEE = 20.0;

    ArrayList<Double> aTCost = new ArrayList<Double>();

    System.out.println("Invoice");
    System.out.println("*****************************");
    System.out.println("Account    \t     Amount Due");

    for(int i = 1; i < acctHolder.size(); i++)
    {

        String[] result = ((String) acctHolder.get(i)).split(" ");

        acctNum = result[0];
        timeMin = result[1];
        totalTime = result[2];

        double tTime = Double.parseDouble(totalTime);

        String morningTime = "08:00";
        String nightTime = "22:00";
        DateFormat timeMins = new SimpleDateFormat("kk:mm");
        Date callTime = timeMins.parse(timeMin);
        Date dawnTime = timeMins.parse(morningTime);
        Date niteTime = timeMins.parse(nightTime);

        if(callTime.compareTo(dawnTime) > 0 && callTime.compareTo(niteTime) < 0 )
        {
            feeCost = tTime * DAYRATE;
            totalCost = feeCost + BASEFEE;
        }
        else
        {
            feeCost = tTime * NIGHTRATE;
            //totalCost = feeCost + BASEFEE;
        }

        aTCost.add(totalCost);

        //double sum = 0;
        for(Double d : aTCost)
            sum += d;

        System.out.println(acctNum + "               $"+ feeCost);

    }
    //for(int i = 0; i < acctHolder)
    System.out.println("*****************************");
    System.out.println("Total                " + sum);

}

A: I ran your code with the sample data from the link, and got the following result:
Invoice
*****************************
Account          Amount Due
10011               $1.224
10011               $1.476
10033               $1.7000000000000002
*****************************
Total                128.1

So, I can't reproduce the ArrayIndexOutOfBoundsException (my best guess is that in the file you were reading you had less than 3 fields in one of the lines, so result[2] was out of bounds).
The second problem I can see, is that you are using Double. That is why one of the results is "1.7000000000000002" instead of "1.7". You should have a look at BigDecimal, and search for "double problems" or "float problems" on a search engine.
The third problem is that you are adding all the previous costs to sum for each line on the file. This is why your total sum is so high. You have to put the summing loop outside the loop one the lines.
And for grouping the results by accounts, what you need is not and ArrayList, but a HashMap, using the account number as key.

A:                    import java.util.ArrayList;
                   import java.util.Arrays;
                   String stringToSplit = "1,2,3,4,5";
                   ArrayList<String> arrayFromString =new ArrayList<String>(
                   Arrays.asList(stringToSplit.split(",")));

You can Splite and Store in array List


text:
Q: Confidence interval for the median - continued I have a set of values $x_i\quad i=1,…,N$ of which I can calculate the median M. Each $x_i$ has an error $\delta x_i$.
The $x_i$ values are the result of a maximum likelyhood estimation and their error is calculated using the Cramer-Rao inequality.
How could I proceed to calculate the error on the median $\delta M$?
Some time ago I asked a similar question but at the time I did not consider the error on the $x_i$ values. How this additional uncertainty modifies the answer/way of thinking?


text:
Q: Understanding the proof of Prop 13.11 of Joy of Cats Theorem. Embeddings of dense subcategories preserve limits.

Part of the Proof. Let $\bf{A}$ be a dense subcategory of $\mathbf{B}$ with embedding $E : \bf{A}\to\bf{B}$, and let $D : \bf{I}\to \bf{A}$ be a diagram with a limit $\mathcal{L} = (L\overset{l_i}{\to}D(i))_{i\in \text{Ob}(\mathbf{I})}$. Then $\mathcal{L}$ is a cone over $E\circ D$. Let $\mathcal{S} = (B\overset{f_i}{\to}D(i))_{i\in \text{Ob}(\mathbf{I})}$ be an arbitrary cone over $E\circ D$. By density there exists a diagram $G : \bf{J}\to \bf{A}$ and a colimit $(G(j)\overset{c_j}{\to} B)_{j\in \text{Ob}(\mathbf{J})}$ of $E \circ G$. For each object $j$ of $\text{Ob}(\bf{J})$, $(G(j)\overset{f_i\circ c_j}{\to} D(i))_{i\in \text{Ob}(\mathbf{I})}$ is a cone over $D$. Hence for each $j \in \text{Ob}(\bf{J})$ there exists a unique morphism $g_j : G(j)\to L$ with $f_i \circ c_j = \ell_i \circ g_j$ for each $i \in \text{Ob}(\bf{I})$....

In this proof of Proposition 13.11 of Joy of Cats, I don't understand the reason for writing, the last line. Of course this will happen if $f_i \circ c_j$ is an $\mathbf{A}$-morphism. But I am not sure how that is true unless $\mathbf{A}$ is a full subcategory of $\mathbf{B}$. Could anyone explain?

A: By definition a (colimit-)dense subcategory is a full subcategory, see definition 12.10 in the linked file. So since $f_i \circ c_j$ is an arrow between two objects in $\mathbf{A}$, that arrow must also be in $\mathbf{A}$. So indeed, the existence of $g_j$ follows from the universal property of the limit $\mathcal{L}$ in $\mathbf{A}$.


text:
Q: Simplifying if statements in errors output Have multiply if statements for my error output in project. Can it be simplified?
if self.Lot_Mean_r<=0 or self.Lot_SD_r<=0 or self.SSB_DF_r<=0 or self.SSW_DF_r<=0 or self.SST_DF_r<=0:
            if self.Lot_Mean_r<=0:
                self.ui.textEdit_status_N.append("Error: Lot Mean negative or less than 0")
            if self.Lot_SD_r<=0:
                self.ui.textEdit_status_N.append("Error: Lot SD negative or less than 0")
            if self.SSB_DF_r<=0:
                self.ui.textEdit_status_N.append("Error: SSB DF negative or less than 0")
            if self.SSW_DF_r<=0:
                self.ui.textEdit_status_N.append("Error: SSW DF negative or less than 0")
            if self.SST_DF_r<=0:
                self.ui.textEdit_status_N.append("Error: SST DF negative or less than 0")
else:  [main code]

A: One possible way would be to go with a dict :
attr_dict = {"Lot Mean": self.Lot_Mean_r,
            "Lot SD": self.Lot_SD_r,
            "SSB DF": self.SSB_DF_r,
            "SSW DF": self.SSW_DF_r,
            "SST DF": self.SST_DF_r}

for key, value in attr_dict.items() :
    if value <= 0 :
        self.ui.textEdit_status_N.append(f"Error: {key} negative or less than 0")


text:
Q: Datatable - Using linq I want to update a row with the count I have a C# datatable with:
Id        ParentId    Name
========  =========== =====
1                     A
2          1          b
3          1          c
4          2          d
6          5          e

I want to add a column or just the result that will identify any ParentIds that do not have an Id. Basically in the above table, I want to find Id=6 since ParentId 5 is invalid.
I want to identify anywhere a parentId is not listed as an Id
I thought this could be accomplish with Linq.

A: This will return all rows where the ParentId does not appear in any row as Id
rows.Where(r1 => !rows.Any(r2 => r1["ParentId"] == r2["Id"]))


text:
Q: AWS Cognito signup using Steam social login Steam social signin with AWS Cognito
I'm creating a cognito user pool which has user phone number as unique key. I want to integrate Steam social signin to record a user's steam ID. Problem is that AWS Cognito supports OpenID connect while Steam only provides OpenID 2.0 (a deprecated standard).
Has anyone been successful in integrating the two? If no, then what approach should be used?
Why use steam Signin?
Use case demands that users store their own Steam ID only. Accepting Steam ID directly through a text field could be abused.
References

*

*OpenID 2.0 vs OpenID connect

*Steam OpenID official documentation

*Query string to initiate Steam signin


text:
Q: Ruby Geolocation Gem/Plugins What are the available (best) ruby IP-based geolocation gem/plugins?
How do they compare to one another in terms of functionality, performance and ease of use (e.g. do they interact with a web service, or require a separate database, etc.) ?
I'm hoping anyone that has used some can share their experience and give recommendations.

A: Easier to use and faster to set up, but with less features: http://humbuckercode.co.uk/licks/gems/geoip.
No external queries, no schema changes and quite fast.

A: While I've never used it, Graticule looks promising.

A: Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance queries. It's as simple as calling geocode on your objects, and then using a scope like Venue.near("Billings, MT").
https://github.com/alexreisner/geocoder

A: Your current best bet is probably GeoKit (http://github.com/andre/geokit-gem for gem, http://github.com/andre/geokit-rails for plugin). It has built in functionality for Yahoo and Google API keys, distance calculation helpers, reverse geolocation, etc.
However, GeoMereLaal (http://github.com/parolkar/geo_mere_laal/) is based on the working draft of the W3C Geolocaton API. It's very limited at the moment as I could only get it to work in Firefox, but it will be more accurate as it's supported by more browsers since it uses more methods of Geolocation (GPS, WiFi, cookies, IP).

A: RubyGeocoder seems to be the current favorite and it's kept up to date.  Comes complete with a railscast episode! http://rubygeocoder.com/


text:
Q: Angular 2 ngModelChange not working on second dropdown I have two dropdown menus with two different ngModelChange methods:

Type of Healthpros

  <select class="form-control" [(ngModel)]="pros" (ngModelChange)="onSelectProfessions($event)">
    <option *ngFor="let item of professions" value="{{item.id}}">{{item.text}}</option>
  </select>

Type of Specialization

  <select class="form-control" [(ngModel)]="spec" (ngModelChange)="onSelectSpecialities($event)">
    <option *ngFor="let item of specialities" value="{{item.id}}">{{item.text}}</option>
  </select>

Call these methods:
onSelectSpecialities($value){
   console.log("Here");
}

onSelectProfessions($value){
   console.log("Here 2");
}

The problem is that onSelectProfessions gets called when I change its dropdown menu, but onSelectSpecialities never gets called :( It only gets called when I complete remove the onSelectProfessions in the HTML, what am I doing wrong?
Here is my full Component:
import { Component, OnInit, ChangeDetectorRef, Input } from '@angular/core';
import * as globals from '../../../app/globals';
import {Observable} from 'rxjs/Rx';
import { UserService } from '../../../services/user.service';
import { UtilService } from '../../../services/util.service';
import { DataService } from '../../../services/data.service';

/*INSTALL*/
import swal from 'sweetalert2';

declare var $: JQuery;

declare global {
  interface JQuery {
    (selector: string): JQuery;
    rating(): JQuery;
  }
}

@Component({
    selector: 'app-list-professional',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.css']
})
export class ListProfessionalComponent {

    review = {rating:4}
    professionals = [];
    professions = {};
    specialities = {};

    constructor(private userService: UserService, private utilService: UtilService, private dataService: DataService){

        this.textSearch  = "";

    }

    ngOnInit(): void {

        this.utilService.blockUiStart();

        this.userService.getAllProfessionals().subscribe(data => {

            this.professionals = data;

            this.dataService.getProfessions().subscribe(data => {
                this.professions = data;
            });

            this.dataService.getSpecialities().subscribe(data => {
                this.specialities = data;
            });

            this.utilService.blockUiStop();

        });

    }

    onSubmit($value){
        console.log(this.textSearch);
        this.utilService.blockUiStart();
        this.userService.getProfessionalsByUsername(this.textSearch).subscribe(data => {
            this.professionals = data;
            this.utilService.blockUiStop();
        });
    }

    public onSelectSpecialities($value){

        console.log("Here");

        this.utilService.blockUiStart();
        this.userService.getProfessionalsBySpecialities($value).subscribe(data => {
            this.professionals = data;
            this.utilService.blockUiStop();
        });

    }

    public onSelectProfessions($value){

        this.utilService.blockUiStart();
        this.userService.getProfessionalsByProfessions($value).subscribe(data => {
            this.professionals = data;
            this.utilService.blockUiStop();
        });

    }

}

and here is my full data:
[{"id":1,"text":"Cardiology"},{"id":2,"text":"Clinical neurophysiology"},{"id":3,"text":"Endocrinology"},{"id":4,"text":"Geriatrics"},{"id":5,"text":"Internal medicine"},{"id":6,"text":"Nuclear medicine"},{"id":7,"text":"Ophthalmology"}]

and
[{"id":1,"text":"Health Technologist"},{"id":2,"text":"Sport Medicine Physician"},{"id":3,"text":"Medical Receptionist"},{"id":4,"text":"Psychiatry"}]

A: You have not defined 'pros' and 'spec' related binding in component classs. kindly define these model binding variables in component class. 100 % Your problem get solved.
Have executed your code, faced same problem. then got solution and this conclusion.

A: Just copied your html and added my setup code and everything seems to be working fine.
Try the following code:
Component:
import { Component } from '@angular/core';

@Component({
selector: 'app-multi-dropdown',
templateUrl: 'multi-dropdown.component.html'
})
export class MultiDropDownComponent {

professions: any[] = [
    { id: '1', text: 'Professional1' },
    { id: '2', text: 'Professional2' },
    { id: '3', text: 'Professional3' },
    { id: '4', text: 'Professional4' }
];

specialities: any[] = [
    { id: '1', text: 'specialities1' },
    { id: '2', text: 'specialities2' },
    { id: '3', text: 'specialities3' },
    { id: '4', text: 'specialities4' }
];

public onSelectSpecialities($value) {
    console.log('Specialities changed');

}

public onSelectProfessions($value) {
    console.log('Professional changed');
}
}

HTML:

Multidrop down compnent

Type of Healthpros

        <select class="form-control" [(ngModel)]="pros" (ngModelChange)="onSelectProfessions($event)">
            <option *ngFor="let item of professions" value="{{item.id}}">{{item.text}}</option>
        </select>

Type of Specialization

        <select class="form-control" [(ngModel)]="spec" (ngModelChange)="onSelectSpecialities($event)">
            <option *ngFor="let item of specialities" value="{{item.id}}">{{item.text}}</option>
        </select>


text:
Q: Finding maximum of a function of 2 variables I have function defined in such way:
ω0=145199+1;
f=1;
b=ω0/4;
s[ω_] := NDSolve[{x''[t]+b x'[t]+ω0^2 x[t]==f Sin[ω t],x[0]==0,x'[0]==0},x[t],{t,0,2π/ω0}];
x[t_,ω_]:=s[ω][[1,1,2]];

I'm trying to find t and ω for which the max. of the function occurs.
ωmax = NMaximize[{x[t,omg], 0<=t<=2π/ω0},{t, omg}]

Overall I am trying to find resonant frequency for which the largest oscillation occurs.
Unfortunately I get this error:

I have searched the reference, the stack and could not find the answer for the problem.

A: Clear["Global`*"]

ω0 = 145199 + 1;
f = 1;
b = ω0/4;

The differential equation can be solved exactly
x[t_, ω_] = DSolveValue[
   {x''[t] + b x'[t] + ω0^2 x[t] == f Sin[ω t],
    x[0] == 0, x'[0] == 0}, x[t], t] //
  FullSimplify[#, 0 <= t <= 2 π/ω0] &

EDIT: Use of arbitrary precision is necessary. This is done by specifying a WorkingPrecision for NMaximize
ωmax =
 NMaximize[{x[t, ω], 0 <= t <= 2 π/ω0,
    0 < ω < 2 ω0}, {t, ω},
   WorkingPrecision -> 50] // N

(* {7.09473*10^-11, {t -> 0.0000274786, ω -> 84877.3}} *)

Show[
 Plot3D[x[t, ω], {t, 0, 2 π/ω0}, {ω, 0, 2 ω0},
  AxesLabel -> Automatic,
  ClippingStyle -> None],
 Graphics3D[{Red, AbsolutePointSize[5],
   Point[{t, ω, x[t, ω]} /. ωmax[[2]]]}]]


text:
Q: Stubbing array responses with rspec I'm currently working on spec'ing out a rake task that's meant to populate a database using the google_drive gem. The gem allows users to access a spreadsheet ws like so:
# Gets content of A2 cell.
p ws[2, 1]  #==> "hoge"

The function that I'm trying to spec looks like this:
def get_tags(ws, row)
  tags = []
  [1, 21, 22, 23, 26, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40].each do |col|
    tags << ws[row, col] unless ws[row, col].blank?
  end
  tags
end

Fairly self explanatory, it gets passed a row and then adds the column data to tags for each column specified in the array.
My ws array consists of this:
ws = [[nil, 'Good', 'Tultex', '0241', 'Men\s Blend Tee',
            'XS - 3XL', '$3.40', '$4.50', '$4.50', '--', '--', '--',
            'TSC', 'y', 'Adult Unisex', 'Tee Shirt', 'Short Sleeve',
            'Crewneck', '3.2', 'Cotton/Poly (35/36)', 'Fitted', '11',
            '0240 (ladies)', '', 'Std Fitted Crew', 'Tees and Tanks',
            'Nicer - Fashion Fitted', 'Blend', '', '', '', 'Fashionable',
            '', '', '']]

Therefore, I need get_tags to return this:
resultant = ['Good', 'Tee Shirt', 'Short Sleeve', 'Crew Neck',
             'Standard', '', 'Tees and Tanks', 'Least Expensive',
             'Regular Cotton', '', '', '', '', '', '', 'Least Expensive']

My problem is that I have no idea how I can spec an array to accept the type of indexing that ws does (ws[val, val]), since that's usually a range index. I tried creating a two dimensional array but that obviously didn't work. Also tried stubbing it out by doing:
allow(ws).to receive(:[]) do |arg1, arg2|
  ws[arg1][arg2]
end

Which created an infinite loop of stubbiness, so then I tried storing ws into another array called temp and doing this (almost the same thing):
allow(ws).to receive(:[]) do |arg1, arg2|
  temp[arg1][arg2]
end

But I still end up with the same infinite stubbing loop.
Any advice on what steps to pursue next would be greatly appreciated! Thanks in advance :)

A: How about creating a class which handles the needed interface:
class DBStub
  def initialize(data_store)
    @data_store = data_store
  end

  def [](arg1, arg2)
    @data_store[arg1][arg2]
  end
end

ws = DBStub.new(temp)

A: What values do you expect there to be in ws? If you don't care about what the values are and just want to test that they're added you could do
   allow(ws).to receive(:[]) { rand(1000) }


text:
Q: How do I send an email to the user on submit of php form How do I send an email to the user with the data they submitted in the form that includes a little message using there name and thanking them on submit of php form.
Here is my current php code. It currently just shows them a message that says there name and that the message has been sent and then sends me an email to my email address.
<?php
    if(isset($_POST['submit'])){

        $to = "benlevygraphics@gmail.com";
        $headers = "From: " . $_POST['email'];
        $subject = "Ben, you have been contacted...";
        $body = "Name: " . $_POST['name'] . "\nEmail: " . $_POST['email'] . "\nWebsite: " . $_POST['web'] . "\nMessage: " . $_POST['message'];

        if(mail($to, $subject, $body, $headers)){

        echo("
".$_POST['name'].", your message has been sent!
");

        }
        else{
           echo("
".$_POST['name'].", Message delivery failed...
");
        }
   }
?>

I am new to php and I have read stuff online and I still don't understand so if you could be clear in your examples or help I would greatly appreciate it very much. Thanks!

A: Look into your php.ini beacuse you have to enter a SMTP Server.
At my file it begins in line 1087 with "[mail function]"

A: Assuming your current code is already working fine, you can do this to send yourself an email together with the recipient:

*

*Set $to to $_POST['email']

*Set $headers to "From: {$_POST['email']}\r\nBcc: benlevygraphics@gmail.com"

*Adjust $body and $subject to your needs.

Btw, I can't say this often enough; make sure that your page has some form of CSRF protection.
How to properly add CSRF token using PHP
The above is just one way, there are others, just search for it :)


text:
Q: Command "ping" is not found error discord.py Whenever I run my discord python code, and test it in the discord chat, it says the ping command is not found even though I defined it in the code and the .run(token) command is at the bottom.
The error message I get is: "Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found"
import discord
from discord.ext import commands
token = "[private token]"

client = commands.Bot(command_prefix="!")

@client.event
async def whenReady():
    print("Bot is ready")

@client.command()
async def ping(ctx):
    await ctx.send("What it do babyy")

client.run(token)

The bot should've replied with the phrase "what it do babyy" when I type in the !ping command but instead I get the error.
I also did replace the private token in code above with filler for obvious reasons.
Any helps would be appreciated, I am new to the discord API and I'm learning off the documentation and some forums here and there.

A: Try passing the parameter pass_context = True
import discord

client = commands.Bot(command_prefix="!")
TOKEN = "token"

@client.event
async def whenReady():
    print("Bot is ready")

@client.command(pass_context=True)
async def ping(ctx):
    await ctx.send("What it do babyy")

client.run(token)


text:
Q: Theorem $17$, Chapter $3$ (Marcus' Number Fields): Every ideal in a Dedekind domain is generated by at most two elements I understand that similar questions have been asked before, but I am looking for an explanation of certain steps in Marcus' proof of the same, in Theorem $17$, Chapter $3$ of Number Fields. I shall paraphrase the proof slightly for convenience.
Theorem. Let $I$ be an ideal in a Dedekind domain $R$, and let $\alpha$ be any nonzero
element of $I$. Then there exists $β ∈ I$ such that $I = (α, β)$.

Proof. It is sufficient to construct $\beta\in R$ such that $I = \gcd((\alpha),(\beta))$.

*

*I know that $\gcd(J,J') = J+J'$, so we expect $I = (\alpha) + (\beta)$ to imply $I = (\alpha,\beta)$. Indeed, $(\alpha) + (\beta) = (\alpha,\beta)$ follows from definitions, as $(\alpha) + (\beta) = R\alpha + R\beta = (\alpha,\beta)$.

Let $P_1^{n_1}P_2^{n_2}\ldots P_r^{n_r}$ be the prime decomposition of $I$, where $P_i$ are distinct. Then, $(\alpha)$ is divisible by all $P_i^{n_i}$. Let $Q_1,\ldots, Q_s$ denote the other primes (if any) which divide $(\alpha)$. We must construct $\beta$ such that none of the $Q_j$ divide $(β)$, and for each $i$, $P_i^{n_i}$ is the exact power of $P_i$ dividing $(β)$. Equivalently, $$\beta\in \bigcap_{i=1}^r (P_i^{n_i} - P_i^{n_i+1}) \cap \bigcap_{j=1}^s (R - Q_j).$$

*Why must we construct such a $\beta$? I know that $A|B$ if and only if $B\subset A$, but I do not see an immediate contradiction.

This can be accomplished via the Chinese Remainder Theorem. Fix $β_i ∈ P_i^{n_i} − P_{i}^{n_i+1}$ (which is necessarily nonempty by unique factorization) and let $β$ satisfy the congruences $$\beta\equiv \beta_i \bmod P_i^{n_i+1}, \quad i = 1, \ldots, r$$
$$\beta\equiv 1 \bmod Q_j, \quad j= 1,\ldots,s$$
(To show that such a $β$ exists we have to show the powers of the $P_i$ and the $Q_j$
are pairwise co-maximal: that the sum of any two is $R$. This is easy to verify if one
interprets the sum as the greatest common divisor.)

*I understand the Chinese Remainder Theorem in the following form: Let $R$ be a commutative ring with unity, and $I_1, \ldots, I_n$ be pairwise relatively prime ideals in $R$. Then,
$$R\left/\bigcap_{i=1}^n I_i\right. \cong R/I_1 \times \ldots \times R/I_n$$
and the canonical map $r + \bigcap_{i=1}^n I_i \mapsto (r+ I_1, \ldots, r+I_n)$ is a ring isomorphism. How does this help us construct the required $\beta$? Moreover, what does congruence modulo an ideal mean? My guess is that $a \equiv b \bmod I$ if and only if $a-b \in I$. Even if this is true, I have trouble seeing where the congruences in Marcus' proof come from.

I would appreciate any details and explanations. Thank you very much!


text:
Q: Как вывести из БД sqlite3 строку (в которой есть html теги), так, чтобы эти теги читались? Как вывести из БД sqlite3 строку (в которой есть html теги), так, чтобы эти теги читались?
Например строка "
Тут самый обычный текст
" , выводилась бы как
Тут самый обычный текст
 ?

A: Ответом является использование esвведите сюда описание ссылкиcape


text:
Q: Is it possible to use Microchip's ZCD (Zero cross detect) circuitry in an isolated SMPS? Let's say you have a device which is fed by AC line voltage and features an isolated SMPS. The switcher outputs 5 VDC, and that powers a PIC micro. I'm curious how is the Microchip's ZCD (Zero cross detection) module supposed to work here? In the technical brief (TB3138), they give the following diagram:

However that assumes the AC and the PIC share the same ground, which is not the case. Probably they assume the PC will be on the non-isolated side, or that the isolation would be a 50/60 Hz transformer. I've searched Microchip's app notes on this topic, and I couldn't find any mention of this scenario.
Any ideas about how to interface the AC to the ZCD pin, is it even feasible?
(And yes, I know those opto-couplers cost pennies).

A: I'd use either a very small 50/60Hz step-down transformer (in the low single digit VA range) as a coupling transformer if space wasn't a major issue, or a Y1 capacitor in the few-nanofarad range as a coupling cap if I was tight on space.  Either way, the relatively light load of the input shouldn't pose an issue, and the coupling device will act to limit the current so you won't need the resistors any longer.


text:
Q: Don´t preload images in XML (google maps API v3) Hey i have a question that seems very tricky.
I want to add images for every Infowindow in my map. But the clue is that the images shouldn't parse directly from the XML, because if there are 300 markers and for every marker an image, that would by a very big data which have to load on mapstart. Is it possible to load the image only if the marker has cliked ?
Heres my code:

A: You don't have to care about these images.
Before you click the markers it's simply a string, no images will be loaded.
Only when you click on the marker this string will be used to create a -node inside the infoWindow(what will force the download)


text:
Q: Safari Error When Playing Video in React App In my React app I am running into an issue in Safari (this works fine in Chrome and Firefox) where, when I mouseover a video to play it, I get the following error:

NotAllowedError: The request is not allowed by the user agent or the
platform in the current context, possibly because the user denied
permission.

The relevant code block is this:
{ this.state.url ?
  <video className="video"
    onMouseOver={event => {
      this.onVideoPlay(this.state.url, event);
    }}
    onMouseOut={event => {
      this.onVideoPause(this.state.url, event);
    }}
    src={`${this.state.url}`} >
  </video>
  : null
}

And my two functions look like this:
  onVideoPlay = async (videoUrl, event) => {
    if (!videoUrl || !event || videoUrl === 'url(${videoBg})') return;
    if (!this.state.isPlaying) {
      await event.target.play();
      this.setState({ isPlaying: true });
    }
  };

  onVideoPause = async (videoUrl, event) => {
    if (!videoUrl || !event) return;
    if (this.state.isPlaying) {
      await event.target.pause();
      this.setState({ isPlaying: false });
    }
  }

What is the issue here, and how can I resolve it?

A: If I had to bet, I'd say the issue is trying to play a video unmuted without direct user interaction.
According to Safari docs:

A  element can use the play() method to automatically play without user gestures only when it contains no audio tracks or has its muted property set to true. If this video element gains an audio track or becomes unmuted without a user gesture, playback pauses. Playback stops if the video element isn't visible onscreen or is out of the viewport.

Configuring the video to play muted should solve the issue, as the MDN guide for autoplay also states.
You can argue that, in your case, you do have a user gesture, mouseover. But that doesn't count as interacting with the site. It has to be a click or a keypress, as the webkit blog specifies.
Does it work with click, for instance?


text:
Q: i keep getting the error "expected a string (for built-in components) or a class/function (for composite components) but got: undefined" I've looked at similar answers, but they didn't help.
im importing my AuthProvider into my _app.js as:
import React from 'react'
import '../styles/globals.css'
import Navbar from './Navbar'
import AuthProvider from '../Firebase/AuthContext'

const MyApp = ({ Component, pageProps }) => {
  return (
    <AuthProvider>
    <Navbar />
  <Component {...pageProps} />
  </AuthProvider>
  )
}

export default MyApp

the error comes up when i go to my About.js page:
import React from 'react'
import {Component} from 'react'

class About extends Component {

    render() {
        return(

ABOUT PAGE

        )
    }
}

export default About

that ERROR leads me to my Index.js page:
import React from 'react';
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
//import AppBar from '@mui/material/AppBar'
//import Toolbar from '@mui/material/Toolbar'
import Typography from '@mui/material/Typography'
//import Button from '@mui/material/Button'
//import Link from 'next/link'
import { Container } from '@mui/material'
import FirebaseClient from '../FIREBASE/FirebaseClient'
FirebaseClient()

export default function Home() {
  return (

        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />

    <Container>

HOME PAGE

    </Container>

          Powered by{' '}

            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />

  )
}

but tho, when i look again, it says that i have an "anonymous function" in my
Auth.js file:
import React, { useState, useEffect, useContext, createContext } from "react";
import nookies from "nookies";
import FirebaseClient from "../FIREBASE/FirebaseClient";
import firebase from "firebase/app";
import "firebase/auth";
const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  FirebaseClient();
  const [user, setUser] = useState(null);

 *** ERROR HERE, my console points to my useEffect ***
useEffect(() => {
    return firebase.auth().onIdTokenChanged(async (user) => {
      console.log("auth changed");
      console.log(user ? user.id : "Nothing");
      if (!user) {
        setUser(null);
        nookies.set(undefined, "token", "", {});
        return;
      }

      const token = await user.getIdToken();
      setUser(user);
      nookies.set(undefined, "token", token, {});
    });
  }, []);
  return (
    <AuthContext.Provider value={{ user }}>
      {children}
    </AuthContext.Provider>
  );
};
export const useAuth = () => useContext(AuthContext);

what am i doing wrong?
I'm doing exactly the same as i did in a previous Next project,
idk why its not working.
i even tried pasting what someone recommended me to paste,
still, same errors.
I've tried clearing my cache, error.
my firebase says it's init.
so, im stuck


text:
Q: ExceptionHandler not work in EventListener i need to initialize the data ConfigurationItem after my app is running, so i created the InitializingDataConfig class
in the saveConfItem i check if the item exist or not, if it already exists, i throw this error UnicityException
the problem is in the case of the item exists the exeption is not showing, but when i add an existing ConfigurationItem using postman it throws the exeption
@Component
public class InitializingDataConfig {

    private final CommandService service;

    public InitializingDataConfig(CommandService service) {
        this.service = service;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void initialize() {
        List<ConfigurationItemDto> configurationItems = DataUtil.readJsonFile();
        for (ConfigurationItemDto item : configurationItems) {
            service.saveConfItem(item);
        }
    }

}

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice()
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(UnicityException.class)
    public ResponseEntity<Object> unicityException(UnicityException ex) {
        return buildResponseEntity(new ApiError(CustomHttpStatus.UNIQ_REQUEST, new Date(), ex.getMessage()),
            HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<Object> buildResponseEntity(ApiError apiError, HttpStatus status) {
        return new ResponseEntity<>(apiError, status);
    }

}


text:
Q: Rust: allocator API: expected struct `std::alloc::Global` when I provide my own allocator I want to use my own allocator in alloc::vec::Vec::new_in. However, Rust tells me "expected struct std::alloc::Global". How can I use my own allocator? I'm on Rust nightly 1.60.
#![feature(allocator_api)]

use std::alloc::{Allocator, AllocError, Layout};
use std::ptr::NonNull;

struct PageAlignedAlloc;

unsafe impl Allocator for PageAlignedAlloc {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        std::alloc::System.allocate(layout.align_to(4096).unwrap())
    }

    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        std::alloc::System.deallocate(ptr, layout)
    }
}

fn main() {
    let vec = Vec::<u8>::new_in(PageAlignedAlloc);
}

A: alloc::vec::Vec uses the Global allocator as the default for the second generic parameter. You can see this in the source code of the alloc library:
pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
    buf: RawVec<T, A>,
    len: usize,
}

This is the reason for the error message.
To compile your code, you need to provide a full type definition like this instead:
Original answer
let vec = Vec::<u8, PageAlignedAlloc>::new_in(PageAlignedAlloc);
I don't know if there are any issues regarding that. I think the Rust compiler should be capable of inferring the type by itself in that case in the future.

Updated, thanks to @eggyal 's comment
let vec = Vec::<u8, _>::new_in(PageAlignedAlloc);


text:
Q: How to get the latest 2 records of a ID I understand that it can be a repetitive question but please can anyone help me form a query to get the latest 2 records for any particular ID . StartTime and EndTime here are UnixTimestamps here. EndTime can be 0 or NULL based on the status in general.
ID  StartTime   EndTime  Status
1   1000        1003     Closed
1   1003        1005     Closed
2   1002        1008     Closed
2   1008        1009     Closed
3   1002        1005     Closed
3   1005        1010     Closed
4   1006        0        Open
2   1009        1012     Closed
1   1005        1008     Closed
3   1010        0        Open

Output
ID StartTime  EndTime Status
1  1003       1005    Closed
1  1005       1008    Closed
2  1008       1009    Closed
2  1009       1012    Closed
3  1005       1010    Closed
3  1010       0       Open
4  1006       0       Open

A: Use window functions:
select t.*,
from (select t.*,
             row_number() over (partition by id order by starttime desc) as seqnum
      from t
     ) t
where seqnum <= 2;

Use dense_rank() if there are multiple rows on a given date, and you want two dates.


text:
Q: Best way to draw/animate this scenario in an iPhone app My next iOS app will be my first attempt at having some basic animation beyond the core UI controls provided by the SDK.
This isn't anything complicated. I essentially need to display 5-6 icons on the screen, move them along straight lines, have them fade in and out as a set, and potentially draw lines that visually connect specific icons to each other.
OpenGL ES seems like it's probably overkill for this, as does Quartz 2D (?) but what's the best way in terms of (a) ease of programming and (b) minimizing performance/memory impact?
Should I rely solely on UIKit, making each icon its own view or layer? UIView seems to have all the basic animation (fade, move) capabilities I'll need.

A: UIKIt and CoreAnimation whenever possible. It's very easy to animation, move views around, and create effects between views using CA. You'll use bits and pieces of Quartz to draw little bits, but for the most part you shouldn't have to write drawing code at all.
UIViews are extremely cheap objects to create and draw, assuming you don't do anything crazy. You can throw hundreds of UIImageViews on the screen and animate them around while barely stressing the CPU.
There are a couple UIKit & Core Animation drawing session videos from WWDC 2011, I recommend you watch them - it's a wealth of information that doesn't exist anywhere else.


text:
Q: Cuda Memory Transfer overhead As it is known that copying data to the GPU is slow I was wondering what specifically "counts" as passing data to the GPU.
__global__
void add_kernel(float* a, float* b, float* c, int size) {
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }

int main() {
int size = 100000; //Or any arbitrarily large number
int reps = 1000;   //Or any arbitrarily large number

extern float* a; //float* of [size] allocated on the GPU
extern float* b; //float* of [size] allocated on the GPU
extern float* c; //float* of [size] allocated on the GPU

 for (int i = 0; i < reps; ++i)
add_kernel<<<blocks, threads>>>(a, b, c, size);

}

Does something such as passing size to the kernel incur (significant) overhead? Or does "data transfers" refer more specically to copying large arrays from the heap to the GPU.
IE would this variant be (much) faster
__global__
void add_kernel(float* a, float* b, float* c, int size, int reps) {
for (int j = 0; i < reps; ++j)
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }

int main() {
int size = 100000; //Or any arbitrarily large number
int reps = 1000; //Or any arbitrarily large number

extern float* a; //float* of [size] allocated on the GPU
extern float* b; //float* of [size] allocated on the GPU
extern float* c; //float* of [size] allocated on the GPU

add_kernel<<<blocks, threads>>>(a, b, c, size, reps);
}

IE (again) in "ideal" CUDA programs should programmers be attemping to write a large majority of the computational programs in purely CUDA kernels or write CUDA kernels that are then called from the CPU (in the instance that passing values from the stack does not incur significant overhead).
Edited for clarity.

A: Everything counts. In order to run the kernel CPU needs to pass somehow which kernel to call and with which parameters. On "micro-level", if your kernel performs only several operations, these are considerable expenses. In real life, if your kernels do a lot of work, they are neglible.
And relatively big service expenses can be if such small operations are not pipelined. You can see this in NVidia's Visual Profiler. I don't know/remember exact numbers, but the order is following. Bandwidth between CPU and GPU can be like 1 GB/s, so 1 byte/nanosecond. But actually to send 4 bytes packet and to get acknowledge will take something like 1 microsecond. So to send 10000 bytes - like 11 microseconds.
Also execution of operations are optimized for massive execution on GPU, so execution of 10 consecutive operations with one 32 threads warp can take like 200 GPU clock cycles (like 0.2 microsecond). And say 0.5 microsecond for sending command for kernel execution before it will start.
In real life the problem is usually in that to sum 100 million of numbers you'll spend 0.4 seconds because of bandwidth limitation and say 0.1 microsecond for calculation itself. Because top GPU can perform about 1000 operations in each cycle near 1 nanosecond long.

A: Hi I have benchmarked the two versions. Simply calling CUDA functions DOES have a noticeable overhead
This is the output --
 Calculating... (BlackCat_Tensors) reps outside
It took me 27.359249 clicks (27.359249 seconds).

 Calculating... (BlackCat_Tensors) reps inside
It took me 10.855168 clicks (10.855168 seconds).

This is my benchmark --
/*
 * test_area.cu
 *
 *  Created on: Jan 11, 2018
 *      Author: joseph
 */

#ifndef TEST_AREA_CU_
#define TEST_AREA_CU_

#include <omp.h>
#include <stdio.h>

int threads() {
    return 256;
}
int blocks(int size) {
    return (size + threads() - 1) / threads();
}

__global__
void add_kernel(float* a, float* b, float* c, int size) {
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }
}

__global__
void add_kernel(float* a, float* b, float* c, int size, int reps) {
    for (int j = 0; j < reps; ++j)
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }
}

int main() {
int sz = 10000; //Or any arbitrarily large number
int reps = 10000;   //Or any arbitrarily large number

float* a; //float* of [size] allocated on the GPU
 float* b; //float* of [size] allocated on the GPU
 float* c; //flo

cudaMalloc((void**)&a, sizeof(float) * sz);
cudaMalloc((void**)&b, sizeof(float) * sz);
cudaMalloc((void**)&c, sizeof(float) * sz);

float t = omp_get_wtime();
printf("\n Calculating... (BlackCat_Tensors) reps outside\n");

for (int i = 0; i < reps; ++i) {
add_kernel<<<blocks(sz), threads()>>>(a, b, c, sz);
cudaDeviceSynchronize();
}
t = omp_get_wtime() - t;
printf("It took me %f clicks (%f seconds).\n", t, ((float) t));

 t = omp_get_wtime();
printf("\n Calculating... (BlackCat_Tensors) reps inside \n");

add_kernel<<<blocks(sz), threads()>>>(a, b, c, sz, reps);
cudaDeviceSynchronize();

t = omp_get_wtime() - t;
printf("It took me %f clicks (%f seconds).\n", t, ((float) t));

 cudaFree(a);
 cudaFree(b);
 cudaFree(c);
}

#endif /* TEST_AREA_CU_ */

A: Here's a secondary benchmark:
I imagine the threads for the inside loop could be higher as it is calculating more and ergo should have an even greater disparity in performance.
/*
 * test_area.cu
 *
 *  Created on: Jan 11, 2018
 *      Author: joseph
 */

#ifndef TEST_AREA_CU_
#define TEST_AREA_CU_

#include <omp.h>
#include <stdio.h>

int threads() {
    return 256;
}
int blocks(int size) {
    return (size + threads() - 1) / threads();
}

__global__
void add_kernel(float* a, float* b, float* c, int size) {
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }
}

__global__
void add_kernel(float* a, float* b, float* c, int size, int reps) {
    for (int j = 0; j < reps; ++j)
   for (int i = 0; i < size; ++i) {
       a[i] = b[i] + c[i];
   }
}

int main() {
int sz = 10000; //Or any arbitrarily large number
int reps = 1000;   //Or any arbitrarily large number

float* a; //float* of [size] allocated on the GPU
 float* b; //float* of [size] allocated on the GPU
 float* c; //flo

cudaMalloc((void**)&a, sizeof(float) * sz);
cudaMalloc((void**)&b, sizeof(float) * sz);
cudaMalloc((void**)&c, sizeof(float) * sz);

float t = omp_get_wtime();
printf("\n Calculating... (BlackCat_Tensors) reps outside\n");

for (int i = 0; i < reps; ++i) {
add_kernel<<<blocks(sz), threads()>>>(a, b, c, sz);
cudaDeviceSynchronize();
}
t = omp_get_wtime() - t;
printf("It took me %f clicks (%f seconds).\n", t, ((float) t));

 t = omp_get_wtime();
printf("\n Calculating... (BlackCat_Tensors) reps inside \n");

add_kernel<<<blocks(sz), threads()>>>(a, b, c, sz, reps);
cudaDeviceSynchronize();

t = omp_get_wtime() - t;
printf("It took me %f clicks (%f seconds).\n", t, ((float) t));

 cudaFree(a);
 cudaFree(b);
 cudaFree(c);
}

#endif /* TEST_AREA_CU_ */

 Calculating... (BlackCat_Tensors) reps outside
It took me 14.969501 clicks (14.969501 seconds).

 Calculating... (BlackCat_Tensors) reps inside
It took me 13.060688 clicks (13.060688 seconds).


text:
Q: Redirect Wordpress Sub Folder to a Sub Domain I have a site that is actually a multisite using subdomains and I would like to remap the subfolder translations to a sub domain.
domain.com (main site)
blog.domain.com (mu site for the blog)

With WPML, I have:
domain.com/fr/ (for the French translation)
blog.domain.com/fr/ (for the French translation)

I would like to have the following:
domain.com/fr/ --> fr.domain.com
blog.domain.com/fr/ --> blogue.domain.com

I think this could be possible with Rewrite rules, but I can't get it to work properly.
Here is the current default Wordpress MU .htaccess:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

Many thanks for your help!

A: Keep your .htaccess like this:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^fr/(.*)$ http://fr.domain.com/$1 [NC,R=302,L]

RewriteCond %{HTTP_HOST} ^blog\.domain\.com$ [NC]
RewriteRule ^fr/(.*)$ http://blogue.domain.com/$1 [NC,R=302,L]

RewriteRule ^index\.php$ - [L]

RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

RewriteRule ^(.+?\.php)$ $1 [L]

RewriteRule . index.php [L]

A: You can add to .htaccess:
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^/fr/ http://fr.domain.com/fr/ [R,L]

RewriteCond %{HTTP_HOST} ^blog\.domain\.com
RewriteRule ^/fr/ http://blogue.domain.com/fr/ [R,L]


text:
Q: Advises needed on Zend Framework 2 modules and models architecture I would like to start working with Zend Framework 2 and need some guidance as to the architecture of the framework. I compared Akrabat's ZF2 tutorial with it's ZF1 equivalent and the main difference I noticed so far seems to be the use of modules. I like the idea with modules as being independent and re-usable pieces of code and am thinking it could help segmenting my application and make it more maintainable. For instance I could have the following URL => module mapping:
http://example.org/products => Products module
http://example.org/services => Services module
http://example.org/oauth => Oauth module
[...]

What I'm confused about, is that some of my modules will share the same underlying database resources (e.g. both Products and Services use the same table for comments) and therefore the same database models. Accordingly, I'm wondering:
Where should I put my database models when those are used by multiple modules?

A: See the following article: http://adam.lundrigan.ca/2011/09/module-dependencies-in-zf2/
You can create a third module (example: Base, Main) that is a dependency for the Products and Services modules, or you can add the Models to one of your modules and use that module as a dependency for the other one.
Module.php
/**
 * Get dependencies
 *
 * @return array
 */
public function getDependencies()
{
    return array(
        'BaseModule' => array(
            'version' => '>=0.1.0',
            'required' => true
        ),
    );
}


text:
Q: Bitwise commands such as Bitor with many inputs? Matlab takes only two inputs with bitwise commands such as bitor. bitor(1,2) returns 3 and bitor(1,2,4) does not return 7 but:

ASSUMEDTYPE must be an integer type name.

Currently, I create for-loops to basically create a bitwise command to take as many inputs as needed. I feel the for-loops for this kind of thing is reinvention of the wheel.
Is there some easy way of creating the bitwise operations with many inputs?
Currently an example with some random numbers, must return 127
indices=[1,23,45,7,89,100];
indicesOR=0;
for term=1:length(indices)
    indicesOR=bitor(indicesOR,indices(term));
end

A: If you don't mind getting strings involved (may be slow):
indicesOR  = bin2dec(char(double(any(dec2bin(indices)-'0'))+'0'));

This uses dec2bin to convert to strings of '0' and '1'; converts to numbers 0 and 1 by subtracting '0'; applys an "or" operation column-wise using any; and then converts back.
For AND (instead of OR): replace any by all:
indicesAND = bin2dec(char(double(all(dec2bin(indices)-'0'))+'0'));

For XOR: use rem(sum(...),2):
indicesXOR = bin2dec(char(double(rem(sum(dec2bin(indices)-'0'),2))+'0'))

EDIT: I just found out about functions de2bi and bi2de (Communications Toolbox),  which avoid using strings. However, they seem to be slower!
indicesOR  = bi2de(double(any(de2bi(indices))));
indicesAND = bi2de(double(all(de2bi(indices))));
indicesXOR = bi2de(double(rem(sum((de2bi(indices))));

Another approach is to define a recursive function, exploiting the fact that AND, OR, XOR operations are (bit-wise) associative, that is, x OR y OR z equals (x OR y) OR z. The operation to be applied is passed as a function handle.
function r = bafun(v, f)
%BAFUN  Binary Associative Function
%   r = BAFUN(v,f)
%   v is a vector with at least two elements
%   f is a handle to a function that operates on two numbers

if numel(v) > 2
    r = bafun([f(v(1), v(2)) v(3:end)], f);
else
    r = f(v(1), v(2));
end

Example:
>> bafun([1,23,45,7,89,100], @bitor)
ans =
   127


text:
Q: Cloud Integration: An error occurred when creating the project. Please retry I created a new GAE app, but the Cloud Integration section on the Settings page tells me that "An error occurred when creating the project. Please retry."
I have pressed the Retry button multiple times over a period of many hours, but it's just not working.  I found this thread, which repeatedly says that the issue is solved, but it's not resolved for me.
Is anyone from Google monitoring this forum? Can you help?

A: The only solution seems to be to create a new app, and hope for the best (it worked for me). Sadly, if you delete the problem app, the app-id is lost forever.

A: This is a bit late, but in case someone else stumbles on this question.
In the google cloud console, activate billing from the Storage>Cloud Storage > Browser tab, then activate / retry under Cloud Integration from appengine.google.com.
I didn't need to create a new app id, when I went that route.


text:
Q: How I can manage optional values in Firebase Firestore and avoid empty fields in database? In my context, there is the possibility of optional values.
For example, in this database, the field iVisperas can be empty in multiple cases. I think is a bad practice to keep empty fields (?).

Into my code, I map the snapshot to one class.
I don't want to keep the field iVisperas as an empty field in Firestore but I don't know how to determine from the model class if this field exists or not.
How I can achieve this. This is my model class from the document. Actually, at getTituloVisperas method I check if field iVisperas is empty. If I want to create iVisperas field only when it contains data, how I can manage that into the model class?
public class MetaLiturgia {
    private String fecha;
    private int tiempo;
    private String semana;
    private String mensaje;
    private String salterio;
    private int color;
    private String meta;
    private String titulo;
    private String iVisperas;

    private int weekDay;

    public MetaLiturgia() {
    }

    public String getTituloVisperas() {
        if (iVisperas.equals("")){
            return titulo;
        }else{
            return iVisperas;
        }

    }
//...
}

A:
For example, in this database the field iVisperas can be empty in multiple cases.

Seeing that all the fields in your MetaLiturgia class are set to private, I assume that you are using a constructor and public getters. If you want that your iVisperas property not to hold any value then simply do not instantiate it in the constructor or create another constructor without it.

If I want to create iVisperas field only when it contains data, how I can manage that into the model class?

In that case, you should use a Map and update that document only when the value for your iVisperas property is available.

I think is a bad practice to keep empty fields (?).

There is no benefit in keeping empty fields as long as are not needed. Remember, every property count in that 1 MiB (1,048,576 bytes) maximum size for a document.
According to Suhas Ch's answer, please also note that a property of type String which is empty ("") and a property which holds null, occupy the same amount of space in a document.
Edit:
Another possible solution is to assign a default value, in this case, 0, right inside the model (MetaLiturgia) class.

A: While creating field, set the type for iVisperas as null

and in the model class
public class MetaLiturgia {
    private String fecha;
    private int tiempo;
    private String semana;
    private String mensaje;
    private String salterio;
    private int color;
    private String meta;
    private String titulo;
    private String iVisperas;

    private int weekDay;

    public MetaLiturgia() {
    }

    public String getTituloVisperas() {
        if (iVisperas.equals(null)){
            return titulo;
        }else{
            return iVisperas;
        }

    }
//...
}

A: When do you know if the field is empty?
You could delete attribute from your model class and create another class which inherits fro your model class.
There you can add the value. When it comes to saving the object, you wont write the field if its not used.
But I dont know if this is worth the effort, since you will have to create a newObject of the subclass once your attribute is used.


text:
Q: Four-part distributed Query issue from 2014 to 2008R2 From a SQL Server 2014 RTM in our DEV environement, I am executing this query using a SQL login.
select t.noshipid, y.nofolder
                        from distantserver.distantdatabase.dbo.sometable t (nolock)
                        inner join  somedatabase.dbo.sometable y (nolock)
                            on cast(t.nobill as bigint) = y.nobill
                        where t.type_payment = 'CE'
                        group by t.noshipid, y.nofolder

distantserver is in 2008 R2.
I get back an error

Msg 8522, Level 16, State 3, Line 1 Microsoft Distributed Transaction
  Coordinator (MS DTC) has stopped this transaction.

If I execute the same query on the production server which is 2008 R2, no errors.
1: The SQL login in question has the necessary access.
2: The provider being used to connect to the 2008 R2 server is SQLNCLI10
Questions:
1: Is it possible that upgrading the DEV server to 2014 is causing these issues?
2: Are there any know issues using a four-part identifier from 2014 to 2008 R2 ?
from distantserver.distantdatabase.dbo.sometable

instead of using openquery
FROM    OPENQUERY([distantserver],

because using OPENQUERY, the query does not return errors.
3: Are there any sp_configure options or linked server options I need to configure because of 2014?
Update 14:41
If I add
BEGIN DISTRIBUTED TRANSACTION

at the top, the distributed part works fine. I just want to emphasize the fact that before upgrading, this was not necessary.

A: Ideally, you should be using the SQLNCLI11 and not SQLNCLI10.  SQLNCLI11 since that connects back to SQL 2008R2/2008/2005 versions.
There is a known bug with SQLNCLI10 that is worth knowing (even though shows that there is a problem when connecting from SQL Server 2008R2 to 2000, but it shows that you are encountering it from SQL Server 2014 to 2008R2).
Also, since you are using linked servers - refer to : Which one is more efficient: select from linked server or insert into linked server?


text:
Q: Task.Factory.StarNew and ApplicationDbContext Update I need to update a table of my ApplicationDbContext within a Task; however, I'm not getting it done. Here is the error message I've got:

ex.Message = "Cannot access a disposed object. A common cause of this
  error is disposing a context that was resolved from dependency
  injection and then later trying to use the same context instance
  elsewhere in your application. This may occur if you are calling
  Dispose...

I understand it has something to do with threading which I'm not so familiar.
Here's the code:
  [HttpPost]
        public ActionResult WebHook([FromBody] BotRequest data)
        {

         Task.Factory.StartNew(() =>
                {

                //Read value from Table
                ContextWatsonFB contextWatsonFB = _context.ContextWatsonFB.Where(m => m.RecipientId == recipientid).FirstOrDefault();

                if (contextWatsonFB == null)
                {
                    contextWatsonFB = new ContextWatsonFB()
                    {
                        RecipientId = recipientid
                    };
                    _context.Add(contextWatsonFB);
                    _context.SaveChanges();

                }
                else
                {
                    if (!string.IsNullOrEmpty(contextWatsonFB.Context))
                    {
                        model = JsonConvert.DeserializeObject<Context>(contextWatsonFB.Context);
                    }

                }

                ///DO SOME STUFF ////////////////

                ///Here I need to update my table using some values processed above in "some stuff"

                ContextWatsonFB contextWatsonFB = _context.ContextWatsonFB.Where(m => m.RecipientId == recipientid).FirstOrDefault();

                contextWatsonFB.Context = JsonConvert.SerializeObject(context);
                _context.Update(contextWatsonFB);
                _context.SaveChanges();

                }
        }

As you can figure it out, its a webhook connection for Facebook, which requires the process to be handled in a Task. Within "some stuff", basically I'm consuming IBM Watson Conversation service whom persist a conversation "context" that I'm not able to send back and forth to Facebook, that's why I figure it out to persist such data in a table to keep the differences among multiple request from facebook messenger.

A: Luckily, the following code did the trick:
        private readonly IServiceProvider _provider;

        public FacebookBotController(ApplicationDbContext context, IServiceProvider provider)
        {
            _provider = provider;

}

  [HttpPost]
        public ActionResult WebHook([FromBody] BotRequest data)
        {

            if (data == null || data?.entry?.Count == 0)
            {
                return new StatusCodeResult(StatusCodes.Status204NoContent);
            }

            try
            {

                var task = Task.Factory.StartNew(async () =>
                {

                    using (IServiceScope scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        ApplicationDbContext _contx = _provider.GetService<ApplicationDbContext>();

                        ContextWatsonFB contextWatsonFB = await _contx.ContextWatsonFB.Where(m => m.SenderId == senderId).FirstOrDefaultAsync();

                        if (contextWatsonFB == null)
                        {
                            context = null;
                        }
                        else
                        {
                            context = JsonConvert.DeserializeObject<Context>(contextWatsonFB.Context);
                        }

                    }

}
}


text:
Q: MouseOver on asp.net webform I am working on a asp.net webform with labels and textboxes and would like to include help image next to label so that when i mouseover on the image it should bring the help description from the table in the database. Can someone help me how to achieve this.
Thanks

A: pls see this link :
http://api.jquery.com/category/selectors/
http://api.jquery.com/load/
$(".myDiv").live('keyup focus focusout change click mouseenter mouseover',function(){
         // Your command
})

A: There are allot of Jquery tooltip plugins, from the built in one to fancy looking stuff. Have you looked at any of these?
http://www.1stwebdesigner.com/css/stylish-jquery-tooltip-plugins-webdesign/


text:
Q: NSURLConnection response returns 500 Status Code I am trying to connect to a local node.js server setup and authenticate the user. I keep getting the 500 status code and can't figure out what I am missing.
I have tried hitting the server with these credentials from a web browser, and it works as expected.
Note: I do understand I have to use the NSURLSession instead of NSURLConnection, but for now, I need to get this to work.
Here is my code,
func signInUserWithDetails(userName:String,userPassword:String,serverURL:NSURL) {
    let credDic :[String:String]=["user[name]":userName,
                                   "user[password]":userPassword ]
    self.httpMethod="PUT"
    self.httpPath="/account"
    self.expectedStatusCode=201

    self.actualStatusCode=NSNotFound
    self.requestUniqueIdentifier = NSUUID().UUIDString

    let urlComponents = NSURLComponents(URL: serverURL, resolvingAgainstBaseURL: false)!
    urlComponents.path = httpPath
    let formedURL = urlComponents.URL!
    var requestOrg = NSMutableURLRequest(URL: formedURL)

    requestOrg.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    requestOrg.addValue("application/json", forHTTPHeaderField: "Accept")
    requestOrg.HTTPMethod=self.httpMethod!

    print(requestOrg.allHTTPHeaderFields) // Output 1

    do{
        let theJSONData = try NSJSONSerialization.dataWithJSONObject(credDic,options: NSJSONWritingOptions.PrettyPrinted)
        let theJSONText = NSString(data: theJSONData,encoding: NSASCIIStringEncoding)

        requestOrg.HTTPBody = theJSONData;

        let tempD=try NSJSONSerialization.JSONObjectWithData(requestOrg.HTTPBody!, options: []) as? [String:String]
        print("\(tempD)")  //Output 2

    }catch let error as NSError {
        print(error)
    }

   connection = NSURLConnection(request: requestOrg, delegate: self, startImmediately: true)!
}

And I am just printing out the response with this,
func connection(didReceiveResponse: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    print("----------------------didReceiveResponse")
    self.response=response
    print("Response Received:"+"\(self.response)")
    let urlResponse:NSHTTPURLResponse = response as! NSHTTPURLResponse
    let responseCode=urlResponse.statusCode
    self.actualStatusCode=responseCode
}

And the result I get is
Optional(["Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"])
Optional(["user[password]": "R", "user[name]": "R"])
----------------------didReceiveResponse
Response Received:Optional(<NSHTTPURLResponse: 0x7faba269d440> { URL:   http://localhost:3000/account } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 1464;
"Content-Type" = "application/json";
Date = "Sat, 26 Dec 2015 08:34:45 GMT";
"X-Powered-By" = Express;
} })

And the didReceiveData throws this error
{"error":{"message":"Cannot read property 'name' of undefined","stack":"TypeError: Cannot read property 'name' of undefined\n    at Object.exports.signIn [as handle] ( .......

A: Status code 500 means, that the server could not process your data and ran into an internal error. This oftentimes is caused by improperly encoded HTTP messages, where the server was unable to catch all possible errors.
When looking at your code, it becomes immediately apparent:
You are not sending a properly application/x-www-form-urlencoded encoded data to the server. This is likely the main cause of your problem. The other cause might be, that it's likely not a PUT but a POST method which is required to sign-in.
But before explaining how you encode your data properly, I would suggest to find out whether your server accepts JSON as content data (application/json). If so, properly encoding the data is much easier: having a JSON object (your variable credDic), simply convert it to JSON as UTF-8 in a NSData container. Then, get the length in bytes, set headers Content-Type and Content-Length accordingly.

A: I had a similar issue but after tried to include Content-Type using application/json, it was solved.
Example: request.addValue("application/json", forHTTPHeaderField: "Content-Type")

A: The client application gets an HTTP status code of 500 with the message "Internal Server Error" as a response for API calls. The 500 Internal Server error could be caused by an error during the execution of any policy within Edge or by an error on the target/backend server.
The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request. This error is usually returned by the server when no other error code is suitable


text:
Q: Why keyboard keys aren't aligned? I am training to become a touch typist and find out that some keys, like "c", ",", "y" are very tricky to reach because they stand in a difficult angle for fingers.
So, I think there would be so much easier to touch type if keyboard keys were aligned between rows.
Why they're not?

A: (This is an educated guess based on tinkering with typewriters when I was a kid)
Its generally accepted The QWERTY keyboard was laid out in such a way that keys likely to be pressed in quick succession were on different parts of the keyboard to reduce the likelihood of jamming.
I posit that the offset of keys is a similar artifact - that the keys needed to be offset so that each key (which was on an arm which struck a ribbon in a center point of the keyboard) could reach the center point.  The following picture (from Wikimedia, under CC license) shows the arrangement of keys and levers.

Note that some ergonomic keyboards have the kind of key alignment you are referring to, but superimposed on a curved base.


text:
Q: Check a box based on the current url There is a lot of similar questions, but I couldn't find a solution so here goes. I am making a custom wordpress theme, and I have an accordion in the sidebar that is a menu. The expanding of a list is triggered by a checkbox.

    <input id="ac-1" name="accordion-1" type="checkbox" />
    Menu category 1

List item 1

List item 2

List item 3

    <input id="ac-2" name="accordion-1" type="checkbox" />
    Menu category 2

List item 4

List item 5

List item 6

It all works well, even on mobile phones and tablets, but the problem is that whenever a visitor changes a page, any checked option will be cleared. What I wish to achieve is the following: If a user is on list item #1 page, the parent checkbox would be checked (in this case, Menu category 1 would be expanded on page load), since the page belongs to that category. I need a way to check a certain box based on the current url. I found an option to cache the sidebar with AJAX but that really does not work for me, because if all the items were expanded on a previous page, they would remain the same on a new page, and I want only the relevant parent to be expanded. Also, the cache thing looks like an overkill. I found a php shortcode to preserve the marks on refresh,
<?php if($_POST['check'] == 'checked'): ?>checked="checked"<?php endif; ?>

but that doesn't work on url change, only refresh.
Bare in mind that I use a php menu shortcode for WP, and not static ul li as shown in this question. I'm developing locally so I can't provide a link

A: Not necessarily an answer but a workable solution. I've used jQuery as I've assumed you are probably using it, as most accordions these days are built with jQuery plugins.
You could add hashes to the URL that correspond to the checkbox ID:

    <input id="ac-1" name="accordion-1" type="checkbox" />
    Menu category 1

List item 1

List item 2

List item 3

Grab the hash from the URL, find the corresponding checkbox with the same ID and trigger a click and check it:
$(document).ready(function() {
    var hash = window.location.hash; // for example ac-1
    if (hash) {
        $('#'+hash).prop('checked', true).triggerHandler('click');
    }
});

Check this JSFIDDLE demo. I made a basic accordion menu and faked a URL hash to make it work.
UPDATED QUESTION
As requested, it's pretty simple doing it for the URL. Try this:
$(document).ready(function() {
    // get url
    var url = $(location).attr('href');
    // get part of url after last slash
    var accordionID = url.substr(url.lastIndexOf("/")+1);
    // trigger a click on checkbox representing that accordion li
    $('a[href="'+accordionID+'"]').closest('div').find(':checkbox')
        .prop('checked',true).triggerHandler('click');
});

See the demo here.


text:
Q: Adding an offset to a pointer If I have a pointer to an object and I want to get a pointer to an object that is say 16 bytes after the pointer how do I add the 16 byte offset to the pointer?
Also, memory addresses in 32bit systems look like this 0x00000000. If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped?

A:
If I have a pointer to an object and I want to get a pointer to an object that is say 16 bytes after the pointer how do I add the 16 byte offset to the pointer?

Casting through char* will work, but this may be considered bad practice depending on the details of your scenario:
T *ptr = initialize_ptr(); // Do whatever initialization you need to.

ptr = (T*)(((char*)ptr) + 16);

Also, memory addresses in 32bit systems look like this 0x00000000. If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped?

The difference between 2 and 1 is 1 -- exactly one byte would be skipped.

A: Pointers count bytes, so to point at the next byte you would need to change a pointer's value by 1. Pointer arithmetic, however, counts the objects pointed to by the pointer, and incrementing a pointer increases its value by the size of its pointee type. If you want to point at bytes, use a char pointer, since char has size 1 by definition, and pointer arithmetic on char pointers is lets you point at bytes:
T * p  = get_pointer();

char * cp = reinterpret_cast<char*>(p);

cp += 16;

Casting pointers to and from char types does not constitute type punning and is explicitly allowed by the standard. However, you must not use the resulting pointer to access any objects that aren't actually at that address.

A: You would do this :
char *arr = (char*)((void*) ptrToSomeObject);
&arr[15]

Whats happening under the hood

*

*Any ptr can be converted to 'void*'

*'void *' can be converted to any type of ptr.

*arr[15]  ==    (arr+15bytes)


text:
Q: Procedure or function has too many arguments specified in FormView and SQL SERVER c# I have one stored procedure called VideoGalleryDelete . I am using FormView and Gridview to insert, update, show and delete data. VideoGallery is my primary table with PK VideoId and it has a foreign key as CategoryId .
When i click Delete linkButton, its says Procedure or function has too many arguments specified
This is my SP :
ALTER PROCEDURE [dbo].[VideoGalleryDelete]
@VideoId int
AS
BEGIN

DELETE FROM [dbo].[VideoGallery]
      WHERE VideoId = @VideoId
      END

GridView and its assigned SqlDataSource :
<asp:GridView ID="gvVideo" CssClass="table" runat="server" OnSelectedIndexChanged="gvVideo_SelectedIndexChanged" AutoGenerateColumns="False" DataKeyNames="VideoId,CategoryId" DataSourceID="sdVideoList">
    <Columns>
        <asp:BoundField DataField="VideoId" Visible="false" HeaderText="VideoId" InsertVisible="False" ReadOnly="True" SortExpression="VideoId" />
        <asp:BoundField DataField="VideoLink" HeaderText="Video Link" SortExpression="VideoLink" />
        <asp:BoundField DataField="CategoryId" HeaderText="Category Id" SortExpression="CategoryId" />
        <asp:TemplateField ItemStyle-CssClass="Center" HeaderStyle-Width="15%">
            <ItemTemplate>
                <asp:ImageButton ImageUrl="~/images/edit.png" ID="lnkedit" Style="margin-left: 15px" CommandName="Select" runat="server" Width="20px"></asp:ImageButton>
                <asp:ImageButton ImageUrl="~/images/delete.png" ID="lnkDelete" CommandName="Delete" Style="margin-left: 15px" runat="server" Width="20px" OnClientClick="return ConfirmDelete();"></asp:ImageButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:SqlDataSource ID="sdVideoList" runat="server" ConnectionString="<%$ ConnectionStrings:WebAAERT_DBConnectionString %>" DeleteCommand="VideoGalleryDelete" DeleteCommandType="StoredProcedure" SelectCommand="VideoGallerySelect" SelectCommandType="StoredProcedure">
    <DeleteParameters>
        <asp:Parameter Name="VideoId" Type="Int32" />
    </DeleteParameters>
    <SelectParameters>
        <asp:Parameter DefaultValue="0" Name="CategoryId" Type="Int32" />
    </SelectParameters>

A: I think you're misusing the DataKeyNames property of the grid view control.This property should ideally contain only the primary key field(s) to identify the current row.Also every single value set on this property will be passed through to the Delete command.
Your delete stored proc takes one parameter but two values are being passed through beacuase of DataKeyNames="VideoId,CategoryId".So you can do what @Chris Flynn suggested or change your grid view to DataKeyNames="VideoId"


text:
Q: migrating infopath forms using sharegate not working - SharePoint Online I'm doing some migration of list(customised infopath form) using sharegate but when i go and try and open the form after migration the form opens up using the out of the box form and not infopath.
The correct site features and site collection features have been activated.
Has anyone faced any similar issue?
Thanks in Advance

A: After migration, you need to re-publish the form into your list.
Try to re-publish the form and then check the results.
Note: InfoPath forms are currently not supported on Modern experience list on Office 365, it can only work in classic experience list.


text:
Q: Why this code of capturing picture from a device don't run properly? I was just trying to write a code to capture an image and save that image in default directory with a name test.jpg. My device do capture the image but it runs the else part of the test case and shows error capturing image.In xml file there is only a button and android:onClick is set to process
public class MainActivity extends Activity {
private File imagefile;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void process(View v)
{
    Toast.makeText(this,"Inside the process",Toast.LENGTH_SHORT).show();
    Intent  intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    imagefile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test.jpg");
    Uri temp = Uri.fromFile(imagefile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,temp);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
    startActivityForResult(intent,0);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode==0)
    {
        switch (resultCode){
            case Activity.RESULT_OK:
                if(imagefile.exists())
                {
                    Toast.makeText(this,"File was saved at "+imagefile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this,"Error captureing image",Toast.LENGTH_SHORT).show();
                }
                break;
            case Activity.RESULT_CANCELED:
                break;
        }
    }
}
}

A: 1.Use checkSelfPermission
2.Use requestPermissions
3.Use onRequestPermissionsResult

*

*If permission is granted , you can do something you want ,else you should do requestPermissions in your code .

*If you request permissions,you can deal with result in onRequestPermissionsResult method .And if permissions granted , you can do something you want ,else deal with that permission Denied .
Try this .
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 0;

// process in your code
public void process(View view) {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                MY_PERMISSIONS_REQUEST_CAMERA);
    } else {
        // permission_granted
        callMethod();
    }
}

/**
 * do something you want
 */
public void callMethod() {
    Toast.makeText(this, "Inside the process", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    imagefile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test.jpg");
    Uri temp = Uri.fromFile(imagefile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, temp);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    startActivityForResult(intent, 0);
}

/**
 * onRequestPermissionsResult
 *
 * @param requestCode
 * @param permissions
 * @param grantResults
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted
            callMethod();
        } else {
            // Permission Denied
            Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}


text:
Q: Reference Parent property I have a form that in certain situations doesn't have a parent.
Then it fails to open.
So I wrap it in an 'if'
It still fails to open.
Private Sub Form_Open(Cancel As Integer)
    If Not Parent Is Nothing Then  << Error
        Me!Button1.Enabled = Not (Nz(Parent!Lock, 0))
        Me!Button2.Enabled = Not (Nz(Parent!Lock, 0))
    End If
End Sub

gives "Run-time error '2452': The expression you entered has an invalid reference to the Parent property."
But if I declare the variable, then the original code won't work.

A: This is a tricky one, as if the form has no parent, any access to the property (even testing if it's empty) will trigger an error.
The easiest workaround is testing using error trapping:
Public Function HasParent(obj As Object) As Boolean
    On Error GoTo ExitFunction
    If Not obj.Parent Is Nothing Then
        HasParent = True
    End If
ExitFunction:
End Function

Private Sub Form_Open(Cancel As Integer)
    If HasParent(Me) Then
        Me!Button1.Enabled = Not (Nz(Parent!Lock, 0))
        Me!Button2.Enabled = Not (Nz(Parent!Lock, 0))
    End If
End Sub


text:
Q: SSL handshake problem: server resets connection after "server hello done" So, I'm having a problem establishing a ssl handshake in python. After analyzing the captured packets in wireshark, I've detected that the server (in this example I'm trying to connect to https://www.google.com) just sends a FIN/ACK packet after the "Server Hello Done", not waiting for the client's response which comes after that, and then the connection ends with a hard RST from the server side.
Any ideas on why this could be happening? I've for example checked the cyphers sent in the "Client Hello" and "Server Hello" and they match correctly. What else could be going wrong in the handshake?
Additional notes: The original client request is a python request get with a field proxies, which is redirected and handled by a "super proxy". A connection is established between these two. Then, the "super proxy" sends the data received from the client, through a websocket, to a "proxyClient", which then sends the data to the server requested, and then collects the response, sending it to the "superProxy", which then sends it to the client. So this is the components involved in this handshake, which include several "redirections" of data between components.
Wireshark printscreen:
wireshark_printscreen