text:
Q: Make template function for nested container I'm trying to make a generic test function that takes a container such as list, set or vector, and returns nested container: list of lists, set of sets, vector of vectors. Non-generic functions look like this:
vector<vector<string>> test(vector<string>& in_container)
{
    vector<vector<string>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

list<list<int>> test(list<int>& in_container)
{
    list<list<int>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

set<set<float>> test(set<float>& in_container)
{
    set<set<float>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

But I dont know how to make one template test function that would be equivalent to these separate test examples.

A: vector and list (and deque) have identical sets of template parameters and are ordinary sequences, so you can cover them with
template <typename T, typename U, template <typename, typename> class C>
C<C<T, U>, std::allocator<C<T, U>>> test(C<T, U> &in)
{
  C<C<T, U>, std::allocator<C<T, U>>> out;
  // Fill it here
  return out;
}

int main()
{
  std::vector<int> v;
  std::vector<std::vector<int>> vv = test(v);

  std::list<int> l;
  std::list<std::list<int>> ll = test(l);
}

(The code is a bit convoluted since we have to specify the allocator type for the outer container explicitly, but it can probably be improved.)
Meanwhile set is a different kind of container (associative), which will probably require a dedicated function anyway.

A: I don't think you can do this automatically, but you can set up a template function if you specify the type:
template <typename T>
T test(typename T::value_type& in_container)
{
    T out_container;
    return out_container;
}

int main()
{
    vector<string> v;
    v.push_back("hello");
    auto w = test<vector<vector<string>>>(v); // w is a vector<vector<string>> now
}


text:
Q: React router ignoring slash in URL React router renders both Foo and FooBar for the route /foo/bar
ReactDOM.render(
(<BrowserRouter>
        <div>
                <Route path="/foo/bar" component={FooBar}/>
                <Route path="/foo" component={Foo}/>
        </div>
</BrowserRouter>)
, document.getElementById("root"));

Why on earth would it run both routes? I think this is insane.
How would I use nested routes (without :/params in case I want to do more than one nested route? Such as /foo/bar/baz/whatever?).
Would an answer to this question even make sense without mentioning which version I'm on?

A: With React Router V4, you can use the Switch component to ensure only the first matched route is rendered:
import { Switch, Route } from 'react-router-dom'

...

<Switch>
  <Route path="/foo/bar" component={FooBar}/>
  <Route path="/foo" component={Foo}/>
</Switch>

You could also use the exact prop to ensure the /foo route is only matched when the url is /foo and not /foo/bar:
<Route path="/foo" exact component={Foo}/>
<Route path="/foo/bar" component={FooBar}/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: List of all frames on a page I am working on  a problem where I need to enter data into a form in a iFrame.
The problem is that the iframe does not have an ID or name.  It is the
first iframe (or frame) on the page, so I was planning to get a list
of the frames on the page and select the first one in the returned
list.  I have done something simliar with windows
ie:
order_window = page.driver.browser.window_handles[0]
page.driver.browser.switch_to.window(order_window)
can something similar be done with frames?
if so how?
cucumber (1.0.6)
Capybara (1.1.1)
selenium-webdriver (2.5.0)


text:
Q: Permalinks for a custom post type - with a page template (custom query) and taxonomy archive I'm having trouble getting my permalinks working with a specific custom post type setup.
Here's the code for the custom post type:
function jc_attactions() {
$labels = array(
    'name' => 'Attractions',
    'singular_name' => 'Attraction',
    'add_new' => 'Add New',
    'add_new_item' => 'Add New Attraction',
    'edit_item' => 'Edit Attraction',
    'new_item' => 'New Attraction',
    'all_items' => 'All Attractions',
    'view_item' => 'View Attraction',
    'search_items' => 'Search Attractions',
    'not_found' => 'No Attractions found',
    'not_found_in_trash' => 'No Attractions found in Trash',
    'parent_item_colon' => '',
    'menu_name' => 'Attractions'
);
$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'menu_icon' => 'dashicons-tickets-alt',
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'attractions', 'with_front' => false  ),
    'capability_type' => 'post',
    'hierarchical' => false,
    'menu_position' => null,
    'has_archive' => false,
    'supports' => array('title', 'editor')
  );
register_post_type( 'attractions_cpt' , $args );

Instead of using the archive template, I use a page with a custom template/query to render the results. In this case, the template simply outputs the list of taxonomy terms with some stuff from ACF fields on the term etc.. This part is working just fine.
I also have a custom taxonomy. Code:
function create_attracts_tax() {
$labels = array(
    'name'              => 'Category',
    'singular_name'     => 'Category',
    'search_items'      => 'Search Categories',
    'all_items'         => 'All Categories',
    'parent_item'       => 'Parent Category',
    'parent_item_colon' => 'Parent Category:',
    'edit_item'         => 'Edit Category',
    'update_item'       => 'Update Category',
    'add_new_item'      => 'Add New Category',
    'new_item_name'     => 'New Category',
    'menu_name'         => 'Categories'
);
$args = array(
    'labels' => $labels,
    'show_admin_column' => true,
    'hierarchical' => true,
    'rewrite' => array( 'slug' => 'attractions', 'with_front' => false ),
    'show_ui' => true,
    'query_var' => true,
    'public' => true
);
register_taxonomy( 'attract_cats', 'attractions_cpt', $args );

There are no detail pages for these, I simply have a page, /attractions/ and a taxonomy (will use default taxonomy template file) that on the taxonomy archive, will just list out the posts.
My problem is with permalinks. I would ideally like the permalink to simply be /attractions/taxonomy-slug/ for the archive pages.. Unfortunately no matter what I do I get 404's. If I simply add something like attractions/category to the taxonomy rewrite, it of course works and ends up being /attractions/category/business/ but I really would rather not have the extra "category" in there.
I've been googling (and even have a few posts bookmarked here over the years), but everything I find seems to be about getting creative for the actual single post page slugs. In this case, I am just looking for the tax archive to not 404.
Any ideas?

A: I've actually had a brain fart, and just figured it out.. Since I don't have any single posts, there was no reason to even be rewriting the CPT itself. I simply removed the rewrite line from the CPT and everything is working perfectly.


text:
Q: curl query to check out a document using CMIS I am trying to checkout a document using the REST-based CMIS protocol, but I get an error from the server (Alfresco).
Am I misusing curl?
Or am I missing something in my request?
curl --user admin:admin -F "atomentry=@atomentry.xml" http://localhost:8080/alfresco/service/cmis/checkedout

With atomentry.xml being:
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>

A: I was wrong with both curl and the XML... here is what worked:
curl -X POST -uadmin:admin "http://localhost:8080/alfresco/s/cmis/checkedout" -H "Content-Type:application/atom+xml;type=entry;charset=UTF-8" -d @atomentry.xml

With atomentry.xml being:
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/" xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>


text:
Q: PHP insert into MySQL database with REST I am attempting to test inserting in a database using a restful web service. I followed this tutorial https://trinitytuts.com/build-first-web-service-php/
Whenever I post the data I get back successful but the database doesn't display the information (IE it created an entry but all the fields are blank). I am 75% sure it is the Advanced Rest Client but I don't know whats wrong with it. Here's the code/Post command.
Post string is name=Apple&email=banna%40orange.com&pwd=12345&status=ok, Picture of how I send it using Advanced Rest Client.

confi.php file
 <?php
 $conn = mysqli_connect("localhost", "root", "", 'tuts_rest');
 ?>

Rest of the code
        <?php

include_once('confi.php');

if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = isset($_POST['name']) ? mysqli_real_escape_string($_POST['name']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : "";
$password = isset($_POST['pwd']) ? mysqli_real_escape_string($_POST['pwd']) : "";
$status = isset($_POST['status']) ? mysqli_real_escape_string($_POST['status']) : "";

 // Insert data into data base
 $sql = "INSERT INTO users (ID, name, email, password, status) VALUES ('' , '" . $name . "', '" . $email . "', '" . $password . "', '" . $status . "');";
 $qur = $conn->query($sql);
 if($qur){
 $json = array("status" => 1, "msg" => "Done User added!");
 }else{
 $json = array("status" => 0, "msg" => "Error adding user!");
 }
}else{
 $json = array("status" => 0, "msg" => "Request method not accepted");
}

mysqli_close($conn);

/* Output header */
 header('Content-type: application/json');
 echo json_encode($json);
?>

Thank you!

A: Instead of this use my code(I change all of your code and add extra security whether you can remove the header as you wish). here you can easily insert the data from json format into database.
in Advance rest client you see there is a button Raw where you can write json data type. For this example,

{
      "name": "Ashraf",
      "email":"ash@yahoo.coom",
      "pwd": "1234",
      "status": "nice"
  }

Now click send button and see your data will be inserted in your database

<?php

// Include confi.php
include_once('confi.php');
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
 // Get data
 $content=trim(file_get_contents("php://input"));
 $data = json_decode($content, true);

if(
    !empty($data['name']) &&
    !empty($data['email']) &&
    !empty($data['pwd']) &&
    !empty($data['status'])
){
 $name=$data['name'];
 $email=$data['email'];
 $password=$data['pwd'];
 $status=$data['status'];

 // Insert data into data base
 $sql = "INSERT INTO users (name, email, password, status) VALUES (? , ?, ?, ?)";
 $qur=mysqli_query($conn,$sql);

//sanitize
   $name=htmlspecialchars(strip_tags($name));
       $email=htmlspecialchars(strip_tags($email));
       $password=htmlspecialchars(strip_tags($password));
       $status=htmlspecialchars(strip_tags($status));
   //bind values
   $stmt = $conn->prepare($sql);
   if($stmt)
   {
    $stmt->bind_param("ssss", $name, $email, $password,$status);

  if($stmt->execute())
  {
   $json = array("status" => 1, "msg" => "Done User added!");
  }
  else
  {
   $json = array("status" => 0, "msg" => "Error adding user!");
  }
 }
 else
 {
  $json = array("status" => 0, "msg" => "Request method not accepted");
 }
}

@mysqli_close($conn);

/* Output header */
 header('Content-type: application/json');
 echo json_encode($json);
?>

A: Because you are using mysql_real_escape_string. The function is deprecated. You may use mysqli_real_escape_string instead of that.

A: Thanks for all the help guys! I have it working though I do not understand it. The problem was indeed in my Advanced Rest Client application. I was sending the payload as application/json and it wasn't getting the POST data but when I changed the Content-Type to application/x-www-form-urlencoded it worked. If anyone wants to explain why that fixed it I will appreciate it and I'm sure others will as well.


text:
Q: Can pipes be used across LAN computers? Can pipes be used across LAN computers?
In particular I'm looking for Windows, but if you have more info on other platforms, that will also help others who find this thread later.

A: Yes they can.

Named pipes can be used to provide
  communication between processes on the
  same computer or between processes on
  different computers across a network.
  If the server service is running, all
  named pipes are accessible remotely

http://msdn.microsoft.com/en-us/library/aa365590.aspx

A: It should also be noted that a TCP/IP connection is effectively a pipe in the sense that you shove bytes in one end and they come out the other. TCP/IP connections are available on pretty much any platform you are likely to care about.


text:
Q: Drawing torus in opengl I need to draw a torus which is very thin. What I found by searching internet is just formal description of the function glutSolidTorus() But problem is probably I am not getting what they are saying about the parameter. Every time I am trying to draw it by changing the parameters what comes out is a very fat torus.
glutSolidTorus(1.0f, 0.005f, 32, 32);

What I thought is that 1 unit is total torus radius and cross section(fat or thin determining) radius is 0.005 unit. Certainly I am wrong. Can somebody please explain me what's the problem and what to do?

A: Looking at http://www.opengl.org/documentation/specs/glut/spec3/node84.html
I noticed the following:
void glutSolidTorus(GLdouble innerRadius,
                    GLdouble outerRadius,
                    GLint nsides, GLint rings);

And your shape for the torus is that the inner radius is bigger that the outer radius. Try switching them around and see if that is what you want.
lutSolidTorus(0.005f, 1.00f, 32, 32);

The thickness of the torus is defined by the first parameter, innerRadius, while the second one defines how wide the torus spreads.
Edit:
please visit the link in the comment bellow.


text:
Q: Problemas subiendo imagenes mediante formsets de django Buen día la razón por la que hago esta entrada es porque estoy batallando para cargar imágenes utilizando formsets de django, al crear un nuevo producto dos formas aparecen para cargar dos imágenes más, el problema es que al cargar todos los formularios si se crean en la Base de datos estos registros, pero sin las imágenes que se deben cargar. ¡Gracias por adelantado!
models.py
class Etiqueta(models.Model):
    nombre = models.CharField(max_length = 20)
    def __str__(self):
        return self.nombre
    class Meta:
        verbose_name = 'Etiqueta'
        verbose_name_plural = 'Etiquetas'
class Producto(models.Model):
    nombre = models.CharField(max_length = 70)
    descripcionCorta = models.CharField(max_length = 150)
    descripcionDetallada = models.TextField()
    imagenPrincipal = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True)
    precioOriginal = models.PositiveIntegerField()
    precioDescuento = models.PositiveIntegerField(null=True, default= None, blank=True)
    cantidad = models.PositiveSmallIntegerField(null=True, blank=True)
    especificaciones = models.TextField(null=True, blank=True)
    calificacion = models.PositiveSmallIntegerField(null=True, blank=True)
    categoria = models.CharField(max_length = 30)
    fechaCreacion = models.DateField(auto_now_add=True)
    etiqueta = models.ManyToManyField(Etiqueta)
    def __str__(self):
        return self.nombre
    class Meta:
        verbose_name = 'Producto'
        verbose_name_plural = 'Productos'
class FotografiaProducto(models.Model):
    producto = models.ForeignKey(Producto, null=True, blank=True, on_delete=models.CASCADE)
    fotografia = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True)
    def __str__(self):
        return str(self.id)

views.py
@login_required()
def addProducto(request):
    data = {
        'form-TOTAL_FORMS': '2',
        'form-INITIAL_FORMS': '0',
        'form-MAX_NUM_FORMS': '',
    }
    FotoProductoFormSet = formset_factory(FotoProductoForm, extra=2)
    if request.method == 'POST':
        formaFoto = FotoProductoForm(request.POST, request.FILES, prefix='fotografia')
        productoForm = ProductoForm(request.POST, request.FILES)
        formset = FotoProductoFormSet(data, request.POST, request.FILES)
        if productoForm.is_valid() and formset.is_valid():
            nuevoProducto = productoForm.save(commit=False)
            nuevoProducto.imagenPrincipal = request.FILES['imagenPrincipal']
            nuevoProducto.save()
            post = get_object_or_404(Producto, pk=nuevoProducto.id)
            for form in formset:
                nuevaImagen = form.save(commit=False)
                nuevaImagen.producto = post
                nuevaImagen.save()
            return redirect('productoList')
    else:
        productoForm = ProductoForm()
        formset = FotoProductoFormSet(prefix='fotografia')
    return render(request, 'producto/formularioProducto.html', {'form':productoForm, 'formset':formset})

forms.py
class ProductoForm(forms.ModelForm):
    class Meta:
        model = Producto
        fields = [
            'nombre',
            'descripcionCorta',
            'descripcionDetallada',
            'imagenPrincipal',
            'precioOriginal',
            'precioDescuento',
            'cantidad',
            'especificaciones',
            'categoria',
            'etiqueta'
        ]
        labels = {
            'nombre': 'Nombre',
            'descripcionCorta': 'Descripcion corta',
            'descripcionDetallada': 'Descripcion detallada',
            'imagenPrincipal': 'Imagen principal',
            'precioOriginal' : 'Precio original',
            'precioDescuento': 'Precio con descuento',
            'cantidad': 'Numero de articulos disponibles',
            'especificaciones': 'Especificaciones',
            'categoria': 'Categoria',
        }
        widgets = {
            'nombre': forms.TextInput(),
            'descripcionCorta': forms.TextInput(),
            'descripcionDetallada': forms.TextInput(),
            'precioOriginal': forms.NumberInput(),
            'precioDescuento': forms.NumberInput(),
            'cantidad': forms.NumberInput(),
            'especificaciones': forms.TextInput(),
            'categoria': forms.TextInput(),
        }

    #etiqueta = forms.ModelMultipleChoiceField(queryset=Etiqueta.objects.all())
    def __init__(self, *args, **kwargs):
        super(ProductoForm, self).__init__(*args, **kwargs)
        self.fields["etiqueta"].widget = CheckboxSelectMultiple()
        self.fields["etiqueta"].queryset = Etiqueta.objects.all()
class FotoProductoForm(forms.ModelForm):
    def __name__(self):
        return self.__class__.__name__
    class Meta:
        model = FotografiaProducto
        fields = [
            'fotografia',
        ]
        labels = {
            'fotografia' : 'Fotografia Secundaria',
        }

formularioProducto.html
{% extends 'usuarios/base.html' %}
{% block content %}

Registro Reventeando

    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        {{form2.as_p}}
        {% for forma in formset %}
            {{forma.as_p}}
        {% endfor %}
        <button>Guardar</button>
    </form>
{% endblock %}


text:
Q: Is it a bug in jackson-datatype-jsr310 deserializer? I know that's presumptuous to image found a bug in a library used every day by thousands of developpers. So I think the answer to my title question is "NO !!!", but ...
I have an object containing a date that I receive from my front end (JS), and I store it into a MongoDB database. I use Spring to get this object (with a REST Controller), and Spring to perform persistance (with a MongoDBRepository). My computer is configured with a CEST clock, so GMT+2 (UTC +0200).
The date in my POJO is stored in a LocalDateTime.
Here is my object :
class Test{
  LocalDateTime when;
  String data;
  // getter setters...
}

The following unit test show that Spring (which use jackson-jsr310) fill my LocalDateTime with an UTC Date Time.
mockMvc.perform(post("/test")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .content("{\"when\":\"2017-03-31T14:20:28.000Z\",\"data\":\"toto\"}")).andExpect(status().isOk());

List<com.robopec.models.Test> tests =  testRepository.findAll();
Assert.assertEquals(14, tests.get(0).getWhen().getHour());

We can see in the jackson source code LocalDateTimeDeserializer.java line 74 :
 return LocalDateTime.ofInstant(Instant.parse(string), ZoneOffset.UTC);

But when I save in my database, spring use spring-data-commons to convert my LocalDateTime to a Date before storing the date in the database.
We can read in spring-data-commons/../Jsr310Converters.java this :
public static enum LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
        INSTANCE;
        @Override
        public Date convert(LocalDateTime source) {
            return source == null ? null : Date.from(source.atZone(systemDefault()).toInstant());
        }
    }

