text:
Q: Best way to convert time string `1'29.30"` to time format I have a DataFrame with column contains string with time format.
It's looks like this 1'29.30" and it represent 1 minute 29 seconds and 30 centisecond (30/1000 seconds).
I would like to convert it to time format.
My only idea is to create regexp expresion for it.
There is an other way for this task?
Eg. of my df['time_str']
124    1'29.30"
125    1'29.36"
126    1'29.54"
127    1'29.93"
128    1'30.62"
129    1'30.80"
130    1'30.83"
131    1'31.22"
Name: time_str, dtype: object

A: You can use pandas.to_datetime with a custom format '%M\'%S.%f"', then keep only the time part (without the date part)
import pandas as pd

data = ['1\'29.30"', '1\'29.36"', '1\'29.54"', '1\'29.93"',
        '1\'30.62"', '1\'30.80"', '1\'30.83"']

df = pd.DataFrame(data, columns=['time'])
df['time'] = pd.to_datetime(df['time'], format='%M\'%S.%f"').dt.time

A: I think regex would be the best bet, but rather than a time format you are likely looking for a timedelta. Time would be a given time of day as an example, whereas you appear to have a measurement of time passing. Try using the following, I tested with an individual time but I'll leave it to you to plug this into the dataframe to convert each string.
import re
from datetime import timedelta

original = "1'29.30\""
regex = re.compile("([0-9]*)'([0-9]*).([0-9]*)\"")
matches = regex.match(original).groups()
# Notice that I had to convert centiseconds to milliseconds
delta = timedelta(minutes=int(matches[0]), seconds=int(matches[1]), milliseconds=int(matches[2])*10)


text:
Q: Implementing Max Reduce in Cuda I've been learning Cuda and I am still getting to grips with parallelism. The problem I am having at the moment is implementing a max reduce on an array of values. This is my kernel
__global__ void max_reduce(const float* const d_array,
                     float* d_max,
                     const size_t elements)
{
    extern __shared__ float shared[];

    int tid = threadIdx.x;
    int gid = (blockDim.x * blockIdx.x) + tid;

    if (gid < elements)
        shared[tid] = d_array[gid];
    __syncthreads();

    for (unsigned int s=blockDim.x/2; s>0; s>>=1)
    {
        if (tid < s && gid < elements)
            shared[tid] = max(shared[tid], shared[tid + s]);
        __syncthreads();
    }

    if (gid == 0)
        *d_max = shared[tid];
}

I have implemented a min reduce using the same method (replacing the max function with the min) which works fine.
To test the kernel, I found the min and max values using a serial for loop. The min and max values always come out the same in the kernel but only the min reduce matches up.
Is there something obvious I'm missing/doing wrong?

A: Your main conclusion in your deleted answer was correct: the kernel you have posted doesn't comprehend the fact that at the end of that kernel execution, you have done a good deal of the overall reduction, but the results are not quite complete.  The results of each block must be combined (somehow).  As pointed out in the comments, there are a few other issues with your code as well.  Let's take a look at a modified version of it:
__device__ float atomicMaxf(float* address, float val)
{
    int *address_as_int =(int*)address;
    int old = *address_as_int, assumed;
    while (val > __int_as_float(old)) {
        assumed = old;
        old = atomicCAS(address_as_int, assumed,
                        __float_as_int(val));
        }
    return __int_as_float(old);
}

__global__ void max_reduce(const float* const d_array, float* d_max,
                                              const size_t elements)
{
    extern __shared__ float shared[];

    int tid = threadIdx.x;
    int gid = (blockDim.x * blockIdx.x) + tid;
    shared[tid] = -FLOAT_MAX;  // 1

    if (gid < elements)
        shared[tid] = d_array[gid];
    __syncthreads();

    for (unsigned int s=blockDim.x/2; s>0; s>>=1)
    {
        if (tid < s && gid < elements)
            shared[tid] = max(shared[tid], shared[tid + s]);  // 2
        __syncthreads();
    }
    // what to do now?
    // option 1: save block result and launch another kernel
    if (tid == 0)
        d_max[blockIdx.x] = shared[tid]; // 3
    // option 2: use atomics
    if (tid == 0)
      atomicMaxf(d_max, shared[0]);
}

*

*As Pavan indicated, you need to initialize your shared memory array.  The last block launched may not be a "full" block, if gridDim.x*blockDim.x is greater than elements.

*Note that in this line, even though we are checking that the thread operating (gid) is less than elements, when we add s to gid for indexing into the shared memory we can still index outside of the legitimate values copied into shared memory, in the last block.  Therefore we need the shared memory initialization indicated in note 1.

*As you already discovered, your last line was not correct.  Each block produces it's own result, and we must combine them somehow.  One method you might consider if the number of blocks launched is small (more on this later) is to use atomics.  Normally we steer people away from using atomics since they are "costly" in terms of execution time.  However, the other option we are faced with is saving the block result in global memory, finishing the kernel, and then possibly launching another kernel to combine the individual block results.  If I have launched a large number of blocks initially (say more than 1024) then if I follow this methodology I might end up launching two additional kernels.  Thus the consideration of atomics.  As indicated, there is no native atomicMax function for floats, but as indicated in the documentation, you can use atomicCAS to generate any arbitrary atomic function, and I have provided an example of that in atomicMaxf which provides an atomic max for float.

But is running 1024 or more atomic functions (one per block) the best way?  Probably not.
When launching kernels of threadblocks, we really only need to launch enough threadblocks to keep the machine busy.  As a rule of thumb we want at least 4-8 warps operating per SM, and somewhat more is probably a good idea.  But there's no particular benefit from a machine utilization standpoint to launch thousands of threadblocks initially. If we pick a number like 8 threadblocks per SM, and we have at most, say, 14-16 SMs in our GPU, this gives us a relatively small number of 8*14 = 112 threadblocks.  Let's choose 128 (8*16) for a nice round number.  There's nothing magical about this, it's just enough to keep the GPU busy.  If we make each of these 128 threadblocks do additional work to solve the whole problem, we can then leverage our use of atomics without (perhaps) paying too much of a penalty for doing so, and avoid multiple kernel launches.  So how would this look?:
__device__ float atomicMaxf(float* address, float val)
{
    int *address_as_int =(int*)address;
    int old = *address_as_int, assumed;
    while (val > __int_as_float(old)) {
        assumed = old;
        old = atomicCAS(address_as_int, assumed,
                        __float_as_int(val));
        }
    return __int_as_float(old);
}

__global__ void max_reduce(const float* const d_array, float* d_max,
                                              const size_t elements)
{
    extern __shared__ float shared[];

    int tid = threadIdx.x;
    int gid = (blockDim.x * blockIdx.x) + tid;
    shared[tid] = -FLOAT_MAX;

    while (gid < elements) {
        shared[tid] = max(shared[tid], d_array[gid]);
        gid += gridDim.x*blockDim.x;
        }
    __syncthreads();
    gid = (blockDim.x * blockIdx.x) + tid;  // 1
    for (unsigned int s=blockDim.x/2; s>0; s>>=1)
    {
        if (tid < s && gid < elements)
            shared[tid] = max(shared[tid], shared[tid + s]);
        __syncthreads();
    }

    if (tid == 0)
      atomicMaxf(d_max, shared[0]);
}

With this modified kernel, when creating the kernel launch, we are not deciding how many threadblocks to launch based on the overall data size (elements).  Instead we are launching a fixed number of blocks (say, 128, you can modify this number to find out what runs fastest), and letting each threadblock (and thus the entire grid) loop through memory, computing partial max operations on each element in shared memory.  Then, in the line marked with comment 1, we must re-set the gid variable to it's initial value.  This is actually unnecessary and the block reduction loop code can be further simplified if we guarantee that the size of the grid (gridDim.x*blockDim.x) is less than elements, which is not difficult to do at kernel launch.
Note that when using this atomic method, it's necessary to initialize the result (*d_max in this case) to an appropriate value, like -FLOAT_MAX.
Again, we normally steer people way from atomic usage, but in this case, it's worth considering if we carefully manage it, and it allows us to save the overhead of an additional kernel launch.
For a ninja-level analysis of how to do fast parallel reductions, take a look at Mark Harris' excellent whitepaper which is available with the relevant CUDA sample.

A: Here's one that appears naive but isn't. This won't generalize to other functions like sum(), but it works great for min() and max().
__device__ const float float_min = -3.402e+38;

__global__ void maxKernel(float* d_data)
{
    // compute max over all threads, store max in d_data[0]
    int i = threadIdx.x;
    __shared__ float max_value;

    if (i == 0) max_value = float_min;
    float v = d_data[i];
    __syncthreads();

    while (max_value < v) max_value = v;

    __syncthreads();
    if (i == 0) d_data[0] = max_value;
}

Yup, that's right, only syncing once after initialization and once before writing the result. Damn the race conditions! Full speed ahead!
Before you tell me it won't work, please give it a try first. I have tested thoroughly and it works every time on a variety of arbitrary kernel sizes. It turns out that the race condition doesn't matter in this case because the while loop resolves it.
It works significantly faster than a conventional reduction. Another surprise is that the average number of passes for a kernel size of 32 is 4. Yup, that's (log(n)-1), which seems counterintuitive. It's because the race condition gives an opportunity for good luck. This bonus comes in addition to removing the overhead of the conventional reduction.
With larger n, there is no way to avoid at least one iteration per warp, but that iteration only involves one compare operation which is usually immediately false across the warp when max_value is on the high end of the distribution. You could modify it to use multiple SM's, but that would greatly increase the total workload and add a communication cost, so not likely to help.
For terseness I've omitted the size and output arguments. Size is simply the number of threads (which could be 137 or whatever you like). Output is returned in d_data[0].
I've uploaded the working file here: https://github.com/kenseehart/YAMR

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to send a text message from firebase to a phone number? I want my firebase to send a text message to my app (which is coded in flutter). Can the firebase send SMS using the server?

A: You can use the Twilio third-party service in a Cloud Function.
Have a look at these docs:
https://cloud.google.com/appengine/docs/flexible/nodejs/using-sms-and-voice-services-via-twilio
https://cloud.google.com/community/tutorials/cloud-functions-twilio-sms (which shows how to integrate Twilio in a Cloud Function)
The Firebase Cloud Functions documentation is here: https://firebase.google.com/docs/functions/
Note that you will have to subscribe to a Blaze or Flame plan, because "the Spark plan allows outbound network requests only to Google-owned services".  Check https://firebase.google.com/pricing/ and hover over the question mark next to Cloud Functions for more details.


text:
Q: Cómo validar un Número de Seguridad Social (NSS) de México Pregunta: ¿Cómo puedo verificar que el formato de un NSS mexicano sea válido?
¿Qué es el NSS? El Número de Seguridad Social (NSS) es la identidad social del trabajador. Es expedido por el IMSS y se conforma por 11 dígitos.
Contexto: Quiero validar que un NSS podría ser válido. No me interesa ver si efectivamente existe. Actualmente estoy validando que sean 11 dígitos:
/^\d{11}$/

pero ahora me interesa ver si se puede validar de forma más estricta.

A: Formato del NSS
El Número de Seguridad Social se constituye por:

