text:
Q: Efficiently remove first element in SortedSet I've got a SortedSet to which I'm adding items to (in an uncontrolled order, obviously making use of it's sorting abilities).
Items in the set are always used and removed in order, one at a time.
set.Min.Process();
set.Remove(set.Min);

The problem I'm facing however, is due to the O(log n) aspect of the Remove method, and the binary search nature of a SortedSet, this results in the maximum possible number of comparisons being made for each remove (~log n).
To me it seems weird that a collection based around accessing the min and max items wouldn't have an efficient way to remove them.
Effectively what I'm after is a set.RemoveMin() method, making use of the more optimized approach (comparison free) to get the first element.
Is there any way to do this?
Are there any existing alternative SortedSet implementations out there I could utilize?

A: [EDIT] I instrumented this and it doesn't seem faster than just using SortedSet, so this may not be a good answer!
@randomman159 - If this doesn't help after you've tried it out, please comment to this answer and I will delete it.

What you are describing is a Priority Queue.
Here's a basic implementation using a heap.
Its complexity is O(LogN) for both Enqueue() and Dequeue():
/// Priority Queue data structure.
/// <remarks>
/// Implemented in traditional fashion, using a heap.
/// Based on code from http://www.vcskicks.com/priority-queue.php
///
/// Also see http://en.wikipedia.org/wiki/Heap_(data_structure)
/// and http://en.wikipedia.org/wiki/Priority_queue
/// </remarks>

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]

public sealed class PriorityQueue<T>
{
    /// Constructor.
    /// <param name="comparer">A comparison function for items of type T>.</param>

    public PriorityQueue(Comparison<T> comparer)
    {
        _comparer = comparer;
        _heap = new List<T> {default(T)};
    }

    /// The number of items in the queue.

    public int Count => _heap.Count - 1;

    ///
    /// Returns the value at the head of the Priority Queue without removing it.
    /// Throws an exception if the queue is empty.
    ///

    public T Peek()
    {
        if (this.Count > 0)
        {
            return _heap[1]; // Head of the queue is at [1], not [0].
        }
        else
        {
            throw new InvalidOperationException("Attempt to Peek() into an empty PriorityQueue<T>");
        }
    }

    /// Adds a value to the Priority Queue

    public void Enqueue(T value)
    {
        _heap.Add(value);
        this.bubbleUp(_heap.Count - 1); // Bubble up to preserve the heap property, starting at the inserted value.
    }

    /// Returns the front of the Priority Queue.

    public T Dequeue()
    {
        if (this.Count > 0)
        {
            T minValue = this._heap[1]; // The smallest value in the Priority Queue is the first item in the array

            if (this._heap.Count > 2) // If there's more than one item, replace the first item in the array with the last one.
            {
                T lastValue = this._heap[_heap.Count - 1];

                this._heap.RemoveAt(_heap.Count - 1);       // Move last node to the head
                this._heap[1] = lastValue;
                this.bubbleDown(1);
            }
            else  // Only one item in the queue.
            {
                _heap.RemoveAt(1);  // Remove the only value stored in the queue.
            }

            return minValue;
        }
        else
        {
            throw new InvalidOperationException("Attempt to Dequeue() from an empty PriorityQueue<T>");
        }
    }

    /// Restores the heap-order property between child and parent values going up towards the head.

    private void bubbleUp(int startCell)
    {
        // Requires(startCell >= 0);
        // Requires(startCell < _heap.Count);

        int cell = startCell;

        while (this.isParentBigger(cell))   // Bubble up as long as the parent is greater.
        {
            // Get values of parent and child.

            T parentValue = this._heap[cell/2];
            T childValue  = this._heap[cell];

            // Swap the values.

            this._heap[cell/2] = childValue;
            this._heap[cell]   = parentValue;

            cell /= 2; // Go up parents.
        }
    }

    /// Restores the heap-order property between child and parent values going down towards the bottom.

    private void bubbleDown(int startCell)
    {
        // Requires(startCell > 0);
        // Requires(startCell < _heap.Count);

        int cell = startCell;

        // Bubble down as long as either child is smaller.

        while (this.isLeftChildSmaller(cell) || this.isRightChildSmaller(cell))
        {
            int child = this.compareChild(cell);

            if (child == -1) // Left Child.
            {
                // Swap values.

                T parentValue    = _heap[cell];
                T leftChildValue = _heap[2*cell];

                _heap[cell]   = leftChildValue;
                _heap[2*cell] = parentValue;

                cell = 2*cell; // Move down to left child.
            }
            else if (child == 1) // Right Child.
            {
                // Swap values.

                T parentValue     = _heap[cell];
                T rightChildValue = _heap[2*cell+1];

                _heap[cell]     = rightChildValue;
                _heap[2*cell+1] = parentValue;

                cell = 2*cell+1; // Move down to right child.
            }
        }
    }

    /// Is the value of a parent greater than its child?

    private bool isParentBigger(int childCell)
    {
        // Requires(childCell >= 0);
        // Requires(childCell < _heap.Count);

        if (childCell == 1)
        {
            return false;  // Top of heap, no parent.
        }
        else
        {
            return _comparer(_heap[childCell/2], _heap[childCell]) > 0;
        }
    }

    ///
    /// Returns whether the left child cell is smaller than the parent cell.
    /// Returns false if a left child does not exist.
    ///

    private bool isLeftChildSmaller(int parentCell)
    {
        // Requires(parentCell >= 0);
        // Requires(parentCell < _heap.Count);

        if (2*parentCell >= _heap.Count)
        {
            return false; // Out of bounds.
        }
        else
        {
            return _comparer(_heap[2*parentCell], _heap[parentCell]) < 0;
        }
    }

    ///
    /// Returns whether the right child cell is smaller than the parent cell.
    /// Returns false if a right child does not exist.
    ///

    private bool isRightChildSmaller(int parentCell)
    {
        // Requires(parentCell >= 0);
        // Requires(parentCell < _heap.Count);

        if (2 * parentCell + 1 >= _heap.Count)
        {
            return false; // Out of bounds.
        }
        else
        {
            return _comparer(_heap[2*parentCell+1], _heap[parentCell]) < 0;
        }
    }

    ///
    /// Compares the children cells of a parent cell. -1 indicates the left child is the smaller of the two,
    /// 1 indicates the right child is the smaller of the two, 0 inidicates that neither child is smaller than the parent.
    ///

    private int compareChild(int parentCell)
    {
        // Requires(parentCell >= 0);
        // Requires(parentCell < _heap.Count);

        bool leftChildSmaller  = this.isLeftChildSmaller(parentCell);
        bool rightChildSmaller = this.isRightChildSmaller(parentCell);

        if (leftChildSmaller || rightChildSmaller)
        {
            if (leftChildSmaller && rightChildSmaller)
            {
                // Figure out which of the two is smaller.

                int leftChild  = 2 * parentCell;
                int rightChild = 2 * parentCell + 1;

                T leftValue  = this._heap[leftChild];
                T rightValue = this._heap[rightChild];

                // Compare the values of the children.

                if (_comparer(leftValue, rightValue) <= 0)
                {
                    return -1; // Left child is smaller.
                }
                else
                {
                    return 1; // Right child is smaller.
                }
            }
            else if (leftChildSmaller)
            {
                return -1; // Left child is smaller.
            }
            else
            {
                return 1; // Right child smaller.
            }
        }
        else
        {
            return 0; // Both children are bigger or don't exist.
        }
    }

    private readonly List<T>       _heap;
    private readonly Comparison<T> _comparer;
}

Add your elements using Enqueue() and remove the front elements by using Dequeue().
Also see here for another implementation: https://visualstudiomagazine.com/Articles/2012/11/01/Priority-Queues-with-C.aspx?Page=1


text:
Q: ios5 passing data from calloutAccessoryControlTapped to another controller I am trying to send a nsmutablearray from one navigational embedded view controller to another viewcontroller after this method
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{NSLog(@"tapped %@ %d",view.annotation.title,[res count]);
    gpDetailViewController *gpDetailView = [[gpDetailViewController alloc] init];
    gpDetailView.title = @"Details";
    gpDetailView.detailArray = res;
         [self.navigationController pushViewController:gpDetailView animated:YES];

}

is executed.
Here is the interface and implementation files for gpDetailViewController.
//
//  gpDetailViewController.h
//  livewell prototype
//
//  Created by MyOxygen Mobile on 02/05/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface gpDetailViewController : UIViewController{
    NSMutableArray *detailArray;
}
@property (nonatomic,retain) NSMutableArray *detailArray;

@end

and gpDetailViewController.m
//
//  gpDetailViewController.m
//  livewell prototype
//
//  Created by MyOxygen Mobile on 02/05/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "gpDetailViewController.h"

@interface gpDetailViewController ()

@end

@implementation gpDetailViewController
@synthesize detailArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    detailArray = [[NSMutableArray alloc]init];

    NSLog(@"%@",[self.detailArray count]);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

I am getting a null value when i am trying to print the array elements size.
What could be the reason?

A: Instead of
NSLog(@"%@",[self.detailArray count]);

try this
NSLog(@"%d",[self.detailArray count]);

count is an integer, not a class

redpajama_set_name: RedPajamaStackExchange