So, spring-data JSR310 Converters interpret a localdatetime as an instant in the default system zone.
The problem is that when my front end send "2017-04-03T20:00:00Z", the REST controller store it in a LocalDateTime with the following time : 20:00:00. And when the mongo-data converter convert it into a date, the resulting time is 20:00:00+0200 (because my computer is in CEST time zone).
My conclusion is that I shouldn't store my date in a LocalDateTime but rather in a Date (java.util) or in an Instant.
But, is there a bug in one of the converters ?

A: If I remember correctly, the latest version of the Java driver for mongoDB still use java.util.Date to store dates, so using the Java 8 time api can be a bit of a hassle.
In one project I work on, I switched from Joda Datetime to the Java 8 time a few months ago. I couldn't get my way around with LocalDateTime, ZonedDateTime and so on, so I decided to go with Instant and it worked fine. Just remember to use the ISO8601 Zulu notation for your dates ("2017-03-31T14:20:28.000Z"), which is already what you're doing apparently.


text:
Q: Find this nice limit $$\displaystyle \lim_{x \to \infty} 2x-(2\lfloor x \rfloor +1)\log x$$
Where $\lfloor . \rfloor$ represents floor function.

A: Since $\lfloor x\rfloor/x\to1$ as $x\to\infty$ and $\log(x)\to\infty$ as $x\to\infty$, we have that
$$
\lim_{x\to\infty}[2x-(2\lfloor x\rfloor+1)\log x]=\lim_{x\to\infty}[x(2-(2\lfloor x\rfloor/x+1/x)\log x)]=-\infty.
$$


text:
Q: Existence of a special graph. There is given a construction of ordered k-partite digraph $G=(V_{1},...,V_{k};E)$ :

*

*for every $v \in V$ $d_{in}(v)\ge1$ (in-degree)

*for every $v \in V_{1}$ $d_{out}(v)=0$ (out-degree)

*for $m>l$ $v_{1},v_{2} \in V_{l}$ and $v_{3} \in V_{m}$ is not allowed to $v_{1}v_{3} \in E$ and $v_{2}v_{3} \in E$ at the same time.

*$v \in V_{l}; v_{1} \in V_{m}; v_{2} \in V_{n}$ it is forbidden to have $vv_{1},vv_{2} \in E$, where $l>m,n$

*if $v_{1},v_{2} \in V_{a}$, $v_{3} \in V_{b}$, $v_{4}\in V_{c}$, $v_{5}\in V_{d}$ and $v_{1}v_{4},v_{2}v_{5} \in E$ then we can't take $v_{3}v_{1}, v_{3}v_{2} \in E$ where  $a < b \le c,d$