Los códigos de Subdelegaciones del IMSS están listados en el Manual para Integración del NSS . Si bien algunos (pocos) números no son válidos, podrían serlo en el futuro, por lo que no podemos validar por ese campo. Además, en los casos especiales cuando no se posee un registro de fecha de nacimiento, se utiliza el código 97.
Cuando se posee una fecha de nacimiento, logicamente debe ser menor al año de alta del trabajador.
El dígito verificador es asignado utilizando el algoritmo de Luhn, lo cual nos permitirá realizar la validación del NSS.

Expresión regular
Sólo se validará que sean 11 dígitos, pero usaremos la expresión para capturar los primeros 3 campos por separado:
/^(\d{2})(\d{2})(\d{2})\d{5}$/

Validación Completa
Publico el código en JavaScript para poder ejecutarlo acá, pero es muy sencillo de llevar a cualquier otro lenguaje.

// Devuelve un booleano si es un NSS válido
// (deben ser 11 dígitos sin otro caracter en el medio)
function nssValido(nss) {
    const re       = /^(\d{2})(\d{2})(\d{2})\d{5}$/,
          validado = nss.match(re);

    if (!validado)  // 11 dígitos y subdelegación válida?
        return false;

    const subDeleg = parseInt(validado[1],10),
          anno     = new Date().getFullYear() % 100;
    var   annoAlta = parseInt(validado[2],10),
          annoNac  = parseInt(validado[3],10);

    //Comparar años (excepto que no tenga año de nacimiento)
    if (subDeleg != 97) {
        if (annoAlta <= anno) annoAlta += 100;
        if (annoNac  <= anno) annoNac  += 100;
        if (annoNac  >  annoAlta)
         return false; // Err: se dio de alta antes de nacer!
    }

    return luhn(nss);
}

// Algoritmo de Luhn
//  https://es.wikipedia.org/wiki/Algoritmo_de_Luhn
function luhn(nss) {
    var suma   = 0,
        par    = false,
        digito;

    for (var i = nss.length - 1; i >= 0; i--) {
        var digito = parseInt(nss.charAt(i),10);
        if (par)
         if ((digito *= 2) > 9)
             digito -= 9;

        par = !par;
        suma += digito;
    }
    return (suma % 10) == 0;
}

//Handler para el evento cuando cambia el input
//Elimina cualquier caracter no numérico y comprueba validez
function validarInput(input) {
    var nss       = input.value.replace(/\D+/g,""),
        resultado = document.getElementById("resultado"),
        valido;

    if (nssValido(nss)) { // ⬅ Acá se comprueba
     valido = "Válido";
        resultado.classList.add("ok");
    } else {
        valido   = "No válido";
     resultado.classList.remove("ok");
    }

    resultado.innerText = "NSS: " + nss + "\nFormato: " + valido;
}
#resultado {
    background-color: red;
    color: white;
    font-weight: bold;
}
#resultado.ok {
    background-color: green;
}
NSS:
<input type="text" id="nss_input" style="width:100%;"
       oninput="validarInput(this)"
       placeholder="Ingrese su NSS">

Descripción
Luego de validar que son 11 dígitos y haber separado los 3 primeros campos, se compara que el año de nacimiento sea previo al de inscripción. Como sólo contamos con los últimos dígitos del año, se agrega 100 al número si es menor al año actual (así '05 será mayor a '99 por ejemplo).
if (subDeleg != 97) {   // Si tiene año de nacimiento
    if (annoAlta <= anno) annoAlta += 100;
    if (annoNac  <= anno) annoNac  += 100;
    if (annoNac  >  annoAlta)
        return false; // Err: se dio de alta antes de nacer!
}

Sin embargo, la principal validación es por el algoritmo de Luhn, que consta en tomar los dígitos en posiciones impares, y los dígitos en posiciones pares multiplicados por 2. Se suman todos los dígitos (si alguno de estos fuese mayor o igual a 10 se toma la suma de cada dígito).
var digito = parseInt(nss.charAt(i),10);
if (par)
    if ((digito *= 2) > 9)
        digito -= 9;

Un NSS es válido si el último dígito de esa suma da 0.
return (suma % 10) == 0;


text:
Q: Which is better for a Tile map storing a reference to the tile or tile id I'm working on some JUnit code and this though came to mind. When it comes to creating tile(2D or 3D) based maps what is the idea way to store the tile at a location. Currently the game i'm working on stores it by using an ID. For my JUnits for the game i've been using the reference since the tests are only 16x256x16 sized maps. Without knowing some good memory tools i have no way to test which is more effect. As well i'm unsure which is easier on the processor.
Addition question to this does a reference to a variable use memory?
Bellow is the code. Tile once creates is used for basic information on what the tile looks like etc. It has an id which is used to reference what it is when saved/loaded. MapA and MapB are two different examples of how i want to store a basic test map. Coord system is the map matrix of [x][y][z].
public class Tile
{
   public int id = 0; //Assign when the tile is registered can be 0 - 4096
   //... rest of tile code which is not important
}

public class MapA
{
    int[][][] map = new int[16][256][16]
}

public class MapB
{
    Data[][][] map = new Data[16][256][16]

    public static class Data
    {
       Tile tile;
       int tileRotation;
       // Data that goes with the tile
    }
}


text:
Q: Remove '|' special character from a string My question may find simple, But I am not getting it right. How could I remove "|" from a string so far I have used the following but Its not working

 | ABCD ||

var txt=divVar.html();

1) txt=txt.remove("|");
2)txt=txt.replace (/|/g, '');

A: You have to escape '|' character:
txt=txt.replace (/\|/g, '');

A: You can use split and join:
var newTxt = txt.split('|').join('');

To remove white space, you can use $.trim():
var newTxt = $.trim(txt.split('|').join(''));

Demo

A: If you want to remove just '|' and not '||' than you can use the below mentioned solution

 | ABCD ||

Else, if you want to replace both than use below

 | ABCD ||

Hope this help you to solve your problem
Thanks
Prashant


text:
Q: Firebase ID in Userdefaults I am not able to read and write the firebase node ID in userdefaults
let userRef = recordRef.child("users")

let userRecord = userRef.childByAutoId()
let newUserId = userRecord.key
let newUserDict = ["id": newUserId , "username": "admin" , "password": password , "userType": "power" , "active": "yes"]
let newUser = Users(dictionary: newUserDict as [String: Any])
userRecord.setValue(newUser.toDictionary())

let userdefault = UserDefaults.standard //adding login details in defaults for auto login
userdefault.set(id!, forKey: "schoolId")
userdefault.set(code, forKey: "schoolCode")
userdefault.set("admin", forKey: "username")
userdefault.set(password, forKey: "password")
userdefault.set("power", forKey: "userType")
userdefault.set(newUserId!, forKey: "userId")

now when I am trying to read the schoolId or newUserID I am getting error of having NIL value
print(userDefaults.string(forKey: "userID")!)
print(userDefaults.string(forKey: "userType")!)

any idea how to read and write node id in user defaults?

A: You should use the same keys while adding/retrieving the object. You are using different key while saving i.e, userId and retrieving userID so because userId != userID you will get nil for this key.
A better solution would be to create an enum for UserDefaults keys as below,
enum UserDefaultKey: String {
    case schoolId
    case schoolCode
    case username
}

Extend UserDefaults to set and get the value using the enum item type,
extension UserDefaults {

    public func set<T>(_ value: T?, forKey: UserDefaultKey) {
        self.set(value, forKey: forKey.rawValue)
    }

    public func value<T>(ofType: T.Type, for key: UserDefaultKey) -> T? {
        return self.value(forKey: key.rawValue) as? T
    }
}

Then you can use these keys as below,
let userdefault = UserDefaults.standard
userdefault.set("YYYYY", forKey: .schoolId)
userdefault.set("Kam", forKey: .username)

print(userdefault.value(ofType: String.self, for: .schoolId)!)
print(userdefault.value(ofType: String.self, for: .username)!)


text:
Q: Android: Loading JavaScript with WebView.loadUrl but keeping soft keyboard When a user click on a (html) Textfield in a WebView, the soft keyboard is shown.
But when I load some JS with WebView.loadUrl() the soft keyboard disappears.
I understand the behaviour when you load a new page. But how can I change the behaviour of the WebView when loading JS?
Is there another way to load JS?
I also tried to handle the keyboard manually. But there are too many drawbacks.
It is complicated to determine if the keyboard is shown. And I would have to change my layout:
How to check visibility of software keyboard in Android?

And the keyboard would not be in the control of the WebView anymore.
Q: How to load JS into a WebView, without affecting the soft keyboard?

A: After loading javascript give focus to textfield again. That will solve problem. For giving focus this discussion will be helpful.
Enjoy :)


text:
Q: How to design memberNumbers table SQL I'm struggling to implement table that will hold information about
number of:
childrens - male and female,
adults    - male and female,
elders    - male and female
I have created table stateMembers like this:
    +-----------------------------------------------------+
    | id | stateId | gender  | children | adults | elders |
    +----+---------+---------+----------+--------+--------+
    | 1  | 4       | male    | 2000     | 590    |  900   |
    | 2  | 4       | female  | 2000     | 590    |  900   |
    | 3  | 3       | male    | 500      | 700    |  1900  |
    | 4  | 3       | female  | 200      | 159    |  100   |
    +----+---------+---------+----------+--------+--------+

How can I redesign it to make easy organization of result when other record added for each State.
Inorder to get the total of children male and female, adults male and female.
Thanks in advance.

A: I don't understand your question very well but I think this would be a better construction for the table
+----------------------------------+
| id | stateId | male     | female |
+----+---------+---------+---------+
| 1  | children| 2000     | 590    |
| 2  | adult   | 2000     | 590    |
| 3  | elders  | 500      | 700    |
+----+---------+---------+---------+

A: I would organize it as

id
stateId
gender
age_category
nmbr

1
4
male
children
2000

2
4
male
adults
590

3
4
male
elders
900

4
4
female
children
2000

...
Allowing any grouping you need further on.


text:
Q: Pivot Table MySQL If MySQL table looking something like this

And what I'm trying to do is a pivot table looks like this:
Jenny    Ashley     Meera  Jane
Samantha Christeen  Priya  Julia
NULL     Ketty      NULL   Maria

each column based on their occupation

A: This code will do something near what you want:
set @sql = (
    select group_concat(distinct
        concat(
            "(case when `Occupation`='", Occupation, "' then `Name` end) as `", `Occupation`, "`"
        )
    )
    from t
);

set @sql = concat("select ", @sql, " from t ");

prepare stmt from @sql;

execute stmt;

A: There are plenty of ways of achieving this described here: MySQL pivot table
where the dynamic way of doing it is included in the answer by Abhishek Gupta using GROUP_CONCAT with CONCAT. It is not fast but it is dynamic.
The gist of it is that if you want a dynamic solution then you first have to do a query to find out what columns there are in your data. Then you create a new query based in that information.
If you want a dynamic solution that is also fast then you need to pull the  first query into your programming language (like php or whatever you are using), and use the programming language to create a query that is fast.