text:
Q: CORS JQUERY como solucionar? tengo el problema de que estoy desarrollando un consumo de web service para una pagina, el web service me lo esta proporsionando una entidad, de las que solo te dice aqui esta la URL mira tu como le haces, al inicio consumi con Java pero el proceso es muy lento, luego consumi con Jquery mucho mas rapido solo que este me da problemas de CORS, los msj que recibo son
Access to XMLHttpRequest at 'https://dominiodelainstitucion' from origin 'https://midominio' has been blocked by CORS policy: Cannot parse Access-Control-Allow-Methods response header field in preflight response.
jquery-3.6.0.min.js:2          POST https://farm3.sat.gob.gt/retencion-liberacion-ws/rest/privado/retencionLiberacion/consultar net::ERR_FAILED
y por el momento este es mi codigo que lo genera POSTMAN
var settings = {
                "url": "https://farm3.sat.gob.gt/retencion-liberacion-ws/rest/privado/retencionLiberacion/consultar",
                "method": "POST",
                "timeout": 0,
                "headers": {
                    "Authorization": "Basic MzEkjhlkjhkj5hYzIwMTUr",
                    "Content-Type": "application/json",
                    "Cookie": "visid_incap_2112329=0xk+tVssSjegRxb6moVvoquKumAAAAAAQUIPAAAAAABebEr5ELkke+K1Kp+CTHG/"
                },
                "data": JSON.stringify({
                    "noContenedor": "TCNU1601505"
                }),
            };

            $.ajax(settings).done(function (response) {
                console.log(response);
            });

quiero destacar que no tengo acceso al servidor donde se aloja este web services, yo estoy tratando de consumirlo de postman funciona bien pero ya al subirlo a la pagina es donde muestra los errores


text:
Q: Jersey: list of JSON objects I am trying to retrieve in my Jersey implementation resource class post collection of objects like this:
@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(ArrayList<AnyEmail> email) {
    //emailManager.sendEmail(email);
    return "success";
}