*for some $v,u \in V$ if $Star_{in}(v)=Star_{in}(u)$ then it is improper to have $|Star_{in}(v)|=1$
Does a graph with that given properties exist? If so, please give a example of it and some other properties. I am asking because i do some research on k-partite digraphs and i have added as many conditions as it it possible
Regards.


text:
Q: Auto Paging in Windows Phone 8 newbie in wp8 development
say I have a long paragraph, instead letting user to scroll all the way up and down, is there any way to set the textblock (or other alternative control) auto paging (left and right), so the text would fill up the screen, then scroll right for the next page? tks in advance

A: There are no default controls which provide this and I'm not aware of any 3rd party offering such a control either.
The convention on Windows Phone and most mobile platforms is to have vertical scrolling for text. The exception to this is "books" where the paging metaphor is still used. But this is for more text than just "a long paragraph".
If you do build a control to provide the experience you're after then I strongly recommend performing careful user testing around the users expectations and experience around using it.


text:
Q: Using JQuery plugin for dynamically created HTML so I want to use this JQuery plugin that Stack Overflow has made available to me :)
Auto-size dynamic text to fill fixed size container
However, I need to use this on an HTML element that is dynamically created server side. Example,
I create all the elements, convert them to HTML, and then return them as an array of Json strings basically (in HTML form) to the front end:
public JsonResult GetMessages()
{
    // do conversion work
    List<string> htmlMessages = new List<string>();
    foreach(Message message in this.messages)
    {
        htmlMessages.Add(message.toHTML());
    }
    return Json(htmlMessages);
}

And then on the front end I append them to a div in Jquery like this:
// make my AJAX call
// in the success method I do this
for (var i = 0; i < data.length; i++)
{
    $('#containerDiv').append(data[i]);
}

Now this works fine but how would I then call the JQuery plugin on each of these elements that's appended to format the text size within one of the divs in the element?

A: I don't know what the HTML itself looks like, but try something like this:
// snip...
var $container = $('#containerDiv');
for (var i = 0; i < data.length; i++)
{
    $container.append(data[i]);
}
$container.children('div').textfill({ maxFontPixels: 36 });

It looks like the plugin relies on the element containing a single <span> element, so your HTML will probably have to be structured accordingly. Also based on a wee little test, it looks like the plugin doesn't work correctly when called on a jQuery collection that contains more than one element. The simple fix:
$container.children('div').each(function ()
{
    $(this).textfill({ maxFontPixels: 36 });
});

The "Right Way" is to actually change the plugin, though:
;(function($) {
    $.fn.textfill = function(options) {
        var fontSize = options.maxFontPixels;
        this.each(function () {
            var $this = $(this),
                ourText = $this.find('span:visible:first'),
                maxHeight = $this.height(),
                maxWidth = $this.width(),
                textHeight,
                textWidth;
            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
            } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        });
        return this;
    }
})(jQuery);

So your changed plugin, will that call it on every single span it finds in the container div?

Not quite. My changes just mean that you'd be able to replace
$container.children('div').each(function ()
{
    $(this).textfill({ maxFontPixels: 36 });
});

with
$container.children('div').textfill({ maxFontPixels: 36 });

A: You can use .load() event to add the plugin when dom elements are dynamically added. http://api.jquery.com/load-event/
// make my AJAX call
// in the success method I do this
for (var i = 0; i < data.length; i++)
{
var elem = data[i];
elem.load(function(){
// Plugin here.
});

    $('#containerDiv').append(elem);
}

A: This sounds like it could be a job for livequery, which allows you to run a function when an element is dynamically added to the DOM.


text:
Q: Can i use DD to burn a windows.iso? I've got a Windows 10 ISO that I burned on a USB stick using these instructions:

*

*fdisk -l (my usb is /dev/sdb)

*umount /dev/sdb

*Use gparted to format into FAT32

*dd if=/path/windows10.iso of=/dev/sdb bs=4M
But when I try to boot from the USB, it doesn't work.
I have checked the BIOS and it's by default to boot from USB (I can boot from my Debian and Ubuntu USB but not from the windows one).
Can't dd burn windows ISO?

A: This is what worked for me in order to write/boot Windows 10 PE on as usb drive.
From https://askubuntu.com/a/487970/48496

Install GParted and GRUB on Ubuntu with:
sudo apt-get install gparted grub-pc-bin p7zip-full ntfs-3g

*

*Rewrite the partition table as msdos and format your USB drive as NTFS using GParted (and then "Manage flags" and add the boot flag).

*In GParted, right click the USB partition and select Information. Copy the UUID somewhere as you will need it.

*Copy all files from mounted Windows ISO or DVD to USB drive using your favorite file manager.

*Go to USB drive and if the folder named boot has uppercase characters, make them all lowercase by renaming it.

*Install GRUB on USB:
sudo grub-install --target=i386-pc --boot-directory="/<USB_mount_folder>/boot" /dev/sdX

*Create a GRUB config file in the USB drive folder boot/grub with the name grub.cfg.
Write this into the file:
echo "If you see this, you have successfully booted from USB :) <or whatever you want>"
insmod ntfs
insmod search_fs_uuid
search --no-floppy --fs-uuid <UUID_from_step_2> --set root
ntldr /bootmgr
boot

*Unmount the USB drive and restart your PC. Choose the USB as the first boot device in BIOS and start booting from it.

A: use universal usb installer.  I know.  I did what you did.. however, I used the windows version.
It works..  here is the link http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/


text:
Q: RegEx exclude sub-group text from being included in a parent sub-group For the sake of this question, I'll include a basic example of what I'm trying to do. I have been looking for a method using regex which would allow me to have an input such as this:
$4
.00

To match this in one sub-group 4.00
I have tried numerous methods, all being around the lines of:
\$([0-9]+
\.[0-9]+)
or
\$([0-9]+(?:
)\.[0-9]+)
            ^-- Excludes
 from being placed in a match group, but it does not
                exclude
 from its parent match group, so we still get 4
.00

Both of the methods above match 4
.00
My question is: Are there any other Regex operators that allow me to exclude certain sub-expressions from their parent sub-expressions? (Match 4
.00 but exclude
 giving 4.00 in 1 sub-group)

A: Is there a replace function in whatever language that is?  Something along the lines of:
s.replaceAll( "<.+>", "" )
So that would replace all the tags in your string with the empty string and leave you with what you want.

A: If you want to use regex, you don't have to really do it in one step. you can break it up into steps. Eg: Get the text from  to  and save to variable using /(.*?)<\/a>/. then replace the tags
>>> import re
>>> s="$4
.00"
>>> re.sub("(.*?)<\/a>","\\1",s)
'$4
.00'
>>> var=re.sub("(.*?)<\/a>","\\1",s)
>>> re.sub("<.*?>","",var)
'$4.00'

A: I decided to switch to using lxml. Even for minimal HTML parsing needs, lxml did the trick.


text:
Q: Trying to create an array within an array dynamically with a GET Request I'm trying to create an array within an array with a GET Request I'm making. I want the data look something like
[heroesOfLOTR[Gandalf, Frodo, Aragorn], heroesOfStarWars[Yoda, Luke, ObiWan],heroesOfWheelOfTime[Rand, Matt, Perrin]]

I've looked through multiple posts about multi-dimensional arrays, but the data is usually with a set number, and does not work dynamically. I also see a lot of results that look like this:
[[1,2,3][1,2,3,4][1,2]]