text:
Q: UIPickerView selects entity from managedObjectContext I'm struggling with a CoreData related problem for a while now:
I have a View-based application with a tabbar in it.
The first two tabs are view controllers that display content from my CoreData, the third tab has a UIPickerView, where I can select data.
The third and the second view controllers then should select the right entity based on the UIPickerView selection.
To clarify this a little bit more: in my managedobjectcontext I have 16 entities. Based on the UIPickerView selection in ThirdViewController I want to use the corresponding entity and update the FirstViewController and SecondViewController.
This should also be a persistent solution, so that the user can quit the application, but the selection from UIPickerView should be stored. Maybe this is something for NSUserDefaults?
Any help would be greatly appreciated!

A: I am not exactly clear on whether you need to save an entity name or a particular managed object but in both cases the solution is the same: you need to store a reference in the NSUserDefaults.
To store an entity in the user defaults you would just save the entity name as a string. So something like:
  [[NSUserDefaults standardUserDefaults] setValue:entityNameString forKey:@"currentlySelectedEntity"];

... and to retrieve it:
  NSString *currentEntity=[[[NSUserDefaults standardUserDefaults] valueForKey:@"currentlySelectedEntity"];

If you need to save a reference to a particular managed object, you need to save the managed object ID of the saved object. Saving is very important. Prior to saving the context in which the object was created, the object ID has only a temporary value which will change upon saving. Any reference to object will be lost if you use the temporary value.
To save an object ID:
  NSManagedObject *mo=[NSEntityDescription insertNewObjectForEntityForName:@"TestEntity" inManagedObjectContext:self.managedObjectContext];
  //... save the context
  NSManagedObjectID *moID=[mo objectID];
  NSURL *moIDURI=[moID URIRepresentation];
  [[NSUserDefaults standardUserDefaults] setValue:moIDURI forKey:@"currentlySelectedTestObject"];

... to retrive it:
  NSURL *uri=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentlySelectedTestObject"];
  NSManagedObjectID *moID=[self.persistentStoreCoordinator managedObjectIDForURIRepresentation:uri];
  NSManagedObject *mo=[self.managedObjectContext objectRegisteredForID:moID];

(The above code is uncompiled and may contain typos so don't just copy and paste it.)


text:
Q: parameterized doctype in xsl:stylesheet How could I inject a --stringparam (xsltproc) into the DOCTYPE of a XSL stylesheet? The --stringparam is specified from the command line.
I have several books in docbook5 format I want to process with the same customization layer, each book having an unique identifier, here "demo", so I'm running something like

xsltproc --stringparam course.name demo ...

for each book.
Obviously the parameter is not recognized as such, but as verbatim text, giving the error:

warning: failed to load external entity "http://edu.yet-another-project.com/course/$(course.name)/entities.ent"

Here it is how I've tried, which won't work:
<?xml version='1.0'?>
<!DOCTYPE stylesheet [
<!ENTITY % myent SYSTEM "http://edu.yet-another-project.com/course/$(course.name)/entities.ent">
%myent;
]>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="1.0">

<!-- the docbook template used -->
<xsl:import href="http://docbook.org/ns/docbook/xhtml/chunk.xsl"/>

<!-- processor parameters -->
<xsl:param name="html.stylesheet">default.css</xsl:param>
<xsl:param name="use.id.as.filename">1</xsl:param>
<xsl:param name="chunker.output.encoding">UTF-8</xsl:param>
<xsl:param name="chunker.output.indent">yes</xsl:param>
<xsl:param name="navig.graphics">1</xsl:param>
<xsl:param name="generate.revhistory.link">1</xsl:param>
<xsl:param name="admon.graphics">1</xsl:param>

<!-- here more stuff -->
</xsl:stylesheet>

Ideas?

A: The course.name parameter is given to the XSLT processor. But it is the XML parser that sees the entity declaration containing $(course.name), and the parser won't know what to do with that. The entity cannot be expanded.
You need to declare course.name as a parameter in the stylesheet and then reference it somewhere in a custom template.

A: From http://www.w3.org/TR/xslt#output

<xsl:output
  method = "xml" | "html" | "text" | qname-but-not-ncname
  version = nmtoken
  encoding = string
  omit-xml-declaration = "yes" | "no"
  standalone = "yes" | "no"
  doctype-public = string
  doctype-system = string
  cdata-section-elements = qnames
  indent = "yes" | "no"
  media-type = string />

So, when using XSLT 1.0 you can't parameterize public nor system DOCTYPE strings.
From http://www.w3.org/TR/xslt20/#element-result-document

<xsl:result-document
  format? = { qname }
  href? = { uri-reference }
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = qname
  method? = { "xml" | "html" | "xhtml" | "text" |
  qname-but-not-ncname }
  byte-order-mark? = { "yes" | "no" }
  cdata-section-elements? = { qnames }
  doctype-public? = { string }
  doctype-system? = { string }
  encoding? = { string }
  escape-uri-attributes? = { "yes" | "no" }
  include-content-type? = { "yes" | "no" }
  indent? = { "yes" | "no" }
  media-type? = { string }
  normalization-form? = { "NFC" | "NFD" | "NFKC" | "NFKD" |
  "fully-normalized" | "none" | nmtoken }
  omit-xml-declaration? = { "yes" | "no" }
  standalone? = { "yes" | "no" | "omit" }
  undeclare-prefixes? = { "yes" | "no" }
  use-character-maps? = qnames
  output-version? = { nmtoken }>
  <!-- Content: sequence-constructor -->
</xsl:result-document>

In XSLT 2.0 you can use xsl:result-document instruction for that task.


text:
Q: Override KeyDown from another class C# I have a form that creates a class. This class processes events that are fired on the form. The problem is I am trying to use the KeyDown event, but it isn't working because there are buttons on the form and they are capturing the KeyDown. I found the solution on another post was to override the ProcessCmdKey. The problem is I don't know how to override a method from inside another class. Can anyone tell me how I can capture all KeyDown events from inside my other class?
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Left)
    {
        MoveLeft(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Right)
    {
        MoveRight(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Up)
    {
        MoveUp(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Down)
    {
        MoveDown(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else
        return base.ProcessCmdKey(ref msg, keyData);
}

A: The easiest way to do this would be to expose the KeyDown from Button on the containing form.
class MyForm : Form {
  Button m_button;

  public event KeyEventHandler ButtonKeyDown;

  public MyForm() {
    m_button = ...;
    m_button.KeyDown += delegate (object, e) {
      KeyEventHandler saved = ButtonKeyDown;
      if (saved != null) {
         saved(object, e);
      }
    };
  }
}

Now the calling code can simple hook into the MyForm::ButtonKeyDown event

A: I'm not sure how you're wiring up the events with your class, but if you set the KeyPreview property of the form to True, you can grab a hold of the event there and then pass it along to your class that is processing the events. So even when the button has the focus, the KeyDown will fire the event on the form.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    ... Invoke your class
}


text:
Q: What is the best practice for using ISupportIncrementalLoading in MVVM? It may sound weird and I know that using ISupportIncrementalLoading is for view layer of MVVM.
I am now refreshing my ListView's itemssource in the xaml.cs whenever the collection property updates in the ViewModel. Is there any other (and better) solution for this kind of need?

A: Hello I have been working with ISupportIncrementalLoading using MVVM pattern many times.
I like to create and independent Class that encapsulate all the logic to load all the data I let here an example of one of my classes I hope this helps.
I created an IncrementalCollectionBase to reuse all the code in all of my custom collections.
  public class IncrementalCollectionBase<T> : ObservableCollection<T>,
    ISupportIncrementalLoading,
    INotifyPropertyChanged,
    IIncrementalCollection<T>, IDisposable
{
    private long totalRecordCount;

    public int PageNo { get; set; }
    public int PageSize { get; set; }
    public int PageCount { get; set; }
    public long TotalRecordCount
    {
        get
        {
            return this.totalRecordCount;
        }

        set
        {
            this.totalRecordCount = value;
            OnPropertyChanged(new PropertyChangedEventArgs("TotalRecordCount"));
        }
    }

    public IncrementalCollectionBase()
    {
        this.FeedSize = 10;
    }
    public CancellationTokenSource CancelToken { get; set; }

    public bool HasMoreItems { get; set; }

    private bool isLoading { get; set; }
    public bool IsLoading
    {
        get
        {
            return isLoading;
        }

        set
        {
            isLoading = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsLoading"));

        }
    }

    public int FeedSize { get; set; }

    public event EventHandler<LoadIncrementalCollectionChanged> OnLoadIncrementalCollectionChanged;

    public void Cancel()
    {
        try
        {
            CancelToken?.Cancel();
        }
        catch (Exception ex)
        {

        }
    }

    public virtual Task<IEnumerable<T>> LoadDataAsync()
    {
        throw new NotImplementedException();
    }

    public virtual IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        throw new NotImplementedException();
    }

    public virtual void Setup(CancellationTokenSource cancelToken = null)
    {

        CancelToken = cancelToken;
    }

    public void Dispose()
    {
        try
        {
            Cancel();
            Items.Clear();
        }
        catch (Exception)
        {

        }
    }
}

After of doing this I create my custom collection
    public class MyCustomEntityIncrementalCollection : IncrementalCollectionBase<CustomEntity>
{

    private ISearchentityService searchentityService = null;
    private bool searchMode = false;
    private string key = "";
    private bool IsFirstSearchResult = true;
    private IentityService entityService = null;
    private ILoginService loginService = null;
    private IToastService toastService = null;
    public MyCustomEntityIncrementalCollection(CancellationTokenSource cancelToken, int feedSize = 10)
    {
        Setup(cancelToken);
        this.FeedSize = feedSize;
        toastService = IoC.Get<IToastService>();
        searchentityService = IoC.Get<ISearchentityService>();
        loginService = IoC.Get<ILoginService>();
        entityService = IoC.Get<IentityService>();
    }

    private async Task<IEnumerable<CustomEntity>> Search()
    {
        try
        {
            if (IsFirstSearchResult)
            {

                var result = await searchentityService.SearchAsync(key, loginService.CurrentUser.Id, CancelToken, loginService.CurrentToken.AccessToken, 1, 50);
                if (result == null)
                {
                    toastService.ShowAsync("Sin resultados", "No se han encontrado coincidencias");
                }
                PageNo = result.paging.pageNo;
                PageCount = result.paging.pageCount;
                PageSize = result.paging.pageSize;
                TotalRecordCount = result.paging.totalRecordCount;
                IsFirstSearchResult = false;
                return result.data;
            }
            else
            {
                var result = await searchentityService.SearchAsync(key, loginService.CurrentUser.Id, CancelToken, loginService.CurrentToken.AccessToken, (PageNo + 1), 50);
                PageNo = result.paging.pageNo;
                PageCount = result.paging.pageCount;
                PageSize = result.paging.pageSize;
                TotalRecordCount = result.paging.totalRecordCount;
                return result.data;
            }
        }
        catch (Exception)
        {

        }
        return null;
    }

    public async Task TurnOnSearchMode( string keyword)
    {
        if (string.IsNullOrEmpty(keyword) || string.IsNullOrWhiteSpace(keyword))
            throw new Exception(" keyword is invalid");
        searchMode = true;
        key = keyword;
        IsFirstSearchResult = true;
        this.ClearItems();
        await Task.Delay(500);
       await LoadMoreItemsAsync(1);
    }
    public async Task TurnOffSearchMode()
    {

       searchMode = false;
        IsFirstSearchResult = true;
        key = "";
        this.ClearItems();
        await LoadMoreItemsAsync(1);
    }
    public override async Task<IEnumerable<CustomEntity>> LoadDataAsync()
    {
        try
        {
            if (this.Items.Count == 0)
            {
                var result = await entityService.MyEntities(CancelToken, loginService.CurrentToken.AccessToken, 1, FeedSize);
                if (result != null && result.data != null)
                {
                    PageNo = result.paging.pageNo;
                    PageCount = result.paging.pageCount;
                    PageSize = result.paging.pageSize;
                    TotalRecordCount = result.paging.totalRecordCount;
                    return result.data;
                }
            }
            else
            {
                var result = await entityService.MyEntities(CancelToken, loginService.CurrentToken.AccessToken, (PageNo + 1), FeedSize);

                PageNo = result.paging.pageNo;
                PageCount = result.paging.pageCount;
                PageSize = result.paging.pageSize;
                TotalRecordCount = result.paging.totalRecordCount;
                return result.data;
            }
        }
        catch (Exception)
        {

        }

        return null;
    }

    public override IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        return AsyncInfo.Run(async c =>
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, ( () =>
            {
                IsLoading = true;
            }));

            if (searchMode == false)
            {
                try
                {
                    var data = await LoadDataAsync();
                    if (data != null && data.Any())
                    {

                        HasMoreItems = true;
                    }
                    else
                    {
                        HasMoreItems = false;
                    }

                    if (data != null)
                    {
                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (() =>
                        {

                            foreach (var item in data)
                            {

                                this.Add(item);
                            }
                        })).AsTask().ContinueWith(z => { data = null; });

                    }

                }
                catch (Exception ex)
                {

                    Debug.WriteLine("Se ha producido un error al buscar videos");
                }
            }

            else
            {
                try
                {
                    var data = await Search();
                    if (data != null && data.Any())
                    {

                        HasMoreItems = true;
                    }
                    else
                    {
                        HasMoreItems = false;
                    }

                    if (data != null)
                    {
                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (() =>
                        {

                            foreach (var item in data)
                            {

                                this.Add(item);
                            }
                        })).AsTask().ContinueWith(z => { data = null; });

                    }

                }
                catch (Exception ex)
                {

                    Debug.WriteLine("Se ha producido un error al buscar videos");
                }
            }

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, ( () =>
            {
                IsLoading = false;
            }));
            return new LoadMoreItemsResult() { Count = count };
        });

    }

}

