text:
Q: Buscar strings diferentes entre dos textos (JavaScript) Necesito encontrar palabras diferentes y pequeñas frases de longitud de hasta 5 palabras (o podría ser personalizable) de un texto dentro de otro. Las diferencias quiero guardarlas en un array, de tal forma que solo se guarden las palabras o frases sin repetir (se comprueba antes si ya existe).
De momento he conseguido que me busque las palabras diferentes, pero no sé cómo hacer que ahora siga buscando frases de 2 palabras (consecutivas), en la siguiente iteración de 3 palabras, 4... y así sucesivamente
    var texto = "Aquí va el el primer texto a analizar e incluso con palabras repetidas repetidas";
    var texto2 = "Aquí va el segundo texto a analizar analizar e incluso con algunas palabras repetidas";

    var palabras = texto.split(" ");
    var palabras2 = texto2.split(" ");

    var diferentes = [];

    var max_palabras = 3;
    var max_busquedas = 50; //hasta que diferentes.length>=50
    var cont_palabras = 0;
    var frase = "";
    var newStr = "";
    var addWord = false;

    do {

        for (var i=0; i<palabras.length; i++) {

            console.log("añade palabra = "+addWord);

            if (texto2.includes(palabras[i]) == false) {

                if (diferentes.includes(palabras[i]) == false) { //si no existe en el array de diferencias
                    diferentes.push(palabras[i]);
                }
            }

            if (cont_palabras < 1) {
                frase = palabras[i];
                console.log("FRASE = "+frase);
            }

            if (cont_palabras >= 1 && addWord == true) {

                frase = frase + " " + palabras[i+cont_palabras];
                addWord = false;
                console.log("FRASE = "+frase);

                console.log("Nueva frase construida (cont = "+ (cont_palabras+1) +") = "+ frase);
            }

        }

        cont_palabras++;
        addWord = true;

    } while (cont_palabras <= max_palabras);

    for (var i=0; i<palabras2.length; i++) {

      if (texto.includes(palabras2[i]) == false) {

         if (diferentes.includes(palabras2[i]) == false) { //si no existe en el array de diferencias
            diferentes.push(palabras2[i]);
         }
      }
    }

    for (var j=0; j<diferentes.length; j++) {
       console.log("Elemento "+ j + " diferente en ambos textos = "+diferentes[j])
    }

Cómo puedo hacer que cada vez me vaya cogiendo una palabra más del texto1 y analizando si existe en el texto2, buscando siempre todas las frases posibles (pero las palabras deben ser consecutivas)
PD. He vuelto a actualizar el código con algo de progreso, pero ahora no sé cómo hacer que recurra el texto de 2 en 2 palabras, de 3 en 3...etc

A: A ver si esto se aproxima a lo que buscas.
Lo que hace la función checkDifferences es buscar las cadenas coincidentes entre los dos textos y obtener el resto como diferencias.
Si quieres luego podrías descomponer las diferencias más largas en elementos más pequeños.
La función checkDifferencesByLength busca en el primer texto grupos de palabras de una longitud determinada que no existen en el segundo.

function checkDifferences(text1, text2){
  if (text1.length && text2.length){
    var words1 = text1.split(' ');
    var words2 = text2.split(' ');
    // Busca la mayor coincidencia
    for(var i=(words1.length > words2.length ? words2.length : words1.length); i > 0; i--){
      for(var j=0; j<=words1.length - i; j++){
        var pattern = words1.slice(j, j+i).join(' ');
        var coincidence = text2.indexOf(pattern);
        if (coincidence >= 0){
          // Coincidencia encontrada
          // Objeto diferencias de los textos anteriores a la coincidencia
          var differencesBefore = checkDifferences(words1.slice(0, j).join(' '),
                                      text2.substring(0, coincidence).trim());
          // Objeto diferencias de los textos posteriores a la coincidencia
          var differencesAfter = checkDifferences(words1.slice(j+i).join(' '),
                                      text2.substring(coincidence + pattern.length).trim());
          // Devuelve diferencias anteriores, posteriores y coincidencia actual
          return{
            differences1: differencesBefore.differences1.concat(differencesAfter.differences1),
            differences2: differencesBefore.differences2.concat(differencesAfter.differences2),
            coincidences: differencesBefore.coincidences.concat([pattern], differencesAfter.coincidences)
          }
        }
      }
    }
  }
  // No se ha encontrado coincidencias
  return {
    differences1: text1.length ? [text1] : [],
    differences2: text2.length ? [text2] : [],
    coincidences: []
  };
}

function checkDifferencesByLength(text1, text2, length){
  var words1 = text1.split(' ');
  if (words1.length < length) return null;

  var differences = [];
  for (var i=0; i+length<=words1.length; i++){
    var pattern = words1.slice(i, i+length).join(' ');
    if (text2.indexOf(pattern)<0) differences.push(pattern);
  }
  return differences;
}

var texto = "Aquí va el el primer texto a analizar e incluso con palabras repetidas repetidas";
var texto2 = "Aquí va el segundo texto a analizar analizar e incluso con algunas palabras repetidas";

var result = checkDifferences(texto, texto2);

console.log('Primer texto: ' + texto);
console.log('Segundo texto: ' + texto2);

console.log('Coincidencias:\n' + result.coincidences.join('\n'));
console.log('Elementos diferentes en primer texto:\n' + result.differences1.join('\n'));
console.log('Elementos diferentes en segundo texto:\n' + result.differences2.join('\n'));

var resultByLength = checkDifferencesByLength(texto, texto2, 4);
console.log('Grupos de 4 palabras del primer texto que no existen en el segundo:\n'
  + resultByLength.join('\n'));
resultByLength = checkDifferencesByLength(texto2, texto, 4);
console.log('Grupos de 4 palabras del segundo texto que no existen en el primero:\n'
  + resultByLength.join('\n'));

A:

function shorter(max,s1,s2){
var arr1 = s1.split(" "), arr2 = s2.split(" "), i = 0, l1 = arr1.length, unicas = [];
  for(;i<l1;i++){
    if((arr2.indexOf(arr1[i]) === -1) && arr1[i].length <= max) unicas.push(arr1[i]);
  }
  return unicas;
}

var texto =
"Aquí va el el primer texto a analizar e incluso con palabras repetidas repetidas";
var texto2 =
"Aquí va el segundo texto a analizar analizar e incluso con algunas palabras repetidas";
console.log(shorter(6,texto,texto2));


text:
Q: Ruby Tk entry widget will not update textvariable I'm trying to write a GUI in Ruby using TK for a Mad Libs program. Essentially, it needs to take the user's input from an Entry widget and replace certain words in a line of text with that information.
The following is the relevant code ($content is the parent window):
$name=TkVariable.new()
name=Tk::Tile::Entry.new($content) {width 7; textvariable $name}.grid(:column =>1, :row  =>0, :sticky => 'we')
# Mad Lib base text
$text=TkVariable.new("My name is #{name.get}.")

# Displays end result
def showResult
display=Tk::Tile::Label.new($content) {textvariable $text}.grid(:column =>0, :row     => 6, :sticky => 'we')
end

# Button to replace input in base text.
# Clicking this button adds a new Label widget containing the text. The variables,
#however, retain whatever value they were initialized to (in this case, nothing)
Tk::Tile::Button.new($content) {text 'Submit'; command 'showResult'}.grid(:column => 1,     :row => 5, :sticky => 'we')

As I understand, name.get should give me whatever I've entered into the Entry widget's field. Yet neither name nor $name updates.

A: Text variables don't work this way. It appears you are trying to embed one textvariable into another. When you do "My name is #{name.get}.", it gets the value of the name variable at  the time this statement is executed, it won't dynamically update.
If you want an entry widget and label to be kept in sync, they need to share the same variable.

A: Not sure but try....
def showResult
   $text.value = "My name is #{name.get}."
   display=Tk::Tile::Label.new($content) {textvariable $text}.grid(:column =>0, :row     =>    6, :sticky => 'we')
end

this should update the variable each time showResult is called
but not entirely sure with Entry boxes
this is how I update my TkVariables

redpajama_set_name: RedPajamaStackExchange


text:
Q: event.preventDefault() not working for submit on Wordpress I am writing wordpress plugin.
I have some form jQuery script and I need use event.preventDefault(); (in a shortcode) for that. But event.preventDefault(); is not working for submit button, but it´s working, for example, for a link.
Can anyone help. Thanks in advance.
In shortcode:
echo 'Some text';
echo 'Some text';
echo 'Some text';

echo '<form action=" " class="answerform" method="POST" >';

echo '<input  id=' . $answerid .' class=".submitform" type="submit"  value=' . $answer->answer . '>';
                    echo '</form>';

Script:
jQuery(function($){
$(document).ready(function() {
    $( ".submitform" ).click(function( event ) {
      event.preventDefault();
    });

    $( ".test" ).click(function( event ) {
      event.preventDefault();
    });
});

});

A: You've prepended your submit input element class with a . (ie - class=".submitform" when it should be class="submitform")
It should be, simply:
echo '<input  id=' . $answerid .' class="submitform" type="submit"  value=' . $answer->answer . '>';
echo '</form>';

At the moment, your script is looking for an element with a class of submitform, which doesn't exist (your input element's class is currently .submitform).


text:
Q: MomentJS + VueJS: Getting Relative Time From Now To A Certain Point In The Past I use MomentJS.
in my VueJS-Code I want to get the relative time from now to that point in the past. In my template I incorporate the result of this short piece of JavaScript:
<template>

{{ moment(message.createdAt, 'YYYYMMDD').fromNow() }}

</template>

the object receives the date as follows:
message: { createdAt: Date.now() }

the result is always: a few seconds ago ...
how can I get the correct result (not always "a few seconds ago"):
EDIT:
this is my full template:
<template v-for="message in messages">

{{ message.text }}

{{ moment(message.createdAt).format('D.M.YYYY') }}

{{ moment(message.createdAt).fromNow() }}

</template>

A: Well, you can't use moment directly in your template, as it's not white-boxed (not accessible in the template).

Template expressions are sandboxed and only have access to a whitelist of globals such as Math and Date. You should not attempt to access user defined globals in template expressions.

Source: https://v2.vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions
I would advise you to use some filter instead (you can also do it with methods in a very similar way).
Here is a working example.

new Vue({
    el: "#app",
    data() {
        return {
            messages: [
                {
                    text: 'Message1',
                    createdAt: new Date() // Now
                },
                {
                    text: 'Message2',
                    createdAt: new Date(2016, 3, 1) // 1 April 2017
                }
            ],
            interval: null
        };
    },
    filters: {
        format(date) {
            return moment(date).format('D.M.YYYY')
        },
        fromNow(date) {
            return moment(date).fromNow();
        }
    },
    created() {
        this.interval = setInterval(() => this.$forceUpdate(), 1000);
        // Trigger an update at least each second
        // You should probably raise this duration as refreshing so often
        // may be not useful
    },
    beforeDestroy() {
        clearInterval(this.interval);
    }
});

    <template v-for="message in messages">

{{ message.text }}

{{ message.createdAt | format }}

{{ message.createdAt | fromNow }}

    </template>