Currently, thats what my data looks like, and can't figure to a solution to get it to work like the first array mentioned.
I've tried at least 10 or 15 combinations of code, but am unable to find a solution.
JSON
{ HeroLOTR  heroes:[ {Sam} {Frodo} {Gandalf}], {HeroesOfStarWars  heroes:[ {Yoda} {Luke} {ObiWan}]

A: There are a few things I'd recommend here:
First, create a more descriptive class or struct for your heroes. This isn't a requirement but will make your code much more readable and understandable as you continue development.
class Hero { // Switch "class" to "struct" if you want a struct
  // Add whatever properties you want here
  let name: String

  init?(json: [String: Any]) {
    guard let name = json["name"] as? String else {
      return nil
    }
    self.name = name
  }
}

Second, it appears you're trying to put each of the heroes into an array (a set would work here too). You can again create a class or struct to hold these heroes.
class HeroGroup { // Just switch "class" to "struct" if you want a struct
  let name: String
  let heroes: [Hero]

  init?(json: [String: Any?]) {
    guard let name = json["name"] as? String else {
      return nil
    }
    self.name = name

    self.heroes = (json["heroes"] as? [[String: Any]])?.flatMap { Hero(json: $0) } ?? []
  }
}

Lastly, when you receive your response, you can just write code like the following in your completion closure:
guard let groups = response.value.arrayValue as? [[String: Any]] else {
  return // Have JSON that you can't parse
}

// This will give you [HeroGroup]
self.groupsOfHeroes = groups.flatMap { HeroGroup(json: $0) } // This is a property on your view controller
tableView.reloadData()


text:
Q: About an exception when I try to show a timestamp from a DataFrame i have to generate a parquet file from a csv file, and the parquet file need to have two columns, filename and creation date, so I have to load the csv file, create a DataFrame from it and add it two new columns before I use spark-csv to generate the parquet files.
This is my actual code:
def loadCSV(sqlContext : SQLContext, pathCSV: String, separator: String, haveSchema: String): DataFrame = {

//logger.info("loadCSV. header is " + haveSchema.toString + ", inferSchema is true, pathCSV is " + pathCSV + " separator is " + separator)
sqlContext.read
  .format("com.databricks.spark.csv")
  .option("header", haveSchema) // Use first line of all files as header
  .option("delimiter", separator)
  .option("nullValue","")
  .option("mode","FAILFAST")
  .option("inferSchema", "true") // Automatically infer data types
  .load(pathCSV)

}

def writeDataFrame2Parquet(df: DataFrame, pathParquet: String, saveMode: SaveMode,header: String,delimiter:String): Unit = {

df.write
  .format("com.databricks.spark.csv")
  .option("header", header)
  .option("delimiter",delimiter)
  .option("nullValue","")
  .mode(saveMode)
  //by default, gzip. Another values are uncompressed, snappy, gzip, lzo. This can be changed only at sqlContext Level.
  //Configuration of Parquet can be done using the setConf method on SQLContext or by running SET key=value commands using SQL.
  //.option("codec","spark.sql.parquet.compression.codec" + compression_codec)
  .parquet(pathParquet)
}

@Test
def testAddNewFieldsToDataFrame () : Unit = {

import org.apache.spark.sql.functions._

implicit val sqlContext = CSVtoParquetTest.sql

val pathWrite = "src/test/resources/writefileWithNewField2.parquet"

val df: DataFrame = CSVtoParquet.loadCSV(sqlContext , pathCSVWithHeader, ";", "true")

df.show()

val newDFWithName = df.withColumn("generated-parquet-file",lit("my-generated-parquet-file"))
newDFWithName.show()

val now = Calendar.getInstance().getTime()
val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//esto es un String, tienes que crear un java.sql.Timestamp partiendo de esta cadena.
val reportDate = dateFormat.format(now)

val generatedAt = lit(new Timestamp(dateFormat.parse(reportDate).getTime))
println("generatedAt is " + generatedAt )
val newDFWithNameAndDate = newDFWithName.withColumn("generated_at",generatedAt )
newDFWithNameAndDate.show()

val saveMode = SaveMode.Overwrite
//writeDataFrame2Parquet(df: DataFrame, pathParquet: String, saveMode: SaveMode,header: String,delimiter:String):
CSVtoParquet.writeDataFrame2Parquet(newDFWithNameAndDate , pathWrite, saveMode,"true",",")

//ahora necesito cargar el DataFrame o cargar el fichero parquet recien generado para comprobar que efectivamente hay dos nuevos campos.

val parquetFile = sqlContext.read.parquet(pathWrite)

parquetFile.registerTempTable("FINAL")

//busco uno de los campos recien creados
val distinctCountGeneratedDates = sqlContext.sql("SELECT distinct count(generated_at) FROM FINAL").collect()

Assert.assertNotNull("cannot be null!", distinctCountGeneratedDates )
println("distinctCountGeneratedDates.length is " + distinctCountGeneratedDates.length)
Assert.assertTrue(distinctCountGeneratedDates.length > 0)

val generatedDates = sqlContext.sql("SELECT * FROM FINAL").collect()
Assert.assertNotNull("cannot be null",generatedDates)
Assert.assertTrue(generatedDates.length > 0)
generatedDates.foreach(println)
println("Done!")

}

The test runs fine, but, when i run the code in local mode and generate the parquet file and copied into my SPARK_HOME folder, I run this commands:
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val parquetFile = sqlContext.read.parquet("my_parquet_folder")
## this command break the running!
parquetFile.show

scala> parquetFile.printSchema
root
|-- symbol: string (nullable = true)
|-- longname: string (nullable = true)
|-- ticker: string (nullable = true)
|-- equity_ticker: string (nullable = true)
|-- weight: string (nullable = true)
|-- id_isin: string (nullable = true)
|-- parquetFilename: string (nullable = true)
|-- generated_at: timestamp (nullable = true)

The exception:
Caused by: java.lang.AssertionError: assertion failed: Timestamps (with nanoseconds) are expected to be stored in 12-byte long binaries, but got a 19-byte binary.
at scala.Predef$.assert(Predef.scala:179)
at org.apache.spark.sql.execution.datasources.parquet.CatalystRowConverter$$anon$3.addBinary(CatalystRowConverter.scala:269)
at org.apache.parquet.column.impl.ColumnReaderImpl$2$6.writeValue(ColumnReaderImpl.java:318)
at org.apache.parquet.column.impl.ColumnReaderImpl.writeCurrentValueToConverter(ColumnReaderImpl.java:365)
at org.apache.parquet.io.RecordReaderImplementation.read(RecordReaderImplementation.java:405)
at org.apache.parquet.hadoop.InternalParquetRecordReader.nextKeyValue(InternalParquetRecordReader.java:209)
at org.apache.parquet.hadoop.ParquetRecordReader.nextKeyValue(ParquetRecordReader.java:201)
at org.apache.spark.rdd.SqlNewHadoopRDD$$anon$1.hasNext(SqlNewHadoopRDD.scala:168)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:308)
at scala.collection.Iterator$class.foreach(Iterator.scala:727)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
at scala.collection.AbstractIterator.to(Iterator.scala:1157)
at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$5.apply(SparkPlan.scala:215)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$5.apply(SparkPlan.scala:215)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1839)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1839)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:88)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

I do not understand why this code works in the unit test, but when I run the code in local (and cluster) mode, the timestamp is not been showed fine.
How can a i generate correctly this TimeStamp as a metadata generated field within the parquet file, what do i am doing wrong?

A: I found a solution, I had to cast the timestamp as TimeStampType. this is the code, probably it is not the most optimal, but it works.
val now = Calendar.getInstance().getTime()

  val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  val reportDate = dateFormat.format(now)

  val timestamp: Long = System.currentTimeMillis / 1000

  val generatedAt = lit(new Timestamp(dateFormat.parse(reportDate).getTime))
  println("generatedAt is " + generatedAt )

  var newDFWithNameAndDate : org.apache.spark.sql.DataFrame = null

  if (metadataCreationName == ""){
    println("ATTENTION! mra.generate.metadata.name should not be empty as parameter or as setting in the property file. Applying default name, parquetFilename!")
    newDFWithNameAndDate = newDFWithName.withColumn("generated_at",generatedAt )
  }else {
    newDFWithNameAndDate = newDFWithName.withColumn(metadataCreationName ,generatedAt )
  }

  val schema : StructType = newDFWithNameAndDate.schema
  println("schema is " + schema)
  val listFromSchema : List[StructField] = schema.toList

  val aSeq = mutable.MutableList[org.apache.spark.sql.Column]()

  val elementsType : StringBuilder = new StringBuilder()

  val numElements = listFromSchema.size
  var cont = 1
  //this part need to be optimized!
  for (elementFromSchema <- listFromSchema.reverse){
    println("elementFromSchema is " + elementFromSchema + ". name: " + elementFromSchema.name + ". dataType: " + elementFromSchema.dataType)
    val aColumn : org.apache.spark.sql.Column = new org.apache.spark.sql.Column(elementFromSchema.name)
    println("aColumn is " + aColumn)
    aSeq += aColumn
    val elementDataType = elementFromSchema.dataType
    println(elementDataType)
    val myElement = elementDataType match {
      case TimestampType => "timestamp"
      case StringType => "string"
      case IntegerType => "integer"
    }
    elementsType.append(myElement)
    if (cont<numElements) {
      elementsType.append(";")
      cont+=1
    }
  }//for
  println("elementsType is " + elementsType.toString())
  var df1 = newDFWithNameAndDate.select(aSeq:_*)

  df1 =  CSVtoParquet.castingDataFrame(df1, elementsType.toString(), CSVtoParquet.mapString2DataType)

  df1.show()

  writeDataFrame2Parquet(df1 , path_output_parquet, saveMode,header,separator)

def castingDataFrame(df: DataFrame, typeString: String, mapString2DataType: Map[String, DataType]): DataFrame = {

val arrayDataTypes: Array[DataType] = typeString split ";" map { name => mapString2DataType.getOrElse(name, StringType) }

val xprs = df.columns zip arrayDataTypes map { pairType => df.col(pairType._1) cast pairType._2 as pairType._1 }

df.select(xprs: _*)

}

def writeDataFrame2Parquet(df: DataFrame, pathParquet: String, saveMode: SaveMode,header: String,delimiter:String): Unit = {
logger.info("writeDataFrame2Parquet header is " + header
  +" saveMode is " + saveMode
  + " pathParquet is " + pathParquet
  + " delimiter is " + delimiter
)
df.write
  .format("com.databricks.spark.csv")
  .option("header", header)
  .option("delimiter",delimiter)
  .option("nullValue","")
  .mode(saveMode)
  //by default, gzip. Another values are uncompressed, snappy, gzip, lzo. This can be changed only at sqlContext Level.
  //Configuration of Parquet can be done using the setConf method on SQLContext or by running SET key=value commands using SQL.
  //.option("codec","spark.sql.parquet.compression.codec" + compression_codec)
  .parquet(pathParquet)
}

With this code, you can generate a parquet file with two extra metadata fields like the parquet generated filename and the creation date:
scala> val parquetFileDF = sqlContext.read.parquet("componentes_indices_comma_output7")
parquetFileDF: org.apache.spark.sql.DataFrame = [createdAt1: timestamp, fieldName1: string, id_isin: string, weight: string, equity_ticker: string, ticker: string, longname: string, symbol: string]

scala> parquetFileDF show false
16/12/01 16:59:20 WARN ParquetRecordReader: Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl

|createdAt1           |fieldName1                                                                                |id_isin     |weight   |equity_ticker|ticker   |longname                    |symbol          |
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0010310956|1,589563 |SALM NO      |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0003028904|2,367745 |SCHA NO      |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0010736879|2,513974 |SCHB NO      |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|BMG7945E1057|0,444097 |SDRL NO      |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0003053605|2,276359 |STB NO       |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0010096985|19,105393|STL NO       |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|LU0075646355|2,947026 |SUBC NO      |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0010063308|12,973417|TEL NO       |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0003078800|1,964136 |TGS NO       |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|NO0010208051|6,068747 |YAR NO       |OBX Index|BB - IDX - KINGDOM OF NORWAY|BB,2000000205203|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|US00846U1016|         |A UN         |RIY Index|RIY Index                   |BB,2001000008410|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|US0138721065|         |AA UN        |RIY Index|RIY Index                   |BB,2001000008410|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|US02376R1023|         |AAL UW       |RIY Index|RIY Index                   |BB,2001000008410|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|US00751Y1064|         |AAP UN       |RIY Index|RIY Index                   |BB,2001000008410|
|2016-12-01 16:59:06.0|/Users/aisidoro/Desktop/mra-csv-converter/csvpruebacsvconverter/componentes_indices_comma_output7|US0378331005|         |AAPL UW      |RIY Index|RIY Index                   |BB,2001000008410|
...
+---------------------+-------------------------------------------------------------------------------------------------+------------+---------+-------------+---------+----------------------------+----------------+
only showing top 20 rows


text:
Q: Render text on canvas using WebGL I want to render some text on a canvas using WebGL, which API of WebGL should be used?
Note: "text" can be either plain text or HTML snippet with CSS style

A: Most demos that I've seen that do text of any sort (like a FPS counter) simply create an HTML element with the text they want and position it over the canvas. This would probably be a good approach for most text that you would want to show "in" a canvas (ie: menus).
The only exception would be if you want the text to be an actual part of the 3d scene (like, say, text on a billboard), in which case the methodologies wouldn't be any different than rendering text in standard OpenGL. You can find a very good robust example here: http://dmedia.dprogramming.com/?n=Tutorials.TextRendering1
There's also a WebGL tutorial about text here.

A: For WebGL-rendered text, you can write text to a canvas "2d" context, then create a texture from the canvas. Denny Koch does that in his EnergizeGL framework.