Finally I just call the initial load in my View Model in the constructor or another place.
 this.MyEntities = new Infrastructure.Collections.MyCustomEntityAppraisalIncrementalCollection(cancelToken, 20);

await MyEntities.LoadMoreItemsAsync(1);


text:
Q: "Edit" command in SQL Developer In Toad, you can use
edit tablename where ...

and then simply edit the data in DB. Is there any equivalent in Oracle SQL developer?

A: No, but you can double click on the table name and and then edit it

Note: you should also be able to edit the data from the data grid shown in the SQL Worksheet but I haven't confirmed that

A: Ctrl + Mouse hover over the table or view name, that will open up Table Editor and you can edit the field values.


text:
Q: Get an XIB in iOS 7 S.D.K I have been using iOS for the past couple of months and what i have been doing is when i Click Single View Application, a default View Controller would appear with an XIB.
But with iOS 7, the XIB don't seem to appear, rather the storyboard appears.
I have no idea how to work with Storyboard's. I have neither used them in the past nor do i want to use them in the near Future. Do i always need to go ahead with an empty view and then add the relevant ViewController's
Please let me know if i am doing something silly or is it the new iOS 7 default behavior.
I did try to get into more detail's but could not get relevant answers on Google as well.
Thank you.

A: Step 1 Create New Project
Step 2 Select "Single View Application" -> Next
Step 3 Set ProjectName and other settings -> Next
Step 4 Save Project at location -> create
Step 5 Select Project in Navigator Panel in Left
Step 6 "Remove Main.storyboard" file from project
Step 7 "Add New .xib file in Project"
Step 8 Set Main Interface to your .xib file in "General Tab" on right panel.
Step 9 Paste following code in didFinishLaunchingWithOptions method
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];

A: For iOS 7 compliance the correct XIB you need to use is the interface builder document named: Application, as your primary nib.


text:
Q: What PHP framework is most similar to Apache Wicket? Feature I'm looking for is being component based but not event driven.
I also like the idea of defining component in his parent code but describing its placement and some visual aspects in the template of his parent.

A: On the wicket mailing list they suggest the symfony framework which should be the closest thing in php world to wicket.


text:
Q: recompose pure or React.memo? I'm asking myself if the React.memo is exactly the same as recompose pure() ...
import { pure } from 'recompose';
export default pure(MyComp);

or
import React, { memo } from 'react';
export default memo(MyComp);

Any thoughts?

A: According to the React documentation.
React.memo is a higher order component. It's similar to React.PureComponent but for function components instead of classes.
So they are not exactly the same, but they serve the same purpose.


text:
Q: patching kernel (every update?) I'm about to apply that famous patch that makes vgaarb see nvidia as a VGA device to the kernel.
But Linux releases a new kernel only every 2 month as I know. And Ubuntu kernel releases are even later.
So is the above the only way to patch the new kernel every time?

A: Too short for an answer, but I'll risk it:
Yes, you have to patch the kernel every time. This is logical, and comparable with the update of proprietary modules, such as Nvidia. To automate patching, you could use DKMS, as does Nvidia.


text:
Q: Microphone monitoring disabled, low volume (Blue Yeti USB, Ubuntu 20.04) [SOLVED] I have been using a Blue Yeti USB Mic under Ubuntu 20.04. It was working great. Then, it suddenly started having issues. I'm not sure when it started. It took a while for me to notice.
The mic will pick up sound, but the volume is not as high as it used to be and I can't seem to increase it. The bigger issue, however, is that the monitoring isn't working. That is, I can't hear myself through the headphones that are connected to the mic. I'm currently more concerned about the monitoring.
The mic itself is OK. It works fine under Windows 10. When I reboot to Ubuntu, monitoring also works for a few seconds and then cuts off.
The mic shows up in the input options. I've tried every input version. I've also checked in pavucontrol and tried every setting I could there. The monitoring shows up as an option (if that is what monitoring is in pavucontrol), but I can't change anything (it is not muted).
I'm a Ubuntu sound noob.
Thank you in advance.

A: After much searching, I ran alsamixer. The mic gain was 0. No idea how that happened. I never changed it. Once it was increased, the monitoring starting working again.
The capture was also low. I upped it. That helped with the mic recording volume.
Hope this helps someone.


text:
Q: Ruby routes URI regex I have blog web application on Roda where links have the following URL format: example.com/posts/<id>/<slug>.
For example example.com/posts/1/example-blog-post.
What I want to achieve is to redirect user to example.com/posts/1/example-blog-post in case he either visits:

*

*example.com/posts/1 or

*example.com/posts/1/ (note last backslash)

That's what I got in routes so far:
r.on /posts\/([0-9]+)\/(.*)/ do |id, slug|
  @post = Post[id]

  if URI::encode(@post[:slug]) == slug
    view("blogpage")
  else
    r.redirect "/posts/#{id}/#{@post[:slug]}"
  end
end

With this code:

*

*example.com/posts/1 - FAILS

*example.com/posts/1/ - OK
Can I satisfy both conditions?

A: You could wrap the forward slash followed by the second capturing group in an optional non capturing group:
posts\/([0-9]+)(?:\/(.*))?

Explanation

*

*posts\/ Match posts/

*([0-9]+) Capture group 1, match 1+ digits

*(?: Non capture group

*

*\/(.*) Match / and capture in group 2 0+ times any char except a newline

*)? Close non capture group and make it optional

Regex demo


text:
Q: How to shrink the size of a WTL application? WTL applications are quite small already. However, using VS 2005 a statically linked application with WTL 9.10 weighs in at 136 kB (139,264 Bytes) for the Win32 configuration.
Looking at the executable I noticed a static import of oleaut32.dll. A cursory look with dumpbin shows one import via ordinal.
OLEAUT32.dll
            4181C0 Import Address Table
            41C9B8 Import Name Table
                 0 time date stamp
                 0 Index of first forwarder reference

                  Ordinal   277

Inspecting oleaut32.dll one finds that the export is named VarUI4FromStr.
Digging a little with IDA, I found that VarUI4FromStr was used by ATL::CRegParser::AddValue. Following the dependents from there, showed two calls in ATL::CRegParser::RegisterSubkeys.
Cross-referencing the ATL code of my Visual Studio installation with the findings, I found that the culprit was ATL::CAtlComModule. It does a lot of TypeLib registration stuff that is simply not needed for my use case.
However, the linker seems to leave all of that in, because it cannot reasonably decide to throw it out.
How can I get rid of this seemingly superfluous import?

A: Alas, since WTL::CAppModule derives directly from ATL::CComModule, including the atlbase.h header while having _ATL_NO_COMMODULE defined leads to an error:
Error   1   fatal error C1189: #error :  WTL requires that _ATL_NO_COMMODULE is not defined $(ProjectDir)\wtl\Include\atlapp.h  33

The actual culprit that ultimately pulls in ATL::CComModule is, however, ATL::CAtlComModule. So our goal is to get rid of both of them.
We'll try to trick atlbase.h into excluding all the TypeLib registration code by defining _ATL_NO_COMMODULE anyway, but undefining it right after we're done including it. This way atlapp.h and other WTL headers won't "notice".
#define _ATL_NO_COMMODULE
#include <atlbase.h>
#undef _ATL_NO_COMMODULE
#include <atlapp.h>

Obviously that gets us into some trouble:
1>atlapp.h(1515) : error C2039: 'CComModule' : is not a member of 'ATL'
1>atlapp.h(1515) : error C2504: 'CComModule' : base class undefined
1>atlapp.h(1524) : error C2653: 'CComModule' : is not a class or namespace name
1>atlapp.h(1543) : error C2653: 'CComModule' : is not a class or namespace name
1>atlapp.h(1625) : error C3861: 'GetModuleInstance': identifier not found
1>atlapp.h(1784) : error C2653: 'CComModule' : is not a class or namespace name
1>atlapp.h(1806) : error C2065: 'm_nLockCnt' : undeclared identifier

However, it looks like we should be able to fix this handful of errors quickly.
First of all let's check where ATL::CComModule comes from: it's declared and defined in atlbase.h. We can surely declare our own class and squeeze it in between #include <atlbase.h> and #include <atlapp.h> (see above).
Let's start with the basics, based on what can be found in atlbase.h:
namespace ATL
{
    class CComModule : public CAtlModuleT<CComModule>
    {
    public:
        CComModule() {}
    };
};

Now we get a different set of errors:
1>atlapp.h(1524) : error C2039: 'Init' : is not a member of 'ATL::CComModule'
1>        stdafx.h(31) : see declaration of 'ATL::CComModule'
1>atlapp.h(1625) : error C3861: 'GetModuleInstance': identifier not found

