text:
Q: What is the best way to search for a large number of words in a large number of files? I have around 5000 files and I need to find words in each of them from a list of 10000 words. My current code uses a (very) long regex to do it, but it's very slow.
wordlist = [...list of around 10000 english words...]
filelist = [...list of around 5000 filenames...]
wordlistre = re.compile('|'.join(wordlist), re.IGNORECASE)
discovered = []

for x in filelist:
    with open(x, 'r') as f:
        found = wordlistre.findall(f.read())
    if found:
        discovered = [x, found]

This checks files at a rate of around 5 files per second, which is a lot faster than doing it manually, however it's still very slow. Is there a better way to do this?

A: If you have access to grep on a command line, you can try the following:
grep -i -f wordlist.txt -r DIRECTORY_OF_FILES

You'll need to create a file wordlist.txt of all the words (one word per line).
Any lines in any of your files that match any of your words will be printed to STDOUT in the following format:
<path/to/file>:<matching line>

A: Without more info on your data, a couple of thoughts are to use dictionaries instead of lists, and to reduce the data needed for searching/sorting.  Also consider using re.split if your delimiters are not as clean as below:
wordlist = 'this|is|it|what|is|it'.split('|')
d_wordlist = {}

for word in wordlist:
    first_letter = word[0]
    d_wordlist.setdefault(first_letter,set()).add(word)

filelist = [...list of around 5000 filenames...]
discovered = {}

for x in filelist:
    with open(x, 'r') as f:
        for word in f.read():
            first_letter = word[0]
            if word in d_wordlist[first_letter]:
                discovered.get(x,set()).add(word)

return discovered

A: The Aho-Corasick algorithm was devised for precisely this usage, and implemented as fgrep in Unix.  With POSIX, the command grep -F is defined to perform this function.
It differs from regular grep in that it only uses fixed strings (not regular expressions) and is optimized for searching for a large number of strings.
To run it on a large number of files, specify the precise files on the command line, or pass them through xargs:
xargs -a filelist.txt grep -F -f wordlist.txt

The function of xargs is to fill up the command line with as many files as possible, and run grep as many times as necessary;
grep -F -f wordlist.txt (files 1 through 2,500 maybe)
grep -F -f wordlist.txt (files 2,501 through 5,000)

The precise number of files per invocation depends on the length of the individual file names, and the size of the ARG_MAX constant on your system.


text:
Q: Asp.net connection string in web.config for OPD.NET I have oracle database.I have installed oracle client.Added refrence of Oracle.DataAccess in visual studio 2012 and use two name spaces
using Oracle.DataAccess.Types;
using Oracle.DataAccess.Client;
and using following connection string in web.config
 <connectionStrings>

    <add name="Oracleconnect" connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl.234.9.4)));User ID=hr;password=hr"
          providerName="Oracle.DataAccess.Client" />
      </connectionStrings>

but when I run my application i get following error

ystem.TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception. ---> Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client at Oracle.DataAccess.Client.OracleInit.Initialize() at Oracle.DataAccess.Client.OracleConnection..cctor() --- End of inner exception stack trace --- at Oracle.DataAccess.Client.OracleConnection..ctor(String connectionString) at SchoolsManagementSystem.DAL.GetConnection() in d:\c#\SchoolsManagementSystem\SchoolsManagementSystem\App_Code\DAL.cs:line 20 at SchoolsManagementSystem.DAL.AunthicateUser(String username, String password) in d:\c#\SchoolsManagementSystem\SchoolsManagementSystem\App_Code\DAL.cs:line 24 at SchoolsManagementSystem.Login.btnLogin_Click(Object sender, EventArgs e) in d:\c#\SchoolsManagementSystem\SchoolsManagementSystem\Login.aspx.cs:line 46

Please guide me how can I solve this problem.Why the above error shows

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do some words contain "let"? outlet, booklet, tablet... Are there any other word that contains a conjugation of "let" with other words? Why do these words contain let? If not coincidental, what is the significant meaning of let in these words?

A: Even though all three words you've mentioned contain let, that doesn't mean that they have something in common.

*

*outlet comes from two words: out and the verb let (see this Google search).

*booklet comes from two things: the noun book and the suffix -let that means small, lesser and comes from Old French (see this page for proof).

*tablet comes from two words: the noun table and the Old French word tablete (again, check out this Google search).

So, the three words all having let at the end is just a coincidence.


text:
Q: White space at the bottom of web page Iv been editing this web template for the past few days but when a section is removed the page length stays the same. Everything seems fine with the css and I dont spot anything in the html. I am a beginner so outside eyes can hopefully get this white space taken care of. Check it out, any advice is appreciated: http://solidsm.com

A: Your body tag has an inline style of  height:5314px.
I think that is causing the issue forcing the height to become more than the content height.
Why do you need that height constraint. Remove it .


text:
Q: Elasticsearch index alias I am trying to use elasticsearch to filter millions of data. All data are in one index and I want to access them in a 'direct' way.
What I mean with direct way?
Direct way means for example accessing the 700000th element of this index (not by id). Is this possible somehow?
What I tried already:

*

*from + size works, but seems not to be fast if number of elements > 10000

*Scrolling I didn't try, but it's seem somehow not the right thing for my use-case.

So any other ideas?

A: Scrolling will not work. That will fetch all the data.
I think elasticseach is not the correct use case for what you want to do.
It would be better to use a linked list of the ids, that will let you fetch the id by index and then you can query elasticsearch to get the data.
If you data is such that it does not get modified or deleted then you can add an extra field in the mapping that will act like an auto increment field in a database. You can fetch the data using that field.


text:
Q: Remove tabs and spaces from start of each line I have strings containing code that can have whitespace in front of it (tabs & spaces):
        for foo in bar:
            foo += 1
            for i in range(0, foo):
                print(foo * foo)

Since whitespace defines scope in python, this won't compile. So what is a good way to remove whitespace from the start of each line ONLY if it occurs on every line in the string, giving the following result:
for foo in bar:
    foo += 1
    for i in range(0, foo):
        print(foo * foo)

The code is both generated and compiled in the same python program, so no other tools allowed.

A: The standard library's textwrap.dedent function does exactly what you want.
https://docs.python.org/3/library/textwrap.html#textwrap.dedent

A: Try this,
s = '''
        for foo in bar:
            foo += 1
            for i in range(0, foo):
                print(foo * foo)
    '''

lines = s.split('\n')[1:]  # remove the first empty line, just for this case
nrof_spaces = len(lines[0]) - len(lines[0].lstrip())

result = list()
for line in lines:
    result.append(line[nrof_spaces:])

print('\n'.join([''.join(line) for line in result]))
# Output
for foo in bar:
    foo += 1
    for i in range(0, foo):
        print(foo * foo)

A: Read first line to string a, then :
lead_space=len(a) - len(a.lstrip()))

Now for each line a print :
print(a[lead_space:])


text:
Q: Deleting value present in a neighbor column Hi I am trying to write a python3 script that will remove the value present in other column.
For example:
A   A,B,C
T   H,D,T
H   A,H,D,C

will be:
A   B,C
T   H,D
H   A,D,C

Assuming these are 4th (ref) and 5th (alt) column of my datasheet
I wrote the following code:
with open(two) as infile, open (three, 'w') as outfile:
    reader = csv.reader(infile, delimiter='\t')
    writer = csv.writer(outfile, delimiter='\t')
    for g, pos, code, ref, alt, *rest in reader:
        a = alt.split(',')
        if a == ref:
            writer.writerow([g, pos, code, ref, [alt-ref]] + rest)
        if a != ref:
            writer.writerow([g, pos, code, ref, alt] + rest)

So I meant to write it so that
If the letter in "ref" equals to any splitted string in "alt", that value is deleted from "alt" and exported.
If not, the row is exported as it is.
[alt-ref] does not seem to work.
Can someone help me complete this code?
I would appreciate your help.

A: You should use something like that,
[x for x in alt if x != ref]