text:
Q: TikZ chain adjust positions of on-the-arrow node \documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains}
\begin{document}
\begin{tikzpicture}[start chain=circle placed {at=(\tikzchaincount*30:1.5)},regular/.style={draw,circle,inner sep=0,minimum size=4mm}]
\foreach \i in {0,...,11}
  \node [on chain, regular] (\i) {\i};
\foreach \i [evaluate=\i as \ni using {int(mod(\i+1,12))}] \i in {0,3,6,9}
  {\draw [->] (\i) to [bend right] node[auto] {$p_b$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(Mod(\i-1,12))}] \i in {0,3,6,9}
  {\draw [->] (\i) to [bend right] node[auto] {$q_b$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(mod(\i+1,12))}] \i in {1,2,4,5,7,8,10,11}
  {\draw [->] (\i) to [bend right] node[auto] {$p_g$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(Mod(\i-1,12))}] \i in {1,2,4,5,7,8,10,11}
  {\draw [->] (\i) to [bend right] node[auto] {$q_g$} (\ni); }
\end{tikzpicture}
\end{document}

gave me

Although I have used node[auto] and there is certainly enough room to layout all the on-the-arrow node labels, they still crowd into a mess. I am aware that I have the option of using node[auto,above] or node[auto,below] to fine-tune the position, but that would make the code lengthy. Is there a simple way to lay out those labels beautifully?

A: With PSTricks just for fun as usual!
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-node,pst-plot}

\makeatletter
% Get Label
\def\GL#1#2{\pst@mod{#2}{3}\rem\ifcase\rem $#1_b$ \or $#1_g$ \or $#1_g$\fi}
\makeatother

\begin{document}
\begin{pspicture}[radius=12pt,arcangle=30,arrows=<-](-3,-3)(3,3)
    \curvepnodes[plotpoints=13]{0}{360}{2.5 t 30 add PtoC}{P}
    \multido{\i=0+1}{\Pnodecount}{\Cnodeput(P\i){A\i}{\i}}
    \Cnodeput(P\Pnodecount){A\Pnodecount}{}
    \multido{\ix=0+1,\iy=1+1}{\Pnodecount}
    {
        \ncarc{A\iy}{A\ix}\naput{\GL{p}{\ix}}
        \ncarc{A\ix}{A\iy}\naput{\GL{q}{\iy}}
    }
\end{pspicture}
\end{document}

Just another option
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-node,pst-plot}

\makeatletter
% Get Label
\def\GL#1#2{\pst@mod{#2}{3}\rem\ifcase\rem $#1_b$ \or $#1_g$ \or $#1_g$\fi}
% Angle unit operator
\def\angleunit#1{\degrees[#1]\pstVerb{/angleunit {\pst@angleunit} bind def}}
\makeatother

\begin{document}
\begin{pspicture}[radius=12pt,arcangle=30,arrows=<-](-3,-3)(3,3)
    \angleunit{12}
    \curvepnodes[plotpoints=13]{0}{12}{2.5 t 1 add angleunit PtoC}{P}
    \multido{\i=0+1}{\Pnodecount}{\Cnodeput(P\i){A\i}{\i}}
    \Cnodeput(P\Pnodecount){A\Pnodecount}{}
    \multido{\ix=0+1,\iy=1+1}{\Pnodecount}
    {
        \ncarc{A\iy}{A\ix}\naput{\GL{p}{\ix}}
        \ncarc{A\ix}{A\iy}\naput{\GL{q}{\iy}}
    }
\end{pspicture}
\end{document}

The difference is
\angleunit{12}
\curvepnodes[plotpoints=13]{0}{12}{2.5 t 1 add angleunit PtoC}{P}

where
\makeatletter
\def\angleunit#1{\degrees[#1]\pstVerb{/angleunit {\pst@angleunit} bind def}}
\makeatother

is defined in the preamble.
The simplest one
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-node,pst-plot}

\makeatletter
% Get Label
\def\GL#1#2{\pst@mod{#2}{3}\rem\ifodd\rem $#1_b$ \else $#1_g$ \fi}
\makeatother

\begin{document}
\begin{pspicture}[radius=12pt,arcangle=30,arrows=<-](-3,-3)(3,3)
    \multido{\i=0+1}{12}{\Cnodeput(!2.5 \i\space 1 add 30 mul PtoC){A\i}{\i}}
    \Cnodeput(A0){A12}{}% auxiliary node
    \multido{\ix=0+1,\iy=1+1}{12}
    {
        \ncarc{A\iy}{A\ix}\naput{\GL{p}{\iy}}
        \ncarc{A\ix}{A\iy}\naput{\GL{q}{\numexpr\ix+2}}
    }
\end{pspicture}
\end{document}

No more significant edit in the future!

A: Two problems:

*

*The auto option places the nodes by default to the left, you will need to use auto=right (or the swap option which swaps the default side).

*The auto option snaps to the main compass anchors east, north east, north, …, south and south east.

You want to use circle nodes so that anchors are placed in a circle around the node.
You want to use text depth=+0pt or similar solution to hide the different depths of the subscripts.
And you want to use another auto anchor/angle calculator. This is what this answer has to offer.
By the way, you might be interested in the nodes around center key for the placement of nodes in a chain. One might also add the edge nodes via the join style but that's for another question.
Code
\documentclass[tikz]{standalone}
\usetikzlibrary{chains}
\pgfmathparse{atan2(0,1)}% the CVS version swaps the arguments so I define new atan
                         % functions that have the order of arguments in their name
\ifdim\pgfmathresult pt=0pt % atan2(y, x)
  \tikzset{declare function={atanXY(\x,\y)=atan2(\y,\x);atanYX(\y,\x)=atan2(\y,\x);}}
\else                       % atan2(x, y)
  \tikzset{declare function={atanXY(\x,\y)=atan2(\x,\y);atanYX(\y,\x)=atan2(\x,\y);}}
\fi
\makeatletter
\let\tikz@auto@anchor@orig      \tikz@auto@anchor
\let\tikz@auto@anchor@prime@orig\tikz@auto@anchor@prime
\tikzset{
  Auto/.code=\pgfkeysalso{/tikz/auto=#1}%
    \let\tikz@auto@anchor      \tikz@Auto@anchor
    \let\tikz@auto@anchor@prime\tikz@Auto@anchor@prime,
  auto/.prefix code=\let\tikz@auto@anchor      \tikz@Auto@anchor@orig
                    \let\tikz@auto@anchor@prime\tikz@Auto@anchor@prime@orig}
\def\tikz@Auto@anchor{%
  \pgfmathatanXY@{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}%
  \pgfutil@tempdima=\pgfmathresult pt\relax
  \advance\pgfutil@tempdima-90pt\relax
  \edef\tikz@anchor{\pgf@sys@tonumber\pgfutil@tempdima}}
\def\tikz@Auto@anchor@prime{%
  \pgfmathatanXY@{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}%
  \pgfutil@tempdima=\pgfmathresult pt\relax
  \advance\pgfutil@tempdima90pt\relax
  \edef\tikz@anchor{\pgf@sys@tonumber\pgfutil@tempdima}}
\begin{document}
\begin{tikzpicture}[Auto=right,
  start chain=circle placed {at=(\tikzchaincount*30:1.5)},
  regular/.style={draw,circle,inner sep=+0pt,minimum size=+4mm}]
\foreach \i in {0,...,11} \node [on chain, regular] (\i) {\i};
\tikzset{text depth=+0pt, shape=circle, inner sep=+2pt}
\foreach \i [evaluate=\i as \ni using {int(mod(\i+1,12))}] \i in {0,3,6,9}
  {\draw [->] (\i) to [bend right] node {$p_b$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(Mod(\i-1,12))}] \i in {0,3,6,9}
  {\draw [->] (\i) to [bend right] node {$q_b$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(mod(\i+1,12))}] \i in {1,2,4,5,7,8,10,11}
  {\draw [->] (\i) to [bend right] node {$p_g$} (\ni); }
\foreach \i [evaluate=\i as \ni using {int(Mod(\i-1,12))}] \i in {1,2,4,5,7,8,10,11}
  {\draw [->] (\i) to [bend right] node {$q_g$} (\ni); }
\end{tikzpicture}
\end{document}

Output

A: Some coordinate calculations are also useful.
\documentclass[tikz]{standalone}
\usetikzlibrary{chains,calc}
\begin{document}
\begin{tikzpicture}[start chain=circle placed {at=(\tikzchaincount*30:1.5)},
                    regular/.style={draw,circle,inner sep=0,minimum size=4mm}]
\foreach \i in {0,...,11}
\node [on chain, regular] (\i) {\i};
\foreach \i [evaluate=\i as \ni using {int(mod(\i+1,12))},
           evaluate=\i as \pi using {int(Mod(\i-1,12))}] \i in {0,...,11}
{
\draw [->] (\i) to [bend right] (\ni);
\draw [->] (\i) to [bend right] (\pi);
\node[] at ($($(\i)!0.5!(\pi)$)!1!90:(\pi)$) {\pgfmathparse{Mod(\i,3)==0?"$q_b$":"$p_g$"}\pgfmathresult};
\node[] at ($($(\i)!0.5!(\ni)$)!1!90:(\ni)$) {\pgfmathparse{Mod(\i,3)==0?"$p_b$":"$q_g$"}\pgfmathresult};
}

\end{tikzpicture}
\end{document}

A: Quite similar to the other answers, but with one or two less keystrokes.
\documentclass[border=0.125cm]{standalone}

\usepackage{tikz}
\usetikzlibrary{topaths}

\begin{document}

\begin{tikzpicture}

\foreach \n in {0,...,11}
    \node [draw, circle] at (\n*30+30:2.5) (n-\n) {\n};

\foreach \n [evaluate={\m=int(mod(11+\n, 12)); \p=int(mod(\n+1,3)); \q=int(mod(\n,3)); }] in {0,...,11}{
    \draw [->] (n-\m) to [bend right] node [anchor=\n*30+210] {$P_\ifodd\p b\else g\fi$} (n-\n);
    \draw [<-] (n-\m) to [bend left]  node [anchor=\n*30+30]  {$P_\ifodd\q b\else g\fi$} (n-\n);
}

\end{tikzpicture}

\end{document}


text:
Q: How to fix 'Incomplete wav chunk' error when reading wav with scipy My problem
I'm trying to fit a (machine-learning) model that takes in an audiofile (.wav) and predicts the emotion from it (multi-label classification).
I'm trying to read the sample rate and signal from the file, but when calling read(filename) from scipy.io.wavfile, I'm getting ValueError: Incomplete wav chunk.
What I've tried

*

*I've tried switching from scipy.read() to librosa.read().
They both output the signal and sample rate, but for some reason librosa takes exponentially longer time than scipy, and is impractical for my task.

*I've tried sr, y = scipi.io.wavfile.read(open(filename, 'r')) as suggested here, to no avail.

*I've tried looking into my files and checking what might cause it:
Out of all 2084 wav files, 1057 were good (=scipy managed to read them), and
1027 were bad (=raised the error).
I couldn't seem to find any thing pointing as to what makes a file pass or fail, but nonetheless it's a weird result, as all files are taken from the same dataset from the same origin.

*I've heard people saying I could just re-export the files as wav using some software, and it should work.
I didn't try this because a) I don't have any audio-processing software and it seems like an overkill, and b) I want to understand the actual problem rather than put a bandaid on it.
Minimal, reproducible example
Assume filenames is a subset of all my audio files, containing fn_good and fn_bad, where fn_good is an actual file that gets processed, and fn_bad is an actual file that raises an error.
def extract_features(filenames):
    for fn in filenames:
        sr, y = scipy.io.wavfile.read(fn)
        print('Signal is: ', y)
        print('Sample rate is: ', sr)