I have the @XmlRootElement above `AnyEmail.
However when I post like this with REST client tool:
 emails : [
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"}
      ]

I get:
<title>Apache Tomcat/7.0.22 - Error report</title>
HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception
javax.servlet.ServletException: Servlet execution threw an exception

root cause
java.lang.Error: Error: could not match input
    com.sun.jersey.json.impl.reader.JsonLexer.zzScanError(JsonLexer.java:491)
    com.sun.jersey.json.impl.reader.JsonLexer.yylex(JsonLexer.java:736)

EDITED
Now I tried:
 "emails" : [
           {"body": "Testing the web service", "header": "Hi", "footer": "
test"},
           {"body": "Testing the web service", "header": "Hi", "footer": "
test"}
          ]

and I get:
    SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/API] threw exception
java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:324)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.valueRead(JsonXmlStreamReader.java:165)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.readNext(JsonXmlStreamReader.java:330)

A: Why you don't use a simple Java array???
[
   {"body": "Testing the web service", "header": "Hi", "footer": "
test"},
   {"body": "Testing the web service", "header": "Hi", "footer": "
test"}
]

And then the following method:
@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(AnyEmail[] emails) {
    //emailManager.sendEmail(emails);
    return "success";
}

That should do the trick...

A: This is what should work:
{
"anyEmail" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"}
       ]
}

Also, you may want to use the POJO approach, which is the preferred one for JSON - see here: https://jersey.java.net/documentation/1.18/json.html
The JSON support based on JAXB has various issues with some edge cases, since there isn't a 1:1 mapping between XML (JAXB as designed for) and JSON.

A: I'm neither a Jersey nor Json expert, but did you try using a full JSON object, ie :
{
"emails" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "
test"}
      ]
}

(added braces, and quotes to emails).

A: I had the same problem. You have to wrap the AnyEmail class.
This can help you: https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one

A: // Client
package com.project.rest.model;

import java.util.HashSet;
import java.util.Set;

public class Client {

    private Long id;
    private String email;
    private String lang;

    public Client() {
    }

    public Client(Long id) {
    this.id = id;
    }

    public Client(Long id, String email, String lang) {
    this.id = id;
    this.email = email;
    this.lang = lang;
    }

    public Long getId() {
    return id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getLang() {
    return lang;
    }

    public void setLang(String lang) {
    this.lang = lang;
    }

    @Override
    public String toString() {
    return "Client [id=" + id + ", email=" + email + ", lang=" + lang + "]";
    }

}

//ClientService
package com.project.rest;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.project.rest.model.Client;

@Path("/client")
public class ClientService {

    @POST
    @Path("/sendList")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response consumeJSONList(List<Client> clientList) {

        String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";

        return Response.status(200).entity(output).build();
    }

}

//JerseyClient
package com.project.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;

import com.project.rest.model.Client;
import com.project.rest.model.Device;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

public static void main(String[] args) {

try {

    List<Client> clientList = new ArrayList<Client>();
    clientList.add(new Client(1L, "pruebas@pruebas.com", "es"));
    clientList.add(new Client(2L, "pruebas@pruebas.com", "es"));
    clientList.add(new Client(3L, "pruebas@pruebas.com", "es"));

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    com.sun.jersey.api.client.Client c = com.sun.jersey.api.client.Client.create(clientConfig);

    WebResource webResource = c.resource("http://localhost:8080/project_rest/rest/client/sendList");

    ClientResponse response = webResource.accept("application/json").type("application/json").post(ClientResponse.class, clientList);

    if (response.getStatus() != 200) {
    throw new RuntimeException("Failed sendClientList: HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);

    System.out.println("sendClientList... Server response .... \n");
    System.out.println(output);

} catch (Exception e) {

    e.printStackTrace();

}
}
}

//POM.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.10-b01</version>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
  <groupId>com.owlike</groupId>
  <artifactId>genson</artifactId>
  <version>0.99</version>
</dependency>

A: I am using Jersey 1.17 and can receive list of JSON objects with the following signature and cast them into list of my POJO Objects with Google's gson library, without any issue. Using wrapper to wrap list of POJO objects, is certainly un-natural and not favourable.
   @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({"application/x-javascript", MediaType.APPLICATION_JSON})
public Response doSomething(@Context HttpServletRequest httpServletRequest, JSONArray listOfJSONObjects) {
    Gson gson = new GsonBuilder().create();
    List < MYPOJOClass > myPojoObjectList = gson.fromJson(listOfJSONObjects.toString(), new TypeToken < List < MYPOJOClass >> () {}.getType());


text:
Q: REST APIs and Unity3D: How could the server tell between a legitimate request sent by an official Unity build from some malicious cURL? --LONG VERSION--
I made a super basic REST API to handle user account management (account creation, checking login credentials, etc.) that I will call from a Unity3D game, for which I plan to support mobile (mainly android).
Players would upload drawings that they'd make with a drawing tool that exists inside of the Unity game. I made that tool for the sole purpose of preventing the possibility of someone either uploading a screenshot of a drawing that they didn't draw themselves, or someone uploading a selfie or a pornographic photo (for which I cannot allow the possibility to happen, since my game is primarily targeted to children), and those drawings can be publicly viewed by other players.
--SHORT VERSION--
To store an uploaded drawing I would use a simple $_GET['base64'], but in order to prevent disallowed images from coming in, how can I assure that the request is coming from an official android build and not, say, some cURL or a reverse-engineered Unity project?
That's the whole question.
In the case of a WebGL build I could just block any web request that is not coming from the domain that the WebGL build is in, but in the case of the android build however, as far as I know the server can't really tell a request sent by an official android build from some request sent by a cURL. And I'm pretty sure that someone, with a bit of effort, can figure out how my REST API works. I have no idea of how to effectively secure it.
I'd like some suggestions, and if you think that my current approach is terrible (and it probably is) tell me how to improve on it or what to replace it with.

A: If you are serious about preventing unauthorized clients from sending images to your server the easiest way is to forget about dealing with images entirely.
Instead, I would have the clients and servers work with input data.

*

*Have the client record the inputs the user makes to create their drawing (or, if that is too much, something that approximates the outcome of their inputs, such as sequences of line segments, colors, stroke widths, sticker ids, whatever your drawing system uses). As they draw the image, replace what they just drew with your system's representation of it so they can be certain of its appearance before sending.

*Send, receive, and store the input data as needed

*When the appearance of the drawing is needed, play back the recording to reproduce the drawing.
This is essentially how Jackbox does their drawing games, for instance.
Using this method, someone could try to reproduce a vague depiction of a selfie or pornography with your API of input data BUT if you do things like limit the size of the data, limit the fidelity of the colors, limit the resolution of the start and end of the line segments, etc, the capacity for these things to be reproduced is further and further reduced until it becomes unfeasible.


text:
Q: 2x different size mirrors using ZFS I currently have a 4 uneven drive unRAID box. I'd like to migrate to Ubuntu and ZFS, but not quite sure what is possible with ZFS.  I'd like to buy 2x 6TB drives, to use in a mirrored configuration. Then once I've moved my data I'd like to add in 2 of the old 3TB drives as another mirror.
1) Is the following setup possible:
d1: 6TB
d2: 6TB mirror of d1
d3: 3TB
d4: 3TB mirror of d3

2) When drives drop in price, is it easy to replace d3 and d4 with larger drives?

A: Yes, this is possible. If you read a little on ZFS, you'll find that it's basically a pool of so-called "vdev"s. The simplest vdev would be a plain physical drive. It could also be a mirror consisting of two or more physical drives. This is what you want.
You'd go for this structure:
d1    d2  d3    d4
 \    /    \    /
 mirror    mirror
      \    /
      mypool

To create this zpool, use the following command:
zpool create mypool mirror d1 d2 mirror d3 d4

This will result in a usable capacity of 9 TB. It can tolerate one drive failure per mirror vdev. (Unless you add more mirrors, of course.)
If you want to add vdevs later, use this command:
zpool add mypool mirror d3 d4

To extend the pool size, first enable the autoexpand option:
zpool set autoexpand=on mypool

Then replace one of d3/d4 with a larger drive and wait for it to rebuild. After that, replace the other. The pool should automatically expand to the available drive size.
It might be desirable to turn off autoexpand after the job is done.
Alternatively, you can leave autoexpand alone and use the following commands after you replace both drives:
zpool online -e mypool d3
zpool online -e mypool d4


text:
Q: Substitute factor by ratio in maxima expression I have this expression in maxima:
a^2/sqrt((a*cos(φ))^2+(b*sin(φ))^2)

Can I have maxima rewrite it in terms of a factor times a/b?

A: v:a^2/sqrt((a*cos(φ))^2+(b*sin(φ))^2);

sqrt(trigsimp(ratsubst(k,a/b,v)^2));


text:
Q: Scalable way to stack in CSS I hope everyone will have heard about Sticky Notes. I wanna stack stuff like that. So this is the approach I have till now. I am not sure how to make it scalable for any number of stickies, without using JavaScript.

* {
  font-family: 'Segoe UI';
}
.stickynote {
  position: absolute;
  background: #fc0;
  border: 1px solid #f90;
  border-radius: 5px;
  padding: 10px;
  width: 75px;
  top: 10px;
  left: 10px;
}
.stickynote + .stickynote {
  top: 20px;
  left: 20px;
}

.stickynote + .stickynote + .stickynote {
  top: 30px;
  left: 30px;
}

 Sticky!!!

 Sticky!!!

 Sticky!!!

Problem:

*

*I cannot keep on adding .stickynote + .stickynote + .stickynote for all.

*Is the approach (HTML Structure) correct?

*It is not a good idea to nest them, as they will not be semantically correct. If that was possible, I would have used nested
 and
, but I want all those stickies be siblings.

*Every sticky note has variable heights and may be fixed width. Please don't hardcode the height.

Note: I am ready to provide as much as information. I don't see why this question gets close votes!

A: You can make your elements float and give them a negative margin for the desired effect. The
Floating box
 is to make every annotation skip a line. The visibility is set to hidden so that the element still affects the layout.

Floating box1

Floating box

Floating box2

Floating box

Floating box3

Floating box

Floating box4

CSS:
.floating-box1 {
    float: left;
    width: 150px;
    height: 75px;
    margin: 10px;
    background: #fc0;
    border: 1px solid #f90;
    border-radius: 5px;
    padding: 10px;
}
.floating-box {
    background: #fc0;
    border: 1px solid #f90;
    border-radius: 5px;
    padding: 10px;
    float: left;
    width: 150px;
    height: 75px;
    margin: 10px;
    margin-left:-160px;
}
.nofloat{
    visibility:hidden;
}

jsfiddle for example : http://jsfiddle.net/1nu02a37/

A: This is a really interesting question. I think I'm going to look at it semantically rather than practically at the code.
I understand why you don't want to nest them, and at first thought it seems semantically wrong to do so. But I think that's where you're making a mistake.
Think about a physical stack of sticky notes. Are they beside each other, or have they been combined into another distinct "thing"?
Semantically, they are a stack. You could look at it and say this is a clear physical representation of a list, with the ul being the stack and the li being the notes. This makes perfect semantic sense.
You could also say that the physical placement of each note depends on the physical placement of the one before it. You are physically nesting related notes on each other (they just stick out on the right and bottom) but the organization of each consecutive note depends on the one before it. Some might say this is a design thing and not semantic, but why are you stacking the notes if they're not semantically related to begin with? This means that nesting them can also make perfect sense semantically.
To have them side by side in your code but represented as not side by side to the user actually seems semantically meaningless to me. Unless you have a parent container to represent the stack. Which means you're essentially just using other elements to represent ul/li.

A: A touch of JavaScript can do the trick.

var arrStickyNotes = document.querySelectorAll('.stickynote');
var pos = 0;
for (i = 0; i < arrStickyNotes.length; i++) {
    arrStickyNotes[i].style.top = pos + 'px';
    arrStickyNotes[i].style.left = pos + 'px';
    pos += 10;
}
.stickynote {
    background: #fc0;
    border: 1px solid #f90;
    border-radius: 5px;
    padding: 10px;
    width: 75px;
    position:absolute;
}
.container {
    position:relative;
}

Sticky!!!

Sticky!!!

Sticky!!!

A: EDIT: I did it :). Using transform rotate from the top left on the notes, then reversing the rotation from top left of the parent div. XD
You can change the degrees as long as the parent is negative the same degrees for different offset degrees...
I have eaten my own words saying you can't do it without programming...

I don't know how to overline the rest of the answer, this is the old answer.

The best I could come up with.
Uses pseudo before and after.
Before creates a "bar" the width of the left offset and set height. So if after has more than 200px of height, it falls back to home left.
After is the part that shows the sticky note.
If anyone can figure out how to move this into the element itself, without being in pseudo using the title attribute, then we win! Otherwise that's the closest you can get without creating extra elements. It's about as semantic as sticky notes get too. Very intriguing question!
HTML

CSS
.note:before {
  content: '';
  width: 20px;
  height: 200px;
  float: left;
}
.note:after {
  content: attr(title);
  width: 200px;
  min-height: 200px;
  padding: 10px;
  background: khaki;
  box-shadow: 1px 2px 7px rgba(0,0,0,.3);
  border: khaki 1px outset;
  display: inline-block;
  margin: 10px 0 -190px 0;
}

A: If you're not going to nest them, I don't believe there is a very viable way to do this in a truly scalable fashion. Negative margins will work vertically, but you'll always need an incremental value if you want the notes to extend towards the right.
You can do this with a preprocessor, if you enjoy 4000 lines of source code just for your 1k stack. Trivial, really, but that's still a hard limit.
Sass - DEMO
I would post the output in a snippet, but SO yelled at me.

Body is limited to 30000 characters; you entered 79511.

@mixin notes($m, $n: 10) {
  @for $i from 1 through $n {
    &:nth-child(#{$i}) {
      @each $k, $v in $m {
        #{$k}: $v * $i;
      }
    }
  }
}

* {
  font-family: 'Segoe UI';
}
.stickynote {
  position: absolute;
  background: #fc0;
  border: 1px solid #f90;
  border-radius: 5px;
  padding: 10px;
  width: 75px;
  top: 10px;
  left: 10px;

  @include notes((top: 10px, left: 10px), 1000);
}

CSS is a pretty non-scalable language when it comes to certain repetitive tasks.
I also agree with Syntax Error about the semantics of this.
Realistically, I'm not sure why you would need a scalable CSS solution for markup that obviously has to be generated. There's no way you're manually writing in hundreds of .stickynote elements. Whatever is generating the markup could generate the styles as well.


text:
Q: PostgreSQL concurrency control and Serializable transactions Im building an application that needs to do some concurrent read/write operations on specific tables. Even after reading the official documentation (and many, many articles), the trouble persists, no one talk about the problem I have (and I think it's VERY common)
My DB:

*

*Table accounts with a boolean column called disabled (the other columns can be ignored)

*Table request, that represents some relation between 2 accounts. An account can "request" some action to another account.
The issue:

*

*Accounts cannot request actions to disabled accounts. It is a business rule, so I don't want to put any logic related to this in the database (using triggers/constraints). The database should only guarantee things related with the data (FK's, unique indexes, etc)

Since the database will not handle this business rule, my application will. To do it, every time a new request is issued, the following steps happen:

*

*Open a transaction

*Read target account disabled value
// Concurrency issues happens here
// What happens if the target account update it's disabled value here?

*If the target account is not disabled, create a new "request" row

Do you see the concurrency issue?
At first, I tried to use Explicit Locking, but it is too complexity to handle (my real case is a little bit more complex, but the above example is sufficient). It works, but its not maintainable.
After, I tried to use Serializable transactions, but the problem above persists, although everyone saying "When using Serializable transactions you don't have to think about concurrency"
What do I have to do to ensure this consistency? The explicit locking strategy is the only way?
Thanks!

A: You don't get a serializable violation, because there is not one.
If the actual order is:

*

*T1 begin serializable

*T2 begin serializable

*T1 see that account is not disabled

*T2 disable account

*T1 insert request

*T2 commit

*T1 commit

The outcome of the above is compatible with the serial order of:

*

*T1 begin serializable

*T1 see that account is not disabled

*T1 insert request

*T1 commit

*T2 begin serializable

*T2 disable account

*T2 commit

Because the outcome is compatible with some serial execution, it is not a violation.  If the serial execution it is compatible with is not the one you want, that is an error in your expectations, not in the execution.
If T2 were both to disable the account, and delete all pending requests for that account, in one serializable transaction, then that would be a violation.  One of the two would get served an ERROR when it tried to commit.  But if T2 only disables the account without deleting pending request against it, your business logic allows that outcome, so that is not a violation.

A: If you read the status of an account before you disable it, you will get a serialization error in SERIALIZABLE isolation level. So that would be a way to get what you want.


text:
Q: How to force line-breaks on  ? Sometimes text on my pages looks very strange, real example:
trained professionals and paraprofessionals coming together

...While the parent div is quite narrow so the text is just sticking out of it.
And it looks quite strange, because   actually represents a space.
So, I wonder if it's possible to make the browser account these characters as actual spaces and break the line where necessary without actually replacing them?
EDIT
Why a blind replacing is a problem?
Because   may be needed sometimes.
Consider the following example:
Ranks:

 Marshall

  Leutenant

   Sergeant

If I just use a preg_replace on them it would look differently in the end.
(I would also consider some suggestions if you have any ideas on replacing them smartly (for php platform) If you could think of some algorithm that wouldn't affect formatting.)

A: By definition,   is a non-breakable space. It's very meaning is not to be broken across line endings. If this is not what you intend then I suggest fixing the HTML instead of trying to force the browser into non-standard behaviour.


text:
Q: Opening text containing CSV with Excel from ASP.NET I'm converting an older asp.net intranet application over to .net 4.5. One of the parts I'm having trouble with is supposed to open a string containing CSV data into Excel.
No matter how I attempt to accomplish this, the resulting excel document contains the contents of the website rather than the text I supplied.
On an additional note, I currently have the aspx in a web project, while the utility/business classes reside in another. I don't know if that is part of the problem.
Please help me out with this issue.
CSV sample:
string text = "\"Year\", \"Make\", \"Model\", \"Length\"\n\"1997\", \"Ford\", \"E350\", \"2.34\"\n\"2000\", \"Mercury\", \"Cougar\", \"2.38\""

Code Sample:
private static void OpenCsvFile(string text, string name)
{
    var httpContext = HttpContext.Current;
    httpContext.Response.Clear();
    httpContext.Response.ContentType = "application/vnd.ms-excel";
    httpContext.Response.Charset = "";
    httpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
    httpContext.Response.Write(text);
    httpContext.Response.Flush();
    httpContext.ApplicationInstance.CompleteRequest();
}

Update: The resulting file contains the website contents rather than the CSV text.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>
      "My WebSite"
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="css/style.css" type="text/css" title="WebSite" rel="stylesheet" />

    <form method="post" action="Main.aspx" id="form1" name="form1">

... etc

A: The answer is to reboot your PC.
Yes, it's working now without any further code changes. I just can't believe I spent so long trying to get this to work properly.
Thank you for trying to help, Tim.


text:
Q: calculated column in MS Access table can be edited? I created a table like that
  ID   |TraName |  income   | TrainerRatio%| TrainerMoney  |
  1    |  gym   |    100    |     50       |  50   |
  2    |  spa   |    150    |     60       |  90   |
  3    |Kung fu |    140    |     40       |  56   |
  4    | Karate |    120    |     30       |  36   |
  5    | ADDnew |    ??     |     ??       |  ??   |

I created calculated column TrainerRatio%
IIf(TraName=gym,TrainerRatio=50,IIF(TraName=spa,TrainerRatio=60))

and so on, as i can't write switch in table i don't know why
And created calculated column Trainermoney
=(income*TrainerRatio%/100)

if i add new traing , TrainerRatio% will be 0 , how can i edit it?


text:
Q: Sparse × Sparse matrix product which computes only some its elements Suppose A, B and C are sparse matrices in any format. And I wonder how to compute their dot product efficiently only for elements which are nonzero in C.
It's equal to
prod = A.dot(B)
prod[C == 0] = 0

for dense matrices in Python. But this code is extremely inefficient.
Could you please advise me something? Memory doesn't matter.

A: You could cast C to boolean and take advantage of the fact that the value True will become 1 in the context of multiplication. You can then do element wise multiplication between the product of A.dot(B) and C.
You can achieve that by:
A.dot(B).to_csr().multiple(C.to_csr())

Faster Dot Product
In order to get the fastest possible dot product I would brute search over all sparse formats offered by scipy. Define a timing function such as :
from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        start = time()
        result = f(*args, **kwargs)
        end = time()
        print 'Elapsed time: {}'.format(end-start)
        return result
    return wrapper

@timing
def csr_dot(a, b):
    # Write similar functions for all other formats
    return a.to_csr().dot(b.to_csr())

# This will print some time. Repeat for other formats.
csr_dot(A, B)

You can then choose the format that yielded the best time.


text:
Q: comparing datetime.timedelta and datetime.time in python I have this code where I execute a sql query and get two TIME fields. Now I want to compare these two with other time type field. My current code is below
import datetime

def comp(time1,time2):

        start_time_obj = datetime.datetime.strptime(time1, '%H:%M').time()
        end_time_obj = datetime.datetime.strptime(time2, '%H:%M').time()

        sql_select2 = "select TIME(Start_Time), TIME(End_Time) from table1"
        result2 = cur.execute(sql_select2)

        resultSet2 = cur.fetchall()
        for Start_Time,End_Time in resultSet2:
             if (Start_Time <= start_time_obj <= End_Time) or (Start_Time <= end_time_obj <= End_Time):
                    print("Great!")
                    continue

if __name__ == '__main__':
    comp("08:00","10:00")

When I execute this I get error as TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'datetime.time'. How to remove this?
Note: this is the sample field structure in database - '2017-06-16 08:06:00' for both Start_Time and End_Time. What I want to do is compare the time part in the above field with the time coming as a parameter

A: What if you do
 start_time_obj = datetime.datetime.strptime(time1, '%H:%M').date()
 end_time_obj = datetime.datetime.strptime(time2, '%H:%M').date()

using .date() instead of .time()?


text:
Q: Django class view: __init__ I want to get <Model> value from a URL, and use it as an __init__ parameter in my class.
urls.py
url(r'^(?P<Model>\w+)/foo/$', views.foo.as_view(), name='foo_class'),

views.py
class foo(CreateView):
    def __init__(self, **kwargs):
        text = kwargs['Model']         # This is not working
        text = kwargs.get('Model')     # Neither this
        Bar(text)
        ...

Clearly, I'm missing something, or my understanding of URL <> class view is wrong.

A: You should override dispatch method for such use cases.
class Foo(CreateView):

    def dispatch(self, request, *args, **kwargs):
        # do something extra here ...
        return super(Foo, self).dispatch(request, *args, **kwargs)

For your specific scenario, however, you can directly access self.kwargs as generic views automatically assign them as an instance variable on the view instance.


text:
Q: Is $\mathbb{Q}$ the orbit of a continuous function that is computable when restricted to $\mathbb{Q}$? In the previous post What is the smallest set of real continuous functions generating all rational numbers by iteration? I asked for the smallest set of continuous real functions that could generate $\mathbb Q$ by iteration starting from $0$. Surprisingly one continuous function suffices and this can also be Lipschitz and possibly analytic.
Given that we are applying the function only to rational numbers to generate our sequence the question arises whether it is possible that the function restricted to the rationals is also computable:

Is there a continuous function $f:\mathbb{R}\rightarrow \mathbb{R}$  that generates $\mathbb{Q}$ by iteration where $f$ restricted to $\mathbb{Q}$ is computable?

A: Yes.  This answer is based on the answers to your previous question.
Start with a computable ergodic map $T$ (D. Thomine constructs an example here). For every basic open neighborhood $B_i$, the set $D_i = \bigcup_n T^{-n}(B_i)$ is a dense effectively open set, uniformly in $i$.  So some computable real $p$ meets all the $D_i$, meaning $X = \{ T^n(p) : n \in \omega\}$ is dense.
There is a computable, order-preserving bijection $g: X \to \mathbb{Q}$ (back-and-forth argument), and we may assume that $g(p) = 0$.  $g$ induces a (bi-computable) homeomorphism $G: \mathbb{R} \to \mathbb{R}$.
Define $f = G\circ T\circ G^{-1}$.

Constructing the bijection:
We'll build a computable sequence of rationals $(q_n)_{n \in \omega}$ and define $g(T^n(p)) = q_n$.
Begin with $q_0 = 0$.  Then compute enough of $p$ and $T(p)$ to determine how they are ordered ($p < T(p)$ or $T(p) < p$).  If $p < T(p)$, choose $q_1$ to be a rational greater than 0; otherwise, choose $q_1$ to be a rational less than 0.  In either case, choose $q_1$ to be the appropriate rational with the smallest Gödel number.
Then compute enough of $p$, $T(p)$ and $T^2(p)$ to determine how they are ordered, and choose $q_2$ to be a rational in the same relative position to $q_0$ and $q_1$.  Again, choose the appropriate rational of smallest Gödel number.
Etc.
This is all a computable process, so $g$ is computable.  It's a total order-preserving injection by construction.
Surjectivity is by induction on Gödel number.  For a rational $r$, by the inductive hypothesis all rationals of smaller Gödel number are in the range of $g$.  So fix an $n$ such that all rationals of smaller Gödel number occur in $q_0, \dots, q_{n-1}$, and assume $r$ does not occur in this list, as otherwise we are done.  Define $C = \{i < n : q_i < r\}$.  By the density of $X$, there is an $m \ge n$ with $T^i(p) < T^m(p)$ for all $i \in C$, and $T^m(p) < T^i(p)$ for all $i < n$ with $i \not \in C$.  Fix the least such $m$.  Then by construction, $q_m = r$.


text:
Q: run `nmake` while the current directoy in debug folder I would like to know if is it possible to run nmake from command prompt while the current directory is in debug folder. I found it tedious to change to the previous folder only to run nmake then come back to debug folder to run the executable file.
debug
release
main.cpp
Makefile

I'm using visual studio 2010 in windows 7.

A: By using nmake option /F you can specify the location of your Makefile:
nmake /F ..\Makefile

Alternatively you can invoke a sequence of commands in a single line:
pushd .. & nmake & popd


text:
Q: How can I use value of select the right way if the Node = X and I need an information from the folder where Node = X is in I have a problem with selecting a value from an node. I want to select the information stored in cac:item/cbc:name from the InvoiceLine with ID 2. I can't seem to use value of select in the right way, because it always gets the answer from the first node, the one with ID 1 in InvoiceLince. Can somebody please help me out with selecting the value stored in cac:item/cbc:name from the InvoiceLine with ID 2?
<InvoiceLine>
<ID>1</ID>
<LineExtensionAmount currencyID="EUR">0</LineExtensionAmount>
<TaxTotal>
<TaxAmount currencyID="EUR">0</TaxAmount>
<TaxSubtotal>
<TaxableAmount currencyID="EUR">0</TaxableAmount>
<TaxAmount currencyID="EUR">0</TaxAmount>
<TaxCategory>
<ID>S</ID>
<Percent>0</Percent>
<TaxScheme>
<ID>VAT</ID>
</TaxScheme>
</TaxCategory>
</TaxSubtotal>
</TaxTotal>
<Item>
<Name>
Relatienaam:    : BLABLA
Bezoekadres : BLABLA2
</Name>
</Item>
<Price>
<PriceAmount currencyID="EUR">0</PriceAmount>
</Price>
</InvoiceLine>
<InvoiceLine>
<ID>2</ID>
<LineExtensionAmount currencyID="EUR">0</LineExtensionAmount>
<TaxTotal>
<TaxAmount currencyID="EUR">0</TaxAmount>
<TaxSubtotal>
<TaxableAmount currencyID="EUR">0</TaxableAmount>
<TaxAmount currencyID="EUR">0</TaxAmount>
<TaxCategory>
<ID>S</ID>
<Percent>0</Percent>
<TaxScheme>
<ID>VAT</ID>
</TaxScheme>
</TaxCategory>
</TaxSubtotal>
</TaxTotal>
<Item>
<Name>685000/06.0009/7603/355132.01</Name>
</Item>
<Price>
<PriceAmount currencyID="EUR">0</PriceAmount>
</Price>
</InvoiceLine>

I have already tried the following code:
<xsl:template match="/">
   <xsl:for-each select="/x:Invoice/InvoiceLine/ID[ID='2']">
      <xsl:if test="."><xsl:value-of select="substring(translate(cbc:Name,' ',''),1,6)"/></xsl:if>
   </xsl:for-each>
</xsl:template>

I expect the output of 685000 and not Relati. Am i doing something wrong??

A: The expression you (probably) want is this...
/x:Invoice/InvoiceLine[ID='2']

Currently, by doing /x:Invoice/InvoiceLine/ID[ID='2'], you are selecting the ID element itself, but then only if that ID has a child ID of 2 (which it doesn't).
By doing /x:Invoice/InvoiceLine[ID='2'] you are selecting the InvoiceLine element, and so the relative expression cbc:Name should then also return something.
Do note, this assumes you are handling namespaces correctly, as you have not actually shown any namespace declarations in your XML.
(Note, if you did want to select the ID element, you would write /x:Invoice/InvoiceLine/ID[.='2'], but to then  get the name you would need to do ../cbc:name, where .. is used to get the parent of the current node)

A: When you write /x:Invoice/InvoiceLine/ID[ID='2']
It will find another ID element under <ID>, I am not sure if it gives you error or any wrong output (based on your description)
I am assuming your input without namespaces for now as it is not mentioned in the question.
Try this out: (Modify it to add up the namespaces or modify the question itself)
Assumed Input:
<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceLine>
    <ID>1</ID>
    <LineExtensionAmount currencyID="EUR">0
    </LineExtensionAmount>
    <TaxTotal>
        <TaxAmount currencyID="EUR">0</TaxAmount>
        <TaxSubtotal>
            <TaxableAmount currencyID="EUR">0</TaxableAmount>
            <TaxAmount currencyID="EUR">0</TaxAmount>
            <TaxCategory>
                <ID>S</ID>
                <Percent>0</Percent>
                <TaxScheme>
                    <ID>VAT</ID>
                </TaxScheme>
            </TaxCategory>
        </TaxSubtotal>
    </TaxTotal>
    <Item>
        <Name>
            Relatienaam: : BLABLA
            Bezoekadres : BLABLA2
        </Name>
    </Item>
    <Price>
        <PriceAmount currencyID="EUR">0</PriceAmount>
    </Price>
</InvoiceLine>
<InvoiceLine>
    <ID>2</ID>
    <LineExtensionAmount currencyID="EUR">0
    </LineExtensionAmount>
    <TaxTotal>
        <TaxAmount currencyID="EUR">0</TaxAmount>
        <TaxSubtotal>
            <TaxableAmount currencyID="EUR">0</TaxableAmount>
            <TaxAmount currencyID="EUR">0</TaxAmount>
            <TaxCategory>
                <ID>S</ID>
                <Percent>0</Percent>
                <TaxScheme>
                    <ID>VAT</ID>
                </TaxScheme>
            </TaxCategory>
        </TaxSubtotal>
    </TaxTotal>
    <Item>
        <Name>685000/06.0009/7603/355132.01</Name>
    </Item>
    <Price>
        <PriceAmount currencyID="EUR">0</PriceAmount>
    </Price>
</InvoiceLine>
</Invoice>

Solution can be:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="/">
    <xsl:for-each select="/Invoice/InvoiceLine">
        <xsl:if test="ID ='2'">
            <xsl:value-of select="substring(translate(Item/Name,' ',''),1,6)" />
        </xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Find the demo here: https://xsltfiddle.liberty-development.net/94rmq6x


text:
Q: django static folder is not served in apache2 I have inherited a django application (1.7) and I am supposed to install it on Apache2. Everything runs fine when I do runserver from command prompt but as deploy to apache2/mod_wsgi.
I am pretty sure the STATICFILES_DIRS has been set correctly.
The settings.py is like below:
"""
Django settings for sampleapp project.

Generated by 'django-admin startproject' using Django 1.10.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'tf07wvjy+#g&&#s$spi34_c-jno^8_cb0bw=*dx2ni2+w6x-(h'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# ALLOWED_HOSTS = ['0.0.0.0', 'localhost']
ALLOWED_HOSTS = ['192.168.1.36',  'localhost']

# Application definition

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'south',
    'CordeliaHanelBackend',
    'tastypie',
    'StudioHanel',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CordeliaHanelBackend.urls'

PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
# TEMPLATE_DIRS = (
#     '/var/www/CordeliaHanelBackend-master/StudioHanel/templates/StudioHanel',
# )

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/var/www/CordeliaHanelBackend-master/StudioHanel/templates/StudioHanel','CordeliaHanelBackend/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CordeliaHanelBackend.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'
USE_I18N = True

USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # os.path.join(BASE_DIR, "static"),

    '/var/www/CordeliaHanelFrontend-master/www/dist/',
        # '/var/www/CordeliaHanelFrontend-master/www/app',
        # '/var/www/CordeliaHanelBackend-master/StudioHanel/static',
    )

# STATIC_ROOT = '/var/www/CordeliaHanelFrontend-master/www/app'

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

# DEFAULT_FILE_STORAGE = '/var/www/CordeliaHanelFrontend-master/www/app'

SOUTH_DATABASE_ADAPTER = {
'default': 'south.db.sqlite3'
}

and here is the apache2 configuration site-available file.
<VirtualHost *:80>

WSGIDaemonProcess sampleapp python-path=/var/www/CordeliaHanelBackend-master:/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages
WSGIProcessGroup sampleapp
WSGIScriptAlias / /var/www/CordeliaHanelBackend-master/CordeliaHanelBackend/wsgi.py

    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

# EDIT

Alias /static /var/www/CordeliaHanelFrontend-master/www/dist/
<Directory /var/www/CordeliaHanelFrontend-master/www/dist/>
    Order allow,deny
    Allow from all
</Directory>
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

A: You need to define path to your project in apache's configuration as:
<Directory /path/my/project/www/xyz.com>  # In your case: /var/www/CordeliaHanelBackend-master
    Require all granted
    AllowOverride All
    Options -Indexes
</Directory>


text:
Q: FCM is generating the same token everytime in my activity In my activity actually I have a button and on button click i want to generate FCM ... I want when app is restart and when button is clicked again FCM should generate different token everytime but it is generating same token everytime
FirebaseInstanceId
        .getInstance()
        .getInstanceId()
        .addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                String token = instanceIdResult.getToken();// here same token is generating everytime
                System.out.println("Tokensss " + token);
                SharedPreferences sharedPreferences = SignupActivity.this.getSharedPreferences(cmn.SHARED_SPNAME, MODE_PRIVATE);
                SharedPreferences.Editor sharedPreferencesE = sharedPreferences.edit();
                sharedPreferencesE.putString(cmn.RegistrationTokenforFirebase, token);
                sharedPreferencesE.apply();
                tokenZ = new Token();
                SharedPreferences sharedPreferenceZ = SignupActivity.this.getSharedPreferences(cmn.SHARED_SPNAME, MODE_PRIVATE);
                String tokens = sharedPreferenceZ.getString(cmn.RegistrationTokenforFirebase, "1");
                DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("" + Number);
                //  DatabaseReference myRef = database.getReference(""+Number);
                tokenZ.setToken(tokens);
                database.setValue(tokenZ);
            }
        });

A: Nothing says that getToken() method will generate token every time you call it.

From Docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance.

but also docs clearly say that there are multiple different scenarios in which the token "may change":

*

*The app deletes Instance ID

*The app is restored on a new device

*The user uninstalls/reinstall the app

*The user clears app data.

getToken() gives you the current token, not new token every single time.


text:
Q: Solving linear systems of equations modulo a prime power I am interested in knowing if there is a general theory for solving linear systems of equations modulo a prime power $p^k$. Such questions have been asked here before:

*

*Solving system of linear equations involving modulo power of 2

*System of linear congruences modulo a prime power
but none of them is satisfactory since the first one only points to other not-exactly-relevant questions, and the second points to Gaussian elimination, which AFAIK only gets as general as working over fields.
I think that a reasonable and generic way of finding such solutions is by using a generalization of Hensel's lemma to multivariate equations, but before I dive into such approach I would like to know if there is not an off-the-shelf solution I could use.
Thanks!


text:
Q: Labeling of this diagram How can I add labels to the corners and arrows of the following diagram?
\documentclass{article}
\usepackage{tikz-cd}
\usetikzlibrary{decorations.markings,arrows.meta}
\usetikzlibrary{backgrounds}

\begin{document}

\begin{tikzpicture}
\end{tikzpicture}

\begin{tikzcd}[
sep=2cm,
cells={shape=coordinate},
]
  \ar[draw=none,r, "{\tikz\node[rotate=90,inner sep=0pt] {\tikz\draw[->](0,0) ;};  }" description]
  \ar[dash,r]
&
{}
\\
  \ar[draw=none,r, "{\tikz\node[rotate=270,inner sep=0pt] {\tikz\draw[->](0,0) ;};  }" description]
  \ar[draw=none,u, "{\tikz\node[inner sep=0pt] {\tikz\draw[->>](0,0) ;};  }" description]
  \ar[draw=none,ur, "{\tikz\node[rotate=-45,inner sep=0pt] {\tikz\draw[->>>](0,0) ;};  }" description]
  \ar[dash,r]
  \ar[dash,u]
  \ar[dash,ur]
&
{}
  \ar[draw=none,u, "{\tikz\node[inner sep=0pt] {\tikz\draw[->>](0,0) ;};  }" description]
    \ar[dash,u]
\end{tikzcd}
\end{document}

The diagram stems from the question
How to draw a Klein Bottle

A: Your code unfortunately nests tikzpictures, which can lead to uncontrollable results. However, you are already loading decorations.markings, and using it allows you to avoid the nesting. I add two ways to answer your question, one with tikz-cd and another one with plain TikZ. For your convenience, I define styles ->-, ->>- and ->>>- for the single, double and triple arrows. (EDIT: For your convenience I added the reversed arrow styles.)
\documentclass{article}
\usepackage{tikz-cd}
\usetikzlibrary{decorations.markings}
\tikzset{> at/.style={postaction={decorate,decoration={markings,mark=at position
#1 with {\arrow{>};}}}},
->-/.style={> at=0.5},
->>-/.style={>
at/.list={0.5*\pgfdecoratedpathlength-1.5pt,0.5*\pgfdecoratedpathlength+1.5pt}},
->>>-/.style={>
at/.list={0.5*\pgfdecoratedpathlength-3pt,0.5,0.5*\pgfdecoratedpathlength+3pt}},
< at/.style={postaction={decorate,decoration={markings,mark=at position
#1 with {\arrowreversed{>};}}}},
-<-/.style={< at=0.5},
-<<-/.style={<
at/.list={0.5*\pgfdecoratedpathlength-1.5pt,0.5*\pgfdecoratedpathlength+1.5pt}},
-<<<-/.style={<
at/.list={0.5*\pgfdecoratedpathlength-3pt,0.5,0.5*\pgfdecoratedpathlength+3pt}}}
\begin{document}

\begin{tikzcd}[sep=2cm,cells={nodes={text height=1em,minimum width=0.8em}}]
a
&
b\ar[dash,l,-<-,start anchor=south west,end anchor=south east,"\ell_1"']
\\
c \ar[dash,u,->>-,start anchor=north east,end anchor=south east,"\ell_2"]
\ar[dash,r,->-,start anchor=north east,end anchor=north west,"\ell_3"']
\ar[dash,ur,->>>-,start anchor=north east,end anchor=south west,"\ell_4"]
&
d \ar[dash,u,->>-,start anchor=north west,end anchor=south west,"\ell_5"]
\end{tikzcd}

\begin{tikzpicture}
 \path (0,0) coordinate[label=above left:$a$] (a)
  (2,0) coordinate[label=above right:{$b$}](b)
  (0,-2) coordinate[label=below left:$c$] (c)
  (2,-2) coordinate[label=below right:$d$] (d)
  (b) edge[->-,"$\ell_1$"'] (a)
  (c) edge[->>-,"$\ell_2$"] (a)
  (d) edge[->>-,"$\ell_5$"'] (b)
  (c) edge[->>-,"$\ell_3$"'] (d)
  (c) edge[->>>-,"$\ell_4$"] (b);
\end{tikzpicture}
\end{document}


text:
Q: What package-info do I annotate with XmlJavaTypeAdapters? I've studied Blaise Doughan's answer to a question on this subject but have a further question.
XmlJavaTypeAdapters lets you list a bunch of XmlJavaTypeAdapter annotations, each of which governs how a non-bindable type is mapped to a bindable type by JAXB.
You can use this annotation at the package level.  When you do so, every XmlJavaTypeAdapter annotation needs its type() attribute fully specified.
There does not appear to be a requirement that the package that is being annotated have anything to do with the package of the non-bindable types being adapted.  That is convenient and nice.
That, however, leads me to my next question: if there is no relationship between the annotated package and the package of the type being adapted, how does JAXB discover package-level XmlJavaTypeAdapters annotations?  How, in other words, does it know which packages to consult for potential XmlJavaTypeAdapters annotations?  May I make a random package in, say, a .jar file in my .ear file's lib directory that contains a single, ginormous package-info class that is annotated with all the adapters for all of my non-bindable types?

A: When the JAXB runtime loads a JAXB-annotated class, it looks for a package-info.java in the same package as that class, and checks that to look for package-level annotations. So while XmlJavaTypeAdapters doesn't have to reside in the same package as the "non-bindable" types, it does have to reside in the same package as the "bindable" types.
For example, say I have a JAXB-annotated class A, in package X, which has a property of  type B in package Y. In order to bind the B property, let's say a type adapter is required. That adapter can be specified in A itself, or it can be specified in the package-info.java in package X. Package Y is pretty much arbitrary, and is of no interest to the JAXB runtime.
I hope that makes sense.

A:
There does not appear to be a requirement that the package that is
  being annotated have anything to do with the package of the
  non-bindable types being adapted. That is convenient and nice.

This is correct.  When @XmlJavaTypeAdapter is used at the package level it means apply this adapter to all properties of the specified type for classes that reside in this package.  I'll demonstrate below with an example.
forum8735737.bar.package-info
For this package we will specify an XmlAdapter that will be applied to all fields/properties of type String within this package.
@XmlJavaTypeAdapters({
    @XmlJavaTypeAdapter(value=StringAdapter.class, type=String.class)
})
package forum8735737.bar;

import javax.xml.bind.annotation.adapters.*;

forum8735737.bar.StringAdapter
Our XmlAdapter will simply convert all instances of String to upper case when marshalling:
package forum8735737.bar;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        return v;
    }

    @Override
    public String marshal(String v) throws Exception {
        if(null == v) {
            return v;
        }
        return v.toUpperCase();
    }

}

forum8735737.bar.Bar
Bar represents a POJO in this package with a property of type String:
package forum8735737.bar;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Bar {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

forum8735737.foo.Foo
Foo represents a domain object with a property of type String that exists in a different package.  The XmlAdapter we registered for the forum8735737.bar package will not apply to this class:
package forum8735737.foo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Demo
The following code will create instances of both Foo and Bar and marshal them to XML:
package forum8735737;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import forum8735737.bar.Bar;
import forum8735737.foo.Foo;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class, Bar.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Foo foo = new Foo();
        foo.setName("Foo");
        marshaller.marshal(foo, System.out);

        Bar bar = new Bar();
        bar.setName("Bar");
        marshaller.marshal(bar, System.out);
    }

}

Output
Notice how the value of the name element within bar has been converted to upper case:
<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <name>Foo</name>
</foo>
<?xml version="1.0" encoding="UTF-8"?>
<bar>
   <name>BAR</name>
</bar>


text:
Q: JS slideToggle close other open divs I have about 20 buttons on a page.  I have set them up with jquery to slide toggle to show and hide a div.  It works well but only if the same button is used to close the div before selecting a new div.   I want that if a button is clicked it will slide up open divs, before it slides down its own div.  Right now if a div is still showing, and a different button is clicked, the open div wont close.
I think there are too many buttons to make an if function to test each div by name if open, and then slide up.  is there a general slide up all open divs?
If I add a class and use css to display:block, I dont get animation, so I am using slidetoggle. I am happy to redo my code if there is a better way?  Is there a way to close the open divs?
$(document).ready(function(){
  $('.show1').click(function(){
    $(".row1").slideToggle();
  });

  $('.show2').click(function(){
    $(".row2").slideToggle();
  });

  $('.show3').click(function(){
   $(".row3").slideToggle();
  });
});

A: The easiest way I see is to add a class (like row) to all your div and to hide them using
$(".row").not(".rowX").slideUp(); The not rowX is there to keep the toggle alive (and with that update, order doesn't matter ;)).
That'll end up like:
$('.show3').click(function(){
   $(".row").not(".row3").slideUp();
   $(".row3").slideToggle();
});

A: The simplest way to do this is to check whether or not the other divs are displaying and if they are, close them.  I only show 2 divs below, but you can make an array of the divs and loop through it for all of them.
This has all divs closed and then when one opens, the rest toggle close each time one is clicked.
$("#div1").hide();
$("#div2").hide();

$("#div1Button").click(function () {
   $("#div1").slideToggle();

   if ($("#div2")[0].style.display != "none") {
       $("#div2").slideToggle();
   }
})

$("#div2Button").click(function () {
    $("#div2").slideToggle();

    if ($("#div1")[0].style.display != "none") {
        $("#div1").slideToggle();
    }
})


text: Q: In my app there is no resources folder. How can I add the resources folder in my app to add images and custom fonts In my Xcode there is no resources under target. How can I add resources under target file


text:
Q: Is this "anemic" model acceptable design? I first want to say that I am not trying to accomplish a domain model in my current design.
That being said, I currently am building an architecture that looks like the following:
UI DTO <=> Service DTO <=> Business/Database DTO (using AutoMapper)

I have been reading Eric Evan's DDD book, and have also watched Greg Young's 7 reasons why DDD projects fail, and am afraid of the anemic model. Even though I am not prescribing to DDD, I do not want to create too many layers that it becomes a pain to keep mapping very similar things back and forth.
However, the whole reason that I have the setup that I do is two-fold. Ease of change and obscurity

*

*Ease of change: If my public objects are exposed via my service, and I use the UI and business objects internally, then I much more free to make changes without breaking existing APIs. But, maybe I can use the one DTO and refactor if the DTO's begin to deviate?

*Obscurity: I can expose my public objects, but not expose my full objects and their implementations if they are internal. This is going to need to be a secure product, so I am preparing for that. But, maybe again I can just refactor that later?

So, my question is this: Does my current model make sense, or am I asking for problems later on? Is it ok because these objects are primarily DTO's? Even in Evan's book he implied that this model is ok if it is planned to be distributed over different servers? So, is my layering ok for this reason alone, as I plan on having the UI,Service, and DB layer capable of being on different servers (they arent currently due to no current need)?
I am just trying to be aware of over-architecture, but at the same time trying to avoid under-architecture.....so, is this model structure good or bad for my current implementation?

A: This is the pattern my team uses for development using ASP.NET MVC and WCF, where your business/database dto maps to an entity framework class, your service dto maps to a POCO class/DataContract passed into/out of the WCF service and your UI dto maps to an MVC model.
While this might seem redundant, rarely do the needs of each layer lend themselves to a design where all three dto's in a stack have the same properties. One example where they tend to be different is in foreign keys into lookup tables. In the database layer, this will be represented by an int, while in the service layer, this will be better modeled as an enum, so as to impose type safety, and lastly, in the ui, said field will be converted into a localized string for display to the user.
In regards to your fear about over architecting, there is something to be said about keeping things simple. The forces that would drive me to use this pattern are that I have a need to deploy my application layer independently of my ui or simply that I work on a team with more than two developers. As your team grows, the likelihood that a team member will decide to bypass your business layer and go directly against the database goes up significantly. In doing so, they invariably defeat the purpose of any Aspect-Oriented Programming you have in place - I.e. stuff doesn't get logged or wrapped in transactions. Adding the extra layer and moving it to a separate server creates a clean separation of concerns, and, more importantly, enforces it. A one or two person team may be disciplined enough to avoid this, but, as you grow, it becomes a necessity rather quickly.
Hope that helps!

A:
I first want to say that I am not trying to accomplish a domain model

...

and am afraid of the anemic model

These 2 seem a bit contradictory to me.

Even though I am not prescribing to DDD, I do not want to create too
  many layers that it becomes a pain to keep mapping very similar things
  back and forth.

The notion of anemic or rich domain model as suggested in DDD doesn't assume anything about the number of layers you have, the data structures used by these layers and how these data structures are transformed and passed around from one layer to another.
A rich domain model only means that your business layer contains domain objects that encapsulate behavior in addition to data. You can perfectly have a rich internal domain model and only expose public services acting as facades to their behavior, and have a billion layers underneath if you want to, each manipulating its own kind of DTO's.

So, my question is this: Does my current model make sense, or am I asking for problems later on? [...] I am just trying to be aware of over-architecture, but at the same
  time trying to avoid under-architecture..

Your model doesn't look like over-architectured at all. It only reflects natural layers in a layered application. Like Doug said, it's only normal that DTO's are a bit different in each layer because they don't serve the same purpose.


text:
Q: Web api owin OAuth 2.0 sliding expiration I'm using OAuth 2.0 owin security implementation(Bearer token) in my web api project. Is there any possibility to override default behavior and make sliding expiration of token, and how can I do logout from that kind of authentication?

A: If you follow the Web API template for ASP.NET and OWIN using OAuth, if you make a call to the AccountController logout function and pass in your Bearer token, you will be logged out and the bearer token will cease to be active.
For OAuth, you are expected to refresh the token before it expires or after it expires, or have the user re-authenticate to acquire a new token entirely after expiration. Inherently, the expiration of the token is fixed, but by implementing periodic refresh you end up with the same end result. The expiration slides with each refresh. This can all be configured in your OAuthAuthorizationServerOptions which is passed to your OWIN application context in Startup.Auth.
Hope this helps.


text:
Q: Selecting data from SQL-SERVER2008 - vb6? I'm selecting a bunch of data from SQL-SERVER...
sSql = Select Fname, Lname, Mname, Dob from tblClients

So i run this in my application, check the recordcount and it shows as 1. I run the query in the SQL-SERVER and all the values are NULL. So basically what i'm trying to do is populate a flex grid with data, or hide it if there's none. SO in this case I keep seeing an empty flex grid, even though it should recognize that there are no data being pulled from the server.

A: Since you don't have the PK as one of the fields selected, it is likely that you actually have a record with null values in the four selected fields.  One of the issues in SQL Server is that the resultset display doesn't distinguish between this condition and an actual empty resultset.
Best practice for checking whether you have returned an empty recordset is to check BOF and EOF, so:
With myRS
    If .BOF and .EOF Then
        'Hide FlexGrid and exit
    End If
End With

If .EOF is false, then you have a record with four null values in it.  Best way to check this is include the PK in your selection criteria.  Then you'll see it in your FlexGrid.
Once you've done that, you'll want to evaluate how your process allows null values for these fields if it turns out that you have such, because it seems clear from your post that isn't something that you want to allow.


text:
Q: Importing / Exporting RSA SecKeyRef key using Apple's Security Framework I'm creating an iPhone Objective-C app that uses secure communication between a server and a client. The protocol I want to follow goes like this:

*

*The client is compiled and distributed with the Server's Public RSA key (hardcoded). Let's call this Kspub. (For Key Server Public)

*The client generates an random AES key. Let's call this key Kcaes (for Key Client AES)

*The client encrypts Kcaes using Kspub, and produces the encrypted text: Kspub(Kcaes)

*The client sends Kspub(Kcaes) to the server.

*The server decrypts Kspub(Kcaes) using the server's private key, Kspri. This recovers Kcaes. Now the client and the server both share a common AES key, Kcaes.

*To verify this, the server encrypts Kcaes USING Kcaes. This produces encrypted text Kcaes(Kcaes).

*The server sends Kcaes(Kcaes) to the client.

*The client decrypts Kcaes(Kcaes) using the Kcaes key. This produces Kcaes. If this matches the original Kcaes, then the client knows it has established a secure connection.

*The client and server can now securely exchange information using symmetrical key Kcaes.
I have already implemented server-side and client-side key generation, encryption, and decryption methods. Currently, keypairs generated on the iPhone are being stored in it's keychain. Here's the issue:
I cannot seem to find a method in Apple's Keychain or Security API to import a Public RSA key from a text file. How can I import a key through a text file and store it in a SecKeyRef object?
Thanks!

A: You do this via SecItemAdd, passing:

A dictionary containing an item class key-value pair (Keychain Item Class Keys and Values) and optional attribute key-value pairs (Attribute Item Keys and Values) specifying the item's attribute values.

OSStatus err = SecItemAdd((CFDictionaryRef)
    [NSDictionary dictionaryWithObjectsAndKeys:
     (id)kSecClassKey,         kSecClass,
     kSecAttrKeyTypeRSA,       kSecAttrKeyType,
     keyTagUTF8,               kSecAttrApplicationTag,
     kSecAttrKeyClassPrivate,  kSecAttrKeyClass,
     keyData,                  kSecValueData,
     nil],
 NULL);

Ensure that the attributes to store and retrieve match exactly.

A: SecKeyCreateWithData will accept RSA data in PKCS#1 as well as the x509 public key format.
Because the question mentions a text as opposed to binary file I'll assume the public key is in the standard PEM format. First you'd strip the PEM headers and new lines:
NSMutableString *pemString = [textFileString mutableCopy];
[pemString replaceOccurrencesOfString:@"-----BEGIN PUBLIC KEY-----" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [pemString length])];
[pemString replaceOccurrencesOfString:@"-----END PUBLIC KEY-----" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [pemString length])];
[pemString replaceOccurrencesOfString:@"\n" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [pemString length])];

Now you're left with a Base64 string which you can decode into binary data. I want to point out that Apple's native Base64 methods are not tolerant of padding issues and other standards.
CFDataRef data = (__bridge CFDataRef) [NSData dataWithBase64EncodedString... // Your preferred base64 method here

Now you can get the SecKeyRef via SecKeyCreateWithData.
if (data)
{
    CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    if (dictionary)
    {
        CFDictionarySetValue(dictionary, kSecAttrKeyClass, kSecAttrKeyClassPublic);
        CFDictionarySetValue(dictionary, kSecAttrIsPermanent, kCFBooleanFalse);
        CFDictionarySetValue(dictionary, kSecAttrKeyType, kSecAttrKeyTypeRSA);
        CFErrorRef error = NULL;
        SecKeyRef publicKey = SecKeyCreateWithData(data, dictionary, &error);
        if (publicKey)
        {
            if (error)
            {
                CFShow(error);
                CFRelease(error);
            }
            //...
            CFRelease(publicKey);
        }
        CFRelease(dictionary);
    }
}

From here you can either keep the reference around, or decide to save it in the keychain via SecItemAdd etc.


text:
Q: The directory is not writable by the Web process: /app/backend/web/assets' i'm deploying my app in google app engine when below error appear where can i get permissions from app engine to write to assets folder?

enter image description here

A: This is a duplicate question.  You cannot write to the production server in the cloud. From: https://cloud.google.com/appengine/docs/standard/php/runtime#filesystem

An App Engine application cannot:
write to the filesystem. Applications can use Google Cloud Storage
for storing persistent files. Reading from the filesystem is allowed,
and all application files uploaded with the application are available.

You want to use Google Cloud Storage to upload photos. You can write to the /tmp directory temporarily, but that will not persist.

A: You can not write files to the local filesystem of your App Engine app except for the /tmp directory (see docs).
However, bear in mind that the /tmp directory stores the data temporarily in the memory of the instance. This means that other instances that run your GAE app won't have access to the stored data.
If you need to persist files, you should use Cloud Storage


text:
Q: Faster way to find a sub-string given beginning and end positions in another string using C++? The task is to find a substring (needle) in another string (haystack), given the beginning position  and end position of the "haystack". The the beginning and end positions follow STL convention, i.e. the end position is the position of the character following the interested range.
For example: find "567" with beg_pos=0 and end_pos=8 in "0123456789" should return 5, while find "567" with beg_pos=0 and end_pos=4 in "0123456789" should return -1.
I could imagine two simple implementations:

*

*Method 1: Use size_t pos = haystack.find(needle, beg_pos); to get the substring position, then compare the return value pos with end_pos if found. In the worst case, the find function will go until the end of the string haystack, but the search after end_pos is unnecessary. The performance might be bad if haystack is long.

*Method 2: Use size_t pos = haystack.substr(beg_pos, end_pos-beg_pos).find(needle); to find the position, then return pos+beg_pos if found. This method avoids the problem of unnecessary searching after end_pos, but it requires to allocate a new temporary string, which might also have performance issue.

I am wondering if there is a faster way to accomplish the task.

A: In C++17 we have std::string_view which can be constructed with a pointer and and size.  This will allow you to get a read only slice of the string where nothing would be copied.  You can then use std::string_view::find to find if the sub string exists in that slice.  That would look like
std::string haystack = "lots of stuff";
std::string needle = "something";
std::string_view slice(haystack.c_str() + start, end - start); // use end - start to get size of the slice
auto pos = slice.find(needle);
if (pos == std::string::npos)
    return -1;
else
    return pos; // or pos + start if you need the index from the start and not just in the slice.

A: pre-c++17
Here is a method which I think is optimally quick. It uses std::search, which seems to me to be an iterator-based substr.
In this example the position of the needle is returned relative to the start of the haystack, not the substring being searched:
#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    using namespace std::literals;

    auto my_haystack = "0123456789"s;

    auto needle = "567"s;
    auto find_needle = [&needle](auto first, auto last)
    {
        auto i = std::search(first, last, begin(needle), end(needle));
        if (i == last)
            return std::string::npos;
        else
            return std::string::size_type(std::distance(first, i));
    };

    auto in_substring = [](auto&& str, auto b, auto e, auto&& f) -> std::string::size_type
    {
        using std::begin;
        auto brange = begin(str) + b;
        auto erange = begin(str) + e;
        auto p = f(brange, erange);
        if (p != std::string::npos)
            p += b;
        return p;
    };

    auto pos = in_substring(my_haystack, 0, 4, find_needle);
    std::cout << pos << std::endl;

    pos = in_substring(my_haystack, 0, my_haystack.size(), find_needle);
    std::cout << pos << std::endl;

    pos = in_substring(my_haystack, 1, my_haystack.size(), find_needle);
    std::cout << pos << std::endl;

    pos = in_substring(my_haystack, 1, 4, find_needle);
    std::cout << pos << std::endl;
}

example output (64-bit size_type):
18446744073709551615
5
5
18446744073709551615


text:
Q: Jquery iframe crossdomain dynamic height Is this even possible with jquery only with no bulky plugins?
I know there are lots of plugins and alternatives, i'm searching for the shortest, robustest & most cleanest (preferably relying on jquery)
Here basic jsfiddle to tryout your thoughts:
http://jsfiddle.net/3vPJd/

A: I have to go with "This is not possible" due to the fact that the parent page cannot get the height of the 3rd party page since it is from a different domain than the parent page.
Edit: It is possible to do this if you have some control of the 3rd party page.
I personally would just use the method they already have implemented, it doesn't require jQuery, you just have to include the frame.js.
At that point, all you need is a method on the parent page that listens for when the hash changes and resizes the iframe accordingly, which is also already written by the site you linked. it is a very clean solution already, no real need to modify it. It can be found here.

A: This little library will do what you want. It uses postMessage to talk between the iFrame and the parent, so works cross domain. It also uses MutationObserver and EventListeners to detect changes to the content and keep the iFrame correctly sized.
https://github.com/davidjbradshaw/iframe-resizer


text:
Q: Create UDP-like library in C I am looking to implement some kind of transmission protocol in C, to use on a custom hardware. I have the ability to send and receive through RF, but I need to rely in some protocol that validates the package integrity sent/received, so I though it would be a good idea to implement some kind of UDP library.
Of course, if there is any way that I can modify the existing implementations for UDP or TCP so it works over my RF device it would be of great help. The only thing that I think it needs to be changed is the way that a single bit is sent, if I could change that on the UDP library (sys/socket.h) it would save me a lot of time.

A: UDP does not exist in standard C99 or C11.
It is generally part of some Internet Protocol layer. These are very complex software (as soon as you want some performance).
I would suggest to use some existing operating system kernel (e.g. Linux) and to write a network driver (e.g. for the Linux kernel) for your device. Life is too short to write a competitive UDP like layer (that could take you dozens of years).

addenda
Apparently, the mention of UDP in the question is confusing. Per your comments (which should go inside the question) you just want some serial protocol on a small 8 bits PIC 18F4550 microcontroller (32Kbytes ROM + 2Kbytes RAM). Without knowing additional constraints, I would suggest a tiny "textual" like protocol (e.g. in ASCII lines, no more than 128 bytes per line, \n terminated ....) and I would put some simple hex checksum inside it. In the 1980s Hayes modems had such things.
What you should then do is define and document the protocol first (e.g. as BNF syntax of the message lines), then implement it (probably with buffering and finite state automaton techniques). You might invent some message format like e.g. DOFOO?123,456%BE53 followed by a newline, meaning do the command DOFOO with arguments 123 then 456 and hex checksum BE53


text:
Q: Can't style Ajax script content (nowrap not working?) I'm retrieving a script from a server that inserts a button enclosed in a label into the doc. I have two problems with this: I can't prevent a line break between the button and the button's label, and I can't find a way to do the styling outside the returned script itself.
Firebug shows this XHR response (I've inserted line breaks for readability):
document.getElementById("div-foo1").innerHTML="
     <label style='white-space:nowrap;'>
     <input type='button' id='sButton0' style='width:10px; height:20px;'>
     foo1
     </label>";

The first problem is that white-space:nowrap isn't preventing a line break between the button and the following 'foo1' label. I've also tried an enclosing <nobr></nobr>, with no difference. I know that the styling is generally working, because I can change the button width and see the change in the browser.
The second problem is that I can't find a way to get the styling out of the script. If I put this in the HTML header:
   <style>
   #sButton0 { width:30px; height:20px; }
   </style>

It doesn't work. Can anyone tell me what I'm doing wrong?
Thanks.

A: For your second problem, just remove the style attribute from the  tag. It overrides the style in head.


text:
Q: EclEmma Code Coverage Ignore Junit Tests The only way I have found to not check code coverage on my JUnit tests is to right click on the package, choose Coverage as..., and then choose configuration.  Then I can unclick my test package.  I have tried every possible combination to exclude test under the general preferences/java/code coverage/exclude and not seen any changes.  I always put my tests in a separate test source folder with the same package name as my src code.
Do I really have to configure every single project to ignore my JUnit tests?  This seems redundant.  Why would anyone want to check the coverage of their tests?

A: There is option Only path entries matching in Preferences -> Java -> Code Coverage that is described in documentation at http://www.eclemma.org/userdoc/preferences.html:

Comma separated list of strings that must match with the class path entry. A class path entry matches the filter, if it contains one of the given strings. (e.g. "src/main/java", Default: no filter)

After setting it to src/main/java and running test that is located in src/test/java:

A: ECLEmma just excludes those files which are excluded , but it does not create creating coverage report and giving 0% coverage for that file , generating report
Finally ECL Emma not supporting this.


text:
Q: How can I put the results in a folder with java? I am searching how to create a file and write the results of the program.
I am working in MongoDB with Java and I tried to write a program to put my results in a folder (in My Documents ) in my PC but it did not work that way.
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("behaviourDB_areas");

DBCollection cEvent = db.getCollection("events_searchingTasks");

cursorEvents = cEvent.find();

File directory = new File("C://USER//documents//dirname");
    directory.mkdir();

int count = 0;
if (cursorEvents.hasNext()){
    while(cursorEvents.hasNext()){
        count++;
        System.out.println("num(" + count + "): " + cursorEvents.next().get("type").toString());
    }
}

Suggestions appreciated.

A: I think that the only problem is with "/" character,
if you are on windows you should use "\" instead.
For crossplatform solution use File.separator like
String slash = File.separator;
String dirName = "C:" + slash + USER + slash  + documents + slash + dirname;
File directory = new File(dirName);
directory.mkdir();

Update:
to write output into the file you have to create PrintWriter and open your file, not only directory as in your code.
File outputFile = new File (dirName + slash + "yourFile.txt"); //open file with given name in your directory
PrintWriter writer = new PrintWriter (outputFile, "UTF-8"); // open stream to write data into file

//now inside the loop, instead of System.out.println:
writer.println ("do not forget to accept the answer :]");

here you have some examples of your problem's solutions:
Create whole path automatically when writing to a new file
please note that as far as i understand your problem, it has nothing to do with mongo so your tags are confusing.


text:
Q: Login to Existing Windows Domain through Ubuntu So following is my scenario.
I have a domain network and only single machine with Ubuntu. All users are registered on this windows domain.
I have no control over domain network it is maintained by someone else. What is happening is the machine with Ubuntu is being continuous thrown off the network cause the user is not of the windows domain.
I want to use the existing windows Active Directory or User Directory. I am bad with network terminology and integrate it with Ubuntu.
I have been referring the following guides for the same(Am only allowed to post 2 links):
ActiveDirectoryWinbindHowto
Now the issues is steps are written to follow and proceed. But it doesnt explain what each does so i cannot predict what can go wrong after doing this in my case. Moreover I am very poor at Networking and its concept. And I do not understand LDAP and SAMBA configuration.
Is there an easier resource or easy to use automation tools to take care of this on Ubuntu. I refer the following for automated tools:
likewiseopen
But again how it does at the back is not explained so I cannot predict what can go wrong and it will be difficult to go back.
So now questions are
1 - Is there a guide that actually explains the steps you are doing ??
2 - Is there a safe practice to follow if we take these steps from online for ease of reverting back what has been done?
3 - Are there any currently active automated tools available for this kind of stuff in ubuntu?
And last but not the least
4 - Is this process really this complex??
Any help and direction for proper resource or proper terminology to use for search would be great help.

A: I advise you to have a look at the web site of Samba: www.samba.org.  You will have there full documentation including access to Windows domains.  In your case, I think this is what you need: Setting up samba as a domain member).
Anyway, prepare yourself to have to learn a lot of things, especially if you are novice in networking.