Excellent, so we're in fact only missing two more class functions: GetModuleInstance and Init. Let's pull those in as well. For good measure we'll also add GetResourceInstance:
namespace ATL
{
    class CComModule : public CAtlModuleT<CComModule>
    {
    public:
        CComModule() {}
        HINSTANCE GetModuleInstance() throw() { return _AtlBaseModule.m_hInst; }
        HINSTANCE GetResourceInstance() throw() { return _AtlBaseModule.m_hInstResource; }
        HRESULT Init(_ATL_OBJMAP_ENTRY*, HINSTANCE, const GUID*) throw() { return S_OK; }
    };
};

A short test proves that this is working fine. And the oleaut32.dll import is gone along with three more imports from ole32.dll. Great success!
And as a result we have saved 12 kB on the executable size.
Do you know other cool tricks to shrink WTL application size?
IMPORTANT
Note that depending on the features of ATL::CComModule which your code uses, you may have to fall back to using the original. The only other alternative is to extend the above mock version of ATL::CComModule to fix any compilation errors you may run into.
CAUTIONARY NOTE
I have not tested this extensively yet and I'll report back (by editing this answer) if I run into any trouble. However, from looking at it in both the ATL and WTL code as well as in the IDA database prior to my changes, I think this is a safe change.
Bonus trick
You may also use the 6001.18002 standalone WDK (for Vista SP1), which supports to target Windows 2000 (SP4) and newer. It includes ATL 7.0 and is therefore suited to build ATL+WTL applications.
To do that you just need to add the following two lines to your sources file:
USE_STATIC_ATL=1
ATL_VER=70

Thanks to the WDK, which uses msvcrt.dll, a system DLL, as its default (multithreaded dynamically linked) C runtime, you can then shrink the executable size further by linking dynamically to the C runtime. And in this case, since that particular C runtime is a system DLL (starting with Windows 2000), you can rest assured that it will work.
All of that taken into account you can build standard Windows applications (GUI or console) and DLLs that are really small.
Here is an example sources file which you can use as a template:
# Name of the program
TARGETNAME=progname
# Prefix used for the intermediate/output paths (e.g. objfre_w2k_x86)
TARGETPATH=obj
# A program, not a driver or DLL or static lib
TARGETTYPE=PROGRAM
# windows == GUI, console == Console, native == no subsystem ...
UMTYPE=windows
# Use Unicode ("wide char") instead of ANSI
UNICODE=1
# By default the WDK build treats warnings as errors - this turns it off
BUILD_ALLOW_ALL_WARNINGS=1
# Link dynamically to msvcrt.dll
USE_MSVCRT=1
# Don't link against any of the ATL DLLs
USE_STATIC_ATL=1
# In the 7600.16385.1 WDK you can use 70 as well, which translates to 71
ATL_VER=70
USE_NATIVE_EH=1
 # RTTI is required for some ATL/WTL features
USE_RTTI=1

# GUI programs require these entry points
!IF defined(UNICODE) && $(UNICODE)
UMENTRY=wwinmain
C_DEFINES=$(C_DEFINES) /DUNICODE /D_UNICODE
!ELSE
UMENTRY=winmain
C_DEFINES=$(C_DEFINES) /DMBCS /D_MBCS
!ENDIF

# Include folders
INCLUDES=$(DDK_INC_PATH);$(CRT_INC_PATH);$(SDK_INC_PATH);wtl\Include

# Libraries to link to, not just import libraries
TARGETLIBS=\
            $(SDK_LIB_PATH)\kernel32.lib \
            $(SDK_LIB_PATH)\user32.lib \
            $(SDK_LIB_PATH)\Comctl32.lib \

# Give source files (also resources and .mc) in the current or parent directory
SOURCES=...

The 7600.16385.1 standalone WDK also works for this. The WDKs starting from the Windows 8 WDK now require a Visual C++ into which they can be integrated. This also leads to the binaries requiring the respective C runtime version instead of the msvcrt.dll from prior WDK versions.


text:
Q: Getting Not Found 404 error when tryin to deploy springboot WAR to Wildfly on local with docker image I am trying to deploy springboot API to Wildfly on local using docker container but facing issues.
Docker File:
FROM mechero/wildfly:13.0.0-openjdk-10

# Expose the default's application port
EXPOSE 8080

# Copy the war file to the deployments folder
COPY target/example.war /opt/jboss/wildfly/standalone/deployments/example.war

Under application controller, I have the following:
@PostMapping(value="/abc/def",consumes = MediaType.APPLICATION_JSON_VALUE)
public function {}

I used the following command via CL:
docker build -t wildfly-springboot-app .
docker run -p 8080:8080 -it wildfly-springboot-app

Now I tried the URL: http://localhost:8080/ and I was able to see Welcome to WILDFLY page.
But when I appended my application details to the URL (http://localhost:8080/example/abc/def/, I got "Not Found" error. I am not sure what am I doing wrong?


text:
Q: $_GET[""]; inside POST I wanna to just simple get the number from $sum8 = $_GET["id88"];
My code looks as follow:
    $sum8 = $_GET["id88"];

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            header('Content-Type: application/json');
            $request = json_decode(file_get_contents('php://input'));
             $result = new DataSourceResult('mysql:host=server:3306 ;dbname=database_4', 'user_4', 'pass@#');
            $type = $_GET['type'];
            $operation = $_GET['operation'];
            if ($type == "dependency") {
                $columns = array('ID', 'PredecessorID',
'SuccessorID', 'Type');
                $table = "GanttDependencies";
            } else {
                $columns = array('ID', 'ParentID', 'OrderID',
'Title', 'Start', 'End', 'PercentComplete', 'Expanded', 'Summary');
                $table = "GanttTasks where project_id =$sum8";
            }

And strangely I cannot get the number - it's empty...
If I put below echo like:
 echo $test;

I see the number from id88 - so it should work...but dosen't
Can you look at this? Or maybe there is some another alternative for this?
URI:
<?php
   $val = $_GET['id88'];
   echo "<iframe src='http://www.somepage.com/gantt_chart/gantt_chart?id88=$sum8' width='100%' height='650' scrolling='vertical' frameBorder='0'></iframe>";
?>

A: Before your continue reading it will be great if you read this article
Look at the last point Visibility:
GET: Data is visible to everyone in the URL
POST: Data is not displayed in the URL
So if you don't have id88 in the URL it will be empty. If you want to get this value add to the URL.
Example: domain.com?id88=88


text:
Q: Creating an object with variable Key in Twig Using twig I want to create an object with a variable key & value.
If I do
{% set k = "TheKey" %}
{% set v = "TheValue" %}
{% set object = { k : v } %}

the result is { k: "TheValue" } instead of { "TheKey": "TheValue" }
Is it possible to do in twig what you can do in Javascript?
var obj = {
    [myKey]: value,
}

A: You should surround the key attribute with parenthesis:
{% set k = "TheKey" %}

{% set v = "TheValue" %}
{% set object = { (k) : v } %}

    {% for key, value in object %}
        <li>{{ key }}: {{ value }}</li>
    {% endfor %}

Check this working fiddle: https://twigfiddle.com/a61r9f


text:
Q: How do you say: $\sqrt[z] x$ where $z > 3$? My whole mathematics is in chaos right now.... I forgot how to say: $\sqrt[z] x$
and I don't know where else to ask -
I know how to say ${d}\sqrt x$ - this is just: $d$ times the square root of $x$;
Also, ${d}\sqrt[3] x$: $d$ times the cube root of $x$;
But, what if $z > 3$?
Would you say, $d$ times the fourth root [or fifth, sixth, etc. depending on your variable $z$] of $x$?
Thanks for your help - I know this is probably simple, but I really don't know what it would be called in order for me to Google it.

A: We say "the $z$-th root of $x$". You could also say "$x$ to the power $1/z$" which has the benefit of working for non-naturals.
On a side note, for what it's worth, I would read d$\sqrt{x}$ as "$d$ square root of $x$", I wouldn't use the "times".
As you've remarked, square and cube root are just fancy names, just as they are for the indices; we say $x^2$ and $x^3$ as $x$ squared and $x$ cubed, but $x^4$ as $x$ to the power of four.
As pointed out by symplectomorphic: most people say $x$ to the fourth for $x^4$.

A: Yes. We call them fourth root, fifth root, and so on. It gets hairy for non-natural numbers, but in that case you're better off using exponents anyways.


text:
Q: Apply using statement to the return type of a function without applying to the entire namespace I'm trying to create a function that takes an underlying container, and returns a boost::iterator_range based on a custom iterator that does some processing on the elements.
E.g.
// The range class, templated on the underlying iterator type
template<class Iter> using CustomRange = boost::iterator_range<CustomIterator<Iter>>;

using std::begin;
template <class Container>
auto make_custom_range(Container& c) -> CustomRange<decltype(begin(c))> {
    using std::end;
    return make_custom_range_from_iterators(begin(c),end(c));
}

The code works (given suitable definitions for CustomIterator and make_custom_range_from_iterators).
My concern is the using std::begin declaration, which I think will cause std::begin to be imported into the entire namespace where my function is declared.  I prefer not to use std::begin explicitly in the decltype so that  ADL can work (as in this question: Relying on ADL for std::begin() and std::end()?).
I think in C++14, I could just use an auto return type here.  Is there a C++11 solution?  Is there a way to let the return type see the using declaration without exposing it to the entire namespace?

A: Put the using declaration in a separate namespace:
namespace adl_helper
{
    using std::begin;

    template <typename T>
    auto adl_begin(T&& t) -> decltype(begin(std::forward<T>(t)));
}

template <class Container>
auto make_custom_range(Container& c)
    -> CustomRange<decltype(adl_helper::adl_begin(c))>
//                          ~~~~~~~~~~~~~~~~~~~~^
{
    using std::begin;
    using std::end;
    return make_custom_range_from_iterators(begin(c),end(c));
}

DEMO

A: Throw everything into another namespace and put your usings in there. Then bring your new helpers into your top namespace:
namespace details {
    using std::begin;
    using std::end;

    template <typename C>
    auto adl_begin(C&& c) -> decltype(begin(std::forward<C>(c))) {
        return begin(std::forward<C>(c));
    }

    template <typename C>
    auto adl_end(C&& c) -> decltype(end(std::forward<C>(c))) {
        return end(std::forward<C>(c));
    }
}

using details::adl_begin;
using details::adl_end;

template <typename C>
using adl_begin_t = decltype(adl_begin(std::declval<C>()));

template <typename C>
using adl_end_t = decltype(adl_end(std::declval<C>()));

In C++14, you won't need the trailing return types, but will also need to do the same for cbegin and cend. With that, you don't have to remember to have the usings ever again and just use the adl_* methods everywhere:
template <class Container>
CustomRange<adl_begin_t<Container&>> make_custom_range(Container& c) {
    return make_custom_range_from_iterators(adl_begin(c), adl_end(c));
}


text:
Q: Mapbox GL JS embed image in toggle menu

I would like to embed images inside of the toggle controls so that the user can use the toggle menu as a legend, how do I go about this using Mapbox GL JS?
    <!DOCTYPE html>

    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.20.0/mapbox-gl.css' rel='stylesheet' />

A: You can put this right before the end of your for loop:
var img = document.createElement('img');
img.src = "https://example.com/image.jpg"
link.appendChild(img);

This will add  within the  layer toogle named link.
I suggest you check out examples and the documentation for createElement and appendChild to understand how the menu in your code is built and how you can modify it further.


text:
Q: N! modulo algorithm So , from what i have read on the internet , modulo can do this:
(a*b) % n = (a % n * b % n)%n;

Which i understand because a%n * b%n can be bigger than n , so we have to take modulo n again.But i don't get n! mod p.Algorithm from internet:
int result = 1;
for (int i = 1 ; i <= n ; i++)
{
   result = (result * i ) % p;
}
cout<<result;
  Let's say n = 3 , and p is 7.
When i = 1 , result = 1 % 7 ,
when i = 2 , result = (1%7 * 2) % 7 , and when i = 3 ,
result =((1%7*2) % 7 * 3) % 7.

I don't really see the connection between my first statement and this result.From what i see , for n = 2 , n! % 7  should be (1 % 7 * 2 % 7 ) % 7 , not as the algorithm would do it:(1 % 7 * 2 ) % 7.
I know the algorithm is right and i am missing something...Can anyone help me?

A: Mathematically they are the same but the computer has a limited number of bits to represent numbers and if you exceed that limit you will get unexpected results.
See the following example:
Imagine the maximum value that could be stored is 200 and you wanted to compute X * Y % 100.
Lets try some values for X and Y:

*

*X = 103 and Y = 98 ==> 3 * 98 > 296 OVERFLOW

*X = 103 and Y = 103 ==> 3 * 3 > 9 OK
In case 2, if you take the modulus of both before multiplying, you get a result below 200. But if you only take from one variable, you would have 309 % 200, but 309 would become some twisted value since the type can only represent up to 200.
In case 1, you would have to come up with another strategy (maybe a bigger type or transform your multiplication into sums) because the result of the multiplication would extrapolate the 200 limit.


text:
Q: JobScheduler Won't Run in the Background I am trying to run an accounting calculator in the background using JobScheduler, but somehow, it won't do the calculation. The program runs smoothly, thats why it confuses me why it doesn't work. I appreciate your help.
Here's my Job Service class:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService  extends JobService {
private JobParameters params;

int num1a;
int num1b;
int num2a;
int num2b;
int num3a;
int num3b;
int num4a;
int num4b;
int num5a;
int num5b;

int sum1;
int sum2;
int sum3;
int sum4;
int sum5;

SharedPreferences preferences;
SharedPreferences.Editor editor;

@Override
public boolean onStartJob(JobParameters params) {
    this.params = params;
    Toast.makeText(getApplicationContext(), "Start", Toast.LENGTH_LONG).show();
    new MonthlyTask().execute();
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}

private class MonthlyTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPostExecute(Void xVoid) {
        super.onPostExecute(xVoid);
        jobFinished(params, false);
        Toast.makeText(getApplicationContext(), "Finish", Toast.LENGTH_LONG).show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = preferences.edit();
        try {
            num1a = preferences.getInt("expense1", 0);
            num1b = preferences.getInt("subtotal1", 0);
            num2a = preferences.getInt("expense2", 0);
            num2b = preferences.getInt("subtotal2", 0);
            num3a = preferences.getInt("expense3", 0);
            num3b = preferences.getInt("subtotal3", 0);
            num4a = preferences.getInt("expense4", 0);
            num4b = preferences.getInt("subtotal4", 0);
            num5a = preferences.getInt("expense5", 0);
            num5b = preferences.getInt("subtotal5", 0);

        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        sum1 = num1a + num1b;
        sum2 = num2a + num2b;
        sum3 = num3a + num3b;
        sum4 = num4a + num4b;
        sum5 = num5a + num5b;

        editor.putInt("subtotal1", sum1);
        editor.putInt("subtotal2", sum2);
        editor.putInt("subtotal3", sum3);
        editor.putInt("subtotal4", sum4);
        editor.putInt("subtotal5", sum5);
        return null;
    }
}
}