Additional info
Using VLC, it seems that the codecs are supported by scipy.io.wavfile, but in either case, both files have the same codec, so it's weird they don't have the same effect...
Codec of the GOOD file:

Codec of the BAD file:

A: I don't know why scipy.io.wavfile can't read the file--there might be an invalid chunk in there that other readers simply ignore.  Note that even when I read a "good" file with scipy.io.wavfile, a warning (WavFileWarning: Chunk (non-data) not understood, skipping it.) is generated:
In [22]: rate, data = wavfile.read('fearful_song_strong_dogs_act10_f_1.wav')
/Users/warren/mc37/lib/python3.7/site-packages/scipy/io/wavfile.py:273: WavFileWarning: Chunk (non-data) not understood, skipping it.
  WavFileWarning)

I can read 'fearful_song_strong_dogs_act06_f_0.wav' using wavio (source code on github: wavio), a package I created that wraps Python's standard wave library with functions that understand NumPy arrays:
In [13]: import wavio

In [14]: wav = wavio.read('fearful_song_strong_dogs_act06_f_0.wav')

In [15]: wav
Out[15]: Wav(data.shape=(198598, 1), data.dtype=int16, rate=48000, sampwidth=2)

In [16]: plot(np.arange(wav.data.shape[0])/wav.rate, wav.data[:,0])
Out[16]: [<matplotlib.lines.Line2D at 0x117cd9390>]

A: I solve the problem by changing this number "4" to "1"  in the file wavefile.py file,
in this condition of the code:
-   len(chunk_id) < 1
   if not chunk_id:
            raise ValueError("Unexpected end of file.")
        elif len(chunk_id) < 1:
            raise ValueError("Incomplete wav chunk.")

but it was by just intuition and good luck, now i wonder why this works and what are the possible reasons?


text:
Q: Increase in inappropriate Not An Answer flags? Since the shift away from using flag weight, I have noticed an increase in the number of items in the flag queue in the 10k tools flagged inappropriately as Not An Answer (IMO).
Here is one example of what I'm seeing.
Namely, low quality or incorrect answers being flagged as Not An Answer.
Generally, when I see these I agree that the posts are low quality, but I frequently think that they are in fact answers, just very low quality ones.
Sometimes, it seems someone is going through several low quality answers to a single question and flagging them as Not An Answer.
My question is, how should I respond to these Not An Answer flags if I disagree with them, but agree that the post is wrong or low quality?

*

*Mark as invalid flag?

*Add a low quality flag, if I think downvotes are not a sufficient response?

*Flag the question if it's answers are attracting multiple Not An Answer flags?

Some combination of these three? I'm curious what would be most helpful for the moderators...

A: I think your examples are clear cases that are answers, just bad ones. As such, flagging as not an answer is incorrect. I would mark those flags as invalid if I came across them.
I voted to delete the second question, in hopes of adding votes to convince a mod to delete it.
Down voting is certaiinly appropriate, though it's not always necessary. An old post with a negative score already probably doesn't need more, but that's up to you.
I'm not sure if I would go "low quality" on those.

A: I thought both of the examples you linked to were borderline, but I do think there's been an increase in the number of inappropriate "Not an Answer" flags lately.  I dismissed over a dozen this morning that were just pointing out technically inaccurate answers that should have just been downvoted.  There were several other "Not an Answer" flags on answers to questions that were already closed as "Not Constructive".
The best things you can do to help us out in these cases are two things you already suggested.

*

*Mark as invalid flag when "Not an Answer" is used to point out a wrong answer that should have been simply downvoted.

*Flag the question if its answers are attracting multiple Not An Answer flags and the question needs moderator attention (closed or deleted).  This will help us head off additional inappropriate flags.


text:
Q: JavaScript LinkedList with function as node? So Im working on a leetcode problem: https://leetcode.com/problems/merge-two-sorted-lists/ specifically dealing with linkedlists. Now there is TONS of information on linkedlist available so im gonna focus on this specific leetcode problem and it being javascript.
So normally with LL's you have a node represented by an object/class. Im sort of "rusty" on JS so bear with me. Im used to Ruby and C++ so how "objects" are represented in memory in JS is something im still kinda getting re-used to.
Right now this JS question has the linked list represented by a function like this:
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */

So I understand the solution and and everything...but I guess what im struggling with is how this function how no constructor so "this" would represent the DOM object (window) when im thinking in terms of using JS normally (doing automation)...so I guess can someone clear up for me how exactly this works?
Is there an object called ListNode or something in memory like a normal JS object or what? In C++ or Ruby it makes sense because we literally create an object (in ruby, everythings an object! Wheee!) so I can make sense of it in my head....or heck even using a class makes more sense because we have an instance of an object.
But for some reason this is confusing to me. How is this "object" represented when it's just a function?
ANOTHER confusing thing was how when I would print ".next" of a node of these lists, it would actually print the "rest" of the array of numbers....like if I said list2.next (at any point during the traversal of list2) it would print the rest of list2's numbers starting with where I was at. So that made things even more confusing at how things are "actually" being represented.

A: Because the function references this and assigns to properties of it, I think it's safe to say that it's called as a constructor. For example:

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}
const node1 = new ListNode(5);
const node2 = new ListNode(3, node1);
console.log(node2);