A: Cobaltway's reply is working, but I would advise to extract the whole logic into a small component of its own, so you don't  force Vue to re-render the whole component each time.
I created exactly this as an example a while ago, please see this fiddle:
https://jsfiddle.net/Linusborg/meovg84x/
Vue.component('dynamic-from-now',{
    name:'DynamicFromNow',
  props: {
    tag: {type: String, default: 'span'},
    value: {type: String, default: ()=> moment().toISOString() },
    interval: {type: Number, default: 1000}
  },
  data() {
    return { fromNow: moment(this.value).fromNow() }
  },
  mounted () {
    this.intervalId = setInterval(this.updateFromNow, this.interval)
    this.$watch('value', this.updateFromNow)
  },
  beforeDestroy() {
    clearInterval(this.intervalId)
  },
  methods: {
    updateFromNow() {
        var newFromNow = moment(this.value).fromNow(this.dropFixes)
      if (newFromNow !== this.fromNow) {
        this.fromNow = newFromNow
      }
    }
  },
  render(h) {
    return h(this.tag, this.fromNow)
  }
})

Usage:
<dynamic-from-now :value="yourTimeStamp" :interval="2000" :tag="span" class="red" />


text:
Q: MOUSE_OUT outside of a movieclip? I'm having a little problem here,
I'm new to Actionscript 3, and what I'm trying to do is build a navigation menu.
What I did is I made a movieclip, added two listeners to it, MOUSE_OVER, and MOUSE_OUT,
the MOUSE_OVER tells the menu to play, so it then animates the opening of it,
the problem though, that when I put my mouse on the buttons themselves, the menu thinks that the mouse is out of it,
I understand that the mouse left the menu itself and entered some other object,
I thought of making a new rectangle, and on the mouse out, to check whether the mouse is really out of the menu's regions, it didn't work though,
I'd be glad to know how to do that,
thanks in advance

A: You should use the MouseEvent.ROLL_OUT event which fires only if you your mouse is out of the clip and all its children whereas MOUSE_OUT only considers the clip itself.


text:
Q: Grails values from large collection not saving I seem to somehow be loosing values of inputs somewhere between the GSP page and the controller.
I have a REPORT object, which has a large number of COUNT objects, which displays as tabular data through some looping in the GSP. Because there is quite a bit of nested looping, the formula for determining the instance number 'i' of each COUNT is complicated, but if I output it to screen, it is correct (counts from 0 - 419 with no issue).
What all this means is I have ONE block of code which creates the input field for each of the COUNT instances, so the code is exactly the same, and each one is named counts[0].total through to counts[419].total as you would expect (there are other hidden values to determine which column and row each COUNT sits in as well, but this is still all being output by the same single block of code iterated 420 times) BUT, somewhere along the line, SOME of these values are being lost - about 70% of the values persist to the DB on save, but the other 30% or so disappear and remain as 0.
There is no pattern to which ones save and which don't, though it is always the same values that don't work. I have two reports doing this that use the same code (though the report is different) and I have one report which does this perfectly...
I have managed to work out this much
SOMETHING In grails is limiting the set size to 256 - It will not allow me to save more than 256 objects at once, but I cannot work out how to override this.
if it's not within grails, could it be a limit to the HTTP post method?
Any help someone please? I am rapidly running out of hair.

A: The limit to GET and POST request data size is both limited from client side and server side.
In Grails:
The default value is 2 MB (refer maxPostSize attribute of the <Connector> in server.xml.)
And if this size exceeded:
HTTP 1.1 returns Status Code 414 Request-URI Too Long for the cases where a server-defined limit is reached.
But older browsers limit the size of GET request to 255 bytes ( so check your are not using the GET request).


text:
Q: Android: "TextView does not support text selection. Action mode cancelled" "TextView does not support text selection. Action mode cancelled."
I get this error when I try to bring up the context menu in an EditText in a PopupWindow in Android. The selection markers also do not work.
The question has been asked a number of times but has stayed unanswered:
How to enable selection markers for EditText in PopupWindow?
PopupWindow not triggering sytem context dialog on EditText long-press
I am just another person dealing with the same issue. Any ideas?

A: If TextView, have you tried textView.setTextIsSelectable(true);
Or if EditText, editText.setSelectAllOnFocus(true);

A: I believe this is an Android bug, and I just reported it as such: https://code.google.com/p/android/issues/detail?id=62508
We will see whether Google agrees.

A: try
et.setTextIsSelectable(true);
et.setFocusable(true);
et.setFocusableInTouchMode(true);

A: Check if you have
android:focusable="false" or
android:focusableInTouchMode="false" in your xml layout.