Here's my Main Activity
    public class MainActivity extends AppCompatActivity implements android.view.View.OnClickListener{
    //Do stuffs
    public void onClick(View view) {
    if (view == findViewById(R.id.btnSave)) {
     JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(),
                MyJobService.class.getName()));
        //run job service after every 5 seconds, which put back to 15 mins...but thats fine
        builder.setPeriodic(5000);
        builder.setPersisted(true);
        jobScheduler.schedule(builder.build());
        finish();
    }}

A:
I am trying to run an accounting calculator in the background using JobScheduler

This example is really strange.

but somehow, it won't do the calculation

Um, well, if by "the calculation", you mean addition, it is doing the addition. However, you then throw away the results. You edit() the SharedPreferences without calling apply() or commit() to save the changes.


text:
Q: If radio button is selected, change list of link_to paths in Rails 4 I have a list of link_tos like this:

<%= link_to "Carpooling", offers_path(:category => {:category => "Carpooling"}) %>

 <%= link_to "Tutoring", offers_path(:category => {:category => "Tutoring"}) %>

<%= link_to "Studying", offers_path(:category => {:category => "Studying"}) %>

<%= link_to "Career", offers_path(:category => {:category => "Career"}) %>

<%= link_to "Art", offers_path(:category => {:category => "Art"}) %>

<%= link_to "Culture", offers_path(:category => {:category => "Culture"}) %>

I would like to have two radio buttons, one called Offers and one called Requests. If the Requests radio button is selected, I'd like the paths to change to requests_path.... If the Offers radio button is selected, I'd like the paths to stay as they are.
I haven't coded radio buttons before, so am not sure where to start. I'm thinking I'll be using the radio_button_tag helper, or should I make this into a form and use f.radio_button? My main problem is figuring out the conditional statement. Any ideas?

A: You can use polymorphic_path to route to the 'index' action for different resources, without needing to hardcode a method name.

<%= link_to "Carpooling", polymorphic_path(params[:selected_resource], :category => {:category => "Carpooling"}) %>

where params[:selected_resource] matches the name of your radio input, and the values of that input are either "requests" or "offers"

A: It sounds like you want the set of links to change dynamically, as in the page loads, and the user can opt to select Requests or Offers.  If that's the case, I'll give you the basic approach here, and I'm confident you can take it from there.
First, the radio buttons are client-side elements, which are interacted with after the page has been rendered for the user.  So, any rails helpers et al will no longer be useful here.  So, to accomplish this conditional logic, you'll need the help of client-side coding, or more specifically, javascript via jQuery.
There are many approaches you can take here, but here's a quick one that I would recommend.
First, draw ALL the elements that you want to appear on the page, like so:
<%= link_to "Text 1", my_path, :class => 'link request_link' %>
<%= link_to "Text 2", my_path, :class => 'link offer_link' %>

This will yield HTML like:
Text 1
Text 2

For the radio buttons, you can use form_for or radio_button_tag, really doesn't matter, but the resulting HTML you want will look something like:
<input class="link_selector" type="radio" name="link_selector" value="request_link" />
<input class="link_selector" type="radio" name="link_selector" value="offer_link" />

Notice that the value for the radio button matches the class name of the link, and the class name for the buttons is link_selector.  The approach here will be to add a listener to the link_selector radio buttons such that when one is selected:

*

*Grab the value of the selected radio button

*Hide the link elements

*Show the links where the class == the value of the selected radio button.

Some pseudo-code:
//This happens when the page is ready
jQuery(document).ready(function() {
  //Hide all links
  $(".link").hide();

  //Add a listener to the radio buttons
  $(".link_selector").change(function() {
    var value = $(this).val()
    $(".link").hide();      //Hide all links
    $("." + value).show();  //Show the appropriate links
  });

  //Optionally, pre-select one of the radio buttons at this point, which
  //should trigger the listener to show the proper links; otherwise, no
  //links will appear when the page initially loads.
});

Again, there are many ways to accomplish this, but the takeaway here is that you'll need to use javascript to do it.
Hope that helps!


text:
Q: Express.js- Calling three Dependent MongoDB queries sequentially for each loop I have to insert multiple different JSON objects in MongoDB and then check whether the some of the data already exist in the database and run another query based on whether the data exists or not for each JSON Object. How can I do in expressjs? I am using mongojs package for working with MongoDB. The code I typed is below:
app.post('/addcard/:id', function(req, res) {
console.log("Received Add Card Request");
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var yrval = req.body.yrval;
var monval = req.body.monval;
var dateval = req.body.dateval;

for (var i=0;i<req.body.phone.length;i++){
  //console.log(i);
  var card = new Card({

    cardType                    : req.body.cardtype,
    cardTitle                   : req.body.cardtitle,
    allowMultipleStore          : false,
    phoneNumber                 : req.body.phone[i],
    messageUser                 : req.body.message,
    expiryDate                  : new Date(year+yrval,month+monval,day+dateval),
    creditPoints                : req.body.creditpoints,
    punchCount                  : req.body.punch,
    messageReachPunchLimit      : req.body.limitmessage,
    merchantUsersId             : mongoose.Types.ObjectId(req.body.merchantuserid),
    merchantId                  : mongoose.Types.ObjectId(req.params.id)
  });
console.log(card);
  db.carddata.insert(card, function (err,docInserted){

   // console.log(card);
   console.log(i);
    if (err) throw err;

    db.userdata.find({phoneNumber:req.body.phone},function (err,docs){
      console.log("hiss");
      if (err) throw err;

      if (docs.length!=0){
        var carduser = new CardUsersAssignment({

  cardId                            : docInserted._id,
  userId                            : docs[0]._id,
  remainingCreditPoints             : req.body.creditpoints,
  remainingPunchCount               : req.body.punch
  });
        db.carduser.insert(carduser,function (err){

      console.log(" Card Details saved successfully_existing");
        //console.log(i);

        })

      }//If (docs.length!=0)
      else{

  console.log(" Card Details saved successfully");

}

    })//Finding by PhoneNumber
    console.log(i+1);

})//Insert Function
console.log("hi");

} // End of For Loop
res.json({
  success:true,
  message:"Hello. You did it!"
});

});

This code is written as if I were writing for sequential execution. I know that NodeJS is asynchronous. I tried async.waterfall but it is giving error with the mongodb query function. Any help would be great. I am a NodeJS noob. Links to article which discuss similar scenarios would also be great.

A: You can achieve this using async library.
There is two way to do it.

*

*Use async each to iterate your data and inside each check data is first check data is already exist or not, based on find result you can return or insert the doc.

*It is the same as 1st, the only different is you just can to use waterfall for find and insert.