When a function is called with new, the this inside it references the instance being created (an object whose internal prototype is the .prototype of the function), rather than the globalThis / undefined in strict mode. (There's nothing on the prototype here.)
The implementation of the function doesn't look relevant here though, because you don't ever call it, you only use the objects - and the only thing you care about on the objects is the two properties they have, so from your perspective, it could also be like

const node1 = { val: 5, next: null };
const node2 = { val: 3, next: node1 };
console.log(node2);


text:
Q: HTMLparser class not working in iPhone I am trying to convert string containing HTML data to html tags.
I tried using HTMLParser for which i included libxml2, libxml2.2 frameworks but the framework doesn't extract to any class. Hence the class HTMLparser is not declared.
HTMLparser *htmlParser = [[[HTMLparser alloc] init] autorelease];

I also tried the following code
DOMDocument *document = [self DOMDocumentFromHTML: currentElementValue];

and
NSXMLDocument * doc = [[NSXMLDocument alloc]initWithXMLString: htmlString
                                        options: NSXMLDocumentTidyHTML
                                          error: &error];

But i face the same problem. The classes are not declared. And i cannot use the NSScanner class for i need to extract content from the HTML content. Can someone help me in knowing how to solve this issue.
Thanks in advance.


text:
Q: Passing mutable variables as arguments wastes memory? I wonder if using mutable variables can lead to memory being wasted.
Consider the following two examples, whose output (the values a, b, and c) should be identical:
// Example 1

let mutable mut = Map.empty

mut <- mut |> Map.add "A" 0
let fA (m: Map<string,int>) x = m.["A"] + x
let a = fA mut 0 // 0

mut <- mut |> Map.add "B" 1
let fB (m: Map<string,int>) x = m.["A"] + m.["B"] + x
let b = fB mut 0 // 1

mut <- mut |> Map.add "C" 2
let fC (m: Map<string,int>) x = m.["A"] + m.["B"] + m.["C"] + x
let c = fC mut 0 // 3

In Example 1 each function takes a mutable argument and must (I presume) make a copy of that argument.
in total three copies are made.
// Example 2
let mutable mut = Map.empty

mut <- mut |> Map.add "A" 0
mut <- mut |> Map.add "B" 1
mut <- mut |> Map.add "C" 2

let fA (m: Map<string,int>) x = m.["A"] + x
let fB (m: Map<string,int>) x = m.["A"] + m.["B"] + x
let fC (m: Map<string,int>) x = m.["A"] + m.["B"] + m.["C"] + x

let immut = mut

let a = fA mut 0 // 0
let b = fB mut 0 // 1
let c = fC mut 0 // 3

In Example 2 each function makes a copy of the same immutable argument.
Presumably the compiler is smart enough not to use any additional memory when making these copies. For each copy could be just a pointer to the original object.
So even though on average the objects copied in Example 1 are smaller than the immutable object in Example 2, less memory will be used in Example 2.
Is this reasoning correct?

A: In your example, the Map<'K, 'V> value is immutable and the only mutable thing is the reference mut that you are using to keep a reference to the current instance of the Map<'K, 'V> value. The compiler does not need to make a copy of the value (I don't think there is a case where the F# compiler would make a copy behind your back - aside from value types).
This means that your two examples are pretty much the same - the only real difference is that in Example 2, you are passing a map containing more values to the three functions, so the lookup may be slightly longer (but that's a theoretical issue at best).
The issue you are hinting at could happen if you implemented the code as follows using a mutable data structure (resize array) and explicit copying:
let data = ResizeArray<string * int>()

data.Add("A", 0)
let f1 =
  let lookup = dict data
  fun x -> lookup.[x]

data.Add("B", 1)
let f2 =
  let lookup = dict data
  fun x -> lookup.[x]

f1 "A" // = 0
f1 "B" // error
f2 "A" // = 0
f2 "B" // = 1


text:
Q: UITestException not marked as serializable I am trying to a create coded UI test for my WPF program but I get this exception when I click Generate Code:

Type
  'Microsoft.VisualStudio.TestTools.UITest.Extension.UITestException' in
  Assembly 'Microsoft.VisualStudio.TestTools.UITest.Extension,
  Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not marked as serializable.

Steps I followed:

*

*I created an example solution, put only a button in the WPF form

*Ran the program

*Added a coded UI test project to my solution

*Started recording

*Clicked the button

*Paused recording

*Clicked "Generate Code" and then "Add and Generate"

This is when I get the exception. How can I solve this problem?

A: I found Walkthrough: Creating, Editing and Maintaining a Coded UI Test after posting the question. Turns out I should have started the program after starting the recording.
For future referance:

*

*Add a coded UI test.

*Start the exe file from the project's bin/Debug folder.

*Start recording.

*Click stuff.

*Close the exe.

*Pause recording and generate code.


text:
Q: What runs when the OS is completely corrupted? When the OS is completely corrupted, what does the computer run? How does it detect bootable devices?

A: The computer bios will have a list of bootable devices.  It will check them in a specified order to look for a boot sector.  If it finds a boot sector it will boot whatever os the boot file in the boot sector tells it to.  If the os is corrupt the user will have to either repair it or tell the bios to boot from a different device.


text:
Q: How to swap columns in eigen3 SparseMatrix What is an efficient way to swap columns in a ColMajor eigen SparseMatrix?
I have tried the following:
SparseMatrix<mpz_class,ColMajor> H;
SparseVector<mpz_class> v;

// Somehow initialize H.

v = H.col(i);
H.col(i) = H.col(j);
H.col(j) = v;

which I think is not correct (assignment doesn't make a copy I assume?)  I don't actually understand why this doesn't work, while e.g. the following does seem to work as intended:
v = H.col(i); w = H.col(j);
H.col(i) = s*v + t*w;  // s, t are some mpz_class elements.

A way which actually works is:
SparseMatrix<mpz_class,ColMajor> H, H_;
PermutationMatrix<Dynamic,Dynamic> P;
P.setIdentity();
P.applyTranspositionOnTheRight(i,j);
H_ = H; H = H_ * P;

Now this I assume makes a copy of the entire matrix H?  So I would prefer the first method, or some efficient H *= P in place permutation.  Or something like swap(H.col(i),H.col(j)).

A: The problem with the first version is that H is being partly modified before reading to the H.col(j) object (which is now invalid). You can workaround by copying both columns first:
Hi = H.col(i);
Hj = H.col(j);
H.col(i) = Hj;
H.col(j) = Hi;

Of course, it would be better to support H.col(i).swap(H.col(j)) as for dense matrices...
Also, if you apply numerous swap, then better fill them in a Eigen::Transpositions, convert it to a Eigen::PermutationMatrix and apply it once (or directly compute a unique permutation).


text:
Q: How to make manifest available for a generic type in scala? Given a scala http client being parsed through json4s, I had the following working code to transform a Future of a HttpResponse into a Future of a case class:
  def getJobIds(): Future[Seq[Job]] = {
    ...
    var req = HttpRequest(
      method = HttpMethods.GET,
      uri = uri
    )

    val res: Future[HttpResponse] = Http().singleRequest(req)

    res.flatMap {
      case response@HttpResponse(StatusCodes.OK, _, _, _) => {
        val buffer = ByteString("")

        response.entity.dataBytes
          .runFold(buffer)(_ ++ _)
          .map(_.utf8String)
          .map(
            (body: String) => {
              parse(body).as[Seq[Job]]
            }
          )
      }
      case _: Any => throw new Throwable("Error!")
    }
  }

Now I wanted to extract the logic to transform the HttpResponse to a case classes using generics in order to not repeat myself for other calls:
  def getJobIds(): Future[Seq[Job]] = {
    ...
    val res: Future[HttpResponse] = Http().singleRequest(req)
    transformResponse[Seq[Job]](res)
  }

  private def transformResponse[T](r: Future[HttpResponse]): Future[T] = {
    r.flatMap {
      case response@HttpResponse(StatusCodes.OK, _, _, _) => {
        val buffer = ByteString("")

        response.entity.dataBytes
          .runFold(buffer)(_ ++ _)
          .map(_.utf8String)
          .map(parse(_).extract[T])
      }
      case _: Any => throw new Throwable("Error!")
    }
  }

Yet this now throws:
 Metronome.scala:46:32: No Manifest available for T

for the line
.map(parse(_).extract[T])

How do I make the code work with the use of generics?

A: The issues comes from json4s extract method.
If you look it up you'll find that its defintion is:
  def extract[A](implicit formats: Formats, mf: scala.reflect.Manifest[A]): A =
    Extraction.extract(jv)(formats, mf)

For some reason, the implicit Manifest look-up works for the concrete type, yet for the generic case you'll have to define the implicit manifest for your T type:
  private def transformResponse[T](r: Future[HttpResponse])
                                  (implicit ev: scala.reflect.Manifest[T]): Future[T] = {
    r.flatMap {
      case response@HttpResponse(StatusCodes.OK, _, _, _) => {
        val buffer = ByteString("")

        response.entity.dataBytes
          .runFold(buffer)(_ ++ _)
          .map(_.utf8String)
          .map(parse(_).extract[T])
      }
      case _: Any => throw new Throwable("Error!")
    }

Now your code will compile and run.


text:
Q: Cross Domain XMLHttpRequest using CORS or Web Proxy My client has a very specific technical issue they have asked us to find a resource for.  It is very specific, so I was wondering if anyone could steer us in the right direction (so I can steer them).
They are trying to do a XMLHttpRequest to a different domain than the page is on in order to talk to a third party BI site that they want to access. When they try to access the third party BI site within their website, it breaks and does not pull  up the site. The browser is blocking it as it usually allows a request in the same origin for security reasons.  They have been told that they need to do something different when they want to do a cross-domain request using CORS.  Or should they use Web proxy? Or another method?
How would they go about starting to resolve this with no experience in either area?
Our client's site is primarily written in PHP/JavaScript and this would be a huge help for a problem they have been trying to fix for about two weeks.
Thoughts?

A: We got the same problem when we accessed fonts from our sub domain. And finally we added the following in .htaccess and it worked for us.
<ifmodule mod_expires.c>
    <Filesmatch "\.(jpg|jpeg|png|gif|js|css|swf|ico|woff|mp3)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>


text:
Q: Frameset and javascript variables interaction I know that framesets are not exactly cutting-edge technology, but I had to debug an old application and I came across an unexpected behaviour.
Here is some simple HTML pages to show this behaviour.
index.html :

  <frameset rows="22,*" border="0">
    <frame name="menu" src="menu.html" marginheight=0 marginwidth=0>
    <frame name="submenu" src="content1.html">
  </frameset>

menu.html :

        Content 1
        Content 2

content1.html :

Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive innovation via workplace diversity and empowerment.

content2.html :

Seasonal, whipped java aftertaste lungo ristretto, a turkish chicory affogato saucer. Medium, spoon et skinny americano cappuccino lungo dripper.

The behaviour is what is expected : when we click on a menu link, the content of the submenu is updated.
Now, I add a line in the body of content2.html :
If I click on "content 2" link, the content is refreshed, but from now, when I click an any link, the content of the frame is opened in a new tab.
I can reproduce this behaviour with any modern browser (Chrome, Firefox, Edge, ...) : a name javascript variable in a "main" script change the behaviour of the frameset.
Do anyone have an explanation for that ? I don't think that name is a reserved keyword ? And why this new tab opening and not a broken script ?

A: var name, if used as a global, is the same as window.name.
window.name is the property which holds the name of the frame.
If you change the name to one which doesn't match the target (e.g. from submenu to why), then there is no matching target so a new one has to be created.


text:
Q: ebay Inventory API returning error "Cannot change an auction to private or vice versa if the item has bid or is ending in 12 hours." I have integrated eBay Inventory API for managing the listings of the eBay store. Items are listing successfully but Whenever I tried to update the listing or offer using their API I am getting the following error in response.
Cannot revise the listing. Cannot change an auction to private or vice versa if the item has bid or is ending in 12 hours.

I am trying to update a fixed price item not an item in the auction. I searched and found the possible solution possible solution but still no luck. Can anyone please guide me about this?

A: You can not revise the auction offer data if the listing has a bid or going to end in 12 hours. Changing fixed price items is also revising the offer data which is why API is throwing that error. All you can do is end the listing and create another auction with an updated fixed price, however, the fixed price won't be visible if the listing gets any bids.


text:
Q: Delays in ActionScript (Flash)? Alternatives to setInterval While setInterval is handy, it's kind of limiting. Every time I want to add a Tween I have to add a new method. I do not want to alter the structure of my code just to add in some delays. Isn't there any way to say this without making methods for A and B?
// do A
// wait N seconds
// do B

I don't want to use a while loop with Dates because I think it will be blocking. Isn't there anything like Thread.sleep in ActionScript?

A: The Flash ActionScript Virtual Machine (AVM) is single-threaded. Any loop or sleep function would cause the whole SWF to freeze for the duration of the desired interval.
As far as I know, there is no equivalent to Thread.sleep in AS3, and if there was, it would not do what you wanted for the reason outlined above.
Why don't you want to use functions?
You can use timers if you want more power and/or flexibility than setInterval offers.
EDIT: You can define your functions inline (technically these are called closures); this sounds like it might be closer to what you want. For example:
setInterval(function () {
    // code for A

    setInterval(function () {
        // code for B
    }, 1000);
}, 1000);

A: If you're not against using methods, try using TweenLite. It allows you to play with all sorts of timings.
For example, after you finish an animation, you can call the following:
//call myFunction() after 2 seconds, passing 1 parameter: "myParam"
TweenLite.delayedCall(2, myFunction, ["myParam"]);

which could probably provide you with the delay you're looking for.


text:
Q: Laravel WSOD on fresh install w/o log error message Just another Laravel 4 white screen with no clues.
My context:

*

*Server CentOS 6.5

*Apache 2.2.15

*PHP 5.4.23

*php mcrypt enabled

*php log_errors working

*Laravel fresh install: "$ laravel new project"

*storage folder permissions 777

*there is no laravel error log

*there are no errors on php log

*there are no errors on apache/httpd log
I've tried to do a "manual debug" and the app stops at start.php:
$app = new Illuminate\Foundation\Application;

Going deeper compiled.php I've lost track on the share method call:
use Illuminate\Support\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app['events'] = $this->app->share(function ($app) {
            return new Dispatcher($app);
        });
    }
}

EDIT
Checked same "500 Server Internal Error" using Laravel's server ($ php artisan serve).

A: If there is no error log message it's probably an error log configuration problem.
Check out all php log related params at php.ini:
log_errors = On
error_reporting = E_ALL   // or 32767
error_log = syslog        // log file, 'syslog' value usually means /var/log/messages
                          //   or /var/log/syslog

display_errors = On          // print errors on screen if you're not
display_startup_errors = On  //   in a production environment

In case you're running Apache/VirtualHost, check it out httpd.conf for an alternative log file
<VirtualHost>
    ErrorLog /var/www/example.com/error_log
</VirtualHost>

A: Try running Laravel's server to debug possible errors in your webserver.
php artisan serve

You should have access to localhost:8000
If it does not display Laravel's splash page, then there can be a problem with Composer. If it display the splash page, it could be

*

*Apache configuration

*app/storage directory and subdirectories not being writable by PHP

Also you can check Laravel logs for errors in addition to Apache error logs


text:
Q: Goldbach's conjecture I read about this conjecture on the internet and I found that is not proven yet. So I began to think why  is impossible and one day I've had an idea. I am going to show it to you and I wait your response on it. I would be very happy if you have any suggestions or remarks.
The conjecture states that "Every even integer greater than 2 can be expressed as the sum of two primes". Of course that there are variations of the statement but I believe that this is the essence.
Now, let x be an even number greater than 2 and p,q two prime numbers.Because x is even, x can be the sum of two even numbers or two odd numbers.
Assume that x is the sum of two even numbers(that p,q).Because p,q are primes, it means that the only prime even number is 2.And from that p has to be equal to q and equal to 2.So we have that x=2+2=4 which fits the conjecture.
But what happens if x is the sum of two odd numbers? Again, because p,q are primes, it results that p,q are odd primes bigger than 2 (we already knew that because every prime number greater than 2 is odd).
And now begins the "idea."
Suppose that p is not prime, p greater than 2.From the theorem above, p is not odd which means it is even.
But if p is not prime, p is the product of primes so:
p=a1 x a2 x… x an where  a1, a2,…,an are primes bigger than 2.
Because p is a product of prime numbers bigger than 2, we conclude that a1,…,an are odd. So in the end p is the product of odd numbers so it's odd.
Finally, we assumed that p is not prime which meant that p is even and  showed that p is odd(contradiction). So the assumption is false…and from that p is prime.
It goes the same with q.
Is this ok? Am I missing something or my logic is not good?
I want to say that this  is just a little attempt, just an idea…is the reason why I need your help, advice or piece of information.Any comment is welcomed. Sorry if my English is bad.
Thank you!

A: $24=9+15$ gives an example of an even number which is the sum of two odd numbers, neither of which is prime.  So this is a multiple counter-example to your logic (there are many more), which said

Suppose that $p$ is not prime, $p$ greater than $2$. From the theorem above, $p$ is not odd which means it is even

In fact any odd non-prime would be a counter-example and $9$ is the smallest composite odd number
The fact that $24=5+19=7+17=11+13$ shows $24$ is not a counterexample to the Goldbach conjecture


text:
Q: Hibernate on Oracle: mapping String property to CLOB column WARNING: see my own answer below. The problem is caused by old Oracle drivers that were present on the classpath in addition to 10.2.0.4. Problem solved. Leaving the rest of this question for posterity.
I've been banging my head against the following. Here's a simple POJO distilled from my application code:
@Entity
@Table(name = "PIGGIES")
public class Piggy {
    private Long id;
    private String description;

    public Piggy() {}

    @Id
    @GeneratedValue
    @Column(name = "PIGGY_ID")
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    @Lob
    @Column(name = "PIGGY_DESCRIPTION")
    public String getDescription() { return description; }
    public void setDescription(String d) { description = d; }
}

There's a String property and a CLOB column. When the contents are short (e.g. "hello world"), it persists just fine. With longer strings, I get the following exception:
java.sql.SQLException: operation not allowed: streams type cannot be used in batching
        at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
        at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
        at oracle.jdbc.driver.OraclePreparedStatement.addBatch(OraclePreparedStatement.java:4236)
        at org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:172)
        at org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:172)
        at org.hibernate.jdbc.BatchingBatcher.addToBatch(BatchingBatcher.java:31)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2403)