A: I have check around one hour, i found the solution: setwidth = wrapcontent (it's working with me)

A: I replaced PopupWindow with DialogFragment, that solved my problem. You may try same. Also, I observed DialogFragment is more stable and I recommend it over PopupWindow. I faced multiple issues with PopupWindow, those were fixed when I started using DialogFragment.
I did not set selectAllOnFocus property.


text:
Q: Import functions of a dynamically loaded module I have the following two files:
# script.exs
Code.eval_file("module.ex");

import MyModule # Doesn't work
my_function() # What I want

# module.ex

defmodule MyModule do
  def my_function() do
    IO.puts "My Function"
  end
end

When running elixir script.exs, it errors with the following message:
** (CompileError) script.exs:3: module MyModule is not loaded and could not be found
However, if you would write MyModule.my_function(), the code runs without errors.
So, is it somehow possible to import functions from a dynamically loaded module?

A: Elixir is a compiled language and even what has a .exs extension and what is called script, is to be compiled into BEAM before execution.
The issue is import MyModule cannot be compiled because at the moment the compiler knows nothing about this module. The good news is we might fool the compiler.
Put all the code you need into a separate file:
# script.ex

import MyModule
my_function()

and use runner.exs script which will be compiling both:
# runner.exs

Code.eval_file("module.ex")
# IO.inspect Code.ensure_loaded(MyModule)
Code.eval_file("script.ex")

Now runner.exs would happily call my_function().


text:
Q: Somehow a folder on my MS Outlook got deleted Here's the problem:
somehow a folder on my MS Outlook got deleted (don't ask...)
Fortunately, Outlook compacts and stores all the info from inbox, sent, and all folders.
This is saved as a DBX file under "Documents and settings / owner / local settings / application data / identities / (identity)
I can find these files, but how do I restore them?
I cannot import or export them.
Is there a way to restore / convert or other?

A: To recover your email do the following

*

*Sign in to your Outlook.com account (via a Computer/Laptop)

*Go to your Deleted folder (found on the left pane under Folders)

*Look for "Lost a message?", and click "recover deleted messages"

For more: https://groups.google.com/forum/?hl=en#!topic/deleted-dbx-files-want-to-restore/Mg9-5RTzCR8


text:
Q: Want allow only lower case or "_" using sfValidatorRegex in symfony I want to allow only lower case charecters or "_" character for text box using  sfValidatorRegex of Symfony 1.4.
I had used different types of patterns like /^[a-z_]+$/i but they didn't work for me.
So if anyone can know, please help me out.

A: Correct Pattern is '/^[a-z_]+$/'


text:
Q: Fastify not working on Docker / Kubernetes I have very simple app that returns "Hello World" string, it works fine locally. As you will see from app code below it runs on port 4000. When I create docker image and run a container, I can't access it from localhost:4000 on my machine, but I can see that docker got to node index.js command correctly and app is running without any errors.
I also tried to deploy it to Kubernetes cluster, when I access load balancer ip I get ERR_EMPTY_RESPONSE. After inspecting this app through kubectl I can see that everything is running fine, image was downloaded and pod is running.
I'm struggling to understand what I missed and why it only works locally.
NodeJS app
import fastify from 'fastify';

const server = fastify();

server.get('/', (_request, reply) => {
   reply.status(200).send("Hello World");
});

server.listen(4000, error => {
  if (error) {
    process.exit(1);
  }
});

Dockerfile
FROM node:14.2-alpine

WORKDIR /app

COPY package.json yarn.lock /app/

RUN yarn

COPY . .

EXPOSE 4000

CMD ["node", "index.js"]

Kubernetes manifest
---
# Load balancer
apiVersion: v1
kind: Service
metadata:
  name: development-actions-lb
  annotations:
    service.beta.kubernetes.io/do-loadbalancer-name: "development-actions-lb"
    service.beta.kubernetes.io/do-loadbalancer-algorithm: "round_robin"
spec:
  type: LoadBalancer
  selector:
    app: development-actions
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 4000
---
# Actions deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: development-actions
spec:
  replicas: 1
  selector:
    matchLabels:
      app: development-actions
  template:
    metadata:
      labels:
        app: development-actions
    spec:
      containers:
        - image: registry.digitalocean.com/myapp/my-image:latest
          name: development-actions
          ports:
            - containerPort: 4000
              protocol: TCP
      imagePullSecrets:
        - name: registry-myapp

A: First when I tried your code, I try it using a local docker but the behavior is just the same, so I expect it to be ebcause of the fact that fastify by default only listen to localhost.
docker build -t development-actions:latest .
docker run -it -p 4000:4000 development-actions:latest

Inside of Docker you should mentioned explicitly '0.0.0.0' since By default fastify is istening only on the localhost 127.0.0.1 interface. To listen on all available IPv4 interfaces the example should be modified to listen on 0.0.0.0 like so I change it to the following:
const server = require('fastify')({ logger: true })

server.get('/', (_request, reply) => {
   reply.status(200).send("Hello World");
});

server.listen(4000, '0.0.0.0', error => {
  if (error) {
    process.exit(1);
  }
});

The rest should be the same. To try it locally you can do it by using:
Reference:

*

*https://www.fastify.io/docs/latest/Getting-Started/#your-first-server


text:
Q: How secure is my ASP.NET code? I've developing an ASP.NET application that interfaces with Google Maps and retrieves marker information from a database. The marker information is split into tables in the database, where the name of the table reflects a company (e.g. CompanyA_MarkerData, CompanyB_MarkerData etc). In order to periodically update the map with new marker data, I use setTimeout in JavaScript to regularly call my 'UpdateMarkers' JavaScript function. 'UpdateMarkers' makes a call to a web service which performs the database query and returns a list of markers back to the JavaScript, which in turn updates the map.
The main issue I have with this method is that my web service requires that I pass it the name of the company so that it knows which table in the database to access. As you can imagine , this poses a security risk as anyone can pass a different company name to the web service and be able to retrieve the data from other companies, as well as their own.
In order to avoid this problem, I am restructuring my program as follows: When the system administrator creates users for my application, they can also assign a company ID to this user. The company ID is stored using the Profile object in ASP.NET. I am moving the web service code into a class with shared functions so that they can be called only within my pages (but not by anyone, like with web services). The functions will still require a company name passed to be passed to them. However, rather than the JavaScript making direct calls to these shared functions, the JavaScript will call a set of page methods (which as I understand it, are not public like web services). These page methods will then use the Profile object to retrieve the company name attached to the user currently logged in and then make a call to my shared database functions and return the info back to the JavaScript.
I think that this second method is more secure than the first, because I don't allow the client to pass different options to my code and retrieve unauthorized data. The server side code works out the parameters that need to be sent. However, I am wondering if there is a better way of doing this that I am missing out?
Thanks
--Amr

A: All you need is a method of checking server-side whether the user is allowed to access the data for that company.
I assume you're using AJAX, since you say you're retrieving information from your own database with Javascript. So whichever server-side script/program you call, put the user authentication code in there.


text:
Q: Styling or Replacing the Standard Select Element I've done a lot of searching and can't seem to find the answer to what I thought might be a fairly straight forward question.
I want to style a select on my page so that it is basically a green square with the selected number (1 - 20) shown in white in the middle.
Here is what I have so far:
select
{
    width: 1.2em;
    height: 1.5em;
    background-color: #3CB23C;
    -moz-border-radius: 0.2em;
    border-radius: 0.2em;
    border: 0.06em outset #666;

    text-align: center;
    color: #fff;
    font-weight: bold;
    font-size: 4em;
}

It looks fine so far but I cannot find anything on how to remove the arrow in order to make this look like a plain box with the number in.
(And before I get a thousand replies on why I shouldn't do this... I know. I have read them all before!! I'm not asking you to tell me if I should I'm asking how I do! It is for a mobile app where a number will be selected by tapping the green box and then choosing the number from the resulting list. It will be obvious what the box does so there is no need to get into an accessibility conversation here please).
I have read a lot about not being able to style selects and other form elements very easily and I have also read a lot of answers that go something like:

"You can't style the control it's self, but using JavaScript you can
  hide it and create a JavaScript functional control to act like a drop
  down list. When an item is selected it selects the item in the drop
  down list."

but then surprisingly few examples.
So does anyone have a way pf styling the arrow so that it 'disappears' or if it is not possible to use simply CSS to remove the arrow then does any one have any good examples of how to replicate this effect with Javascript?
Thank You

A: In wekbit browsers, you can use:
select {
  -webkit-appearance: none;
}

It doesn't work in ie or firefox, even with -moz-appearance: none; or appearance: none;
jsFiddle

But IMHO, it is better to do this way: style customized elements and animate them with jQuery. Then add a hidden select that is filled with jQuery with the elements above. It is a bit longer, but this way you won't have so much browsers compatibility problems.

A: @pinouchon's answer is correct for how to remove the arrow. And if you're OK with the default styling for the part that drops down, you can save yourself a whole ton of work (keyboard usage, accessibility concerns, cross-platform behavior, mousedown-vs.-click-vs.click and hold, ...).
But, while you can use -webkit-appearance/-moz-appearance to override the style for the part that is initially displayed, there doesn't seem to be any way to restyle the part that drops down. In that case, you'll need to go the route of creating a fake select menu with JavaScript and inserted HTML elements, and hoping you cover all the abovementioned use cases.
An example of this latter approach that our team has begun using is Felix Nagel's selectmenu jQuery UI plugin.

A: here is little tip how you might do it.
idea is to hide arroes with owerflow:hidden; div.
<style>
div{
    float:left;
    width:90px;
    height:100px;
    overflow:hidden;
}
select
{
    float:left;
    width: 3.2em;
    height: 1.5em;
    background-color: #3CB23C;
    margin-left:-8px;

    text-align: center;
    color: #fff;
    font-weight: bold;
    font-size: 4em;
}
</style>
<div>
    <select>
        <optgroup label="Server-side languages">
        <option>21</option>
        <option>22</option>
        </optgroup>
        <optgroup label="Client-side languages">
        <option>23</option>
        <option>25</option>
        </optgroup>
    </select>
</div>


text:
Q: Error compiling the io programming language I'm trying to compile io but it's failing and I can't understand why. Here's what I did to compile it:
mkdir build && cd build
cmake ..
make

Here's a gist of output from cmake
Which seems fine but when I run make (gist of the output)
it fails with something to do with python: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
I've also tried installing with Homebrew.
I'm running Mac OS 10.6.7.
How could I get io to compile (it seems a great language and I'd really like to start using it)?

A: Looking at your make log then this line could the the cause:

In file included from /Library/Frameworks/Python.framework/Headers/Python.h:57

I don't have that file here (or in my ~/Library/Frameworks/ and Io compiles successfully for me.
So perhaps you are using a different version of Xcode (I'm using 3.2.6 64 bit) or you have installed some Python Xcode stuff?  Whatever the difference it looks like the Io build doesn't quite like this (yet).
If you not concerned about having the Python bridge addon then I think you can just delete it (rm -r io/addons/Python) and rebuild your source.


text:
Q: Track a particular row of a table of webclient page which has no unique id and this table keeps populating datas concurrently I'm working with web client-GUI-automation testing tool development using selenium-x path-css.
With this webclient, it has a panel area at the lower panel.
Within this panel is a table which has no unique id for its row.
Scenario: When I add a VM through webclient-GUI,  on clicking finish button, this lower panel area's table list at its first row that the task has started with
td: taskname, date, target  in its row[1] of a table.
In this case if a single task is happening, then this table would have only one row.
So that i can check as
   tr[1]td[1] = "Create_Vm" and confirm that the task has started.
But if multiple VM's say:3(vm1,vm2, vm3) are created concurrently, then the table would have
tr[1]td[1]
tr[2]td[1]
tr[3]td[1]

*

*All to be create_vm.

My problem is how do I track a particular task say:vm2 using selenium-xpath-css as there is no unique id for table rowid?

A: If let's say VM name is in the first column and your desired webelement is in the second column. You can do something like this.
//*[contains(text(),'vm2')]../../td[2]

Find out your column using contains text and then go to it's parent node. And then to your desired column.

A: if the items are displayed in the order they are started, then do this:
//table//tr[x+1]/td[1]
if in reverse then:
//table//tr[position()=last()+1-x]/td[1]
where x is the vm number.


text:
Q: Twitter Boostrap - getting alert message to stick to the top of the page I've been trying to get bootstrap's alerts messages to stick to the top like the navbar component but no success.
First, the context:
I'm sending an ajax request through jQuery and then process the response. This part of the idea is complete. All I need to do now is to know how to make an alert message appear at the top of the page right under the navbar that is fixed to the top thanks to bootstrap's navbars. I've tried many things with the affix classes but still can't do it.
Here's where I try to create a div element behaving like the alert message:
success:function(msg) {
    if (msg == "fail") {
        $('body').append('
<button type="button" class="close" data-dismiss="alert">×</button>Error ! You can\'t specify a closed status if status is not set as "closed"
');
    }
}

So I know for sure this works since the alert message is added but... at the bottom of the page. I want it to be like 5 pixels under the navbar component but can't make this work.
Any idea what I need to set to make this work?

A: If you want an element inserted before all other elements use .prepend(). this inserts the object as the first child instead of as the last like .append():
success:function(msg) {
    if (msg == "fail") {
        $('body').prepend('
...
');
    }
}

that gets it at the top of the page, then it'll be up to you to make sure it's where you want it thereafter.
Also, I would also look at either using a templating system or build your object using jQuery and avoid long string insertions (though I suppose this may be personal preference).

A: You should append it but to the navbar element.
success:function(msg) {
    if (msg == "fail") {
        $('.navbar').append('
<button type="button" class="close" data-dismiss="alert">×</button>Error ! You can\'t specify a closed status if status is not set as "closed"
');
    }
}

A: you can make a div before the nav bar

                Success

...

then from the JS you can call
 $("#dvmsg").fadeIn().fadeOut(1000);


text:
Q: ng-value dont work on select with ng-options I use this controller to make Years value in ng-options select:
    $http.post('http://www.lavorirapidi.it/app/include/profilo.asp?username='+username+'&id='+user_id)
    .success(function(data){
        $scope.profilo = data;
        $scope.nome = username;
        })
    .error(function(){alert("Errore di comunicazione!")});

$scope.totalyears = 100;
$scope.years = [];
var currentYear = new Date().getFullYear();
    for (var i = currentYear; i > currentYear - $scope.totalyears; i--) {
    $scope.years.push(i - 1);
    }

and this is the html:
        <select class="form-control" ng-model="profilo.anno" ng-options="o for o in years" ng-value="profilo.anno">
          <option value="YYYY">YYYY</option>
        </select>

But I notice that if the ng-value exist (for example is 1999), is not set on the select menu!
Where is the problem?!
EDIT
I think my problem is in the controller!

A: try this : link
Controller code:
 $scope.totalyears = 100;
    $scope.profilo = {anno:2013};
    $scope.years = [];
        var currentYear = new Date().getFullYear();
        for (var i = currentYear; i > currentYear - $scope.totalyears; i--) {
        $scope.years.push(i - 1);

    }


text:
Q: GQL query with numeric id in datastore viewer I want to build GQL query to get an object using its numeric id. I'm doing this in Datastore viewer in App management console, so I can't use Model.get_by_id(numeric_id). Something like
SELECT * FROM Model WHERE id = <numeric_id>

also doesn't work.

A: Try this:
SELECT * FROM Model where __key__ = KEY('Model', <numeric_id>)

A: Unfortunately, there does not appear to be a way to write a query equivalent to
SELECT * FROM Model WHERE id = <numeric_id>

which would select all Model entities with the given id. If you're ok with something equivalent to
SELECT * FROM Model WHERE id = <numeric_id> AND parent IS NULL

you can use something like
SELECT * FROM Model where __key__ = KEY('Model', <numeric_id>)

If your entity does have a parent though, you'll need to specify that as part of the key, like
SELECT * FROM Model where __key__ = KEY('ParentModel', <parent_name_or_id>, 'Model', <numeric_id>)

If the parent itself has a parent, you'll need to specify that too. (Grandparent goes left of the parent, and so on.)
Of course if you're not restricted to GQL (like if you're using Python, Go, or Java), you can query the keys, decode them and filter by id, then fetch the corresponding entities. But of course that doesn't work in the Datastore Viewer since you can only use GQL.

A: Another way around is, first get the key for the entity using the id by
key = db.Key.from_path('Model', int(id))

then get the object by
obj = db.get(key)

The advantage is, you do not have to do any string formatting.
reference: problem set 3 at this course, https://classroom.udacity.com/courses/cs253/

A: I was getting this error:

GQL Query error: Encountered ... at line 1, column 42. Was expecting
  one of: UNQUOTED_NAME ... QUOTED_NAME ..."

It turns out that in the Google AppEngine datastore developer's admin console, you should drop the quotes and use something like this:
SELECT * FROM MyEntity WHERE __key__ = Key(MyEntity, 5695872079757312)

A: In my case I had to change the type of ID from String to Long


text: Q: How long was Rey training with Luke? I was talking with some of my friends and we all had very different opinions on how long Rey was on the island with Luke. Is there a definitive answer anywhere, or context in the film that I may have missed that hints to how long this training is? Even though it runs parallel to some scenes with the resistance, it seems likely that Rey was on the island before those scenes started, since we see them sleep multiple times while the resistance scenes appear to be much faster.


text:
Q: Issues of Spark Structured Streaming on Kubernetes I got warnings and errors when I run Structured Streaming on K8s cluster. Here are part of my codes:
  val df = spark
    .readStream
    .format("kafka")
    .option("kafka.bootstrap.servers", brokerServers)
    .option("subscribe", topicName)
    .load()

  val query = df.writeStream
    .outputMode("append")
    .foreachBatch((batchDF: DataFrame, batchId: Long) => {

      val rstDF = batchDF.select($"value")
        .map(row => valueDeserializer.deserialize(topicName, row.getAs[Array[Byte]]("value"), topicValueAvroSchema).toString)
        .transform(runner.spark.read.json)
        .transform(trimDF)

      println(s"Batch $batchId: ${rstDF.count} rows")
      rstDF.show(false)

    })
    .trigger(Trigger.ProcessingTime("120 seconds"))
    .start()

  query.awaitTermination()

The first batch (batch 0) is OK. However, when data arrived for batch 1, I got warnings about task lost due to java.lang.NullPointerException.
...
19/10/12 02:02:18 ERROR TaskSetManager: Task 0 in stage 2.0 failed 4 times; aborting job
...
19/10/12 02:02:18 INFO DAGScheduler: ResultStage 2 (start at MergeKafkaToDelta.scala:124) failed in 17.980 s due to Job aborted due to stage failure: Task 0 in stage 2.0 failed 4 times, most recent failure: Lost task 0.3 in stage 2.0 (TID 4, 172.30.170.218, executor 3): java.lang.NullPointerException
...
19/10/12 02:02:18 ERROR MicroBatchExecution: Query [id = e1f15e44-ad17-452d-97cf-def26f729f38, runId = c0b7c2ba-fca4-4538-8095-cbe2daeec525] terminated with error
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 2.0 failed 4 times, most recent failure: Lost task 0.3 in stage 2.0 (TID 4, 172.30.170.218, executor 3): java.lang.NullPointerException
...

Do you know its root cause? How could I setup configurations and parameters for spark-submit? I got a blog related to it: Spark Streaming Checkpointing on Kubernetes
However, it is based on specific Cloud platform. :-( Do you know general solutions?

A: Seem like spark-on-k8s-operator is a solution: Spark Structured Streaming Applications on Kubernetes. And there is a new version for spark 2.4.4: spark-on-k8s-operator
So I'm working on it and try to work out an example for Structured Streaming.


text:
Q: how to calculate multiple average froma python list ['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952', '1056.394859', '3010.609563', '2421.437603', '4619.861889', '746.040504', '268.3881793', '379.3934898', '1252.527752', '11459.88522', '4862.167506', '506.924289', '634.6737389', '496.4679199', '17941.59143', '919.4998935', '7247.610974', '1166.053214', '47360.91508', '855.2426137', '4020.444585', '4469.896904', '2615.874982', '19862.92009', '2379.619573', '1203.268956', '4399.589212', '6838.825864', '1848.407564', '3527.198403', '33976.85042', '818.8722263', '634.6652078', '469.2685928', '4864.830004', '5103.222941', '1011.239929', '829.9915382', '8571.237936', '3301.953656', '14594.47385', '25688.83822', '4024.393045', '4163.775185', '1775.894366', '3682.012227', '3371.092883', '6651.509488', '7906.092773', '7297.133447', 'end', '4566.874299', 'end', '4255.700077', '1857.648393', '11289.48095', '2070.981805', '1817.505094', '1892.256615', '1757.0048', '59458.46328', '778.5755201', '54987.32423', '2245.172711', '722.2619663', '5116.616632', '3427.865861', '17973.07118', '14398.74281', '66313.92115', '11585.24151', '45294.03043', '6524.744077', '25958.80015', '593.3786209', '2899.040703', '85577.21342', '153576.2633', '5852.008444', '563.0265409', '70796.45356', '565.2123689', '6560.030116', '2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639', '346.5905371', 'end']
I would like to create a function that, given a bin, which is a list (example above), generates averages for the numbers separated by a string 'end'. I am expecting to have 4 averages from the above bin, since there are 4 sets of numbers separated by 4 'end' strings
can someone help me fix my code below which does not seem to work:
def average(bin):
    total = 0.0
    count=0
    for number in bin:
        if number==float(number):
            total += float(number)
            count+=1
            avg = total/count
        elif number=='end':
            continue

    return avg

A: def averages(bin):
    li, s, n = [], 0, 0
    for item in bin:
        if item == 'end':
            li.append(s / n)
            s, n = 0, 0
        else:
            s += float(item)
            n += 1
    return li

Or, you can try this one-liner:
    averages = [sum(k) / len(k) for k in [[float(j) for j in i.split() if j] for i in ' '.join(bin).split('end') if i]]

A: Here's a really concise way to compute these averages:
def average(bin):
    start = 0
    while 'end' in bin[start:]:
        stop = bin.index('end', start)
        if stop > start:
            print sum(map(float, bin[start:stop])) / (stop-start)
        start = stop+1

If you want to keep track of your averages, you can store them and return them at the end of the function:
def average(bin):
    results = []
    start = 0
    while 'end' in bin[start:]:
        stop = bin.index('end', start)
        if stop > start:
            results.append(sum(map(float, bin[start:stop])) / (stop-start))
        start = stop+1
    return results

The line "if stop > start:" will prevent a ZeroDivisionError if you have two 'end' markers in a row in your input.
For even more Python magic, you can replace print with yield and your function will become a generator:
def average(bin):
    start = 0
    while 'end' in bin[start:]:
        stop = bin.index('end', start)
        if stop > start:
            yield sum(map(float, bin[start:stop])) / (stop-start)
        start = stop+1

for a in average(bin):
    print a

A: Your code doesn't work because you are overwriting avg on each pass through the loop. You will need to store the value of avg for each set as a list, or something. You also need to reset count and total whenever you come across an end. Try this:
def average(bin):
    total = 0.0
    count=0
    avgs = []
    for number in bin:
        if number == 'end':
            avgs.append(avg)
            total = 0.0
            count = 0
        else:
            total += float(number)
            count+=1
            avg = total/count

    return avgs

Note there are better ways to accomplish your goal, but in the interest of understanding I tried to make as few changes to your code as possible.

A: Here's a solution (inspired by the others) which also gives the mean of empty sets (NaN) instead of ignoring them.
def average(bin):
  start=0
  o=[]
  while 'end' in bin[start:]:
    stop = bin.index('end',start)
    s=1.0/(stop-start) if stop>start else float('nan')
    o.append(s*(sum(map(float, bin[start:stop]))))
    start=stop+1
  return o

and the corresponding one liner (based on the one by Cornett) is:
[sum(k) / len(k) if k else float('nan') for k in [
 [float(j) for j in i.split() if j] for i in ' '.join(bin).split('end') if i]]


text:
Q: How to iterate through unicode characters and print them on the screen with printf in C? I want to iterate through all (at least the 16 bit) unicode characters and print them on the screen with C.
I know there are related questions on SO but they don't solve the problem with printf in C, but this is what I want to achieve, if it's possible after all. I think it should be possible maybe with a trick I'm not aware of.
Since I want to use printf, I thought about something like this:
for (int i = 0x0000; i <= 0xffff; i++) {

    //then somehow increment the string
    char str[] = "\u25A1\n";
    printf("%s", str);

    char str[] = "\u25A2\n";
    printf("%s", str);

    char str[] = "\u25A3\n";
    printf("%s", str);

    ...

}

But it's a bit of a problem to increment the unicode code point, here \u25A1. I'm aware it's not possible per se because some characters like \u0000 are not printable and the compiler says no. But apart from that, how could I increment from hexadecimal 0000 to ffff and print the character with printf.

A: If the __STDC_ISO_10646__ macro is defined, wide characters correspond to Unicode codepoints. So, assuming a locale that can represent the characters you are interested in, you can just printf() wide characters via the %lc format conversion:
#include <stdio.h>
#include <locale.h>

#ifndef __STDC_ISO_10646__
#error "Oops, our wide chars are not Unicode codepoints, sorry!"
#endif
int main()
{
        int i;
        setlocale(LC_ALL, "");

        for (i = 0; i < 0xffff; i++) {
                printf("%x - %lc\n", i, i);
        }

        return 0;
}

A: In C99, you can use wide character to multibyte character conversion functions wctomb() or wcrtomb() to convert each code point to a local representation, using the current character set. (The code points are in the current character set, not Unicode.) Remember to use setlocale() to ensure conversion functions are aware of the user locale (most importantly, the current character set used). The conversion functions use the LC_CTYPE category, but you should still use setlocale(LC_ALL, ""); as for any other locale-aware program.
(Not all systems have the C.UTF-8 locale installed, so I do not recommend trying to override the locale to the standard C with UTF-8 using setlocale(LC_ALL, "C.UTF-8");. It works on some systems, but not all. AFAIK it does not work in Fedora-based Linux distributions, for example.)
Because you want to output all Unicode code points, I suggest a different approach: Use one of the Universal Character Set Transformation Formats, i.e. UTF-8, UTF-16 (UCS-2 was superseded by UTF-16 in 1996), or UTF-32 (also known as UCS-4). UTF-8 is the one most often used on the Web -- in particular, on this very web page you're looking at right now -- and is very easy to use.
For further reading on why you should prefer UTF-8 over "native wide strings", see utf8everywhere.org.
If you want truly portable code, you can use this header file, utf8.h, to convert UTF-8 to unicode code points (utf8_to_code()) and Unicode code points to UTF-8 (code_to_utf8()):
#ifndef   UTF8_H
#define   UTF8_H
#include <stdlib.h>
#include <errno.h>

#define   UTF8_MAXLEN 6

static size_t utf8_to_code(const unsigned char *const buffer, unsigned int *const codeptr)
{
    if (!buffer) {
        errno = EINVAL;
        return 0;
    }

    if (*buffer == 0U) {
        errno = 0;
        return 0;
    }

    if (*buffer < 128U) {
        if (codeptr)
            *codeptr = buffer[0];
        return 1;
    }

    if (*buffer < 192U) {
        errno = EILSEQ;
        return 0;
    }

    if (*buffer < 224U) {
        if (buffer[1] >= 128U && buffer[1] < 192U)
            return ((buffer[0] - 192U) << 6U)
                 |  (buffer[1] - 128U);
        errno = EILSEQ;
        return 0;
    }

    if (*buffer < 240U) {
        if (buffer[1] >= 128U && buffer[1] < 192U &&
            buffer[2] >= 128U && buffer[2] < 192U)
            return ((buffer[0] - 224U) << 12U)
                 | ((buffer[1] - 128U) << 6U)
                 |  (buffer[2] - 128U);
        errno = EILSEQ;
        return 0;
    }

    if (*buffer < 248U) {
        if (buffer[1] >= 128U && buffer[1] < 192U &&
            buffer[2] >= 128U && buffer[2] < 192U &&
            buffer[3] >= 128U && buffer[3] < 192U)
            return ((buffer[0] - 240U) << 18U)
                 | ((buffer[1] - 128U) << 12U)
                 | ((buffer[2] - 128U) << 6U)
                 |  (buffer[3] - 128U);
        errno = EILSEQ;
        return 0;
    }

    if (*buffer < 252U) {
        if (buffer[1] >= 128U && buffer[1] < 192U &&
            buffer[2] >= 128U && buffer[2] < 192U &&
            buffer[3] >= 128U && buffer[3] < 192U &&
            buffer[4] >= 128U && buffer[4] < 192U)
            return ((buffer[0] - 248U) << 24U)
                 | ((buffer[1] - 128U) << 18U)
                 | ((buffer[2] - 128U) << 12U)
                 | ((buffer[3] - 128U) << 6U)
                 |  (buffer[4] - 128U);
        errno = EILSEQ;
        return 0;
    }

    if (*buffer < 254U) {
        if (buffer[1] >= 128U && buffer[1] < 192U &&
            buffer[2] >= 128U && buffer[2] < 192U &&
            buffer[3] >= 128U && buffer[3] < 192U &&
            buffer[4] >= 128U && buffer[4] < 192U &&
            buffer[5] >= 128U && buffer[5] < 192U)
            return ((buffer[0] - 252U) << 30U)
                 | ((buffer[1] - 128U) << 24U)
                 | ((buffer[2] - 128U) << 18U)
                 | ((buffer[3] - 128U) << 12U)
                 | ((buffer[4] - 128U) << 6U)
                 |  (buffer[5] - 128U);
        errno = EILSEQ;
        return 0;
    }

    errno = EILSEQ;
    return 0;
}

static size_t code_to_utf8(unsigned char *const buffer, const unsigned int code)
{
    if (code < 128U) {
        buffer[0] = code;
        return 1;
    }
    if (code < 2048U) {
        buffer[0] = 0xC0U | (code >> 6U);
        buffer[1] = 0x80U | (code & 0x3FU);
        return 2;
    }
    if (code < 65536) {
        buffer[0] = 0xE0U | (code >> 12U);
        buffer[1] = 0x80U | ((code >> 6U) & 0x3FU);
        buffer[2] = 0x80U | (code & 0x3FU);
        return 3;
    }
    if (code < 2097152U) {
        buffer[0] = 0xF0U | (code >> 18U);
        buffer[1] = 0x80U | ((code >> 12U) & 0x3FU);
        buffer[2] = 0x80U | ((code >> 6U) & 0x3FU);
        buffer[3] = 0x80U | (code & 0x3FU);
        return 4;
    }
    if (code < 67108864U) {
        buffer[0] = 0xF8U | (code >> 24U);
        buffer[1] = 0x80U | ((code >> 18U) & 0x3FU);
        buffer[2] = 0x80U | ((code >> 12U) & 0x3FU);
        buffer[3] = 0x80U | ((code >> 6U) & 0x3FU);
        buffer[4] = 0x80U | (code & 0x3FU);
        return 5;
    }
    if (code <= 2147483647U) {
        buffer[0] = 0xFCU | (code >> 30U);
        buffer[1] = 0x80U | ((code >> 24U) & 0x3FU);
        buffer[2] = 0x80U | ((code >> 18U) & 0x3FU);
        buffer[3] = 0x80U | ((code >> 12U) & 0x3FU);
        buffer[4] = 0x80U | ((code >> 6U) & 0x3FU);
        buffer[5] = 0x80U | (code & 0x3FU);
        return 6;
    }
    errno = EINVAL;
    return 0;
}

#endif /* UTF8_H */

It is not fast, but it should be easy to understand, and supports all possible Unicode code points (U+0000 to U+10FFFF, inclusive), on all systems with at least 32-bit unsigned ints. On systems with 16-bit unsigned ints, your compiler may warn about unreachable code, and it'll only support the first 65536 code points (U+0000 to U+FFFF).
Using above utf8.h, you can easily write a C program that outputs a HTML page containing the Unicode characters you want (excluding control characters U+0000-U+001F and U+007F-U+00BF, inclusive, and invalid code points U+D800-U+DFFF, inclusive). For example, page.c:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "utf8.h"

int main(void)
{
    unsigned char  ch[UTF8_MAXLEN + 1];
    unsigned int   i;
    const char    *str;
    size_t         n, len;

    /* HTML5 DOCTYPE */
    printf("<!DOCTYPE html>\n");
    printf("\n");

    /* Header part. */
    printf(" \n");
    printf("  <title> Unicode character list </title>\n");
    printf("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
    printf("  \n");
    printf(" \n");

    /* Body part. */
    printf(" \n");

    n = 0;
    for (i = 0U; i <= 0xFFFFU; i++) {

        /* Skip Unicode control characters. */
        if ((i >= 0U && i <= 31U) ||
            (i >= 127U && i <= 159U))
            continue;

        /* Skip invalid Unicode code points. */
        if (i >= 0xD800U && i <= 0xDFFFU)
            continue;

        len = code_to_utf8(ch, i);
        if (len > 0) {
            ch[len] = '\0';

            /* HTML does not like " & < > */
            if (i == 32U)
                str = " ";
            else
            if (i == 34U)
                str = """;
            else
            if (i == 38U)
                str = "&";
            else
            if (i == 60U)
                str = "<";
            else
            if (i == 62U)
                str = ">";
            else
                str = (const char *)ch;

            if (n & 1) {
            printf("
", i, i, str);
                printf("U+%04X", i);
                printf(" %s", str);
                printf("
\n");
            } else {
                printf("
", i, i, str);
                printf("U+%04X", i);
                printf(" %s", str);
                printf("
\n");
            }

            n++;
        }
    }

    printf(" \n");
    printf("\n");

    return EXIT_SUCCESS;
}

Redirect the output to a file, and you can open the file in whatever browser you prefer. If your browser is sane, and does not treat local files any different to those it obtains from a web server, then you should see the correct output.
(If you see multiple characters per code point after U+00A0, your browser has decided that because the file is local, it is using a different character set that it explicitly states it uses. Switch to a sane browser if that happens, or override the character set selection.)
If you want, you can just print the codes out as UTF-8 text, say using text.c:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "utf8.h"

int main(void)
{
    unsigned char  ch[UTF8_MAXLEN + 1];
    unsigned int   i;
    size_t         len;

    for (i = 0U; i <= 0xFFFFU; i++) {

        /* Skip Unicode control characters. */
        if ((i >= 0U && i <= 31U) ||
            (i >= 127U && i <= 159U))
            continue;

        /* Skip invalid Unicode code points. */
        if (i >= 0xD800U && i <= 0xDFFFU)
            continue;

        len = code_to_utf8(ch, i);
        if (len > 0) {
            ch[len] = '\0';
            printf("U+%04X %s \n", i, ch);
        }
    }

    return EXIT_SUCCESS;
}

but then you must either be sure your terminal or terminal emulator supports UTF-8 and uses an UTF-8 locale, or you redirect the output to a text file and open that file in an editor which either assumes the file uses UTF-8 or lets you explicitly select the UTF-8 character set.
Note that there is a space before and after each character. Because some of the code points are combining characters, they may not show up at all unless they can be combined with another character, and most (all?) combine with space just fine.
If you use Windows, then you must conform to Microsoft stupidity, and add a special "byte order mark" -- printf("\xEF\xBB\xBF"); -- to the beginning of the output, so that its utilities like Notepad recognizes the file as UTF-8. It's a Windows-only wart, and treat it as such.
Questions?

A: The function to convert a 16-bit Unicode codepoint to a multibyte character sequence is c16rtomb; there is also c32rtomb if you want to handle 32-bit codepoints:
#include <uchar.h>

mbstate_t ps;
char buf[MB_CUR_MAX];
size_t bytes = c16rtomb(buf, i, &ps);
if (bytes != (size_t) -1) {
  printf("%.*s\n", bytes, buf);
}

If c16rtomb is not available you will need to use platform-specific facilities.

A: I would go for something like this (using raw UTF-8 encoding):
char unicode[3] = { 0x00, 0x00, 0x00 };
for(size_t i=0; i<0xffff; i++)
{
    printf("%s\n", unicode);
    uint16_t * code = &unicode[0];
    *code = *code +1;
}

*

*Define a string on 3 bytes, the last one is the NULL terminating byte allowing a display via printf

*Consider the two first bytes as your 16-bit unicode and increment it on each loop

Of course it can be optimized as:

*

*Many characters won't be displayable

*The cast char* -> uint16_t is not very elegant (triggers a warning)

*As there is 2 bytes for UTF-8 encoding it will actually browse 11 bits of codepoints. To get the 16 bits you might want to actually use uint32_t and define a 5 bytes char* buffer

[EDIT] As stated in the comment, this loop will actually generates a lot of invalid UTF-8 sequences.
Indeed, going from U+007F to U+0080 is a +1 for code points but in UTF-8 you jump from 0x7F to 0xC280: you need to exclude some ranges in the loop.


text:
Q: Hyperstack deployment problem: No such file to load -- models/application_record.rb (LoadError) I am using hyperstack version 1.0.alpha1.4
My app works fine in development, but when I try to deploy it in production mode, I get the following error:
       /app/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:33:in `require': No such file to load -- models/application_record.rb (LoadError)
        from /app/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `block in require'
        from /app/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:257:in `load_dependency'
        from /app/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `require'
        from /app/app/models/application_record.rb:5:in `<top (required)>'
...

How can I solve this? Thank you in advance.

A: Hyperstack places an application_record.rb file under app/hyperstack/models/
with contnets:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
  regulate_scope all: true
end

but also requires an application_record.rb under app/models with the following contents:
# app/models/application_record.rb
# the presence of this file prevents rails migrations from recreating application_record.rb
# see https://github.com/rails/rails/issues/29407

require 'models/application_record.rb'

do these files exist?
also the main difference between production and development is that during development auto loading work but in production assets must be precompiled.
did you miss this step?


text:
Q: When MATCHing to CREATE a node1-[relationship]->node2 set a default node2 (end node) if it doesn't exist If I was doing something like:
OPTIONAL MATCH (start: {id: "1"})

OPTIONAL MATCH (end: {id: "2"})

CREATE start-[myRelationship:MyRelationshipType { title: "foobar" }]->end

If 'end' is null (i.e. it was not found) I want to make end a default node.
I'm loading data from a CSV so this would let me easily identify all the connections that couldn't be formed because of missing end nodes (all nodes that are in the csvs are created before the above, where i'm only trying to setup relationships).
It's a bit of a doozy, any ideas?
@MagnusVortex and I were looking at doing a MERGE but really I feel like i want some kind of conditional (if end IS NULL { end = MATCH {id:"my_default_node"})... something like that

A: [EDITED]
If you want to create a (unique) relationship from an existing start node to an existing end node (or, if the latter does not exist, to a default node):
MATCH (start{ id: "1" }), (default {id:"my_default_node"})
OPTIONAL MATCH (end {id: "2"})
WITH start, CASE WHEN end IS NULL THEN [default] ELSE [end] END AS todo
FOREACH (x IN todo | CREATE UNIQUE (start)-[:MyRelationshipType { title: "foobar"}]->(x));

This query does nothing if the start or deafult nodes are not found. Also, if the start node already has an appropriate relationship, this query will make no DB updates.
Original answer
If you want to create a (unique) relationship from an existing start node to an end node (that is created if it does not already exist):
MATCH (start{ id: "1" })
CREATE UNIQUE (start)-[myRelationship:MyRelationshipType { title: "foobar" }]->(end {id: "2"});

This query does nothing if the start node is not found. Also, if the start node already has a matching relationship (to a matching end node), this query will make no DB updates.
Less performant solution
As a point of interest, the following query produces the same results (but its profile shows it is much more complex to execute, and probably requires more DB hits):
MATCH (start { id: "1" })
MERGE (end { id: "2" })
MERGE (start)-[myRelationship:MyRelationshipType { title: "foobar" }]->(end);


text:
Q: boost serialization of opaque types I want to be able to serialize a Windows HANDLE:
typedef void *HANDLE

If I try to compile using following:
struct Foo
{
    HANDLE file;

protected:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int /*version*/)
    {
        ar & file;
    }
};

I get compile errors:
c:\projects\3rdparty\src\boost\include\boost/mpl/print.hpp(51) : warning C4308: negative integral constant converted to unsigned type
        c:\projects\3rdparty\src\boost\include\boost/serialization/static_warning.hpp(92) : see reference to class template instantiation 'boost::mpl::print<T>' being compiled
        with
        [
            T=boost::serialization::BOOST_SERIALIZATION_STATIC_WARNING_LINE<98>
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/check.hpp(98) : see reference to class template instantiation 'boost::serialization::static_warning_test<B,L>' being compiled
        with
        [
            B=false,
            L=98
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/oserializer.hpp(313) : see reference to
function template instantiation 'void boost::archive::detail::check_object_tracking<T>(void)' being compiled
        with
        [
            T=Foo
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/oserializer.hpp(525) : see reference to
function template instantiation 'void boost::archive::detail::save_non_pointer_type<Archive>::invoke<T>(Archive &,T &)' being compiled
        with
        [
            Archive=boost::archive::text_oarchive,
            T=Foo
        ]

But if I change file to an int, everything is fine.
How do I tell boost to serialize HANDLEs as ints?
Thanks

A: HANDLE is a Windows-API-specific data type defined in winnt.h. According to the MSDN,

A handle to an object.
  This type is declared in WinNT.h as follows:
typedef PVOID HANDLE;

So, now we see that HANDLE is really just void * -- representing a handle to an object. Think about what it is that you're trying to do; does it make sense to serialize a pointer to some object in the Windows API?
Instead, try to serialize what it takes to retrieve an equivalent HANDLE; judging by the name of the member, I'm going to guess you used CreateFile -- so, you'll need to know...

*

*The file name

*The desired access (e.g. GENERIC_READ | GENERIC_WRITE)

*The share mode (e.g. FILE_SHARE_DELETE)

*Optionally, the security attributes

*The creation disposition (i.e. CREATE_NEW, TRUNCATE_EXISTING, etc.)

*The file or device flags and attributes

*Optionally, a template file -- for copying its attributes when creating a file

Now, if you really don't want to be doing that -- you're positive you want the pointer value -- maybe try serializing it after casting via reinterpret_cast to std::intptr_t or std::uintptr_t (as might be defined in cstdint as of C++11).
ar & reinterpret_cast<std::intptr_t>(file);

... then you should couple this with something as follows (when deserializing):
std::intptr_t _file;
ar & _file;
HANDLE file = std::reinterpret_cast<HANDLE>(_file);

A: Ended up solving the problem by splitting the serialization. Seems like a hack though:
struct Foo
{
    HANDLE file;

protected:
    friend class boost::serialization::access;

    template<class Archive>
    void save(Archive & ar, const unsigned int /*version*/) const
    {
        unsigned int _file = reinterpret_cast<unsigned int>(file);
        ar & _file;
    }

    template<class Archive>
    void load(Archive & ar, const unsigned int /*version*/)
    {
        unsigned int _file;
        ar & _file;
        file = reinterpret_cast<HANDLE>(_file);
    }
    BOOST_SERIALIZATION_SPLIT_MEMBER()
};


text:
Q: How to implement ACL / role based authorization with angular 2? What is the best way to implement ACL / paper-based with angular 2?
My scenario, in a nutshell, is this: The roles are dynamic and are based on the permissions that the client can configure that can also be dynamic.
I need to prevent the user from having access to a particular resource that he is not authorized to do. For this I thought of using the concept of Guards of the Angular. With CanActivate Guard I could set whether to let the user pass or not, based on information I would put in each route. This information would be the name of the resource to which that route refers. When I got to the guard I could compare with his role and see if his role has access to this feature and whether or not to allow navigation.
But with that in could fall into two more problems:
1 - How to redirect the user to a resource that he has access to? Would I have to list the route files and look for someone who is compatible with his role and then redirect there?
2 - How to disable components that it can not see on pages that it can access? For example, it has access to the listing page X but it does not have access to create a new item, so I need to remove the Create Something button. Or rather, how to do this with divs elements that contains specific information for some roles but not for the role of it?
I would like to know how best to approach this scenario within the angular ecosystem.
Thanks for listening.

A: You can try to use ngx-permissions library for this. It supports, then, else syntax, lazy loading, isolated lazy loading. Add the library to the project:
@NgModule({

 imports: [
    NgxPermissionsModule.forRoot()
 ]
 })
 export class AppModule { }

Load Roles
NgxRolesService
 .addRole('ROLE_NAME', ['permissionNameA', 'permissionNameB'])

 NgxRolesService.addRole('Guest', () => {
  return this.sessionService.checkSession().toPromise();
 });

 NgxRolesService.addRole('Guest', () => {
     return true;
 });

use in templates

You can see this text congrats

protect Your Guard
const appRoutes: Routes = [
 { path: 'home',
component: HomeComponent,
canActivate: [NgxPermissionsGuard],
data: {
  permissions: {
    only: ['ADMIN', 'MODERATOR'],
    except: ['GUEST']
   }
  }
 },
];

For detail documentation checkout wiki page.

A: Check CASL, there are articles about integration in Vue and Aurelia but for Angular 2+ implementation should be very similar
The main idea that you can define abilities per user
import { AbilityBuilder } from 'casl'

// allow to read and create Todo-s for everybody and update for assignees
export default AbilityBuilder.define(can => {
  can(['read','create'], 'Todo')
  can(['update'], 'Todo', { assignee: user.id })
})

There is also an article in documentation about how to map abilities to different roles


text:
Q: Arduino Uno same frequency on ALL PWM pins I'm controlling a BLDC motor with an inverter/driver IC doing the switching work.
I need to provide 6 PWM signals for the driver all at the same frequency. The exact frequency doesn't really matter, as long as its between 5kHz to 10kHz and all the PWM pins are the same.
I'm currently using an Arduino Uno, I'm not sure how to program each PWM pin (3, 5, 6, 9, 10, 11) for all the same frequency as the timers(0, 1 and 2) for particular pins have different clock speeds.

*

*Pins 5 and 6: controlled by timer0, base frequency 62500Hz

*Pins 9 and 10: controlled by timer1, base frequency 31250Hz

*Pins 11 and 3: controlled by timer2, base frequency 31250Hz

timer1 and timer2 will be okay and can be scaled down by the prescaler value 8 (7812.5Hz). Not sure how to get timer0 to the same frequency?
http://playground.arduino.cc/Main/TimerPWMCheatsheet
I'm sure a work around is relatively simple. Is it possible to divide the frequency for timer0 by a number which is not a prescaler value, say 40?
Thanks in advance.
Pat.

A: You haven't included the chip number for your motor controller, but I'm pretty sure you won't be able to achieve what you want with six different timers. The issue is that the PWM on the different pins all have to be synchronized, not just toggled on and off for the right amount of time.
Instead, you should use a single timer and toggle all the outputs at the correct synchronization. This page has the start of an example in the section "Bit-banging Pulse Width Modulation". You would have to modify it to toggle more pins.
That example is probably still not good enough. Instead, you should be using an interrupt service routine to toggle the pins. That way, the PWM runs more independently and allows the loop function to do more.
Your routine will be attached to an output compare interrupt on a timer, and you will have to keep the values of the various PWM outputs in some volatile variables. The output compare register will be set to wake up for the next toggle. When the routine runs, it will perform the toggle and set the output compare register for the toggle. The details of the timing and synchronization will depend on the datasheet for your controller.
The loop function can read inputs and adjust the volatile variables to change the motor speed.
There are also motor drivers that do all this for you. All you have to do is provide a direction and speed, and the chip creates the 6 PWMs for you.


text:
Q: Extract data from Specific format CSV files Given such data format of one row in CSV file:
'data(g1),data(g1)','data(g2),data(g2),data(g2),,,',,,'data(g5),,,data(g5)',

This is in a CSV format, but for a separate group of data, it use
''

to group them, like:
.....'data(g2),data(g2),data(g2),,,'....

But there are such awkward situations: a row could miss some groups, and for a group, it could miss some fields. But for all the missing part, it still use a comma to separate them. So each row will always have 6 groups of data. Then how can I got all 6 groups of data properly(even it contains nothing)?
I try to use regular expression like this:
String row = <the above data row>;
String[] dataGroups = row.split(',');

But this one definitely will not work since in each group of data, it also use comma to separate data. Any effective ways in Java to doing this? It will be awesome if I can have all 6 groups of data stored in a
String[] dataGroups

which have a length of 6.
Then the rest part will be easy.

A: Hm. What about a regex like this?
('.*')?,('.*')?,('.*')?,('.*')?,('.*')?,('.*')?

It's ugly, but it may work correctly...
Per http://www.regular-expressions.info/java.html , you'd do something like this:
Matcher m = Pattern.compile("('.*')?,('.*')?,('.*')?,('.*')?,('.*')?,('.*')?").matcher(row);
m.find();
m.group(1); //gives you the first group on the line;
//change the index to get the other groups

You could then split each group with .split(',')
Here's a live version: http://regex101.com/r/jR0iM4/1

A: Is your file format reliable enough to have ' only as start and begin of data group? Then you could remove ' at beginning and end of row, then spilt row by ',' (three symbols) instead of just comma.

A: I think this becomes more of a sanitization issue. Does all the rows begin and start with single quote (').
If so, you can do the following:

*

*Get all the content within quotes via regex.

*Then for each row, split into columns by splitting on comma.

*Then record the split groups into List> where the external list are the rows and the nested lists are the columns.

*You could then adjust this with commas toward the end if the nested list is not of size 6.

In my opinion, this is cleaner to read and consume.

A: As per one of your comments, you need to parse this:
....,'data(gn),data(gn),subdata='datavalue',data(gn),,',.....

Only the CSV parser in uniVocity-parsers can parse that. Your input has unescaped quotes inside a quoted value. This will break any other CSV parsing library for Java (feel free to try).
What you have is similar to this:
something,"text with "unescaped quotes" here",something else

You want this as the output:
something
text with "escaped quotes" here
something else

You just need to throw your input into uniVocity-parsers' CSV parser
CsvParserSettings parserSettings =  new CsvParserSettings();
parserSettings.setParseUnescapedQuotes(true); //this is enabled by default

CsvParser parser = new CsvParser(parserSettings);
List<String[]> allRows = parser.parseAll(getReader("/examples/bean_test.csv"));

More details about this feature here.
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).


text:
Q: GeoKettle and scheduling transformations / jobs? Is there any possibility to schedule a transformation or job with GeoKettle?
I would like to perform the same task every day.

A: I'm not sure if it is possible, by using Spoon, you can view the steps here. In short, you will be able to set the task up for transformation and create a schedule to automate the tasks. Here are some visuals of the steps provided. I would imagine similar method may employed to work with GeoKettle.

In the Schedule a Transformation dialog box, enter the date and time that you want the schedule to begin in the Start area, or click the calendar icon (circled in red) to display the calendar. To run the transformation immediately, enable the Now radio button.

Set up the End date and time. If applicable, enable the No end radio button or click on the calendar and input the date and time to end the transformation.
If applicable, set up a recurrence under Repeat.
End date and time are disabled unless you select a recurrence. From the list of schedule options select the choice that is most appropriate: Run Once, Seconds, Minutes, Hourly, Daily, Weekly, Monthly, Yearly.
Make sure you set parameters, arguments and variables, if available. Click OK.
In the Spoon button bar, click the Schedule perspective.


text:
Q: How to check if text is visible with seleniumbase? Using seleniumbase I just want to check if some text is available. I just want to get a boolean flag, indicating text is available (True) or not (False).
The methods provided by seleniumbase seem to throw an exception if the text is not available. Is there another method that just returns a boolean flag, or do I have to use a try/except construct?

A: Just use self.is_text_visible():
self.is_text_visible(text, selector="html")

Eg:
self.is_text_visible("Welcome")
self.is_text_visible("Welcome", "h1")


text:
Q: A universal term for "educación básica y media" I'm writing my curriculum vitae in english, but attended school in Chile. In our education system we have "educación básica y media". Those are the first twelve years of formal education before the University. I'm struggling to find a good translation for this term. In particular I'm interested in finding a term that can be universally understandable, independent of the particular schooling system of different countries.

A: From all the given options, "Pre-University Schooling" is the one I like the most because of its universality.
This was previously posted as a comment.

A: I would recommend you write

"Completed Primary and Secondary Education (12 years) in [name of city], Chile."

This will be clearly understood by any English speaker.

A: Maybe it depends on which English-speaking country you're looking to use the CV in, but in the UK we have Primary (7-10) and Secondary (11-15) which I guess should be sufficient elsewhere, unless somebody else can say different?  We also use Further Education to refer to the period between Secondary (or High) school and University (referred to as Higher Education).  This isn't compulsory, but obviously universities will require those qualifications in order to gain entry.


text:
Q: O que é e como se usa reentrância? A algum tempo atrás ouvi falarem de aplicações que usam uma tecnologia/técnica chamada reentrância, mas o que é exatamente a reentrância e como eu poderia adicionar isso em uma aplicação?

A: Um código reentrante é um código thread-safe e reutilizável por outros acessos, que independente de quem o acessou, se os parâmetros forem os mesmos, o resultado sempre será o mesmo. É válido para códigos que são compartilhados entre outros projetos, programas, threads, etc.
Em outras palavras, é um procedimento reutilizável pelo mesmo local que foi acessado. Ele funcionará em um thread dedicado a quem o acessou, sem deixar que outros processos, threads ou programas interfiram no resultado de outros threads.
Imagine este código:
static int y = 20;

int obterY() {
    y = y + 20;
    return y;
}

Em uma instância compartilhada, vários threads irão ter resultados diferentes, nunca conforme vão sendo chamados. Em acessos simultâneos isso pode ser um problema quando y está em memória compartilhada.
Imagine quando um procedimento chama obterY() esperando que venha 40 mas obtém 60, porque neste meio tempo uma outra thread modificou y.
Este é um exemplo de código não reentrante.
Veja um exemplo disso no .NET Fiddle. Dá pra reproduzir em outras linguagens, mas escolhi o C# para isso. Percebe que vários valores esperados (se não todos) estão incorretos com base no que receberão. Os valores incorretos estão marcados com (!!!) no começo.
static int y = 20;

int obterY() {
    lock(y) { // irá impedir que outros threads modifiquem y
        return y + 20; // y permanece 20
    }
}

Dessa forma, outros processos sempre receberão os valores esperados.
Veja funcionando no .NET Fiddle. Neste exemplo foi utilizado o lock para travar um objeto na execução daquele thread. Dessa forma, os outros threads terão que esperar terminar o bloco de bloqueio até que possam chamar.
Mas reentrância não se limita apenas à threading, mas também processos, armazenamento em arquivos, ou qualquer outra coisa que altere o resultado final de um algoritmo em que os parâmetros de entrada foram os mesmos.
É legal também ver o que é a condição de corrida.
Reentrância e Idempotência
Ambos não são a mesma coisa, por mais que parecidos. Idempotência é quando um procedimento vai sempre produzir o mesmo resultado, mesmo se for chamado várias vezes pelo mesmo lugar.
Um código compartilhado, ou reentrante, deve ser interpolável entre quem for usar e garantir que o resultado será o que o thread chamador esteja esperando.
Além disso, um código reentrante não pode se comunicar com códigos não reentrantes, pois isso também irá torna-lo não reentrante. Eles devem ser sincronizados, ou seja, uma modificação deve refletir os futuros resultados em igual, e não para apenas um processo/thread.
É difícil dizer ao que a reentrância se limita, se é threading, processos, usuários, etc., isso cabe a linguagem e ao procedimento especificar o que está sendo feito.


text:
Q: Azure Data Flow store SHA256 product in a SNOWFLAKE Binary field I am trying to store the output of this transformation: sha2(256,"Some value") into snowflake.
The target column is of type BINARY.
I am running into errors such as:
Binary value '6228F...' is too long and would be truncated.
and
string is not a legal hex encoded value.
What the correct conversion here to get the digest stored in a binary column?
Thanks
Stephen

A: toBinary(sha2(256,"my data"))
Check your BINARY field in snowflake is BINARY(64) not BINARY(16).


text:
Q: Realm won't save the variable/object once the application is closed. How do I fix this? I already have one Realm object working perfectly fine with the Realm. But, my Points object is not saving. When running the app on the Android emulator, clearing it from recents clears the points variable of the Points class. There is only one instance of Points throughout the entire application. I'll insert code of how I'm using Points below. I've also observed the variable updating in the Realm using Stetho with chrome, so it's definitely saving to the database.
MyApplication class where I initially create the object in Realm:
public class MyApplication extends Application {

static Realm realm;

@Override
public void onCreate() {
    super.onCreate();

    Realm.init(this);

    RealmConfiguration config = new RealmConfiguration.Builder()
            .name("chargerpoints.realm")
            .schemaVersion(1)
            .build();

    realm = Realm.getInstance(config);
    realm = Realm.getDefaultInstance();

    Points pts = realm.where(Points.class).findFirst();

    if(pts == null) {
        Points myPoints = new Points();
        myPoints.setId(1);
        myPoints.setPts(0);
        realm.beginTransaction();
        realm.copyToRealmOrUpdate(myPoints);
        realm.commitTransaction();
    }

MainActivity where I increment the points integer variable of myPoints object using a timer:
static int points;

Points myPoints;

Context context = this;

Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR_OF_DAY);

private Timer timer;
private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        if(hours > 7 && hours < 15){
            KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if (myKM.inKeyguardRestrictedInputMode()) {
                points++;
            } else {
                realm = Realm.getDefaultInstance();
                myPoints = realm.where(Points.class).findFirst();
                realm.beginTransaction();
                myPoints.setPts(points);
                realm.copyToRealmOrUpdate(myPoints);
                realm.commitTransaction();
            }
            displayPoints();
        }
    }
};

I have basically tried every possible combination and haven't come close to data persistency with the Points class so far. I already have another object working fine with Realm, so its confusing as to why this one wouldn't work. Thanks for the help!


text:
Q: How to ignore collation in mysql query I have got a field in mysql table with the type SET and collation latin general ci and i am querying like this
SELECT * FROM `tblCountry` WHERE FIND_IN_SET("KAN", `tLang`)

, It works fine in sqlyog, but in phpmyadmin it gives me error
#1267 - Illegal mix of collations (utf8_unicode_ci,COERCIBLE) and (latin1_general_ci,IMPLICIT) for operation 'find_in_set'

So how to ignore the collation type, is there any work around for this

A: SELECT  *
FROM    tblCoutnry
WHERE   FIND_IN_SET(CAST('KAN' AS CHAR CHARACTER SET latin1) COLLATE latin1_general_ci, tlang)


text:
Q: How to auto change background on flutter i was new on flutter coding and i'm still learning, i tried to coding the design i found in internet but now i'm stuck on how to make background change depend on what image in front of it.
the front image is like using carousel slider so it will change the image when i slide so i want make change it change the background image too corresponding the front image
here my source code:
class _MainCafeProfileState extends State<MainCafeProfile> {
  int _current = 0;
  final CarouselController _controller = CarouselController();
  final List<Widget> ImgList = [
    HeaderCafeProfileWidget(imageUrl: 'assets/images/images_equipment_1.png'),
    HeaderCafeProfileWidget(imageUrl: 'assets/images/images_equipment_2.png'),
    HeaderCafeProfileWidget(imageUrl: 'assets/images/images_equipment_1.png'),
  ];
  @override
  Widget HeaderImageCard() {
    return Align(
      alignment: Alignment.topCenter,
      child: Stack(
        children: [
          Column(
            children: [
              CarouselSlider(
                options: CarouselOptions(
                  initialPage: 0,
                  enableInfiniteScroll: false,
                  viewportFraction: 1,
                  height: 280,
                  onPageChanged: (index, reason) {
                    setState(() {
                      _current = index;
                    });
                  },
                ),
                items: ImgList,
              ),
              // SLIDER INDICATOR
              Container(
                transform: Matrix4.translationValues(0, -40, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: ImgList.asMap().entries.map((entry) {
                    return GestureDetector(
                      onTap: () => _controller.animateToPage(entry.key),
                      child: Container(
                        width: _current == entry.key ? 18 : 4,
                        height: 4,
                        margin: EdgeInsets.symmetric(
                            vertical: 8.0, horizontal: 4.0),
                        decoration: BoxDecoration(
                          color: whiteColor,
                          borderRadius: BorderRadius.all(
                            Radius.circular(2),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: whiteColor,
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.only(bottom: 8),
            width: double.infinity,
            height: 297,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/images_equipment_1.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: BackdropFilter(
              filter: ImageFilter.blur(
                sigmaX: 5,
                sigmaY: 5,
              ),
              child: Container(
                decoration: BoxDecoration(
                  color: Neutral10.withOpacity(0.2),
                ),
              ),
            ),
          ),
          SingleChildScrollView(
            child: Column(
              children: [
                // HeaderCafeProfile(),
                HeaderImageCard(),
                TitleCafeProfile(
                  title: 'Rivarno Kopi',
                  rating: 4.8,
                  price: '\$\$',
                ),
                MainContent(),
                ReviewCafeProfile(
                  imageUrl: 'assets/images/1.jpg',
                  title: 'A Review: Ancala Coffee & Bistro',
                  desc:
                      'Description container, where you can spoil about the review',
                ),
              ],
            ),
          ),
          BackButtonWidget(),
        ],
      ),
    );
  }
}

[]
i was try making the background change depend on the image front of it, so when the front image was slide the background image will change to
[]
[]

A: You can use the functionality of computeLuminance (Reference Here)
Or either,
Check this package Palette Generator


text:
Q: The difference between a YIELD statement and a GROUP combined YIELD clause in Nebula Graph FETCH PROP ON person "..." YIELD properties(person).name as name, properties(vertex).age as age
| GROUP BY $-.name YIELD $-.name, max($-.age) as max_age

FETCH PROP ON person "..." YIELD properties(person).name as name, properties(vertex).age as age
| YIELD $-.name, max($-.age) as max_age

As title, is there a difference between using the YIELD statement independently and the GROUP combination YIELD clause?

A: Equivalent syntax. The yield clause of native ngql supports both implicit and explicit groupby, where implicit groupby behavior is consistent with cypher standards. For details,see neo4j docs.


text:
Q: Category slug not showing on sitemap xml using Yoast plugin I have this problem in my sitemap.xml. I was wondering why in the list, the category slug is not present while in the dashboard permalink section, the URL is displaying its category link.
Here are some of the screenshots to further explain what I mean:

*

*So in the image below you can see the links of the products and the links don't have its category being set in the dashboard:

*Here is the screenshot showing what the links look like in the dashboard and what I expect the sitemap links to display:

Note: This sitemap is generated via Yoast SEO plugin version 4.8.

A: 1) Try to disable Cache plugins, or any plugins that might be related
2) Update related plugins (if they need) and also, you'd better update WordPress too (as seen in your screenshot, it needs update)
3) Regenerate Sitemap (update that page)
4) Check if fixed.
5) if so, then re-enable the above disabled plugins and then regenerate sitemap and see if it's broken again, then some plugin conflicts with it.


text:
Q: Error while import resource file Business Data Connectivity I am trying to use powershell for importing a resource file in Business Data Catalog but I keep getting the following error
Import-SPBusinessDataCatalogModel : The root element of a valid
Metadata package must be 'Model' in namespace
'http://schemas.microsoft.com/windows/2007/BusinessDataCatalog'. The root in the given package is 'Model' in namespace'http://schemas.microsoft.com/windows/2007/BusinessDataCatalog/Resources'.

Error was encountered at or just before Line: '2' and Position: '2'. At M:\PowerShell\ImportModel.ps1:13 char:35
+  Import-SPBusinessDataCatalogModel <<<<  -Path $file.FullName -Identity $bdc -force -ModelsIncluded -PropertiesIncluded -Verbose
+ CategoryInfo          : InvalidData: (Microsoft.Share...alogModelCmdlet:SPImportSPBusinessDataCatalogModelCmdlet)
[Impo     rt-SPBusinessDataCatalogModel], PackageFormatException
+ FullyQualifiedErrorId : Microsoft.SharePoint.BusinessData.SharedService.SPImportSPBusinessDataCatalogModelCmdlet

When I manualy import the resource file everything is ok.
This is the resource file i Use
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<Model xmlns="http://schemas.microsoft.com/windows/2007/BusinessDataCatalog/Resources" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="CZ.Sharepoint.BCS.Correspondentie.Zorg">
  <LobSystems>
    <LobSystem Name="Correspondentie">
      <Properties>
        <Property Name="WildcardCharacter" Type="System.String">%</Property>
      </Properties>
      <LobSystemInstances>
        <LobSystemInstance Name="Correspondentie">
          <Properties>
            <Property Name="AuthenticationMode" Type="System.String">PassThrough</Property>
            <Property Name="DatabaseAccessProvider" Type="System.String">SqlServer</Property>
            <Property Name="RdbConnection Data Source" Type="System.String">TSTSQL10</Property>
            <Property Name="RdbConnection Initial Catalog" Type="System.String">PRD_Correspondentie</Property>
            <Property Name="RdbConnection Integrated Security" Type="System.String">SSPI</Property>
            <Property Name="RdbConnection Pooling" Type="System.String">True</Property>
            <Property Name="ShowInSearchUI" Type="System.String"></Property>
          </Properties>
        </LobSystemInstance>
      </LobSystemInstances>
    </LobSystem>
  </LobSystems>
</Model>

And the powershell script
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$serviceContext = "http://localhost/"

$bdc = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType Catalog -ServiceContext $serviceContext
$pathtobdcmfiles = Get-Location
$importFiles = Get-Childitem -path $pathtobdcmfiles | Where {$_.extension -eq ".bdcr" -and $_.basename -ne "catalog"}

foreach ($file in $importFiles) {
 Import-SPBusinessDataCatalogModel -Path $file.FullName -Identity $bdc -force -ModelsIncluded -PropertiesIncluded -Verbose
 write-host $file.fullname
 }

A: The following script worked for me.  Im just importing properties but you could modify it to account for any other content contained in the resource file.
#imports the BCS resource file
function ConfigureBCSModel([string]$path)
{
    $results = $null;

    # open the settings file
    $data = Get-Content $path

    # link to the central admin web context
    $centralAdmin = (Get-spwebapplication -includecentraladministration | where {$_.IsAdministrationWebApplication} | select Url -First 1).Url

    #connect to the bdc service
    $bdc = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType Catalog -ServiceContext $centralAdmin

    #import the package
    $bdc.ImportPackage($data, [ref]$results, [Microsoft.SharePoint.BusinessData.Parser.PackageContents]::Properties)

    # write out the import setting values
    foreach($result in $results)
    {
        Write-Host "Setting Import message: " $result;
    }
}

A: The error message seems to have the answer.  Have you tried changing your xmlns?
xmlns="http://schemas.microsoft.com/windows/2007/BusinessDataCatalog/Resources"
to
xmlns="http://schemas.microsoft.com/windows/2007/BusinessDataCatalog"

A: MLF Answer is correct. (Can't use comments yet.)
You get the next error because you haven't specified the Type attribute in your LobSystem element.
Here is an example
http://msdn.microsoft.com/en-us/library/ff817559.aspx


text:
Q: vncserver not accessible using hostname in DISPLAY I have a vncserver running on a RHEL 6.8 box.  When I access this session via a VNC viewer, I notice that I cannot run x programs (like xterm) if I modify the DISPLAY variable to include the server's hostname.  For example:
[foo][/home/user]>echo $DISPLAY
:5.0
[foo][/home/user]>xhost +
access control disabled, clients can connect from any host
[foo][/home/user]>xterm

<xterm window opens - I type 'exit' in the xterm to close it>

[foo][/home/user]>hostname
foo.mydomain.com
[foo][/home/user]>export DISPLAY=foo.mydomain.com:5.0
[foo][/home/user]>xterm
xterm Xt error: Can't open display: foo.mydomain.com:5.0
[foo][/home/user]>xhost
xhost:  unable to open display "foo.mydomain.com:5.0"
[foo][home/user]

I can ping to myself using this hostname:
[foo][/home/user]>ping foo.mydomain.com
PING foo.mydomain.com (192.168.1.200) 56(84) bytes of data.
64 bytes from foo.mydomain.com (192.168.1.200): icmp_seq=1 ttl=64 time=0.026 ms
64 bytes from foo.mydomain.com (192.168.1.200): icmp_seq=2 ttl=64 time=0.027 ms
64 bytes from foo.mydomain.com (192.168.1.200): icmp_seq=3 ttl=64 time=0.029 ms

Here's the VNC entry in the process list:
user   22129     1  0 16:15 pts/70   00:00:22 /usr/bin/Xvnc :5 -desktop foo.mydomain.com:5 (user) -auth /home/user/.Xauthority -geometry 1270x1014 -rfbwait 30000 -rfbauth /home/user/.vnc/passwd -rfbport 5905 -fp catalogue:/etc/X11/fontpath.d -pn

And the contents of .Xauthority:
[foo][/home/user]>xauth
Using authority file /home/user/.Xauthority
xauth> list
foo.mydomain.com:5  MIT-MAGIC-COOKIE-1  <long hex value>
foo.mydomain.com/unix:5  MIT-MAGIC-COOKIE-1  <same long hex value as above>
xauth>

DISCLOSURE: I realize that whether DISPLAY contains the hostname or not makes little difference on the local system.  The issue I'm really trying to figure out is why I have the same problem exporting a DISPLAY from a remote host to this VNC server - I get the same "Can't open display" message.  In the past when I've gotten that message, the problem was always xhost not allowing remote connections.  But this time setting "xhost +" did not help.  I thought the fact that using a hostname in the DISPLAY var on the local machine also triggering the problem was a clue.
Any thoughts on how to debug this problem?  Thanks!

A: Try to add -listen tcp in VNCSERVERARGS:
VNCSERVERARGS[2]="-geometry 800x600 -listen tcp"

or, if you are opening the session directly from command line:
vncserver -listen tcp


text:
Q: regex to replace backslash and single quote with single quote using postgres regexp_replace() Just as the title states, I'm not the best w/ regex, so can anyone provide the appropriate regex for the following:
UPDATE table SET column = REGEXP_REPLACE(column, {regex}, '''');

Basically, I'd like to replace any instances of backslashes (\) followed by one or more single quotes with one single quote.
So, the string Hello World\'s or Hello World\'''''s should become Hello World's, but not Hello World\s.

A: This is relatively straightforward. Note that both the backslash character \ as well as the single-quote character ' (which you escaped in the OP) need to be escaped. The difference is that the backslash has to be escaped in the regex itself, whereas the single quote is escaped in the string literal. Anyway, enough of that digression.
UPDATE table SET column = REGEXP_REPLACE(column, '\\''+', '''', 'g');

Hope this helps.

A: You can try the following:
SELECT REGEXP_REPLACE(column, '\\''['']*', '''','g') from table

Edit: of course \''+ is better
SELECT REGEXP_REPLACE(column, '\\''+', '''','g') from table


text:
Q: Imaginary, holomorphic and bounded function, zero everywhere at $(i+n^\beta)$. Blaschke condition?
Is there a function $h\ne 0$, holomorphic and bounded on $\mathbb{H_+=\{z \in \mathbb{C}: Im\,z > 0}\}$ zero exactly at at all points $(i+n^\beta)$, $0 \lt \beta \lt +\infty$, $n\gt 0$ ?

I have tried to use the Blashcke condition below.
Let $g=h \circ \phi$ where $\phi: \mathbb{D} \rightarrow \mathbb{H_+} $ with $\phi(z)=i\frac{1+z}{1-z}$.
Then $g$ is holomorphic and bounded on $\mathbb{D}$ and $h(i+n^\beta)=(g\circ \phi^{-1})(i+n^\beta)=0$, where $\phi^{-1}(z)=\frac{z-i}{z+i}:\mathbb{H_+}\rightarrow \mathbb{D}$.
The function $h$ will be zero at all $(i+n^\beta)$ if $\sum_{n \gt 0} (1-|\phi^{-1}(i+n^\beta)|) \lt \infty$.
We have $|\phi^{-1}(i+n^\beta)|=\frac{n^\beta}{|2i+n^\beta|}=\frac{n^\beta}{\sqrt{n^{2\beta}+4}}$.
Also, $1-\frac{n^\beta}{\sqrt{n^{2\,\beta}+4}}=\frac{n^\beta \sqrt{1+4n^{-2\beta}}-n^\beta}{n^\beta\sqrt{1+4n^{-2\beta}}}\approx \frac{n^\beta (1+2n^{-2\beta})-n^\beta}{n^\beta(1+2n^{-2\beta})}=\frac{2n^{-2\beta}}{1+2n^{-2\beta}}\approx 2n^{-2\beta}$.
Hence, $\sum_{n \gt 0} (1-\frac{n^\beta}{\sqrt{n^{2\beta}+4}})$ satisfies the Blaschke condition if and only if $2\beta \gt 1$ i.e $\beta \gt \frac{1}{2}$.