First Approach:
async.each(req.body.phone, function(data, callback) {
  // Create card Info
  db.carddata.insert(card, function (err,docInserted){
    if (err) {throw err;}
    db.userdata.find({phoneNumber:req.body.phone},function (err,docs){
      if (err) {throw err;
      } else if ( docs.length ){
         // create carduser data
         db.carduser.insert(carduser,function (err){
           if (err) {throw err;}
           callback();
         }
      } else {
         console.log(" Card Details saved successfully");
         callback();
      }

  }
}, function(err) {
  // if any of the file processing produced an error, err would equal that error
  if( err ) {
    // One of the iterations produced an error.
    // All processing will now stop.
    console.log('A file failed to process');
  } else {
    console.log('All files have been processed successfully');
  }
});

Second Approach:
async.each(req.body.phone, function(data, callback) {
   //create card data
   let data = {}
   data.phone = req.body.phone;
   data.docInserted = data.docInserted;
   data.cardata = cardData;
   async.waterfall([
     insertCard,
     updateDataFind,
     cardDataInsert,
     async.apply('insertCard', data)
   ], function (err, result) {
    if(err){
      if(err.success){
        callback();
      }
      throw err;
    }
    callback();
   });
}, function(err) {
  // if any of the file processing produced an error, err would equal that error
  if( err ) {
    // One of the iterations produced an error.
    // All processing will now stop.
    console.log('A file failed to process');
  } else {
    console.log('All files have been processed successfully');
  }
});
function insertCard(data, callback){
  db.carddata.insert(card, function (err,data.docInserted){
    if(err){throw err;}
    callback(null, data);
  }
}
function updateDataFind(data, callback){
  db.userdata.find({phoneNumber:data.phone},function (err,docs){
     if (err) {throw err;}
     else if (docs.length!=0){ callback(null, data); }
     else { callback({success:true}) }
  }
}
function cardDataInsert(data, callback){
   // create card user or pass from data.
   db.carduser.insert(carduser,function (err){
     if (err) {throw err;}
     callback(null, data);
   }
}


text:
Q: selecting rows in gridview in asp.net through Shift key (Selecting multiple rows from one to many using shift) How to select group of rows through shift keys in javascript. For example, I have a ASP.NET Grid View that has few rows. When I click on a row and then press shift key and then click on another row, how to select the rows in between these first row selected and the latest row clicked.
I need to implement this in Javascript. I have a gridview that contains some of the columsn which are hidden and not displayed in the UI columns.


text:
Q: Pandas: Alternating iterrows() from left to right and right to left I'm pretty new to programming, and so far this problem has been 'above my paygrade', so any help you can give on this is greatly appreciated!
I have a DataFrame object that looks like this:
               Dan          Mike            Dave
0  Adrian Peterson    Eddie Lacy  Jamaal Charles
1   Calvin Johnson   Leveon Bell      Dez Bryant

I would like to create a new DataFrame object that looks like this:
             Player       Drafter
0   Adrian Peterson           Dan
1        Eddie Lacy          Mike
2    Jamaal Charles          Dave
3        Dez Bryant          Dave
4       Leveon Bell          Mike
5    Calvin Johnson           Dan

I'm not sure how to iterate through the first row, left to right, and then through the second row from right to left.
Thank you so much for any help!

A: I think in this case it's good to show at least 3 rounds in order to check the code (assuming you want something more general than for just 2 rounds), so I'll expand the sample data:
               Dan          Mike            Dave
0  Adrian Peterson    Eddie Lacy  Jamaal Charles
1   Calvin Johnson   Leveon Bell      Dez Bryant
2        Tom Brady  Lionel Messi    Lebron James

First of all, use stack() to get a tentative draft order.
df2 = df.stack().reset_index().reset_index()
df2.columns = ['Order','Round','Drafter','Player']

   Order  Round Drafter           Player
0      0      0     Dan  Adrian Peterson
1      1      0    Mike       Eddie Lacy
2      2      0    Dave   Jamaal Charles
3      3      1     Dan   Calvin Johnson
4      4      1    Mike      Leveon Bell
5      5      1    Dave       Dez Bryant
6      6      2     Dan        Tom Brady
7      7      2    Mike     Lionel Messi
8      8      2    Dave     Lebron James

Note that order is correct for Rounds 0 and 2, but not 1.  A fairly easy way to fix the order for round 1 is to multiply by negative 1 (more specifically all rounds not divisible by 2) and then sort:
df2['Order'] = np.where( df2['Round'].mod(2)==1, -df2['Order'], df2['Order'] )

df3 = df2.sort(['Round','Order']).reset_index(drop=True)

   Order  Round Drafter           Player
0      0      0     Dan  Adrian Peterson
1      1      0    Mike       Eddie Lacy
2      2      0    Dave   Jamaal Charles
3     -5      1    Dave       Dez Bryant
4     -4      1    Mike      Leveon Bell
5     -3      1     Dan   Calvin Johnson
6      6      2     Dan        Tom Brady
7      7      2    Mike     Lionel Messi
8      8      2    Dave     Lebron James

At this point the draft order is now correctly held by the index and you can delete the Order column (I'm just leaving it there to make it more obvious how the code works).

A: This solution iterates through each row in the DataFrame via iterrows, reverses the row if it is odd numbered row [::(-1 if n % 2 else 1)], and then concatenates the results together with the list of Drafters which has been repeated by the number of rows in the DataFrame via df.columns.tolist() * df.shape[0].  The players and drafters are joined via a zip function, and then passed to the DataFrame constructor.
draft = pd.DataFrame(zip(pd.concat([pd.Series(row.values)[::(-1 if n % 2 else 1)]
                                    for n, row in df.iterrows()],
                                   ignore_index=True),
                         df.columns.tolist() * df.shape[0]),
                     columns=['Player', 'Drafter'])
draft['round'] = 1 + draft.index.values // df.shape[1]

>>> draft
            Player Drafter  round
0  Adrian Peterson     Dan      1
1       Eddie Lacy    Mike      1
2   Jamaal Charles    Dave      1
3       Dez Bryant     Dan      2
4      Leveon Bell    Mike      2
5   Calvin Johnson    Dave      2
6        Tom Brady     Dan      3
7     Lionel Messi    Mike      3
8     Lebron James    Dave      3


text:
Q: Sorting by property of foreign key object I'm making a third party app for a game.
In my domain I have the class 'player'. Players can attack/defend attacks of other players and while doing so they earn attacking/defending points. The API of the game is pretty awful (Online txt files in csv format) so there's little manipulation I can do other than bulk insert the files into my database and work from there.
Doing so I have a player table and a Points_Att table. In my EF configuration Player owns one Points_Att and Points_Att has one property: points. And each player has a 'Player_Att' object.
I'm trying to get the top X attackers from the database. But I can't sort on Player_Att.points, I tried the following code:
return _players.Where("conditions").OrderBy(p => p.Points_Att.Points).Take(X).ToList();
This gives me an array of the first X players in my database, it doesn't sort. I tried changing the Player_Att object to an int which would be easier to work with but my limited knowledge seems to stop me from doing so...
So basically I need to sort on player.Points_Att.Points or I need an int object rather than a Player_Att object.
If anything isn't clear please feel free to ask, I browsed my problem for a couple of hours now and i'm not getting any further.
Thanks in advance.
EDIT:
Models:
public class Player
{
    public Player_Att PointsAttacking { get; private set; }
}

public class Player_Att
{
    public int Points { get; private set; }
}

Mapping:
internal class PlayerConfiguration : IEntityTypeConfiguration<Player>
    {
        public void Configure(EntityTypeBuilder<Player> builder)
        {

            builder.OwnsOne(p => p.PointsAttacking).OnDelete(DeleteBehavior.Cascade);

        }

public class Player_AttConfiguration : IEntityTypeConfiguration<Player_Att>
{
    public void Configure(EntityTypeBuilder<Player_Att> builder)
    {
        builder.ToTable("Player_Att");
    }
}


text:
Q: Discrete dense subset Let $K$ be a compact Hausdorff space such that the set $D$ of isolated points in $K$ is countable and dense in $K$. Consider the linear subspace $A$ of $C(K)$ consisting of those functions $f\in C(K)$ such that $f$ is constant on $K\setminus D$ and the set $\{x\in D\colon f(x)= 0\}$ is finite or its complement in D is finite.
Is $A$ a closed subspace of $C(K)$?

A: *

*Try a very simple space for an example.  Can you find one which has only one non-isolated point?

*On this space, find a continuous function $f \notin A$.

*Find a sequence of functions $f_n \in A$ such that $f_n \to f$ uniformly.  This will show that $A$ is not closed.

A: I cannot give a full solution to your problem, but
here is what I think I found out.

*

*Let $y_1, \dots, y_n \in \mathbb{R}$ be any real numbers
then for any $x_1,\dots,x_n \in D$ define
$f(x_i) = y_i$ and $f(x) = 0$ everywhere else.
For every closed $A \subset R$ you have $f^{-1}(A)$
closed in $K$ hence $f$ is continuous and so $f \in A$.

*Any $g \in C(K)$ which is not constant on $K\setminus{D}$
lies in the interior of $C(K)\setminus{A}$, as all the $h \in C(K)$
with $\|g-h\|< \frac{1}{2} (\max_{x \in K\setminus{D}}{g(x)} - \min_{x \in K\setminus{D}}{g(x)})$
cannot be constant on $K\setminus{D}$.

*This leaves us considering $g \in C(K)$ with $g(x) = y_0$
for all $x \in K\setminus{D}$ and some $y_0$ and $g(x) = 0$
for infinitely many $x \in D$ and $g(x) \neq 0$ for infinitely many $x \in D$.
Note that for any open neighborhood $U$ of $y_0$ we have
$g^{-1}(U)$ containig all but finitely many elements of $D$.
Hence we conclude $y_0 = 0$.
Now for every $\varepsilon > 0$ you can choose $f \in A$
with $f(x) = g(x)$ for all $x \in D$ with $|g(x)| \geq \varepsilon$
and $f(x) = 0$ everywhere else.
It follows that $\|f-g\| < \varepsilon$ and as $\varepsilon >0$ was
arbitrary we conclude $g \in \overline{A}$.

*So all in all $A$ is not closed as long as the second condition is
not superfluous.


text:
Q: Error: getaddrinfo ENOTFOUND 127.0.0.1 - Windows 32 bits - Node v6.11.2 I'm launching a server with the following script (arranca_server.sh)
# Arranca servidor Node
export NODE_ENV=development-curso
export NODE_PORT=9001
export NODE_HOST=127.0.0.1
node server

And Node returns:
>     events.js:160
>           throw er; // Unhandled 'error' event
>           ^
>
>     Error: getaddrinfo ENOTFOUND 127.0.0.1
>         at errnoException (dns.js:28:10)
>         at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

Node version:
$ node -v
v6.11.2

S.O. Windows 7 32 bits

What have I tried?

*

*Differents NODE_HOST like: localhost, 0.0.0.0, 127.0.0.1, computer_name, empty, ::1, computer_ip and others...

*Differents NODE_PORT like: 9001, 12001, 30001, ...

*Adding 127.0.0.1 localhost in c:\windows\system32\drivers\etc\hosts

Any ideas?

A: SOLVED
In my case I have solved it by changing my file arranca_server.sh
# Arranca servidor Node
export NODE_ENV=development-curso
export NODE_PORT=9001
export NODE_HOST=127.0.0.1
node server

by this other arranca_server.bat
# Arranca servidor Node
SET NODE_ENV=development-curso
SET NODE_PORT=9001
SET NODE_HOST=127.0.0.1
node server


text:
Q: Share Records Insufficient Privileges I have a trigger on a custom object that inserts a share record after the insert of the custom object record.
When I go to insert the Share record, I get an INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY error. I can understand that this would happen to the custom object record because the org wide defaults are set to private but why would this be happening to the Share record? Is there an additional step I need to take to be able to insert the Share record?
The trigger has to be an after insert to be able to associate the custom object record to the share record.
trigger SingleShareRecord on SG_you__c (after insert) {

if (Trigger.isInsert) {
    if (Trigger.isAfter) {
        List<SG_you__Share> sharesToCreate = new List<SG_you__Share>();
        for (SG_you__c ex : Trigger.new) {
            SG_you__Share sg = new SG_you__Share();
            sg.ParentId = ex.Id;
            sg.AccessLevel = 'Edit';
            sg.UserOrGroupId =  ex.CreatedById;
            sharesToCreate.add(sg);
        }

        if (!sharesToCreate.isEmpty()){
            Database.SaveResult[] srList = Database.insert(sharesToCreate);

            // Process the save results.
            for (Database.SaveResult sr : srList) {
                if (sr.isSuccess()) {
                    system.debug('success');
                } else {
                    // Get first save result error.
                    Database.Error err = sr.getErrors()[0];
                }
            }
        }
    }
}
}


text:
Q: Convert HEX to IEEE 754 float I am writing a bash script to interpret Modbus RTU messages in the Enron history format. The message is binary. I need to convert some of the bytes to 32bit floats. I want to use POSIX available programs or at least very commonly available ones. Bash, AWK, sed, od, etc.
Given 00b74e47 I have tried to use od but I am expecting 52919.000000. od is not giving me the result I am expecting.
echo -ne "\x00\xb7\x4e\x47" | od -tfD
0000000          5.91070985e-315
0000004

A: If python3 is your option, please try the following:
echo "436a508c" | python3 -c 'import struct; print(struct.unpack("!f", bytes.fromhex(input()))[0])'

Yields:
234.31463623046875

Hope this helps.

A: With GNU Debugger:
gdb --batch -ex "print/f (float *) 0x436A508C"

Output:

$1 = 234.314636

Source: Using the linux command line in bash as a programmer's calculator

A: Like this?
$ crackNum --sp 436A508C
                  3  2          1         0
                  1 09876543 21098765432109876543210
                  S ---E8--- ----------F23----------
          Binary: 0 10000110 11010100101000010001100
             Hex: 436A 508C
       Precision: SP
            Sign: Positive
        Exponent: 7 (Stored: 134, Bias: 127)
       Hex-float: +0x1.d4a118p7
           Value: +234.31464 (NORMAL)

You can write a wrapper around crackNum to get rid of the 0x or post-process the output.
crackNum is a Haskell program, you can download it from hackage: http://hackage.haskell.org/package/crackNum

A: od -tfD converts to a double-precision floating-point number. od -tfF will convert to a single-precision floating-point number and will give the expected result.
echo -ne "\x00\xb7\x4e\x47" | od -tfF
0000000           52919
0000004

Hexdump can also be used. -e tells hexdump to output using a format string. 1/4 tells hexdump to use 4 bytes for the conversion. The %f is to output to a float.
echo -ne "\x00\xb7\x4e\x47" | hexdump -e '1/4 "%f" "\n"'
52919.000000


text:
Q: MYSQL : How to retrieve a certain Value of a variable value? i have a question with regard to a complicated query. So the task is the following:
With which connections can or could one fly from Düsseldorf (ICAO_Code : EDDF)
to Rome (ICAO_Code: LIRA), whereby a travel time of 24 hours should not be
exceeded,
you are allowed to change trains for a maximum of 1 hour and have a minimum
transfer time of 1 hour?

The tables look like this:
**flightexecution** (FlightNo, DepartureDateAndTimeUTC, ICAO_Origin,
ICAO_Destination, PlaneID, FlightDurationInMinutes)

and
**airport** (ICAO_Code, AirportName, Address,ID)

My current code looks like this:
SELECT fe.ICAO_Code_Origin,
    CASE
    WHEN fe.ICAO_Code_Origin = 'EDDF' AND fe.ICAO_Code_Destination = 'LIRA'
    THEN 'DIREKTFLUG'
    ELSE fe.ICAO_Code_Destination
    AS via,
    CASE
    WHEN fe.ICAO_Code_Origin = 'EDDF' AND fe.ICAO_Code_Destination = 'LIRA'
    THEN 0
    ELSE DATEDIFF(min, , SELEC....

The last statement is the problematic one. I want to say: "Time difference between the (DepartureDateAndTime of the intermediate stop) - (DepartureDateAndTime + FlightDurationInMinutes).
But how do i tell MYSQL that i want this specific ICAO_Origin?

A: Look up the SELECT syntax
SELECT FlightNo,...
FROM flightexecution fe
WHERE fe.ICAO_Code_Origin = 'EDDF'
  AND fe.ICAO_Code_Destination = 'LIRA'
  AND FlightDurationInMinutes < 24*60;

Insufficient information on trains is provided to answer that alternate.


text:
Q: How do I setup Sendmail + Dovecot + Roundcube on CentOS6 Pretty much what the title says. I've been digging all over the internet trying to figure this stuff out.
I have a CentOS 6 box. I have Sendmail and Dovecot and Roundcube all installed. Roundcube can't send mail out because Sendmail doesn't have some auth plugin. I've tried installing the auth plugin and sendmail still doesn't use it.
I seriously just don't understand email setup. Its a total pain. I also need SSL support, I don't even know where to begin. The only answer I've been given is "Read the manual". Well, that doesn't help, its huge and confusing.

A: I would suggest to use postfix instead of sendmail. It's a little bit easier to understand. Take a look at the Centos wiki there is an article on how to setup a simple mail server.
Also please check out the workaround tutorial it explains step by step what needs to be done (and most important why) it is designed for Debian but it's really easy to modify it for CentOS. In case you're still not confident, find someone who could do the setup for you. There is a chance that you will do something wrong and create an open relay which will be exploited by spamers.

A: I would get postfix + dovecot working, and worry about roundcube after. You only need a web server (and database) for Roundcube.
This one is for Centos 5, but should be close.
http://wiki.centos.org/HowTos/postfix

A: I went ahead and did Postfix + postfix.admin + Dovecot + Roundcube and the setup was very easy. I used this tutorial
http://www.campworld.net/thewiki/pmwiki.php/LinuxServersCentOS/Cent6VirtMailServer
I used parts from this tutorial to setup pipes
http://wiki.zimbra.com/wiki/Configuring_Postfix_to_work_with_piped_scripts
Mainly this part.. (Edited since we are not using Zimbra)
Edit /etc/postfix/transport and place the following lines at the top
# Pipe transports for RT queues
# YOU HAVE TO ADD THE PIPES TO /etc/postfix/master.cf if you want them to work!!!
rt@example.com     rt-pipe
rt-comment@example.com     rt-comment-pipe

Create the transport db by executing
postmap /etc/postfix/transport

The transport definitions 'rt-pipe' and 'rt-comment-pipe' must now be defined. Edit /etc/postfix/master.cf.in and add the following lines to the end of the file
rt-pipe         unix    -       n               n               -               -       pipe
    flags= user=www argv=/usr/bin/php -q /path/to/php/script.php
rt-comment-pipe         unix    -       n               n               -               -       pipe
    flags= user=www argv=/usr/bin/php -q /path/to/php/script.php

To make it all work, I had to create an alias for rt@example.com back to its self rt@example.com in postfix.admin, otherwise I was presented with this error..
550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table
 This part will probably differ depending on the setup you have used
Restart postfix and test
service postfix restart

I decided the setup I was going for just could not be accomplished, so I'm hosting email in two spots. It isn't a huge deal though, everything is working fine for me now. DNS is helping point where the email is hosted, and we have no issues with this setup what so ever.
Also should note that mxtoolbox reports it is not an open relay, and all is configured nicely. This is actually the preferred setup for what we are going to be doing with our servers anyway, so I've added all the steps to an auto configuration script for new servers :)


text:
Q: How to fill a list using Completion Handlers [SWIFT UI] I want to fill a list using a completion handler, the problem is that it's loading nil in the first execution and marks errors when I try to consume my View where I have my list that it's filled by completion handler... Any suggestions to fix this?
this is how I try to fill my list
let invitationService: InvitationService = InvitationService()
@State private var invitationsList : [Appointment]?

init() {
    let defaults = UserDefaults.standard
    let userId = defaults.integer(forKey: "userId")
    var appointmentList : [Appointment]?

    invitationService.getInvitations(id: userId, completionHandler: { (appointment) in
        if appointment != nil{
            appointmentList = appointment
        }
    })

    _invitationsList = State<[Appointment]?>.init(initialValue: (appointmentList))
}

as you can see I would need to fill my list until InvitationService Request ends but If I try to put it inside the code I got a

Escaping closure captures mutating 'self' parameter

error
I mean
  invitationService.getInvitations(id: userId, completionHandler: { (appointment) in
            if appointment != nil{
                appointmentList = appointment
                self._invitationsList = State<[Appointment]?>.init(initialValue: (appointmentList))
            }
        })

My VIEW
var body: some View {
    NavigationView{

    ZStack{
        colors["LightGray"]?.edgesIgnoringSafeArea(.all)
        Text("Hey").onAppear(){
            let defaults = UserDefaults.standard
                                   let userId = defaults.integer(forKey: "userId")

                                   self.invitationService.getInvitations(id: userId) { (appointment) in
                                       self.invitationsList = appointment

                                   }
        }
        List {

            ForEach(invitationsList!, id: \.self){invitation in
                NavigationLink(destination: InvitationDetailView(invitation: invitation)){
                    HStack{
                        VStack(alignment: .center){
                            Text(invitation.startDate.prefix(2))
                                .font(.largeTitle)
                            Text(invitation.startDate[2..<6]).font(.subheadline)

                        }.padding()
                        Spacer().frame(width:UIScreen.main.bounds.width/15, alignment: .leading)

                        ImageView(withURL: invitation.imageProfile,widthValue: 80, heightValue: 80)
                            .aspectRatio(contentMode: .fit)
                            .clipShape(Circle())
                        Spacer()
                        VStack(alignment: .leading){
                            Text(invitation.titleVisit)
                                .font(.headline)
                                .frame(width: UIScreen.main.bounds.width/3, alignment: .leading)
                            Text(invitation.typeVisit)
                                .font(.footnote)
                            Text(invitation.startDate.suffix(9))
                                .font(.caption)
                        }.padding()
                    }
                    .background(self.colors["White"])
                    .cornerRadius(25)
                    .foregroundColor(self.colors["Black"])
                    .shadow(radius: 2, x: 0, y: 0)
                }

            }.onDelete(perform: delete)

        }

    }.hideNavigationBar(text: "back".localized)
}

}

I'm trying to execute and when I do that invitationsList is nil

A: I recommend do not put such things into View.init, because SwiftUI view is struct, value, and can be re-created several times during layout/rendering. The better approach is to do this after view appeared (or, what is better, outside view hierarchy at all).
Anyway being in view here is possible approach
...
let invitationService: InvitationService = InvitationService()
@State private var invitationsList : [Appointment]? = nil

// nothing for init in this case

var body: some View {
    Text("Any subview here")
    .onAppear {
       let defaults = UserDefaults.standard
       let userId = defaults.integer(forKey: "userId")

       self.invitationService.getInvitations(id: userId) { (appointment) in
           self.invitationsList = appointment
       }
    }
}