I'm using Hibernate 3.2.3 with Oracle JDBC driver 10.2.0.4. The exception's message indicates that batching may be at fault. While I can disable batching in this simple case, I need to have it enabled for the "real" POJOs. In fact, as things stand right now, query batching is the only reason we're using Hibernate at all.
So, my question is, how can I make the above work?
EDIT: Interesting observation: the value of my "description" property persists just fine as long as it's exactly 1333 characters long or shorter. Such an odd number!
EDIT 2: In an attempt to find a solution, I modified the getProperty() annotations as follows, which has made no difference:
@Lob
@Type(type="text")
@Column(name = "PIGGY_DESCRIPTION", length = Integer.MAX_VALUE)
public String getDescription() { return description; }

EDIT 3: Here's the DDL for "PIGGIES":
CREATE TABLE "PIGGIES"
 (  "PIGGY_ID" NUMBER NOT NULL ENABLE,
"PIGGY_DESCRIPTION" CLOB,
 CONSTRAINT "PIGGIES_PK" PRIMARY KEY ("PIGGY_ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "BBDATA"  ENABLE
 ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
  TABLESPACE "BBDATA"
LOB ("PIGGY_DESCRIPTION") STORE AS "SYS_LOB0000177753C00002$$"(
TABLESPACE "BBDATA" ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10
NOCACHE
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)) ;

And here's the entire stack:
org.hibernate.exception.GenericJDBCException: could not update: [com.bamnetworks.cms.types.Piggy#934]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2425)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2307)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2607)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:92)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:232)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
Caused by: java.sql.SQLException: operation not allowed: streams type cannot be used in batching
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    at oracle.jdbc.driver.OraclePreparedStatement.addBatch(OraclePreparedStatement.java:4236)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:172)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:172)
    at org.hibernate.jdbc.BatchingBatcher.addToBatch(BatchingBatcher.java:31)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2403)
    ... 45 more

A: Have you tried dropping the @Lob annotation, and just annotating it with @Column?  In my experience, you don't need to tell hibernate the column type for a CLOB, it will determine it on its own.
Can you include a snippet of the client code which is performing the batching operation?

A: Moron alert: it turns out that I had a stale JAR with 9-something Oracle JDBC classes on my classpath. Having cleaned that up, everything simply worked magically with just the following annotations:
@Lob
@Column(name = "PIGGY_DESCRIPTION")
public String getDescription() { return description; }

Blame the fat fingers.


text:
Q: closing multiple GLUT windows independently In my GLUT program i have created two windows. when i try to close one window entire program shuts down. can anyone tell how to avoid it.
My code to create window is as follows
int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(ww,wh);
    window1 = glutCreateWindow("sample");
    glutReshapeFunc(changeSize);
    glutIdleFunc(renderScene);
    glutDisplayFunc(renderScene);
    window3 = glutCreateWindow("sample2");
    glutReshapeFunc(changeSize);
    glutDisplayFunc(renderScene2);
    glutIdleFunc(renderScene2);
    glutMouseFunc(mouse);
    glutPostRedisplay();
    glutMainLoop();
    return 1;
}

A: I don't recall GLUT being able to close windows independently in the same thread, like that. As you only use a single glutMainLoop() call to get them going, thereby when the main loop is killed for one window, it's killed for all of them.
You could try creating the windows in their own Thread. That might work, but I'm not entirely sure.
Something else you could try, is to use GLFW instead, using GLFW, you need to create the main loop etc, yourself. Bottom line, that's much easier to use and it gives you a lot more control, over your OpenGL programs. Also if you don't already have it, you should get something like GLEW.

A: You've just left the capabilities of GLUT with this demand. But you're lucky: GLUT =/= OpenGL and there are many other frameworks that will satisfy your needs. How about you take a look at Qt, which offers you not only a runtime environment and a OpenGL widget, but also a large set of widgets to draw UI elements with.


text:
Q: Android studio + Firebase - Cannot Write data I'm trying to write into my Cloud Firestone the data regarding the registered user in collection Users,
of course it must be associated with UID code in Authorization (The Registration/login system working correctly and write auths in my Firebase).
XML Register Button:
<Button
    android:id="@+id/RegisterBtn"
    android:layout_width="0dp"
    android:layout_height="51dp"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="92dp"
    android:layout_marginEnd="16dp"
    android:layout_marginRight="16dp"
    android:text="REGISTER"
    app:backgroundTint="#870404"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/Password" />

JAVA Register:
...
FirebaseFirestore database;
String userID;
...

database = FirebaseFirestore.getInstance();

mRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = mFullName.getText().toString().trim();
                String email = mEmail.getText().toString().trim();
                String password = mPassword.getText().toString().trim();
                String confirmPassword = mconfirmPassword.getText().toString().trim();

...
//REGISTER THE USER
                fAuth.createUserWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        finish();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(Register.this, "Error!" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

                //FIRECLOUD INSERT DATA
                //GET ID FROM AUTH
                userID = fAuth.getCurrentUser().getUid();
                saveOnFireCloud(userID,name,email);

            }
        });

...
 private void saveOnFireCloud(String userID, String name, String email) {
        Map<String,Object> mappa = new HashMap<>();
        mappa.put("id",userID);
        mappa.put("name",name);
        mappa.put("email",email);
        database.collection("Users").document(userID).set(mappa)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        Toast.makeText(Register.this, "Data Inserted!", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(Register.this, "Error Inserting Data!" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

In Cloud Firestone I just created collection Users.
I noticed that in Tool>Firebase>Firestone Cloud tell me:
Connect your app to Firebase

*

*✓ Connected

but even if I already clicked on and seems built correctly,
on bottom "Add Cloud Firestone to your App" button still appear instead of ✓
Did I developed the steps to link the UID in the correct way?
When I click on register button,receive no errors in runtime, the Auth user is created but the Users data remains blank...I literally get mad, I'm just stuck on this step!
Thank you in advance for your answers!!
EDIT:
Thanks a lot for the answers,Frank.
Yes, if I set the breakpoint inside:
private void saveOnFireCloud(String userID, String name, String email):
this is the result at the line:
database.collection("Users").document(userID).set(mappa):
this = { Register@17322 }
userID = "YVI9zPC2VJbpd4JpMCeBOZNDsbD2"
name = "a" email = "test@gmail.com"
mappa = {HashMap@17356}
size = 3
database = {FirebaseFirestone@17357}

But if I set 2 breakpoints of
public void onComplete(@NonNull Task<Void> task) { and public void onFailure(@NonNull Exception e)

the debug skips over... and data is not witten..

A: I solved by replacing the method:
database.collection("Users").document(userID).set(mappa)

with the method:
database.collection("Users").add(mappa)

Seems that the .set(Hashmap) method can be used just to replace an existing object,
instead the method .add(Hashmap) add the object to the database. I inserted correctly the record in the collection.
By the way, now I m stuck again on this problem, I tried to test it again and now, does not insert data in FirebaseCloud.
When I click on continue,nothing happens! just in console "Frames are not available"
Resolved 2.0:
It seems that Android studio has bugs with cash, to solve it, cancel AndroidStudio Folder in C:\Users\PIDIOTTO\AppData\Roaming\Google and Restart Android Studio! :)