Create a new list without value ref`


text:
Q: Getting time of execution of request and response in ajax Please, I want to use stopwatch to get the seconds from the time of sending of request through ajax and success function.

A: You can do it like this:
var start_time = new Date();
$.ajax({
  // Other params
  success: function () {
    var end_time = new Date();
    alert("Time taken: " seconds(end_time) - seconds(start_time));
  }
});
function seconds(date_obj) {
  return date_obj.getTime();
}

Please figure out seconds() yourself.


text:
Q: Confused with BEM naming convention - need correction? I'm creating ecommerce site for learning purposes and I've got problem. I'm using BEM naming convention and I don't know if I'm doing it good, here's my code:

      {$flag.label}

{$product.name}

      {$product.price}
      {$product.regular_price}

I have biggest issue with the product badges and product prices, I think something's wrong over there?

A: The only thing I can see to consider here is the use of the price and badge block classes. If they can exist on their own (outside of the product block) then what you have is fine. However, if they will only ever exist inside a product then you might like to change them to product__price and product__badge


text:
Q: How to display 2nd last record using mysql query? db table.
applicant
       app_id(p)   fullname
        ------------------------------------
           1       John Bie
           2       Hanna

rec_list

       Id(p)   app_id(f)  fullname request
       ------------------------------------
        1         1       John Bie   ball
        2         1       John Bie   bag
        3         2       Hanna      Jewelry
        4         1       John Bie   tshirt
        5         2       Hanna      Dress

here's my query: it will show the last 2nd record of the app_id.
$app1 = $_GET["app_id"];
       $query = mysql_query("SELECT * FROM rec_list WHERE app_id = $app1 ORDER BY id DESC LIMIT 1,1")

the result will show the 2nd record.
Name: John Bie
last request: Bag

but when I viewed the Bag in my preview.php script
the result still
Name: John Bie
last request: Bag

how to make it show like this: ball>bag>tshirt
Name: John Bie
last request: ball

A: Try this one:
SELECT columns FROM table ORDER BY id DESC LIMIT 2;

A: Try this.....
You can put your cuurent request value in $curr_request variable.
i.e when you view tshirt, $curr_request will be tshirt.
$query = mysql_query("SELECT * FROM rec_list WHERE app_id = $app1 AND request != '$curr_request' ORDER BY id desc LIMIT 1")


text:
Q: Duda con objetos y tablas en JS Estoy empezando con JS y tengo una duda sobre los objetos y como pintar su contenido en tablas.
He creado una tabla con 3 columnas, con PELICULA, AÑO y PAIS.
Dentro de cada una de esas columnas quiero añadir los datos del objeto película, pero no lo consigo.
Lo intenté de varias formas pero no me sale:
¿Cómo podría hacerlo para que me aparezca cada cosa en su columna?
En la primera forma lo hice del siguiente modo y me crea muchos  con un :
'use strict'

//Array del objeto

var peliculas = [
    {titulo: 'La verdad duele', year: 2014, pais: 'UK'},
    {titulo: 'Diamantes de sangre', year: 2010, pais: 'EEUU'},
    {titulo: 'Agora', year: 2009, pais: 'España'}
]

//Recorrer peliculas

var listaPeliculas = document.querySelector(".listaPeliculas");

for (const indice in peliculas) {
   let tr = document.createElement("tr");
   let td = document.createElement("td");
   //Titulo
   td.append(peliculas[indice].titulo);
   tr.append(td);
   listaPeliculas.append(tr);
}

for (const year in peliculas) {
    let tr = document.createElement("tr");
    let td = document.createElement("td");

    //Año
    td.append(peliculas[year].year);
    tr.append(td);
    listaPeliculas.append(tr);
}

En la segunda forma lo hice de este modo y solo me aparece la última película y no sé porqué. Para ello creado en el html esto:

'use strict'

//Array del objeto

var peliculas = [
    {titulo: 'La verdad duele', year: 2014, pais: 'UK'},
    {titulo: 'Diamantes de sangre', year: 2010, pais: 'EEUU'},
    {titulo: 'Agora', year: 2009, pais: 'España'}
]

console.log(peliculas);

//Recorrer peliculas

var pelicula = document.querySelector("#pelicula");
var anio = document.querySelector("#anio");
var pais = document.querySelector("#pais");

for (const indice in peliculas) {

    pelicula.innerHTML = peliculas[indice].titulo;
    anio.innerHTML = peliculas[indice].year;
    pais.innerHTML = peliculas[indice].pais;
}

Espero que alguien me pueda ayudar,
Muchas gracias!

A: Tienes varios fallos en tu codigo que intentare explicartelo.
Primera forma:

*

*Utilizar querySelector es un poco arriesgado, ya que solo devuelve el primer elemento. ¿Que pasa si el selector(.listaPeliculas) se utiliza en un elemento que no es?

*No es necesario recorrer cada clave del objeto por separado, tal y como lo estas haciendo para titulo y año.

Segundo paso:

*

*Cuando haces innerHTML no es acumulativo. Es decir siempre te pondra el ultimo registro.

En total tu codigo con unos cambios quedaria algo asi.

'use strict'

//Array del objeto
var peliculas = [
    {titulo: 'La verdad duele', year: 2014, pais: 'UK'},
    {titulo: 'Diamantes de sangre', year: 2010, pais: 'EEUU'},
    {titulo: 'Agora', year: 2009, pais: 'España'}
]
//Tabla con los contenidos
var listaPeliculas = document.getElementById('tabla');

//Aqui vamos a guardar los tr y td con su informacion.
let tablaContent = ``

//Recoremos las peliculas
//El operador in es para obtener el indice,
//en cambio of es el objeto en si.

for (const item of peliculas) {
  //Fijate que utilizamos += para acumular los datos.
  //Template strings syntax
   tablaContent += `

      ${item.titulo}
      ${item.year}
      ${item.pais}

  `
}
//Finalmente añadimos el contenido a la tabla
listaPeliculas.innerHTML += tablaContent
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

      TITULO
      AÑO
      PAIS

Espero que te sirva de ayuda.
Saludos!!!

A: Creo que este es lo que buscas.

function buildTable(labels, objects, container) {
  var table = document.createElement('table');
  var thead = document.createElement('thead');
  var tbody = document.createElement('tbody');

  var theadTr = document.createElement('tr');
  for (var i = 0; i < labels.length; i++) {
    var theadTh = document.createElement('th');
    theadTh.innerHTML = labels[i];
    theadTr.appendChild(theadTh);
  }
  thead.appendChild(theadTr);
  table.appendChild(thead);

  for (j = 0; j < objects.length; j++) {
    var tbodyTr = document.createElement('tr');
    for (k = 0; k < labels.length; k++) {
      var tbodyTd = document.createElement('td');
      tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
      tbodyTr.appendChild(tbodyTd);
    }
    tbody.appendChild(tbodyTr);
  }
  table.appendChild(tbody);

  container.appendChild(table);
}

var labels3 = ['ID', 'MOVIE TITLE' ,'YEAR', 'COUNTRY'];
var objects3 = [
  {"id": "1",  'movie title': "La verdad duele",  'year': "2014",  'country': "UK"},
  {"id": "1",  'movie title': "Diamantes de sangre",  'year': "2010",  'country': "EEUU"},
  {"id": "1",  'movie title': "Agora",  'year': "2009",  'country': "SPAIN"}
];

buildTable(labels3, objects3, document.getElementById('c'));
table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
}

LISTA DE PELICULAS

A: Esto te valdría, aun que, la respuesta de Emerson es mas elaborada y reusable que esta

'use strict'

//Array del objeto

var peliculas = [
    {titulo: 'La verdad duele', year: 2014, pais: 'UK'},
    {titulo: 'Diamantes de sangre', year: 2010, pais: 'EEUU'},
    {titulo: 'Agora', year: 2009, pais: 'España'}
]

let tabla = document.getElementById("table");

for (const pelicula of peliculas) {
    let tr = document.createElement('tr');
    let tdTitulo = document.createElement('td');
    let tdAnio = document.createElement('td');
    let tdPais = document.createElement('td');
    tdTitulo.innerText = pelicula.titulo;
    tdAnio.innerText = pelicula.year;
    tdPais.innerText = pelicula.pais;
    tr.appendChild(tdTitulo);
    tr.appendChild(tdAnio);
    tr.appendChild(tdPais);
    tabla.appendChild(tr);
  }

    Pelicula
    Año
    Pais


text:
Q: Vue.js Safari mobile and compatibility I have a Vue.js component that works fine on Firefox, Chrome but Safari and Safari mobile browsers it fails.
The console returns:

Object.values is not a function

Is there a solution to this problem?
The full code is below:
<template>

{{meal}}

              <select v-model="selected" v-model.lazy="creditsPerMeal[meal]" v-on:change="createSelection()">
                <option v-for="option in options" v-bind:value="option">
                  {{ option }}
                </option>
              </select>

Credits used: {{creditsSum}}/{{credits}}

    Dietary
    <input type="textarea" name="dietary" v-model="dietary" class="form-control">

PRICE: £{{cost}}

          <form action="/checkout" v-on:submit.prevent="onSubmit" method="post" id="buy_now_form">
              <input type="hidden" v-bind:value="select_meal" name="selected_meals" required>
              <input type="hidden" name="price" v-bind:value="cost">
              <input type="submit" value="BUY NOW" class="btn btn-default" :disabled="this.creditsSum != this.credits">
          </form>

Subscribe

              4 Weeks
              <button type="submit" class="btn btn-default" v-on:click="fourWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>
              8 Weeks
              <button type="submit"  class="btn btn-default" v-on:click="eightWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>

Subscribe

              4 Weeks
              <button type="submit" class="btn btn-default" v-on:click="fourWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>
              8 Weeks
              <button type="submit"  class="btn btn-default" v-on:click="eightWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>

Subscribe

              4 Weeks
              <button type="submit" class="btn btn-default" v-on:click="fourWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>
              8 Weeks
              <button type="submit"  class="btn btn-default" v-on:click="eightWeek" :disabled="this.creditsSum != this.credits">SUBSCRIBE</button>

</template>

A: The problem lies with Object.values which is not supported by all browsers. You can use a polyfill for Object.values to get support.
You can check for more information this website
edit:
I see that you use import in your code . that makes things easier.
use npm install object.values
and in your code at the beginning use
import values from 'object.values';
if (!Object.values) { values.shim(); }

A: This has nothing to do with Vue.js.
Object.values() is experimental and NOT implemented on many browsers. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
You'll have to use a for loop instead!


text:
Q: IE needs to run as Admin just to save file or create folder from Silverlight App I have this Silverligth 5 application that cater MS Word add, edit and save to database in server. Editing the word file requires downloading it from server and save to local drive in %userprofile%\AppData\TheFolder (TheFolder is programmatically created once the application run). The problem is that, even in trusted configured app (in browser; added the site in IE trusted zone, signed the XAP, added registry key and elevate the app) the user (client side) needs to open the IE "run as administrator" to enable full access to this folder and able to save a copy of MS Word. The purpose of a local copy is that, once the upload fails for three times, it can still recover his/her work and later try to edit and upload it again.
How can we avoid to open IE "run as admin". Please help


text:
Q: Как обновить UI, пока работает функция в основном потоке Добрый день. У меня есть приложение на WPF. На MainWindow есть canvas, и функция, которая обрабатывает все контролы в нем. Функция работает в главном потоке, иначе не получить объекты с canvas. Я хочу сделать какую-либо визуализацию процесса на этом экране, например изменение textbox. Как это лучше сделать?
    public void SomeLongFunk()
    {
         foreach(var item in canvas.Children)
         {
              //dosomething
         }
    }

A: Чтобы функция, работающая в потоке "достучалась" до UI объектов, нужно использовать анонимные функции:
this.Invoke((MethodInvoker) delegate () {
textbox.Text = "Almost done!";
});

A: Если ваша функция длинная, и работает при этом с UI-объектами, то вы делаете неправильно. Необходимо длительную работу выгружать в другие потоки, чтобы не блокировать главный поток. Для того, чтобы ваш код всё ещё мог взаимодействовать с UI, можно воспользоваться либо async/await, либо Dispatcher.InvokeAsync, либо IProgress.
Примеры:
async/await:
async Task MoveObjects()
{
    // собираем данные в UI-потоке
    var currentPositions = Arena.Children.Select(child =>
                              new Point(Canvas.GetX(child), Canvas.GetY(child))).ToList();
    for (int i = 0; i < 100; i++)
    {
        // вычисляем новые данные в новом потоке
        var newPositions =
            await Task.Run(() => engine.ComputeNextPositions(currentPositions));
        // присваиваем данные UI-объектам в UI-потоке
        for (int i = 0; i < Arena.Children.Count; i++)
        {
            var child = Arena.Children[i];
            var coord = newPositions[i];
            Canvas.SetX(child, coord.X);
            Canvas.SetY(child, coord.Y);
        }
        currentPositions = newPositions;
        await Task.Delay(25);
    }
}

Dispatcher.InvokeAsync:
Task MoveObjects()
{
    var objects = Arena.Children.ToList();
    return Task.Run(() => MoveObjectsInBackground(objects, Dispatcher));
}

async Task MoveObjectsInBackground(List<UIElement> objects, Dispatcher dispatcher)
{
    // собираем данные в UI-потоке
    var currentPositions =
            await dispatcher.InvokeAsync(() =>
                objects.Select(child => new Point(Canvas.GetX(child),
                                                  Canvas.GetY(child))).ToList());

    for (int i = 0; i < 100; i++)
    {
        // вычисляем новые данные
        var newPositions = ComputeNewPositions(currentPositions);
        // отправляем их в UI-поток
        await dispatcher.InvokeAsync(() =>
            {
                for (int i = 0; i < objects.Count; i++)
                {
                    var child = objects[i];
                    var coord = newPositions[i];
                    Canvas.SetX(child, coord.X);
                    Canvas.SetY(child, coord.Y);
                }
            });
        await Task.Delay(25);
    }
}

IProgress:
Task MoveObjects()
{
    // собираем данные в UI-потоке
    var positions = Arena.Children.Select(child =>
                              new Point(Canvas.GetX(child), Canvas.GetY(child))).ToList();
    var progress = new Progress<List<Point>>(UpdatePositions);
    await Task.Run(() => MoveObjectsInBackground(positions, progress);
}

void UpdatePositions(List<Point> positions)
{
    for (int i = 0; i < Arena.Children.Count; i++)
    {
        var child = Arena.Children[i];
        var coord = newPositions[i];
        Canvas.SetX(child, coord.X);
        Canvas.SetY(child, coord.Y);
    }
}

void MoveObjectsInBackground(List<Point> positions, IProgress<List<Point>> progress)
{
    for (int i = 0; i < 100; i++)
    {
        var newPositions = ComputeNewPositions(currentPositions);
        progress.Report(newPositions);
        currentPositions = newPositions;
        Thread.Sleep(25);
    }
}


text:
Q: camel cxf proxy doesnt work with http endpoint My requirement is to have a  proxy  web service which will receive the request from clients and then route through camel,enrich it and forward it to real webservice at other clients place ,get response and send it back to the original requestor.
i basically looked at camel-cxf-proxy example (http://camel.apache.org/cxf-proxy-example.html) and camel-cxf-example in camel distribution.Its exactly similar to camel-cxf-proxyand came up with this route
<from uri="cxf:bean:soapMessageEndpoint?dataFormat=MESSAGE" />
<camel:convertBodyTo type="java.lang.String"></camel:convertBodyTo>
<to ref="XService"></to>

where endpoints are
<endpoint id="XService" uri="http://xx.xx.xxx.xx:8080/X_Service" />

<cxf:cxfEndpoint id="soapMessageEndpoint" address="http://localhost:8181/ProviderInformationDirectoryService"  wsdlURL="wsdl/HPD_ProviderInformationDirectory.wsdl" endpointName="s:ProviderInformationDirectory_Port_Soap" serviceName="s:ProviderInformationDirectory_Service" xmlns:s="urn:ihe:iti:hpd:2010"/>

As you can see the second service is http endpoint.And first is the camel-cxf proxy.I just have the wsdl and at this point there is no need for impl.the dataformat is MESSAGE as i need the entire soap envelope to be sent to second web service and there are some useful headers in request from client.But when i run this route with a sample soap envelope it always comes up with 500 response.I am thinking that message sent to real webservice is not what it expects.
I tried trace on camel route but it didnt show much.I was hoping it will show real request to http endpoint.i tried to configure interceptor but that didnt work either.Trace only shows following
 Failed delivery for (MessageId: ID-ALHCAN0437-63941-1354828653539-45-2 on ExchangeId: ID-ALHCAN0437-63941-1354828653539-45-1). Exhausted after delivery attempt: 1 caught: org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://X:8080/X_Service with statusCode: 500

I also tried the following which seems to be working.
<from uri="cxf:bean:soapMessageEndpoint?dataFormat=MESSAGE" />
<camel:convertBodyTo type="java.lang.String"></camel:convertBodyTo>
<to uri="bean:callRemoteWS"></to>

callRemoteWS (callRemoteMethod) gets the soapenvelope as string and makes a HTTPPost request to above endpoint , returns back the response.
public String callRemoteMethod(String request) throws Exception{

            HttpClient client = new HttpClient();

            BufferedReader br = null;

            PostMethod method = new PostMethod("http://x.x.x.x:8080/X_Service");

            RequestEntity entity =new StringRequestEntity(request);

            method.setRequestEntity(entity);

            try{
              int returnCode = client.executeMethod(method);

              if (returnCode != HttpStatus.SC_OK) {
                  System.err.println("Method failed: " + method.getStatusLine());
                  return "Error";
                }

                // Read the response body.
                byte[] responseBody = method.getResponseBody();

                System.out.println(new String(responseBody));

                // Deal with the response.
                // Use caution: ensure correct character encoding and is not binary data
               return new String(responseBody);
            } finally {
              method.releaseConnection();
              if(br != null) try { br.close(); } catch (Exception fe) {}
            }

          }

I am  confused why the simple camel-cxf proxy with http webservice didnt work and the second one works (it should and it does :P).Is the code i have ok.It doesnt seem right to me.I am pretty sure some exchange property is set wrong or content sent to real webservice is wrong.The content got from the proxy is used to make the Httppost call in second route.so the content  from proxy cannot be wrong.when it is got from exchange and send to real webservice something goes wrong. Can anybody throw some light on it.

A: I think it was a silly mistake on my part .Soap action header had a different operation and the payload was for a different method.I was invoking the wrong operation with the payload


text:
Q: Will a mac ssd (it already have the os x) boot on a pc? So I broke my macbook and I believe that the ssd is still alive with latest os x on it. If I take out the ssd and put it into a pc will it boot?
I saw that apple forbid using their os on a non mac machine.

A: No, it won't boot natively, nor will it even mount on a Windows machine without a 3rd party translator 'plugin' to be able to read HFS+ or APFS.
Further, if it's APFS then I think only Paragon make a translator - APFS for Windows
They also do one for HFS, but I think there are other alternatives - HFS+ for Windows
Depending on what the macOS version was will depend on which of those you might need. HFS was default until Sierra, since then it's been APFS.


text:
Q: Animated scrollto effect jQuery plugin I used this plug-in and got rid of some unnecessary code, for some reasons it does nor work in FireFox.
Original source: http://djpate.com/2011/01/01/animated-scrollto-effect-jquery-plugin/
my code:
(function (a) {
a.fn.slideto = function (b) {
    var c = {
        slide_duration: "slow",
        offset: 0
    }, b = a.extend(c, b);
    return this.each(function () {
        var c = !1;
        obj = a(this), a("body").animate({
            scrollTop: obj.offset().top + b.offset
        })
    })
}
})($);

Code used to call the plug-in:
$(document).ready(function(){
            $("#scroll").click(function(){
                $("#results").slideto();
            });
        });

A: The problem is some browsers expect you to scroll the html and others the body.
They even change this expectation if on Quirk's mode.
You can use the jquery.scrollTo plugin which handles that for you.
You need to include the plugin and then something like this will do:
$(document).ready(function(){
  $("#scroll").click(function() {
    $(window).scrollTo("#results", {duration:"slow", offset:0});
    return false;
  });
});

Just added the settings you seem to be interested in, it provides a lot more.
BTW, you might want to check jquery.localScroll which sits on top on scrollTo and makes you links scroll automatically based on anchors (f.e <a href="#results">)
Cheers


text:
Q: Why the Covariance between efficient and inefficient estimator is equal to variance of the efficient one in Hausman test? I tried to prove Hausman test for two estimators efficient and inefficient one. Then I encountered with the statement for variance of two estimators saying that: Covariance between the efficient estimator and inefficient is equals to the variance of the efficient one. Thus, asymptotic variance of the difference is equal to the difference of variances of the efficient and ineffient estimator. Why is it so?

A: Just a comment, I find a related result when reading Greene's textbook  "Econometric Analysis".
Let us consider the GLS estimator (efficient) and the OLS estimator (inefficient) of $\beta$ in a linear regression model with heteroscedasticity. One can show that:
$\text{Cov}\left( \hat{\beta}_{GLS}\ ,\ \ \hat{\beta}_{GLS}- \hat{\beta}_{OLS}\right) = 0$
Note that $\hat{\beta}_{GLS}- \hat{\beta}_{OLS}$ is an unbiased linear estimator of 0.
Also, $\hat{\beta}_{GLS}$ is the BLUE of $\beta$ under the assumption of heteroscedasticity.
The intuition for this specific case is that one cannot improve a BLUE by adding or substracting any unbiased linear estimator of 0.
Hope this simple example could be helpful in someway.


text:
Q: How to derive Kac-Moody and Virasoro algebras from their descriptions as central extensions? I am following the notes (https://arxiv.org/abs/hep-th/9904145) to learn conformal field theory, and want to know how to derive the contributions to the Virasoro and Kac-Moody algebras from the central terms.
In their exposition, around Eq(3.25), the Kac-Moody algebra $\mathfrak{\hat g}$ corresponding to a Lie algebra $\mathfrak{g}$ is a central extension of the loop algebra $L\mathfrak{g}$. The $L\mathfrak{g}$ is the set of all Lie-Algebra valued functions on the circle, and is by a Fourier basis $t^a e^{i n \phi}$, where $t^a$ are the generators of $\mathfrak{g}$, and $\phi$ parameterizes the circle. This central extension gives rise to the short exact sequence
$$0 \rightarrow \mathbb{R} \rightarrow \mathfrak{\hat g} \rightarrow L\mathfrak{g} \rightarrow 0$$
Similarly, the Virasoro algebra $Vir$ is a central extension of the algebra of vector fields on a circle, $Vect(S^1)$, which is generated by the vector fields $i e^{i n\phi}\partial_\phi$. These give rise to a short exact sequence, Eq(4.13)
$$0 \rightarrow \mathbb{R} \rightarrow Vir \rightarrow Vect(S^1) \rightarrow 0$$
Let the central elements of the K-M algebra $\mathfrak{\hat g}$ be given by $K$, and that of $Vir$ by $C$.
The lecture notes state that $\mathfrak{\hat g}$ has an algebra
$$[t^a_m,t^b_n] = i f^{abc}t^c_{n+m} + \frac{1}{2}K n \delta^{ab}\delta_{n+m,0}$$
and that $Vir$ is given by
$$[l_m,l_n] = (n-m)l_{n+m} + \frac{1}{12} C (n^3-n) \delta_{n+m,0}$$
It's clear to me that all the terms not involving the central terms $K,C$ are correct, because those are just inherited from the original algebras. I'm confused as to how the other terms can be fixed on just an algebraic level. Any answers or references would be appreciated.


text:
Q: Get path from RequireJS Let's say I have an array of paths I'm loading through Require...
var paths = ['libs/one','libs/two','libs/three'];

And I'm passing them into require as such...
require(paths, function(){

    for (var i=0, max=arguments.length; i<max; i++){
        someObject[CURRENT_PATH] = arguments[i];
    }

});

Is there a way to get the paths in the function(){ ... } so I can use them? I can loop through arguments, but it just gives me the contents of the define()'s.

A: In this case it seems like you want:
someObject[paths[i]] = arguments[i];

You could wrap the code to avoid any global scope as normal:
(function() {
    var paths  = ['libs/one','libs/two','libs/three'];

    require(paths, function () {

        for (var i = 0; i < arguments.length; i++) {
            someObject[paths[i]] = arguments[i];
        }
    });
})();


text:
Q: putting an icon next to two paragraphs. Icon should be vertically in center right next to the paragraphs I want to put an icon next to two paragraphs in a way that the icon is exactly at the center (vertically) on the left hand side of the two paragraphs. This is what I want:

This is what I have:

This is my code:

      Promo Code

    <icon type="Success filled"></icon>

PlayerRegistrationPromotion Applied

      $ in credits available

P.S:
Please note that the spelling and sentences are dummy data and don't matter. The styling here is important. So what's the best way to get the wanted result?

A: Is this what you are after?
https://codepen.io/polinq/pen/abzBYoy
Clarification: display: flex on inner will group the elements in two columns.By default, flex-direction will be row so you will have these element in one row.
I also added another div (inner-two) so it separates the text 'PlayerRegistrationPromotion Applied' and the text about the credit. If you were to remove it the text will be next to each other, not in separate rows.
I hope it is all clear!

      Promo Code

        <icon type="Success filled"></icon>

PlayerRegistrationPromotion Applied

      $ in credits available

.inner {
  display: flex;

}

A: It looks like you're using Bootstrap(?). One way you could do this is by having the 'Promo Code' text on one line that spans the full width and then with the next row having the checkmark icon in a couple columns and the additional text in the remaining columns.
Something like this might get you started:

Promo Code

<icon type="Success filled"></icon>

PlayerRegistrationPromotion Applied

$ in credits available


text:
Q: AWS SageMaker Pipeline Issue - Pipeline variables do not support __str__ operation I'm trying to build SageMaker Pipeline based on Tensorflow framework. I have only Training, Evaluating steps, and Register model. On the evaluation step I declared MetricsSource for ModelMetrics and received an error.
Code is below:
pipeline_model = PipelineModel(
    models=[tf_model],
    role=role,
    sagemaker_session=sagemaker_session
)

eval_res = step_evaluate_model.arguments['ProcessingOutputConfig']['Outputs'][0]['S3Output']['S3Uri']
evaluation_s3_uri = f'{eval_res}/evaluation.json'

model_statistics=MetricsSource(
        s3_uri=evaluation_s3_uri,
        content_type='application/json')

model_metrics = ModelMetrics(model_statistics=model_statistics)

step_register_pipeline_model = pipeline_model.register(
    content_types=['application/json'],
    response_types=['application/json'],
    inference_instances=['ml.m4.xlarge','ml.c5.2xlarge'],
    transform_instances=['ml.c5.2xlarge'],
    model_package_group_name=model_package_group_name,
    model_metrics=model_metrics,
    approval_status=model_approval_status.default_value,
)

Error:
TypeError                                 Traceback (most recent call last)
Input In [17], in <cell line: 17>()
     14 model_metrics = ModelMetrics(model_statistics=model_statistics)
     15 # print('\n',pipeline_model)
---> 17 step_register_pipeline_model = pipeline_model.register(
     18     content_types=['application/json'],
     19     response_types=['application/json'],
     20     inference_instances=['ml.m4.xlarge','ml.c5.2xlarge'],
     21     transform_instances=['ml.c5.2xlarge'],
     22     model_package_group_name=model_package_group_name,
     23     model_metrics=model_metrics,
     24     approval_status=model_approval_status.default_value,
     25 )
TypeError: Pipeline variables do not support __str__ operation. Please use `.to_string()` to convert it to string type in execution timeor use `.expr` to translate it to Json for display purpose in Python SDK.

Could you please help me to solve it? I'd appreciate for any idea. Thanks

A: They way to create model and register model on Pipelines has changed slightly with the introduction of ModelStep, also the instantiation of session_pipeline is needed. Similarly, ModelStep will be used for registering the model .
Reference: https://github.com/aws/sagemaker-python-sdk/pull/3076
Examples : https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html?highlight=ModelStep#sagemaker.workflow.model_step.ModelStep


text:
Q: embedding layer index order meaning in Keras Tensorflow I am using Keras Tensorflow to fit Deep Learning models on mixed data input (both numeric and categorical). Categorical covariates have been encoded as numeric using scikit-learn LabelEncoder and introduced in the DL using an Input layer (one-dimensional). Then, I set Embedding Layers using, for example, for a variable with 6 distinct levels:
variable_emb = Embedding(input_dim=6,output_dim=1,input_shape=(1,),name='variable_emb_emb')(variable_tensor_input)

My question is what is the ordering that Embedding matrix rows follow. Does the i-th row follow the LabelEncoder indexing or it is assigned to the distinct original variable levels according to the sequence in which they occurr in the input data set?

A: Inspired by @ad2004, I do a similar experiment while trying to make settings crystal clear. And the result to be illustrated is: index of embedding layer dirrectly corresponds to the integer representation of your categorical feature.
Firstly design a simple model with an embedding layer
from numpy.random import seed
seed(42)
import tensorflow
tensorflow.random.set_seed(42)

import numpy as np
from keras import Sequential
from keras.layers import Embedding

model = Sequential()
model.add(Embedding(input_dim=3, output_dim=2, input_length=1, name='embedding'))
model.add(Flatten())
model.add(Dense(2, activation="relu"))
model.add(Dense(1))

model.compile(loss = "binary_crossentropy", optimizer = "adam", metrics=['accuracy'])
model.summary()

Then via defining different x_arrays but same y:
normal_order = 1 # or 0

if normal_order:
    x_array = np.array([[0],
                        [1],
                        [2],
                        [0],
                        [1],
                        [2]])
if not normal_order:
    x_array = np.array([[2],
                        [1],
                        [0],
                        [2],
                        [1],
                        [0]])

y = np.array([1,1,0,1,1,0])

we expect the embedding vector of normal_order=1 case should have 0 and 1 to be close to each other, meanwhile, the embedding vector of normal_order=0 case should have 2 and 1 to be close to each other. Running below codes:
model.fit(x = x_array, y, epochs=2000 )

emb_df = pd.DataFrame( model.get_layer('embedding').get_weights()[0]).reset_index()

The emb_df for normal_order=1 case is:
emb_df
#   index         0         1
#0      0 -0.169505 -0.242161
#1      1 -0.246347 -0.211345
#2      2  0.067879  0.062597

while that for normal_order=0 case is:
emb_df
#   index         0         1
#0      0  0.104817  0.014432
#1      1 -0.264942 -0.227623
#2      2 -0.179805 -0.162726

A: I believe that the output rows are simply indexed from 0 to input_dim-1, and whatever integer your LabelEncoder generates for each categorical variate will correspond to the appropriate row.  For instance, if you have 3 categorical variates:  "apple", "pear", "orange" and the LabelEncoder assigns pear=2, orange=0, apple=1, then row 0 of the embedding matrix will be related to "orange", row 1 will be "apple", and row 2 will be "pear."
The below working code snippet shows the idea.  I hope this helps.
import numpy as np
from keras import Sequential
from keras.layers import Embedding

model = Sequential()
model.add(Embedding(5, 2))

model.compile('rmsprop', 'mse')
#model.summary()

input_array = np.array([[1, 1, 1],
                        [1, 2, 2]])
output_array = model.predict(input_array)

print('model.get_weights():')
print(model.get_weights())

print('output_array:')
print(output_array)


text:
Q: Jquery Resizable Handle Left (e) Issue I have the following sample code that use jQuery Resizable for e, w handles. I can see the "e" handle works as expected, but for "w" it always change the "e" width.
What's wrong? Really appreciate for any help, thank you...

            body {
                margin: 50px;
            }

            .row {
                width: 900px;
                height: auto;
            }

            .col {
                position: relative;
                min-height: 331px;
                height: 331px;
                width: 33.333%;
                background: #ccc;
            }

            .handle-w,
            .handle-e {
                background: #fff;
                border: 2px solid #00a0d2;
                border-radius: 50%;
                height: 12px;
                width: 12px;
                cursor: e-resize;
                top: 50%;
                transform: translateY(-50%);
                position: absolute;
            }

            .handle-w {
                left: -7px;
            }

            .handle-e {
                right: -7px;
            }

Or you can see the live demo in jsfiddle here https://jsfiddle.net/yhutxfvr/

A: The easy way around this issue is to set the handles property as follows:
$(document).ready(function () {
    var col = $('.col');

    col.resizable({
        /* Added the following line of code. */
        aspectRaitio: true,

        containment: col.closest('.row'),

        /* The following line of code has been changed. */
        handles: 'n, e, s, w'
    });
});

Additionally, I suggest you review the following posts. Similar but not synonymous issues are discussed:

*

*jQuery Resize On Both Sides

*jQuery UI Resizable Resizing To Left Issue


text:
Q: How do I split last 3 digits in values in a column in a Dataframe into two new Dataframes? df=pd.DataFrame({'col1':[25021,25002,8002,40211,2232,""]})

    col1
0   25021
1   25002
2   8002
3   40211
4   2232
5

I would like to get the following, not too sure how to split based on last 3 digits into col3 and whatever preceding into col1
    col2   col3
0   25     021
1   25     002
2   8      002
3   40     211
4   2      232
5

A: This is my approach:
df['col2'] = df['col1'].astype(str).str[-3:]

df['col1'] = df['col1'].astype(str).str[:-3]

Output:
   col1 col2
0    25  021
1    25  002
2     8  002
3    40  211
4     2  232

A: Try this.
df=pd.DataFrame({'col1':[25021,25002,8002,40211,2232]})
df['col2'] = df['col1'].astype(str).apply(lambda x:x[-3:]).astype(int)
df['col1'] = df['col1'].astype(str).apply(lambda x:x[:-3]).astype(int)

A: Just a play on Pandas' string split method; you can wrap the delimiter(in a regex), so that it is included in the output:
(df
 .astype(str)
 .col1
 .str.split(r'(\d{3}$)', n=1, expand=True)
 .drop(2,axis=1)
 .set_axis(['col1','col2'],axis='columns')
)

    col1    col2
0    25     021
1    25     002
2    8      002
3    40     211
4    2      232


text:
Q: Running 32 bit printer drivers on a 64 bit Windows 7 Pro I just purchased a new workstation for a company network which is Windows 7 Pro 64bit.
Unfortunately they have an Imagistics im2520f Copier/Printer that only has 32bit drivers available.
Windows 7 had no problem installing all the 32bit software, but is there a way to make this 32bit print-driver work on a 64bit system (with a wrapper software or something)?
I tried just adding this device to the 2003 server as a shared printer, but even when you do this, the 64bit machine (printing to the shared printer) must have drivers for the printer (I discovered).
Another idea is this: if I could somehow send print-jobs to the cue of a another workstation (that is 32 bit) I might be able to set it up to where the employee could automatically print though that other machine?
I hoping someone here will know other options/possibilities I haven't considered. Here are the drivers that are available: Link

A: This is a well known phenomenon with migrating to a 64 bit OS. There have been a lot of institutions which have been forced to upgrade to new printers and scanners, etc.
There is one kind of third party solution available that may be of interest. ThinPrint and a couple other vendors have paid products available that can be used as an intermediary driver which may be able to be purposed for this kind of duty. This is basically an application server that creates a file (usually a PDF) on the local host. This is then forwarded to a server (either a print server or a terminal server). This remote printing host can be 32 bit and can do the work of actually sending the job to the printer.
The cost for a solution like this - hardware, software, and time - is generally much more than it would be to simply update the hardware.

A: Here is how I installed it on my Win 7 PC:

*

*"Add a Printer" Wizard

*In my case it is a network printer so I
picked the add with IP option

*Since Windows 7 can't find the
driver automatically I used "Have Disk" and pointed Windows to the "generic MFP 35/25/20ppm PCLe" I downloaded from http://www.oceusa.com/main/view_media.jsp?WebLogicSession=ThPyRhyDxDG16vwKLyWjnqzGN1dKl3X29nkmRLwRQBlnBPTT19WM!1248290065&CONTENT%3C%3Ecnt_id=10134198673384030&FOLDER%3C%3Efolder_id=9852723696640260&bmUID=1360685155879
Hope this recipe works for you too!


text:
Q: Delay between displaying an input value in react what I'm trying to fix is the one-key-delay in the state update with the e.target.value.
I have tried solving it without redux and I have the exact same problem.
http://codepen.io/yoloonthebf/pen/Kmwrpq?editors=0010
Thanks a lot for you help, I hope that you can understand from my pen the issue.
class App extends React.Component{
  //here is the issue ?!
  handleChange(e){

    const BACKSPACE_KEYCODE = 8;
    const keyCodeIn = e.keyCode;
    if ( !isNumber(keyCodeIn) && !(keyCodeIn === BACKSPACE_KEYCODE) ) {
      return e.preventDefault();
    }else{
      store.dispatch({type: 'UPDATE', payload: e.target.value});
    }
    function isNumber(keyCode){
      return (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)
    }
    console.log(store.getState())
  }

  render(){
    return(

{store.getState()}

        <input
          type='text'
          className='form-control'
          maxLength='16'
          onKeyDown={this.handleChange.bind(this)}
        />

    )
  }
}

Edit:
I forgot to mention I only need numbers, 16 of them to be exact, I want to build a Credit Card Validation tool.

A: It's because of your onKeyDown event. The e.target.value is filled after a onKeyUp event, not after a onKeyDown. You should use the onChange event :
http://codepen.io/anon/pen/OmPrNz?editors=0010
I hope it will fit your needs


text:
Q: How do I create (and use) an array of pointers to an array of strings in C? I need to create an array of pointers that will each point to an array of strings.
The base, is a size 2 array of strings (the length of the strings is unknown at start). For example an array of 2 strings (first-name and last-name):
char *name[2];

Now I need to create an array of an unknown size (entered by the user) that will point to the type that I just created.
My idea was to create it this way:
char **people=name;

And then ask the user how many names he would like to enter and allocate enough space to hold all the names.
people=(char**)malloc(sizeof(char*)*num); //num is the number received by the user.

This is where things got too complicated to me and I can't figure out how to I call each individual name to put a string in it.
I built a loop that will receive all the names but I have no idea how to store them properly.
for(i=0;i<num;i++){
    printf("Please enter the #%d first and last name:\n",i+1);
    //Receives the first name.
    scanf("%s",&bufferFirstName);
    getchar();
    //Receives the last name (can also include spaces).
    gets(bufferLastName);
    people[i][0]=(char*)malloc(strlen(bufferFirstName)+1);
    people[i][1]=(char*)malloc(strlen(bufferLastName)+1);
    //^^Needless to say that it won't even compile :(
}

Can anyone please tell me how to properly use this kind of an array of points?
Thanks.

A: from cdecl:

declare foo as array of pointer to array 2 of pointer to char

char *(*foo[])[2];

So, foo[0] is a pointer to array 2 of char *
That is the array, but for your use, you want:

declare foo as pointer to array 2 of pointer to char;

char *(*foo)[2];

Now you can do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *(*foo)[2];

    printf("How many people?\n");
    int n; scanf("%d", &n);

    foo = malloc(sizeof *foo * n);

    for (int i = 0; i < n; i++) {
        char bufFirstName[1024];
        char bufLastName[1024];

        printf("Please insert the #%d first and last name:\n", i+1);

        scanf("%s %s", bufFirstName, bufLastName);

        char *firstName = malloc(strlen(bufFirstName) + 1);
        char *lastName = malloc(strlen(bufLastName) + 1);

        strcpy(firstName, bufFirstName);
        strcpy(lastName, bufLastName);

        foo[i][0] = firstName;
        foo[i][1] = lastName;
    }

    for (int i = 0; i < n; i++) {
        printf("Name: %s LastName: %s\n", foo[i][0], foo[i][1]);
    }

    return 0;
}

Compile with -std=c99
Note that using scanf, strcpy, strlen like that is unsafe because there can be a buffer overflow.
Also, remember to free your malloc's!

A: Not that your approach is wrong, but have you considered instead using a struct that includes first and last name, and then malloc'ing based on the number of names the user will enter:
typedef struct {
    char* first;
    char* last;
} person;

person* people = malloc(num * sizeof(*person));

This just simplifies pointer interaction. While the way you are doing it is a good exercise in understanding pointers better, it may not be the easiest way to understand.
If you are unable to use structs, you should instead be doing:
char** people;
people = malloc(2*num*sizeof(char*));

for (int i = 0; i < 2*num; i++)
    people[i] = malloc(MAX_NAME_SIZE*sizeof(char));

Now you would need to reference the i th person via:
first name: people[i*2 + 0]
last name: people[i*2 + 1]


text:
Q: Rblpapi - bdh function returns NULL with certain fields Does bdh() only work with certain Bloomberg fields on Rblpapi? The following returns NULL:
library(Rblpapi)
blpConnect()
bdh("IBM US Equity", "RR906", start.date = Sys.Date()-22)

and so does using the mnemonic for the field:
bdh("IBM US Equity", "TRAIL_12M_EPS", start.date = Sys.Date()-22)

I can get the current value through bdp() but that's it. bdh() seems to be working fine for Real-time fields but not so for Static ones even though Bloomberg says historical values are available for those through the API.
Has anyone run into this problem? And more importantly, are there any solutions for this? Not sure if I'm missing something obvious.
EDIT:
I figured out a solution. Using the following option returns the correct values:
bdh("IBM Equity", "TRAIL_12M_EPS", Sys.Date()-22, options = c("nonTradingDayFillOption"="ALL_CALENDAR_DAYS"))

Depending on user requirements the value of nonTradingDayFillOption can also be set to ACTIVE_DAYS_ONLY (returns only days when field value changes).

A: Using the following option returns the correct values:
bdh("IBM Equity", "TRAIL_12M_EPS", Sys.Date()-22, options = c("nonTradingDayFillOption"="ALL_CALENDAR_DAYS"))

Depending on user requirements the value of nonTradingDayFillOption can also be set to ACTIVE_DAYS_ONLY (returns only days when field value changes).
Going through the full API documentation does help, I guess...

A: Basically the error here is that you used "IBM Equity" where it should be "IBM US Equity"
Best regards,


text:
Q: SQL Server 2005 Pivot on Unknown Number of Columns I am working with a set of data that looks something like the following.

StudentName  | AssignmentName |  Grade
---------------------------------------
StudentA     | Assignment 1   | 100
StudentA     | Assignment 2   | 80
StudentA     | Total          | 180
StudentB     | Assignment 1   | 100
StudentB     | Assignment 2   | 80
StudentB     | Assignment 3   | 100
StudentB     | Total          | 280

The name and number of assignments are dynamic, I need to get results simlilar to the following.

Student      | Assignment 1  | Assignment 2  | Assignment 3  | Total
--------------------------------------------------------------------
Student A    | 100           | 80            | null          | 180
Student B    | 100           | 80            | 100           | 280

Now ideally I would like to sort the column based on a "due date" that could be included/associated with each assignment.  The total should be at the end if possible (It can be calculated and removed from the query if possible.)
I know how to do it for the 3 assignments using pivot with simply naming the columns, it is trying to do it in a dynamic fashion that I haven't found a GOOD solution for yet.  I am trying to do this on SQL Server 2005
EDIT
Ideally I would like to implement this WITHOUT using Dynamic SQL, as that is against the policy.  If it isn't possible...then a working example with Dynamic SQL will work.

A: I know you said no dynamic SQL, but I don't see any way to do it in straight SQL.
If you check out my answers to similar problems at Pivot Table and Concatenate Columns and PIVOT in sql 2005
The dynamic SQL there is not vulnerable to injection, and there is no good reason to prohibit it.  Another possibility (if the data is changing very infrequently) is to do code-generation - instead of dynamic SQL, the SQL is generated to a stored procedure on a regular basis.

A: To PIVOT this data using dynamic sql you can use the following code in SQL Server 2005+:
Create Table:
CREATE TABLE yourtable
    ([StudentName] varchar(8), [AssignmentName] varchar(12), [Grade] int)
;

INSERT INTO yourtable
    ([StudentName], [AssignmentName], [Grade])
VALUES
    ('StudentA', 'Assignment 1', 100),
    ('StudentA', 'Assignment 2', 80),
    ('StudentA', 'Total', 180),
    ('StudentB', 'Assignment 1', 100),
    ('StudentB', 'Assignment 2', 80),
    ('StudentB', 'Assignment 3', 100),
    ('StudentB', 'Total', 280)
;

Dynamic PIVOT:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(AssignmentName)
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT StudentName, ' + @cols + ' from
             (
                select StudentName, AssignmentName, grade
                from yourtable
            ) x
            pivot
            (
                min(grade)
                for assignmentname in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo
The result is:
| STUDENTNAME | ASSIGNMENT 1 | ASSIGNMENT 2 | ASSIGNMENT 3 | TOTAL |
--------------------------------------------------------------------
|    StudentA |          100 |           80 |       (null) |   180 |
|    StudentB |          100 |           80 |          100 |   280 |

A: The only way I've found to do this is to use dynamic SQL and put the column labels into a variable.

A: you could query information_schema to get the column names and types, then use the result as a subquery when you build your result set.  Note you'll likely have to change the login's access a bit.

A: This is the same as PIVOT in sql 2005
If this data is for consumption in a report you could use a SSRS matrix. It will generate columns dynamically from result set. I've used it many times -  it works quite well for dynamic crosstab reports.
Here's a good example w/ dynamic sql.
http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx

A: select studentname,[Assign1],[Assign2],[Assign3],[Total]
from
(
 select studentname, assignname, grade from student
)s
pivot(sum(Grade) for assignname IN([Assign1],[Assign2],[Assign3],[Total])) as pvt

A: SELECT TrnType
INTO #Temp1
FROM
(
    SELECT '[' + CAST(TransactionType AS VARCHAR(4)) + ']' AS TrnType FROM tblPaymentTransactionTypes
) AS tbl1

SELECT * FROM #Temp1

SELECT * FROM
(
    SELECT FirstName + ' ' + LastName AS Patient, TransactionType, ISNULL(PostedAmount, 0) AS PostedAmount
    FROM tblPaymentTransactions
            INNER JOIN emr_PatientDetails ON tblPaymentTransactions.PracticeID = emr_PatientDetails.PracticeId
            INNER JOIN tblPaymentTransactionDetails ON emr_PatientDetails.PatientId = tblPaymentTransactionDetails.PatientID
                        AND tblPaymentTransactions.TransactionID = tblPaymentTransactionDetails.TransactionID
    WHERE emr_PatientDetails.PracticeID = 152
) tbl
PIVOT (SUM(PostedAmount) FOR [TransactionType] IN (SELECT * FROM #Temp1)
) AS tbl4


text:
Q: Padding between Textview border and drawableLeft This is my TextView layout:

As you can see, there is a padding between the border (the stroke) and the image inside the TextView, which is given using drawableLeft attribute.
I know I could use drawablePadding attribute to adjust the padding between the image and the text, but I want to remove the padding between the stroke and the image. Can I do something like that? And, possibily, from XML?
This is the TextView's layout:
<TextView
            android:id="@+id/txtPlate2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableStart="@mipmap/ic_italian_plate"
            android:textColor="@color/black"
            android:textSize="40sp"
            android:text="text"
            android:textAlignment="center"
            android:paddingStart="0dp"
            android:paddingEnd="5dp"
            android:background="@drawable/plate_textview"/>

and this is plate_textview drawable, where I simply add a stroke:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android">

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dip"
        android:color="@color/black"/>
</shape>

Thanks in advance!

A: The problem is your are using image from mipmap folder. mipmap is only used for launcher icons and its added extra padding and elevation when show on view.

Always keep resource icons in drawable folder and use it as
  @drawable/ic_italian_plate.

#. You can add padding and corners to custom drawable using <padding> and <corners>.
Update plate_textview.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android">

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dp"
        android:color="@color/black"/>

    <padding
        android:top="2dp"
        android:bottom="2dp"
        android:left="2dp"
        android:right="8dp" />

    <corners
        android:radius="2dp" />
</shape>

Update TextView as below:
<TextView
    android:id="@+id/txtPlate2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:gravity="center"
    android:drawableStart="@drawable/ic_italian_plate"
    android:textColor="@color/black"
    android:textSize="40sp"
    android:text="I-123-4568"
    android:textAlignment="center"
    android:background="@drawable/plate_textview"/>

OUTPUT:

Hope this will help~


text:
Q: InputMismatchException when attempting to run program again in do while loop Having successfully created a policy holder and writing the information to csv I try to run the program again using a do while loop but receive an inputmismatchexception after typing surname.
Can someone point me in the right direction or advise what I am doing wrong with this piece of code?
Here is example of what happens...
console
/**
 *
 */
package InsurancePolicySystem;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * @author
 *
 */
public class InsurancePolicy {

    // create variables
    private String surname;
    private int age;
    private String motorType;
    private String motorPolicyId;
    private String addAnother;
    private String pattern = "^[a-zA-Z](\\s?[a-zA-Z]){2,29}$";

    // import scanner for user input
    Scanner scanner = new Scanner(System.in);

    // time stamp number. -1 used on month as time stamp displays next year instead
    // of current year
    int year = Calendar.getInstance().get(Calendar.YEAR);
    int month = Calendar.getInstance().get(Calendar.MONTH) - 1;

    // sum of the year and month
    int timeStamp = year + month;

    /**
     * default constructor
     */
    public InsurancePolicy() {

    }

    /**
     * non default constructor
     *
     * @param surname
     * @param age
     * @param motorType
     * @param motorPolicyId
     */
    public InsurancePolicy(String surname, int age, String motorType, String motorPolicyId) {
        this.surname = surname;
        this.age = age;
        this.motorType = motorType;
        this.motorPolicyId = motorPolicyId;

    }

    /**
     *
     * @return
     */
    public String getSurname() {
        return surname;
    }

    /**
     * Surname should be more than 3 letters and not greater than 20. Anything more
     * will cause a not valid error!
     *
     * @param surname
     * @throws IllegalArgumentException
     */
    public void setSurname(String surname) throws IllegalArgumentException {
        this.surname = surname;
    }

    /**
     *
     * @return
     */
    public int getAge() {
        return age;
    }

    /**
     * Age must be between 18 & 50 Any other age will produce not eligible error!
     *
     * @param age
     * @throws IllegalArgumentException
     */
    public void setAge(int age) throws IllegalArgumentException {
        if ((age >= 18) && (age <= 50)) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Not eligible for an insurance policy!");
        }
    }

    /**
     *
     * @return
     */
    public String getMotorType() {
        return motorType;
    }

    /**
     * motor type should only be either CAR, TAXI or BUS. if statement to prevent
     * other vehicle types and throw error if user inputs a different vehicle.
     *
     * @param motorType
     * @throws IllegalArgumentException
     */
    public void setMotorType(String motorType) throws IllegalArgumentException {
        if (motorType.equals("CAR") || motorType.equals("TAXI") || motorType.equals("BUS")) {
            this.motorType = motorType;
        } else {
            throw new IllegalArgumentException("Not eligible for an insurance policy!");
        }
        this.motorType = motorType;

    }

    /**
     *
     * @return
     */
    public String getMotorPolicyId() {
        return motorPolicyId;
    }

    /**
     *
     * @param motorPolicyId
     */
    public void setMotorPolicyId(String motorPolicyId) {
        this.motorPolicyId = motorPolicyId;
    }

    /**
     * Method to write policy holder particulars to a csv file. Creates ArrayList
     * and uses collect joining to add comma for file.
     *
     * @throws IOException
     */
    public void writeToFile() throws IOException {
        BufferedWriter writer = new BufferedWriter(
                new FileWriter("/Users/johnj/eclipse-workspace/InsuranceProject/insurance.csv", true));

        // creates policy holder (insurance) array
        ArrayList<String> insurance = new ArrayList<String>();
        insurance.add(surname);
        insurance.add(Integer.toString(age));
        insurance.add(motorType);
        insurance.add(motorPolicyId);

        // write array to csv file
        String collect = insurance.stream().collect(Collectors.joining(", "));
        System.out.println(collect);
        writer.write(collect);
        writer.newLine();
        writer.flush();
        writer.close();
    }

    /**
     * Builds and generates user input. Will then add it into an array list and
     * append to writeToFile(). Included do while loop for user to continue creating
     * policy profiles without having to re run program.
     *
     * @param motorType
     */
    public void addPolicyHolder() throws IOException {

        try {

            do {

                // enter policy holder surname. Checks pattern to ensure compliance
                System.out.println("Please type your surname...");
                surname = scanner.next(pattern).toUpperCase().trim();
                setSurname(this.surname);

                // user input age
                System.out.println("Please type your age...");
                age = scanner.nextInt();
                setAge(this.age);

                // user input motor type which is converted to upper case
                System.out.println("Please type your motor type i.e. CAR, TAXI or BUS...");
                motorType = scanner.next().toUpperCase().trim();
                setMotorType(this.motorType);

                System.out.println(); // used to create next line space

                // Motor Policy Id should be 3 characters from surname as well as time stamp. If
                // time stamp odd number add 1 or else add 0 if even.
                motorPolicyId = surname.substring(0, 3) + timeStamp;
                if (timeStamp % 2 == 0) {
                    motorPolicyId = this.motorPolicyId + 0;
                } else {
                    motorPolicyId = this.motorPolicyId + 1;
                }

                // creates csv file
                writeToFile();

                // prints completed user input of policy holder
                System.out.println();
                System.out.println("Surname      :" + this.surname);
                System.out.println("Age          :" + this.age);
                System.out.println("Policy Ref   :" + this.motorPolicyId);
                System.out.println("Motor Type:  :" + this.motorType);

                System.out.println(); // used to create next line space

                // asks user if they would like to create a different policy holder
                System.out.println("Add another Policy Holder (Y or N)..");
                addAnother = scanner.next();
            } while (addAnother.equalsIgnoreCase("Y")); // If N program ends.
        } catch (Exception exception) { // if exception program ends
            System.out.println(
                    "There is a problem ... Policy Holder does meet necessary criteria, run the program again.");
        } finally {
            scanner.close();
            System.out.println("Program ended!"); // end of program
        }

    }

public static void main(String[] args) throws IOException {

        InsurancePolicy insurancePolicy = new InsurancePolicy();
        insurancePolicy.addPolicyHolder();

    }

}

I am able to complete a first run but do while loop fails when trying to add another policy holder.


text:
Q: Match with concatenate across google sheets I have this formula:
=IF(MATCH($A1&B$1,Sheet2!$A$1:$A$100&Sheet2!$B$1:$B$100,0), 1, 0)
I expect the formula in Sheet 1, Column C to produce all ones as in Excel but I only get a 1 when there is a row with a,b in Sheet 2:
https://docs.google.com/spreadsheets/d/1pyuWNNU7S07AC7d4zMvXft5pEz3AeAbeHcQp-wNsXpo/edit?usp=sharing
Why is this and is there a way around it that will also work in Excel?

Edit to clarify:
I want to be able to look up the value in two cells concatenated, e.g., $A1&B$1 and check if this matches any item in the list:
[Sheet2!$A$1&$B$1, Sheet2!$A$2&$B$2, Sheet2!$A$3&$B$3, ...]
Other details that may be important:
In my actual example, the columns I am looking at are not adjacent.
I would like the result to be compatible with as many spreadsheet programs as possible, especially Excel, Google Sheets and LibreOffice.
I will be writing the formula using openpyxl for Python.
Thanks, in advance.

A: I do not believe MATCH() is the appropriate function. There are lots of other options like vlookup(), index().
I like using the QUERY() function personally.
=QUERY(Sheet2!$A1:$B, "SELECT COUNT(A) WHERE A = '"&A1&"' AND B = '"&B1&"' LABEL COUNT(A) ''",0)

QUERY() shows #N/A when no results are found so we can wrap the above function accordingly
=IF(ISNA(query(Sheet2!$A1:$B, "SELECT COUNT(A) WHERE A = '"&A1&"' AND B = '"&B1&"' LABEL COUNT(A) ''",0)), "",query(Sheet2!$A1:$B, "SELECT COUNT(A) WHERE A = '"&A1&"' AND B = '"&B1&"' LABEL COUNT(A) ''",0))

A: the best way to use MATCH is making both parameters (search_key and range) expressed as brackets keys, the answer is:
=IF(MATCH({$A1}&{B$1},{Sheet2!$A$1:$A$100}&{Sheet2!$B$1:$B$100},0), 1, 0)
You MUST press Mayus + enter to asign the formula as an array


text:
Q: How important are properties file lineendings for Spring? I'm using Spring to manage dependency injection and properties for my desktop application. It reads some properties from x.properties files that is not in any archive, but plainly on disk for user convenience. As a precaution I took some steps to make maven take a properties file on build and generate x-win.properties and x-unix.properties with appropriate line endings and permissions, so the end-user would have two files, and program chooses one depending on which platform he/she is on. I made some testing and read the unix file on windows, and I didn't face any problems, which leads me thinking that maybe I'm overengineering and it's pointless hassle, where I could just not care about the lineendings at all. Am I missing something, what are the possible problems I'm facing when ignoring the lineendings completely?

A: Looks like problems arise with wrong line endings, when using some plain text editors like notepad, so my current building logic looks necessary. Thanks @Andreas


text:
Q: How to establish serial connection with Bluetooth device on Win7 I am really frustrated and have no idea where to search for an answer.
Currently I am working on a project to detect drowsiness with an ECG device (Zephyr Bioharness 3). The device works but I can't find it with windows (For example like this). I tried several things:

*

*Find the device with my Smartphone -> works

*Find the device with an Ubuntu on the same Laptop -> works

*Connect directly on Win7 via Bluetooth with this Python Script: Gist -> connects and sends data

*Find other Bluetooth devices with my Laptop on Win7 -> Bluetooth radio is dound

*COM port for (virtual) serial connection to a bluetooth device (device manager)

What I am trying, is getting this script to work: ZephyrApp. Beside some compatibility problems with QT and serial (which I was able to fix), the programm hangs here protocol.py. I suspect the problems of not finding the device relates to the problems with the program. I know this is very special case, but hope anyone has an idea, how to fix this.
Regards,
paul
EDIT: Another PC with Win7 can't detect the device as well, it seems it is a Windows problem.

A: The device can't be detected with Win7, but I found a way to connect via bluetooth directly: https://gist.github.com/darkopetrovic/2127217


text:
Q: Jahia/JVM/Tomcat Crash we are using following configuration:
CATALINA_OPTS="$CATALINA_OPTS -Xms6144m -Xmx6144m -Dcertain.config=/data02/certain/config -Djava.awt.headless=true -XX:MaxPermSize=1024m -server -Dhibernate.jdbc.use_streams_for_binary=true -verbose:gc -XX:+HeapDumpOnOutOfMemoryError -XX:ParallelGCThreads=4 -XX:LargePageSizeInBytes=512m -XX:+UseParallelOldGC -XX:+UseParallelGC -XX:+UseCompressedOops -XX:+AggressiveHeap -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps"
JDK 1.6 version 22
OS:Red Hat Enterprise Linux Server release 6.

CPU:total 4 (1 cores per cpu, 1 threads per core)

Java HotSpot(TM) 64-Bit Server VM (17.1-b03) for linux-amd64 JRE (1.6.0_22-b04)
we keep getting:

# A fatal error has been detected by the Java Runtime Environment:

# java.lang.OutOfMemoryError: requested 17179869200 bytes for Chunk::new. Out of swap space?

#
#  Internal Error (allocation.cpp:215), pid=5845, tid=139708177794816

  Error: Chunk::new

# JRE version: 6.0_22-b04
# Java VM: Java HotSpot(TM) 64-Bit Server VM (17.1-b03 mixed mode linux-amd64 compressed oops)


text:
Q: How to get and print how many times a loop spins in a thread before it gets switched to other threads? Instead of printing o and -, I want to print the number of o and - on the console. However, I have no idea how to get how many times a loop spins in a thread before it gets switched to other threads.
If there are events something likes  OnLeaving and OnEntering on a thread, I can get the number of spins in the given time slice. Unfortunately, I have no such events.
class Program
{
    public const int N = 1000;

    static void Main(string[] args)
    {
        ThreadStart ts = DoWork;
        Thread t = new Thread(ts);

        t.Start();

        for (int x = 0; x < N; x++)
        {
            Console.Write('o');
        }

        t.Join();

    }

    private static void DoWork()
    {
        for (int x = 0; x < N; x++)
        {
            Console.Write('-');
        }
    }
}

Could you show me how to do this scenario?

A: To reiterate: AbhayDixit's comment gives you a cycle counter. You just need to add a locking mechanism and reset the counters after a context switch.
I have modified your code to include a cycle counter. Note that I have increased N significantly. Otherwise, one thread will just run through its 1000 iterations at once - because you no longer have a Write() instruction to slow it down.
class Program
{
    public const int N = 1000000;
    private static object _l = new object();

    private static int _i = 0;
    private static int _j = 0;

    static void Main(string[] args)
    {
        ThreadStart ts = DoWork;
        Thread t = new Thread(ts);

        t.Start();

        for (int x = 0; x < N; x++)
        {
            lock (_l)
            {
                // j-thread has run?
                if (_j > 0)
                {
                    // print and reset j
                    Console.Write("j{0} ", _j);
                    _j = 0;
                }
                _i++;
            }
        }

        t.Join();

        // print remaining cycles
        // one of the threads will have run after the other has finished and
        // hence not been printed and reset.
        if (_i > 0)
            Console.Write("i{0} ", _i);
        if (_j > 0)
            Console.Write("j{0} ", _j);

        Console.ReadKey();

    }

    private static void DoWork()
    {
        for (int x = 0; x < N; x++)
        {
            lock (_l)
            {
                // i-thread has run?
                if (_i > 0)
                {
                    // print and reset i
                    Console.Write("i{0} ", _i);
                    _i = 0;
                }
                _j++;
            }
        }
    }
}


text:
Q: greenDAO generator gives console error that doesn't make sense I'm pretty new to Android development in general, and I've never even used greenDAO. But after spending a lot of time working on my generator class (Where I model my entities), I was finally able to produce something that looked similar to the example given on GitHub.
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
import de.greenrobot.daogenerator.ToMany;

public class simbalDAOgen {

public static void main(String[] args) throws Exception {
    Schema schema = new Schema(1, "com.bkp.simbal"); //Schema(Int version, String package name)
    addCBTrans(schema); //Add the entities to the schema
    new DaoGenerator().generateAll(schema, "../Simbal/src-gen", "../Simbal/src-test"); //Generate DAO files
}

private static void addCBTrans(Schema schema){
    Entity checkbook = schema.addEntity("Checkbook");
    checkbook.addIdProperty();
    checkbook.addStringProperty("name").notNull();
    checkbook.addDateProperty("dateModified");
    checkbook.addStringProperty("balance"); // Use a string property because BigDecimal type should be used for currency

    Entity transaction = schema.addEntity("Transaction");
    transaction.setTableName("TRANS"); // "TRANSACTION" is a reserved SQLite keyword
    transaction.addIdProperty();
    transaction.addStringProperty("name");
    transaction.addStringProperty("category");
    Property transDate = transaction.addDateProperty("date").getProperty();
    transaction.addStringProperty("amount"); // Again use string for BigDecimal type
    transaction.addStringProperty("notes");
    Property cbName = transaction.addStringProperty("cb").notNull().getProperty(); //What checkbook the transaction is in

    ToMany cbToTrans = checkbook.addToMany(transaction, cbName); //Actually ties the transactions to their correct checkbooks
    cbToTrans.setName("Transactions");
    cbToTrans.orderAsc(transDate);
}
}

I then ran the code as a java application to generate my DAO files, just like the documentation on greenDAO says to. The files were successfully generated, however I did get this line in the console in Eclipse:
Warning to-one property type does not match target key type: ToMany 'Transactions' from Checkbook to Transaction

I'm really not sure if I need to be concerned since the files were generated. But what I don't understand is why there's mention of a "to-one" relation when I'm using a "to-many" relation, as can be seen in my code. (There can be many transaction entities in a checkbook entity, and I'm intending to use each checkbook entitys' name to tie the transactions to it.)
Do I need to go back and fix a part of my code? Please ask if I need to clarify anything, and thanks for your time!

A: After looking at the files generated for me by greenDAO, I've found the solution to my problem. It seems to me that the addToMany() method expects a Long property to be passed to it and I was using a String property. So I changed these two lines in my generator code:
Property cbName = transaction.addStringProperty("cb").notNull().getProperty();

ToMany cbToTrans = checkbook.addToMany(transaction, cbName);

to this:
Property checkbookId = transaction.addLongProperty("checkbookId").notNull().getProperty();

ToMany cbToTrans = checkbook.addToMany(transaction, checkbookId);

which solved my problem. I was under the impression I could use any type of property to tie the transactions to the checkbook, so I was trying the use the checkbook name.

A: it seems to be GreenDao only accepts type Long as foreign key


text:
Q: O que é mais rápido para ser lido e editado, um banco de dados ou um .txt? Seria para armazenar e reescrever apenas 1 dígito INT, apagando um e escrevendo outro, na condição de que quando chegar a 5, voltar pro 1, e ir fazendo esse loop toda vez que alguém acessar.
Sempre que alguém acessar a página, o valor seria acrescido de +1 e gravado, exceto que já tivesse em 5, aí voltaria pro 1.
Enfim. PHP + MySQL, ou PHP + .txt, qual é mais rápido para essa finalidade?
Considerando que se fazendo centenas de requests simultâneos não bugue o sistema, qual é melhor?

A: Um arquivo texto flat será sempre mais rápido, ele não tem que fazer quase nada. Um banco de dados executa um conjunto monumental de coisas para garantir a integridade dos dados e fazer isso de uma forma fácil e padronizada.
Isso não quer dizer que seja a melhor opção. Se for acessar o arquivo concorrentemente tem que saber o que está fazendo, caso contrário terá problemas, mesmo em um padrão simples como o relatado.
O que não cria bugs no sistema é dominar todo o processo de desenvolvimento de software, implantação e manutenção da infraestrutura. Isso não é só saber se é melhor usar MySQL ou .txt. Mas se não sabe o que é melhor, vá no mais seguro que é o banco de dados. Pelo menos ele exige menos cuidado.
Uma alternativa intermediária seria o uso do SQLite que possui as características do banco de dados com algumas facilidades do acesso ao arquivo, incluindo melhor performance.
Em alguns casos outro banco de dados pode ser mais útil, quem sabe um NoSQL.

A: Segundo o que descreveu, haverá centenas de conexões simultâneas. Cada conexão incrementa um valor e quando chegar a 5, volta ao valor 1.
Com arquivo txt isso pode ser um problema pois terá que criar condições para impedir inconsistências.
Uma lógica é travar a edição ou acesso ao arquivo caso já esteja aberto por algum usuário:
$f = fopen('fit.txt', 'a');
if(flock($f, LOCK_EX | LOCK_NB)) {
    $n = fread($fp, 4);
    ($n == 5)? $n = 1: $n++;
    fwrite($f, $n);
    flock($f, LOCK_UN);
}
fclose($f);

Usando um banco de dados essa operação é mais segura, no entanto, é óbvio que terá um custo muito maior de processos.
Antes de pensar em performance, pense em consistência. Se a rotina é segura e tem certeza de que não haverá falha, você vai para o "próximo estágio" que é a otimização.
Nesse exemplo acima com flock(), o processo é "super rápido" mas ainda assim pode acontecer alguma falha. Algo inexperado onde demore muito para liberar para o próximo usuário.
Imagine então um cenário onde 200 usuários acessaram no mesmo exato tempo.
O primeiro será o "sortudo". Vai ler e escrever o número e liberar para o segundo, terceiro, quarto. Mas o que estiver por último na fila conseguirá ler e escrever o valor corretamente ou retornará algum erro por longo tempo de espera?
Considere que se o sistema tem centenas de acessos simultâneos, digamos que num único segundo receba 150 conexões e depois de 2 segundos mais 200 e depois de 2 segundos mais 100. Só aí você já tem, num espaço de 5 segundos, 350 neguinho na fila de espera para ler e escrever nesse txt. O sistema pode interromper a execução por volta do número 200 devido a longa espera.
Pode ser o caso de repensar a lógica do negócio.
Caso não tenha essa grande quantidade de conexões simultâneas, aí sim, o simples flock(), como no exemplo, pode resolver e ser ainda uma opção mais viável que um banco de dados, em termos de performance.


text:
Q: Java multiline scanner input I have a specific problem regarding Scanner and its way of doing input from System.in.
What I want to do: I need to read a single input given from System.in. The problem is that this input can have more than one line (the input can have many \n characters).
What I tried:
The obvious thing I tried is Scanner.nextLine() method, but ofcourse, this will not read all data. The next thing I tried is this:
Scanner sc = new Scanner(System.in);
List<String> data = new ArrayList<>();

while(sc.hasNextLine()){
    String line = sc.nextLine();
    if(line.isEmpty()){
        break;
    }
    data.add(line);
}

But this will also skip a lot of data - for instance, when there is an empty line in the middle of given text.
I also tried to remove the break; statement and hope that the while(sc.hasNextLine()) loop will break itself, but this will never happen since scanner will wait for the data.
Can this be done in Java? Thanks for your time

A: If you want to read all input, on multiple lines, into a list of strings, one element per input line, then the user will have to indicate when the input has ended. This is often done by using the End-of-File character: on the Windows Command Prompt, it's Ctrl-Z, and on Linux, OS X and the IntelliJ IDE input window on all platforms, it's Ctrl-D.
You can read the lines with the following code:
Scanner sc = new Scanner(System.in);
List<String> data = sc.tokens().collect(Collectors.toList());

A: If you press Command + D on OS X or Control + D on Windows, you will insert an end of line character.
When the scanner reaches an end of line character, hasNextLine will return false and the loop will terminate.
So remove this:
if(line.isEmpty()){
    break;
}

and type an end of line character after your multi line input.
Alternatively, if this is allowed, you can put your input as a string to the scanner. For example, if you want to input this input:
Hello World
This is a
Multiline
input

You can initialise the scanner like this:
Scanner line = new Scanner("Hello World\n" +
        "This is a\n" +
        "Multiline\n" +
        "input");

Or you can put your input into a file and let the scanner read that:
Scanner line = new Scanner(new File("path to your input file"));

A: Use this type for reading
String read = "";
    Scanner sc = new Scanner(System.in);
    String line;
    while (sc.hasNextLine()) {
        line = sc.nextLine();
        if (line.isEmpty()) {
            break;
        }
        read += line + "\n";
    }
    System.out.println(read);

Here, first we check is there nextline occurs or not. if yes then read data using sc.nextLine() method and if read data is blank then break loop.


text:
Q: How can I check Windows Server 2008 health status and use them with Python I am working on a project for which I need to create a Python class which can determine underlying OS on which it is running and performs a sequence of checks if OS is found to be Windows Server 2003/2008.
Currently my check includes following parameters:

*

*CPU Utilization Check

*RAM Utilization Check

*HD Volume space available

*Well configured network parameters like DNS and DHCP

*RDP and other critical application services running

For 1 to 3 information can be extracted from Windows Task Manager BUT the question in HOW ?
For 4, ipconfig /all output would be fine and I think I would be able to extract them either from some python modules or regex ! (Believe me I am not sure)
For 5, I think I should use powershell trimmed Get-Services output.
I look foreward to seek help on points 1 to 3

*

*How can I extract this information from windows machine ?

*How can I use that information for further processing in Python ?

Apart from this any type of suggestion/query/improvements/known issues are most welcome.

A: Give this a look for parts 1, 2 and 3: http://code.google.com/p/psutil/
As for network parameters, you might have a bit better luck with parsing the output from the following command: netsh interface ipv4 show config for interface configuration and DNS.
However you can also try this: http://alastairs-place.net/projects/netifaces/
It doesn't give very friendly interface names on Windows but works. However I don't think it shows whether you're using DHCP or what you're using for DNS.
Lastly for 5 there is http://code.activestate.com/recipes/303339/ but it is unhelpfully only processes. There's a WMI Python module that can provide service information however: http://timgolden.me.uk/python/wmi/index.html


text:
Q: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to set posix_spawn_file_actions for fd -1 at index 0 In Swift 4, on Xcode Version 9.3.1 (9E501), I am utilizing DispatchQueue.global(qos: .background).async {...} to run a while(true) loop in the background:
func appStartDispatchQueue() {
    DispatchQueue.global(qos: .background).async {

        while(true) {
            let networkStatus = Verification.onCompanyNetwork()

            DispatchQueue.main.async {
                self.onNetwork = networkStatus
            }
            sleep(3)
        }
    }
}

Verification.onCompanyNetwork() is running a ping via bash script to see if there is response from a server on a corporate network.
I need this thread running in the background at all times for this application - so even if it fails, how can I catch the exception and make sure the thread starts up again? Right now I'm not even sure why the thread is failing...
Two discovered crash scenarios so far:

*

*while running app (outside of Xcode), the app crashes on average after 3-6 hours of continuous running

*while running app (inside of Xcode), the app does NOT crash, even after 3-6 hours of continuous running

The entire error message is found below:
Crashed Thread:        1  Dispatch queue: com.apple.root.background-qos

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to set posix_spawn_file_actions for fd -1 at index 0 with errno 9'
terminating with uncaught exception of type NSException
abort() called

Application Specific Backtrace 1:
0   CoreFoundation                      0x00007fff339d9ecd __exceptionPreprocess + 256
1   libobjc.A.dylib                     0x00007fff5fa91720 objc_exception_throw + 48
2   CoreFoundation                      0x00007fff339d9cff +[NSException raise:format:] + 201
3   Foundation                          0x00007fff35ccf581 -[NSConcreteTask launchWithDictionary:error:] + 3236
4   AdminAccess                         0x000000010f268b32 _T011AdminAccess9ScriptingC12shellCommandSSSgSS0D4Path_SaySSG9argumentstFZ + 370
5   AdminAccess                         0x000000010f266e20 _T011AdminAccess9ScriptingC13runBashScriptS2S10scriptName_SS3argtFZ + 32496
6   AdminAccess                         0x000000010f25779b _T011AdminAccess12VerificationC16onCompanyNetworkSbyFZ + 107
7   AdminAccess                         0x000000010f26a834 _T011AdminAccess11AppDelegateC21appStartDispatchQueueyyFyycfU_ + 36
8   AdminAccess                         0x000000010f26a99d _T011AdminAccess11AppDelegateC21appStartDispatchQueueyyFyycfU_TA + 13
9   AdminAccess                         0x000000010f26aa1d _T0Ieg_IeyB_TR + 45
10  libdispatch.dylib                   0x00007fff60b10d53 _dispatch_call_block_and_release + 12
11  libdispatch.dylib                   0x00007fff60b11dcf _dispatch_client_callout + 8
12  libdispatch.dylib                   0x00007fff60b1fe80 _dispatch_root_queue_drain + 671
13  libdispatch.dylib                   0x00007fff60b204bd _dispatch_worker_thread2 + 90
14  libsystem_pthread.dylib             0x00007fff60d526dd _pthread_wqthread + 619
15  libsystem_pthread.dylib             0x00007fff60d52405 start_wqthread + 13

Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff60c9917a mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff60c996d0 mach_msg + 60
2   com.apple.CoreFoundation        0x00007fff339230c2 __CFRunLoopServiceMachPort + 337
3   com.apple.CoreFoundation        0x00007fff33922611 __CFRunLoopRun + 1654
4   com.apple.CoreFoundation        0x00007fff33921d48 CFRunLoopRunSpecific + 463
5   com.apple.HIToolbox             0x00007fff32bb8ab5 RunCurrentEventLoopInMode + 293
6   com.apple.HIToolbox             0x00007fff32bb87eb ReceiveNextEventCommon + 618
7   com.apple.HIToolbox             0x00007fff32bb8568 _BlockUntilNextEventMatchingListInModeWithFilter + 64
8   com.apple.AppKit                0x00007fff30e73363 _DPSNextEvent + 997
9   com.apple.AppKit                0x00007fff30e72102 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1362
10  com.apple.AppKit                0x00007fff30e6c165 -[NSApplication run] + 699
11  com.apple.AppKit                0x00007fff30e5b8a3 NSApplicationMain + 780
12  mace.AdminAccess                0x000000010f26be6d main + 13 (AppDelegate.swift:18)
13  libdyld.dylib                   0x00007fff60b5fed9 start + 1

Thread 1 Crashed:: Dispatch queue: com.apple.root.background-qos
0   libsystem_kernel.dylib          0x00007fff60c9f23e __pthread_kill + 10
1   libsystem_pthread.dylib         0x00007fff60d55c1c pthread_kill + 285
2   libsystem_c.dylib               0x00007fff60c081c9 abort + 127
3   libc++abi.dylib                 0x00007fff5e289231 abort_message + 231
4   libc++abi.dylib                 0x00007fff5e2893cd default_terminate_handler() + 265
5   libobjc.A.dylib                 0x00007fff5fa93c87 _objc_terminate() + 97
6   libc++abi.dylib                 0x00007fff5e294dfe std::__terminate(void (*)()) + 8
7   libc++abi.dylib                 0x00007fff5e294e73 std::terminate() + 51
8   libdispatch.dylib               0x00007fff60b11de3 _dispatch_client_callout + 28
9   libdispatch.dylib               0x00007fff60b1fe80 _dispatch_root_queue_drain + 671
10  libdispatch.dylib               0x00007fff60b204bd _dispatch_worker_thread2 + 90
11  libsystem_pthread.dylib         0x00007fff60d526dd _pthread_wqthread + 619
12  libsystem_pthread.dylib         0x00007fff60d52405 start_wqthread + 13

Thread 2:: com.apple.NSEventThread
0   libsystem_kernel.dylib          0x00007fff60c9917a mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff60c996d0 mach_msg + 60
2   com.apple.CoreFoundation        0x00007fff339230c2 __CFRunLoopServiceMachPort + 337
3   com.apple.CoreFoundation        0x00007fff33922611 __CFRunLoopRun + 1654
4   com.apple.CoreFoundation        0x00007fff33921d48 CFRunLoopRunSpecific + 463
5   com.apple.AppKit                0x00007fff30e7bf89 _NSEventThread + 160
6   libsystem_pthread.dylib         0x00007fff60d53305 _pthread_body + 126
7   libsystem_pthread.dylib         0x00007fff60d5626f _pthread_start + 70
8   libsystem_pthread.dylib         0x00007fff60d52415 thread_start + 13

Thread 3:
0   libsystem_pthread.dylib         0x00007fff60d523f8 start_wqthread + 0
1   ???                             0x0000000054485244 0 + 1414025796

Thread 4:
0   libsystem_pthread.dylib         0x00007fff60d523f8 start_wqthread + 0
1   ???                             0x0000000000000903 0 + 2307

Thread 1 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000000  rbx: 0x00007000054b9000  rcx: 0x00007000054b88b8  rdx: 0x0000000000000000
  rdi: 0x0000000000002703  rsi: 0x0000000000000006  rbp: 0x00007000054b88f0  rsp: 0x00007000054b88b8
   r8: 0x00007000054b8778   r9: 0x00007000054b8950  r10: 0x0000000000000000  r11: 0x0000000000000206
  r12: 0x0000000000002703  r13: 0x0000003000000008  r14: 0x0000000000000006  r15: 0x000000000000002d
  rip: 0x00007fff60c9f23e  rfl: 0x0000000000000206  cr2: 0x00007fff93949188

A: The best Way to do that is using https://github.com/ashleymills/Reachability.swift
in this link you'll see how the ask for google.com server all the time.
https://github.com/ashleymills/Reachability.swift/blob/master/ReachabilitySample/ViewController.swift
there are many ways to do it
let hostReachability = Reachability(hostName:"www.apple.com")
hostReachability.startNotifier()

NSNotificationCenter.defaultCenter().addObserver(
      self,
      selector: "reachabilityChanged:",
      name: kReachabilityChangedNotification,
      object: nil)

it will avoid you to use while(true) or stuff like that is hard to handle with.
enum NetworkStatus {
    case notReachable, reachableViaWiFi, reachableViaWWAN
}
var currentReachabilityStatus: NetworkStatus


text:
Q: Cannot resolve google.sheets in google sheets api I am using Google Sheets API with NodeJS and trying out the simplest demo from https://developers.google.com/sheets/api/quickstart/nodejs
I am getting a runtime error "google.sheets is not a function". When I am inspecting, I got the debug screenshot below,

The google variable is from var google = require("googleapis");, which seems to load well(has a bunch of content inside). Of its properties there does not seem to have a "sheets" property, thus the executing result will say it is not a function.
No one is asking a similar question online. Did I miss a very obvious step of setting up?

A: Change the import to:
var {google} = require("googleapis");