text:
Q: Make Sequelize use returning: true for all mutations Is there any way to make all create/update/destroy operations in Sequelize use returning: true automatically?
I've tried putting it in defaultScope but it doesn't seem to take effect.

A: I don't know if it's possible to configure this, but you can quite easily implement a "hack", by modifying the original Model methods. In the file where you create your Sequelize instance, create a reference to the original Model method you want to modify, and then "substitute" it with a modified function, that calls the original:
 const originalCreate =  Sequelize.Model.create//Create a reference to the original function.

     Sequelize.Model.create =async  function(values,options={}){

           const opt = {...options,returning:true}//Intercept the options and append "returning"
           console.log(values,opt)
           const data =await  originalCreate.call(this,values,opt);//Call the original function.
           return data;

       }

const sequelize = new Sequelize(...)//Create the instance...

You can repeat this interception for every Model method you want to modify.
Note that "returning" works only for Postgres, according to the docs.


text:
Q: I can't find this segmentation fault So I'm doing this codewars kata and I'm succeding in every test but in the end the result fails because my code has a segmentation fault and I don't think I know enough about the language to find it! Can someone please halp?
int is_valid_ip(const char *addr)
{
    char set[] = "1234567890";
    int current;
    int octet_counter = 0;
    char *octet = 0;
    octet = strtok(addr, ".");
    while (octet)
    {
        if (strspn(octet, set) != strlen(octet)) return 0; // checks for spaces
        if (strlen(octet) > 1 && (octet[0]) == '0') return 0; // checks for preceding zeros
        sscanf(octet, "%d", &current);
        if (current < 0 || current > 255) return 0; // checks for range
        octet = strtok(0, ".");
        ++octet_counter;
    }
    if (octet_counter == 4) return 1; // checks for number of octets
    return 0;
};

My code was kind of cleaner but after so much messing around trying to solve this problems it's become this...

A: As strtok() modifies the string to be tokenized and addr is defined as const char * (I assume this is a requirement) you may make a copy of the input string *addr:
char ip[16]; // enought to hold nnn.nnn.nnn.nnn
if(strlen(addr)>15) return 0;
strcpy(ip, addr);

subsequently operate on ip instead of addr

Or... avoid using strtok and parse/scan the string without modifying it.

A: Here's a dumb solution using sscanf, just to show that it's possible. (Below, there are some better solutions.)
#include <stdio.h>

/* True if its argument represents a decimal number between
 * 0 and 255 without leading zeros. Assumes the characters are
 * all digits and that there are at most three of them.
 */
static int good(const char* octet) {
  switch (octet[0]) {
    case '0': return octet[1] == 0;
    case '1': return 1;
    case '2': return octet[1] == 0 || octet[2] == 0
              || octet[1] < '5'
              || octet[1] == '5' && octet[2] < '6';
    default:  return octet[1] == 0 || octet[2] == 0;
  }
}

struct OctetSep { char oct[4], sep[2] };
int is_valid_ip(const char *addr) {
  struct OctetSep bits[4];
  /* The last %c conversion is expected to fail. */
  return sscanf(addr, "%3[0-9]%1[.]%3[0-9]%1[.]%3[0-9]%1[.]%3[0-9]%1c",
                      bits[0].oct, bits[0].sep,
                      bits[1].oct, bits[1].sep,
                      bits[2].oct, bits[2].sep,
                      bits[3].oct, bits[3].sep) == 7
         && good(bits[0].oct) && good(bits[1].oct)
         && good(bits[2].oct) && good(bits[3].oct);
}

Of course, the bulk of the work is being done by good, and it would be easy to make it a bit more general:
#include <stddef.h>

/* This idiocy is avoid problems with signed characters */
static int my_isdigit(char c) { return c >= '0' && c <= '9'; }

/* Returns the address of the first unmatched character after a match
 * of an integer with no leading zeros and maximum value 255.
 * This address may be in the middle of the integer, if it is too big.
 * If the string doesn't start with a digit, returns NULL.
 */
static const char* good(const char* octet) {
  switch (octet[0]) {
    case '0': return octet + 1;
    case '1': return   !my_isdigit(octet[1]) ? octet + 1
                     : !my_isdigit(octet[2]) ? octet + 2
                     : octet + 3;
    case '2': return   !my_isdigit(octet[1]) ? octet + 1
                     : !my_isdigit(octet[2]) ? octet + 2
                     : octet[1] < '5' || octet[1] == '5' && octet[2] < '6'
                                             ? octet + 3
                     : octet + 2;
    case '3': case '4': case '5': case '6': case '7': case '8':
    case '9': return !my_isdigit(octet[1]) : octet + 1 ? octet + 2;
    default:  return NULL;
  }
}

int is_valid_ip(const char *addr) {
  for (const char* i = "..."; (addr = good(addr)); ++addr, ++i) {
    if (*addr != *i) break;
    if (!*i) return 1;
  }
  return 0;
}

But probably the simplest code comes from the use of strtol, although you still need a bunch of manual checks. (This solution scales much better to applications where the valid integer range is larger than 256.)
#include <stdlib.h>

/* This idiocy is avoid problems with signed characters */
static int my_isdigit(char c) { return c >= '0' && c <= '9'; }

/* Returns the address of the first character following the integer
 * starting precisely at the supplied address, provided the integer
 * has no leading zeros and a maximum value of 255. Otherwise,
 * returns NULL.
 */
static const char* good(const char* octet) {
  if (*octet == '0') return octet + 1;
  /* This check is necessary because strtol also accepts whitespace and - */
  if (!my_isdigit(*octet)) return NULL;
  char *endptr;
  long value = strtol(octet, &endptr, 10);
  /* We already handled 0, so value==0 must be an error return */
  if (value <= 0 || value > 255) return NULL;
  return endptr;
}

int is_valid_ip(const char *addr) {
  for (const char* i = "..."; (addr = good(addr)); ++addr, ++i) {
    if (*addr != *i) break;
    if (!*i) return 1;
  }
  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can Prometheus dynamically discover Google Cloud Run services? I'm programmatically deploying Cloud Run services using a Kubernetes Operator. The services expose Prometheus metrics.
I'm struggling to determine a good way to have Prometheus servers discover these services.
Though it seems elegant, using services with ExternalName and ServiceMonitors it is not possible with Prometheus Operator (issue). Using this approach, the Operator could have created ServiceMonitors once it obtained endpoints from deploying Cloud Run services.
There's no Prometheus service discovery mechanism for Cloud Run services. I found a dated example that discovers App Engine services and could possibly be extended to Cloud Run but this uses file-based discovery.
Today, I tried to use CoreDNS and dns_sd_config, thinking I could program CoreDNS and have it provide a dynamic list of services to Prometheus, but IIUC, this would also require persisting changes to a (Core)file and it adds complexity.
I'm not opposed to file-based discovery but it feels "lacking". Even if done with a ConfigMap, I sense I'd need to be forcing Prometheus reloads on changes.
Particularly when lined up against the elegance of the Prometheus Operator, it feels as though I'm missing something obvious.
Should I use Consul?

UPDATE I have a working configuration using Consul. Consul was easy to understand and get working.

In summary, I'd like a service with an endpoint that Prometheus could scrape to determine a list of targets. The service should be programmable to add|remove targets from the list.


text:
Q: Execution failed for task ':app:kaptGenerateStubsDebugKotlin' while building jar file from android project Unable to build library project as jar.
Updated to the latest android studio and gradle versions
task makeJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('build/outputs/')
    include('classes.jar')
    rename ('classes.jar', 'myLib.jar')//you can change this directory where you want to copy your .jar
}

task clearJar(type: Delete) {
    delete 'build/libs/myLib.jar'
}

makeJar.dependsOn(clearJar,build)

gradlew makeJar

Already observed package id 'platform-tools' in 'C:\Program Files (x86)\Android\android-sdk\platform-tools'. Skipping duplicate at 'C:\Program Files (x86)\Android\android-sdk\platform-tools.old923420354'
cvc-pattern-valid: Value '' is not facet-valid with respect to pattern '[a-zA-Z0-9_-]+' for type 'idType'.:
org.xml.sax.SAXParseException; lineNumber: 145; columnNumber: 348; cvc-pattern-valid: Value '' is not facet-valid with respect to pattern '[a-zA-Z0-9_-]+' for type 'idType'.
cvc-type.3.1.3: The value '' of element 'id' is not valid.:
org.xml.sax.SAXParseException; lineNumber: 145; columnNumber: 348; cvc-type.3.1.3: The value '' of element 'id' is not valid.
*****> Task :app:kaptGenerateStubsDebugKotlin FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.

Kotlin could not find the required JDK tools in the Java installation 'C:\Program Files\Java\jre1.8.0_101' used by Gradle. Make sure Gradle is running on a JDK, not JRE.*****

A:
Task :app:kaptGenerateStubsDebugKotlin FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
Kotlin could not find the required JDK tools in the Java installation 'C:\Program Files\Java\jre1.8.0_101' used by Gradle. Make sure Gradle is running on a JDK, not JRE.

It seems like you didn't install the JDK. If you install JDK from here, it may works.


text:
Q: Сервер выдает ошибку 500 $dsn = "mysql:host=$sdd_db_host;dbname=$sdd_db_name;charset=$charset";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);

$pdo = new PDO($dsn, $sdd_db_user, $sdd_db_pass, $opt);

$pdo->prepare("INSERT INTO Tokens (token ) VALUES(?)")->execute([$_GET["token"]]);

Где ошибка?

A: Ошибка 500 означает, что сервер записал ошибку в лог, но не будет ее показывать на экране. То есть, надо смотреть в лог веб-сервера.
Если это локальный сервер, без доступа извне, то удобнее настроить его так чтобы ошибки выводились сразу на экран. Для этого можно добавить к коду строчку
ini_set('display_errors',1);


text:
Q: pyspark - how can I remove all duplicate rows (ignoring certain columns) and not leaving any dupe pairs behind? I have the following table:
df = spark.createDataFrame([(2,'john',1),
                            (2,'john',1),
                            (3,'pete',8),
                            (3,'pete',8),
                            (5,'steve',9)],
                           ['id','name','value'])

df.show()

+----+-------+-------+--------------+
| id | name  | value |     date     |
+----+-------+-------+--------------+
|  2 | john  |     1 | 131434234342 |
|  2 | john  |     1 | 10-22-2018   |
|  3 | pete  |     8 | 10-22-2018   |
|  3 | pete  |     8 | 3258958304   |
|  5 | steve |     9 | 124324234    |
+----+-------+-------+--------------+

I want to remove all duplicate pairs (When the duplicates occur in id, name, or value but NOT date) so that I end up with:
+----+-------+-------+-----------+
| id | name  | value |   date    |
+----+-------+-------+-----------+
|  5 | steve |     9 | 124324234 |
+----+-------+-------+-----------+

How can I do this in PySpark?

A: You could groupBy id, name and value and filter on the count column : :
df = df.groupBy('id','name','value').count().where('count = 1')

df.show()

+---+-----+-----+-----+
| id| name|value|count|
+---+-----+-----+-----+
|  5|steve|    9|    1|
+---+-----+-----+-----+

You could eventually drop the count column if needed

A: Do groupBy for the columns you want and count and do a filter where count is equal to 1 and then you can drop the count column like below
import pyspark.sql.functions as f

df = df.groupBy("id", "name", "value").agg(f.count("*").alias('cnt')).where('cnt = 1').drop('cnt')

You can add the date column in the GroupBy condition if you want
Hope this helps you


text:
Q: i3wm can't create new tiles and mouse won't move I installed i3wm and X using the tutorials in the Arch wiki for a new Arch installation. I have Intel video, so I installed the xf86-video-intel package (which takes care of the driver).
But when I run: startx
I'm taken to i3 (which I've never used before), but the mouse won't move (I'm running Ubuntu dual boot on this machine and mouse works great there) and when I try to create a new tile (alt-enter), the cursor turns into what looks like a clock surrounded by a frame of sorts, and doesn't recover. When I try to exit (alt-shift-e), I'm presented with a tab asking me to be sure, which I have to click with my mouse, which isn't moving, so I can't exit without shutting down (i.e., pressing the i/o power button on the laptop).
Here is a log from startup. I pressed new window a couple of times and then shut the computer down:
06/05/13 01:08:09 - i3 4.5.1 (2013-03-18, branch "tags/4.5.1") starting
06/05/13 01:08:09 - Parsing configfile /home/tjb1982/.i3/config
deciding for version 4 due to this line: # i3 config file (v4)
06/05/13 01:08:09 - [libi3] libi3/font.c Using X font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1
06/05/13 01:08:09 - Used number 1 for workspace with name 1
06/05/13 01:08:09 - auto-starting i3-config-wizard
06/05/13 01:08:09 - startup id = i3/i3-config-wizard/723-0-arch_TIME0
06/05/13 01:08:09 - executing: i3-config-wizard
06/05/13 01:08:09 - Starting bar process: i3bar --bar_id=bar-hjnjco --socket="/run/user/1000/i3/ipc-socket.723"
06/05/13 01:08:09 - executing: i3bar --bar_id=bar-hjnjco --socket="/run/user/1000/i3/ipc-socket.723"
06/05/13 01:08:09 - Not a managed window, ignoring UnmapNotify event
The config file "/home/tjb1982/.i3/config" already exists. Exiting.
06/05/13 01:08:09 - IPC: looking for config for bar ID "bar-hjnjco"
06/05/13 01:08:09 - workspace visible? fs = 0x1bdb0f0, ws = 0x1bdb0f0
06/05/13 01:08:09 - WM_CLASS changed to i3bar (instance), i3bar (class)
06/05/13 01:08:09 - WM_NAME changed to "i3bar for output LVDS1"
06/05/13 01:08:09 - Using legacy window title. Note that in order to get Unicode window titles in i3, the application has to set _NET_WM_NAME (UTF-8)
06/05/13 01:08:09 - This window is of type dock
06/05/13 01:08:09 - Checking window 0x00a00007 (class i3bar)
06/05/13 01:08:09 - dock status does not match
06/05/13 01:08:09 - Checking window 0x00a00007 (class i3bar)
06/05/13 01:08:09 - dock status matches
06/05/13 01:08:09 - ClientMessage for window 0x0000009e
06/05/13 01:08:26 - startup id = i3/i3-sensible-terminal/723-1-arch_TIME366852
06/05/13 01:08:26 - executing: i3-sensible-terminal
06/05/13 01:08:26 - Not a managed window, ignoring UnmapNotify event
06/05/13 01:08:28 - startup id = i3/i3-sensible-terminal/723-2-arch_TIME368252
06/05/13 01:08:28 - executing: i3-sensible-terminal
06/05/13 01:08:28 - Not a managed window, ignoring UnmapNotify event
06/05/13 01:08:30 - startup id = i3/i3-sensible-terminal/723-3-arch_TIME370387
06/05/13 01:08:30 - executing: i3-sensible-terminal
06/05/13 01:08:30 - Not a managed window, ignoring UnmapNotify event
06/05/13 01:08:31 - startup id = i3/i3-sensible-terminal/723-4-arch_TIME371331
06/05/13 01:08:31 - executing: i3-sensible-terminal
06/05/13 01:08:31 - Not a managed window, ignoring UnmapNotify event
[libi3] libi3/font.c Using X font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1

Contents of ~/.i3/config (replaced # with ; for markdown legibility [which I didn't need to do, but I'm leaving it anyway):
; i3 config file (v4)
;
; Please see http://i3wm.org/docs/userguide.html for a complete reference!
;
; This config file uses keycodes (bindsym) and was written for the QWERTY
; layout.
;
; To get a config file with the same key positions, but for your current
; layout, use the i3-config-wizard
;

; Font for window titles. Will also be used by the bar unless a different font
; is used in the bar {} block below. ISO 10646 = Unicode

font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1

; The font above is very space-efficient, that is, it looks good, sharp and
; clear in small sizes. However, if you need a lot of unicode glyphs or
; right-to-left text rendering, you should instead use pango for rendering and
; chose a FreeType font, such as:
; font pango:DejaVu Sans Mono 10

; use Mouse+Mod1 to drag floating windows to their wanted position
floating_modifier Mod1

; start a terminal
bindsym Mod1+Return exec i3-sensible-terminal

; kill focused window
bindsym Mod1+Shift+q kill

; start dmenu (a program launcher)
bindsym Mod1+d exec dmenu_run
; There also is the (new) i3-dmenu-desktop which only displays applications
; shipping a .desktop file. It is a wrapper around dmenu, so you need that
; installed.
; bindsym Mod1+d exec --no-startup-id i3-dmenu-desktop

; change focus
bindsym Mod1+j focus left
bindsym Mod1+k focus down
bindsym Mod1+l focus up
bindsym Mod1+semicolon focus right

; alternatively, you can use the cursor keys:
bindsym Mod1+Left focus left
bindsym Mod1+Down focus down
bindsym Mod1+Up focus up
bindsym Mod1+Right focus right

; move focused window
bindsym Mod1+Shift+j move left
bindsym Mod1+Shift+k move down
bindsym Mod1+Shift+l move up
bindsym Mod1+Shift+semicolon move right

; alternatively, you can use the cursor keys:
bindsym Mod1+Shift+Left move left
bindsym Mod1+Shift+Down move down
bindsym Mod1+Shift+Up move up
bindsym Mod1+Shift+Right move right

; split in horizontal orientation
bindsym Mod1+h split h

; split in vertical orientation
bindsym Mod1+v split v

; enter fullscreen mode for the focused container
bindsym Mod1+f fullscreen

; change container layout (stacked, tabbed, toggle split)
bindsym Mod1+s layout stacking
bindsym Mod1+w layout tabbed
bindsym Mod1+e layout toggle split

; toggle tiling / floating
bindsym Mod1+Shift+space floating toggle

; change focus between tiling / floating windows
bindsym Mod1+space focus mode_toggle

; focus the parent container
bindsym Mod1+a focus parent

; focus the child container
;bindsym Mod1+d focus child

; switch to workspace
bindsym Mod1+1 workspace 1
bindsym Mod1+2 workspace 2
bindsym Mod1+3 workspace 3
bindsym Mod1+4 workspace 4
bindsym Mod1+5 workspace 5
bindsym Mod1+6 workspace 6
bindsym Mod1+7 workspace 7
bindsym Mod1+8 workspace 8
bindsym Mod1+9 workspace 9
bindsym Mod1+0 workspace 10

; move focused container to workspace
bindsym Mod1+Shift+1 move container to workspace 1
bindsym Mod1+Shift+2 move container to workspace 2
bindsym Mod1+Shift+3 move container to workspace 3
bindsym Mod1+Shift+4 move container to workspace 4
bindsym Mod1+Shift+5 move container to workspace 5
bindsym Mod1+Shift+6 move container to workspace 6
bindsym Mod1+Shift+7 move container to workspace 7
bindsym Mod1+Shift+8 move container to workspace 8
bindsym Mod1+Shift+9 move container to workspace 9
bindsym Mod1+Shift+0 move container to workspace 10

; reload the configuration file
bindsym Mod1+Shift+c reload
; restart i3 inplace (preserves your layout/session, can be used to upgrade i3)
bindsym Mod1+Shift+r restart
; exit i3 (logs you out of your X session)
bindsym Mod1+Shift+e exec "i3-nagbar -t warning -m 'You pressed the exit shortcut. Do you really want to exit i3? This will end your X session.' -b 'Yes, exit i3' 'i3-msg exit'"

; resize window (you can also use the mouse for that)
mode "resize" {
        ; These bindings trigger as soon as you enter the resize mode

        ; Pressing left will shrink the window's width.
        ; Pressing right will grow the window's width.
        ; Pressing up will shrink the window's height.
        ; Pressing down will grow the window's height.
        bindsym j           resize shrink width 10 px or 10 ppt
        bindsym k           resize grow height 10 px or 10 ppt
        bindsym l           resize shrink height 10 px or 10 ppt
        bindsym semicolon   resize grow width 10 px or 10 ppt

        ; same bindings, but for the arrow keys
        bindsym Left        resize shrink width 10 px or 10 ppt
        bindsym Down        resize grow height 10 px or 10 ppt
        bindsym Up          resize shrink height 10 px or 10 ppt
        bindsym Right       resize grow width 10 px or 10 ppt

        ; back to normal: Enter or Escape
        bindsym Return mode "default"
        bindsym Escape mode "default"
}

bindsym Mod1+r mode "resize"

; Start i3bar to display a workspace bar (plus the system information i3status
; finds out, if available)
bar {
        status_command i3status
}

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; automatically start i3-config-wizard to offer the user to create a
; keysym-based config which used his favorite modifier (alt or windows)
;
; i3-config-wizard will not launch if there already is a config file
; in ~/.i3/config.
;
; Please remove the following exec line:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
exec i3-config-wizard

A: Can you launch dmenu (Mod1+d) and launch i3-sensible-terminal from there? If not, make sure you have $TERMINAL in your shell configuration file or any of the terminal listed in the link I posted in the 1st comment.

A: I had the same problem, for me the reason was missing mouse drivers and the fact that i did not install xterm. Installing a mouse driver and xterm fixed it for me. https://wiki.archlinux.org/index.php/Touchpad_Synaptics


text:
Q: Android Studio Debugger Port Error - "handshake failed - connection prematurely closed" When I try to attach the Android Studio Debugger to a process, I get the following error:
Error running Android Debugger (8603):
Unable to open debugger port (localhost:8603): java.io.IOException "handshake failed - connection prematurally closed"

Kudos to whoever spelled prematurely that way.
Anyway, how do I get around this problem?
I'm using Android Studio 1.2.2 on Ubuntu.
This did not help.

A: I didn't need to restart my device, only restarting android studio fixed it ( clean your project if needed).
If doesn't work then restart your device.

A: The best and one solution for me was just to restart Android Studio.
Before I tried to restart adb server from command prompt or disable and enable adb integration from tools->Android->Check/Unchek the line, unplug and plug device , but nothing helped.

A: Maybe you should consider retaining only one device or a emulator, because Android Studio or Intellij IDEA only accept one device or emulator when debugging. It works well for me. I hope this can help.

A: Restarting the ADB server worked for me:
$ adb kill-server

$ adb start-server
* daemon not running. starting it now at tcp:5037 *
* daemon started successfully *

$ adb devices
List of devices attached
ce0217127216c0220c  device

A: For me these didnt work: Restart Android Studio,adb kill start server, restart phone.
Worked for me: Tools->Android->Disable and Enabled ADB Integration.

A: I had to restart both my android device and android studio. That seemed to work for me.

A: On Windows, restarting Android Studio didn't work. I instead killed the "adb.exe" process then retried.

A: In my case, often the reason is bad USB cable. Just replace another, better USB cable will work.

A: It shows that your previous debbugger was not closed. You should click stop (red button) to stop your attach previously, and rerun your debbugger. It would attach again


text:
Q: does reportStateAndNotification support multiple device state reporting? I am trying to report the status of a couple of devices via API  and I am getting this error
Request payload:
 {
   "requestId":"3310672920401175639",
   "agentUserId":"5d8f3dd42ce05140dc1c6a20",
   "payload":{
      "devices":{
         "states":[
            {
               "5de28e041729ec0cb40ba906":{
                  "on":true
               }
            },
            {
               "5df49862f53ffa4c1452a448":{
                  "on":false,
                  "brightness":100
               }
            }
         ]
      }
   }
}

Response:
{
   "error":{
      "code":400,
      "message":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list.",
      "status":"INVALID_ARGUMENT",
      "details":[
         {
            "@type":"type.googleapis.com/google.rpc.BadRequest",
            "fieldViolations":[
               {
                  "field":"payload.devices",
                  "description":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list."
               }
            ]
         }
      ]
   }
}

can "states" hold more than one status of the device? or am I doing something wrong with this?

A: The states value in the payload should be an object with each unique device id as a key. It should not be returned with these wrapped into an array. So your request payload should look more like this:
{
  "requestId":"3310672920401175639",
  "agentUserId":"5d8f3dd42ce05140dc1c6a20",
  "payload": {
    "devices": {
      "states": {
        "5de28e041729ec0cb40ba906": {
          "on": true
        },
        "5df49862f53ffa4c1452a448": {
          "on": false,
          "brightness": 100
        }
      }
    }
  }
}


text:
Q: How to create empty data table using PrimeNG I am creating a UI that allows users to input data in batches.
Similar to an Excel spreadsheet but the columns are already fixed.
I'm already using PrimeNG DataTable for other parts of my web app, and I would like to continue using it for the aforementioned feature if possible.
Thanks.

A: I figured it out.
My initial code was correct but because there was an issue when the backing array of the data table was being updated via push.
I had to create a separate array with the empty objects and assign it to the backing array.


text:
Q: Uploading files through a play framework app to S3 without "touching" the disk I have to implement a server that lets some users upload possibly huge files (multi gigabytes worth of files) to S3 (they do not know it is S3 though). I have already implemented something similar in Python and a basic implementation using Play framework.
Right now my uploading function looks like this:
public Result uploadFile() {
      List<Http.MultipartFormData.FilePart> files = request().body().asMultipartFormData().getFiles();
      if (CollectionUtils.isNotEmpty(files)) {
          Bucket bucket = MY_BUCKET;
          UUID timeuuid;
          Promise<UploadResult> promise;
          ObjectNode responseMessage = Json.newObject();
          for (Http.MultipartFormData.FilePart file : files) {
              timeuuid = TimeUUID.now();
              promise = Promise.promise(new UploadFunction(timeuuid, bucket, file.getFile(), obtainS3Connection()));
              responseMessage.set(file.getFilename(), TextNode.valueOf(timeuuid.toString()));
          }
          return accepted(responseMessage);
      } else {
          return badRequest("files empty");
      }
}

I am not worried about the upload code itself and actually I already have implemented it many times. What I am worried about is making it so that Play! does not save Files to disk and that the files sent only "pass through" my server without being written to disk (even as temp files). I have some processing involved and sometime "Client side" encryption of some content by I can do that as a Stream.
I was wondering if Play already does that? Or how would I achieve that?
What I am assuming Play (and Django in my previous version of this service) does is:
Upload --> Play       MyProcessing -------> S3
               \     /
                \   /
                 Disk

What I would like it to do :
Upload --> Play --> MyProcessing -------> S3

The reason I want to do this is that I want the potential to deploy my service on instances with very small disks and I also want the guarantee that nobody can find the unencrypted file (if I choose to encrypt it) once uploaded.
UPDATE: I am not giving up ... just yet.
I have found a few possible solution that unfortunately use Scala. They all revolve around the same theme as this discussion:
Play 2.x : Reactive file upload with Iteratees
I was wondering if this would be possible using Java (I am the only one in my company that knows Scala so I cannot roll out something for which I would be the only person able to do maintenance on it ... because sometimes I wish to take breaks or go on other projects).

A: I have never done this with Play however I have done something similar in Java. The route to success for us was to directly post files to S3. Basically what you do is you generate an upload form for the user where the post URL is not provided by your service but by Amazon and the users browser is directly uploading to S3.
On upload success S3 will then return an empty document with status code 200 when the object is successfully uploaded. In our case we perform the post call via jQuery and wait for the jQuery success handler on the post and only after that we update our systems database. Alternatively it is possible to specify a redirect form field with an URL where the user gets redirected to after successful upload.
Details on this can be found here:
http://doc.s3.amazonaws.com/proposals/post.html


text:
Q: android sqlite: Insert query syntax error Hi I am trying to insert values in my sqlite database but i get "unrecognized token" for the last value exception for byte array. here is code:
 public void insertImage(String userName, String userMob, String meterReading, String readingAddress, String readingRemark, String readingDate , byte[] imageBytes) {
        try {
            mDb.execSQL("INSERT INTO " + IMAGES_TABLE +"(" + USER_NAME + ", " + USER_MOB + ", " + METER_READING_TEXT + ", " + READING_REMARKS + ", " + READING_DATE + ", " + IMAGE + ")" +
                    " VALUES (" + userName + ", " + userMob + ", " + meterReading + ", " + readingAddress + ", " + readingRemark + ", " + readingDate + ", " + imageBytes + ");");
        }
        catch (Exception ex){
            ex.printStackTrace();
            Log.e("-----","dasdasdas");
        }
        }

A: seems you have  6 entry in into clause  but 7 in values
try {
        mDb.execSQL("INSERT INTO " + IMAGES_TABLE +
          "(" + USER_NAME + ", " +
           USER_MOB + ", " +
           METER_READING_TEXT + ", " +
           READING_REMARKS + ", " +
           READING_DATE + ", " +
           IMAGE + ")" +
          " VALUES (" + userName + ", " +
           userMob + ", " +
           meterReading + ", " +
           readingAddress + ", " +
           readingRemark + ", " +
           readingDate + ", " +
           imageBytes + ");");
    }

the number of element in both clause must match


text:
Q: How do i make the user able to go to another screen in a windows form application? I was making a windows form application with Visual Studio 2008 and i was wondering if i could make the user go to another screen instead of being on the same screen. I was coding with Visual C#. Thank you

A: Assuming you've added another Form to your project called "frmRegister", you could open it with code like this in a button click event handler:
    private void button1_Click(object sender, EventArgs e)
    {
        frmRegister register = new frmRegister();
        register.Show();
    }


text:
Q: How to find a country code in multiple languages My problem is that I got a list of countries in different languages. All in text file. E.g:
pl_PL   Japonia
en_GB   Spain
en_EN   Portugal

I am seeking a way to find the code of the country, knowing name in different languages, so i could print it in another languages. E.g:
pl_PL   Japonia    -- translate to english -->     en_EN  Japan
en_EN   Portugal   -- translate to polish  -->     pl_PL  Portugalia

I was thinking to make a hashmap for each language where I would put all available countries and codes, but I don't have idea how to make it. I made already one map like this, but I don't know how to make it for multiple languages.
    Locale[] allLocs = Locale.getAvailableLocales();
    Map map = new HashMap();
    String country = null;

    for (int j=0; j<allLocs.length; j++) {
        Locale.setDefault(new Locale(langArray[0]));
        String countryCode = allLocs[j].getCountry();

        if (countryCode.equals("")) continue;
        kraj =  allLocs[j].getDisplayCountry();
        map.put(country , allLocs[j]);
    }

A: what you are looking for is called exonym or xenonym and there is no out of the box class for that in java,
I would suggest to create a Pair class and then a map<string, pair> so you can match all the combinations in the application
example:
public class I18N {
    private Map<String, Map<String, String>> languages;
    public static void main(String[] args) {
    new I18N();
    }
    public I18N() {
    this.languages = new HashMap<String, Map<String, String>>();
    Map<String, String> l = new HashMap<String, String>();
    l.put("Spanish", "Japon");
    l.put("Polnish", "Japonia");
    languages.put("Japan", l);
    //
    System.out.println(languages.get("Japan").get("Polnish"));
    }
}

so this snippet will look for the country japan and then for that name in the language polnish...
the bad part is that you will need to populate your own Exonym Catalog

A: Maybe the Locale construction went wrong in your attempts. You need to retrieve the following from the input file:
    final Locale locale1 = new Locale("pl", "PL");
    final String country1 = "Japonia";

Then given the target locale:
    final Locale locale2 = new Locale("en", "US");

One can find the country as you did. In java 8:
    final Locale[] locales = Locale.getAvailableLocales();
    Optional<String> country2 = Stream.of(locales)
            .filter((loc) -> country1.equals(loc.getDisplayCountry(locale1)))
            .map((cloc) -> cloc.getDisplayCountry(locale2))
            .filter((s) -> !s.isEmpty())
            .findAny();
    System.out.println(country2.orElse("not found"));

*

*This searches every loc with the display country in the first language.

*Then that cloc of the corresponding country is used for the display country in the second language.

*Non-empty.


text:
Q: celery schedule not work and got KeyError using Django Env: django 1.6.5 python 2.7 celery 3.1.11
My target server to run this project not install djcelery. So, I am not trying to use djcelery.
I am follow DOCSFirst steps with Django AND Using Celery in your Application. When I run celery -A djproj -B -l debug I got KeyError. And There is actually no the target task in [tasks]. Anyone knows how to solve it? Thanks.
Error
[tasks]
  . celery.backend_cleanup
  . celery.chain
  . celery.chord
  . celery.chord_unlock
  . celery.chunks
  . celery.group
  . celery.map
  . celery.starmap
  . djproj.celery.debug_task
  . djproj.celery.defaulttask1
  . djproj.celery.hello

... ...

[2014-06-19 16:08:23,007: INFO/MainProcess] Received task: djproj.celery.hello[794e54c7-62c8-4ad8-bcbb-64ff809366d1]
[2014-06-19 16:08:23,008: DEBUG/MainProcess] TaskPool: Apply <function _fast_trace_task at 0x1036d17d0> (args:('djproj.celery.hello', '794e54c7-62c8-4ad8-bcbb-64ff809366d1', [], {}, {'utc': True, u'is_eager': False, 'chord': None, u'group': None, 'args': [], 'retries': 0, u'delivery_info': {u'priority': 0, u'redelivered': None, u'routing_key': u'celery', u'exchange': u'celery'}, 'expires': None, u'hostname': 'celery@nluckys-Mac.local', 'task': 'djproj.celery.hello', 'callbacks': None, u'correlation_id': u'794e54c7-62c8-4ad8-bcbb-64ff809366d1', 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, u'reply_to': u'20fe5513-efc2-3e69-9541-8e82758f94f9', 'id': '794e54c7-62c8-4ad8-bcbb-64ff809366d1', u'headers': {}}) kwargs:{})
[2014-06-19 16:08:23,010: WARNING/Worker-2] helloincelery
[2014-06-19 16:08:23,010: ERROR/MainProcess] Received unregistered task of type 'apps.app1.tuan.tuantask1'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.

The full contents of the message body was:
{'utc': True, 'chord': None, 'args': [], 'retries': 0, 'expires': None, 'task': 'apps.app1.tuan.tuantask1', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, 'id': 'f2f92c1d-ac6d-4131-a029-123fbfc4ab48'} (220b)
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/celery/worker/consumer.py", line 455, in on_task_received
    strategies[name](message, body,
KeyError: 'apps.app1.tuan.tuantask1'

Shedule seems not working. My full codes are here. Some of codes are pasted as below.
My project folders:
djproj
├── apps
│   ├── __init__.py
│   └──  app1
│       ├── __init__.py
│       ├── admin.py
│       ├── models.py
│       ├── tests.py
│       ├── tuan.py
│       └── views.py
├── djproj
│   ├── __init__.py
│   ├── celery.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── files
├── manage.py
└── run.sh

djproj/djproj/__init__.py
from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

djproj/djproj/celery.py
from __future__ import absolute_import

import os
import datetime
from celery import Celery

from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djproj.settings')

app = Celery('djproj')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

@app.task
def defaulttask1():
    currt = datetime.datetime.now()
    with open("files/defaulttask1.txt", "w") as fo:
        print >> fo, currt.isoformat()+"default_task_1"
        return currt

@app.task
def hello():
    print "helloincelery"

djproj/djproj/settings.py
"""
Django settings for djproj project.

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
from __future__ import absolute_import
from celery.schedules import crontab

BROKER_URL = 'redis://localhost:6379/0'

from datetime import timedelta
CELERYBEAT_SCHEDULE = {
    #'defaulttask1': {
    #    'task': 'djproj.celery.defaulttask1',
    #    'schedule': timedelta(seconds=3)
    #},
    'hello': {
        'task': 'djproj.celery.hello',
        'schedule': timedelta(seconds=4)
    },
    'tuantask1': {
        'task': 'apps.app1.tuan.tuantask1',
        'schedule': timedelta(seconds=6)
    },
    #'tuantask2': {
    #    'task': 'app1.tuan.tuantask2',
    #    'schedule': crontab(minute=55, hour=17)
    #}
}

TIME_ZONE = 'Asia/Shanghai'

DATETIME_FORMAT = 'Y-m-d H:i:s'

TIME_FORMAT = 'Y-m-d H:i:s'

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+df53@zaea16*pa%)kyta=ciam#$1c1&tjx-5!59f+nlo)n#!4'

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

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.app1',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'djproj.urls'

WSGI_APPLICATION = 'djproj.wsgi.application'

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

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

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

LANGUAGE_CODE = 'zh_CN'

#TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static/'

djproj/apps/app1/tuan.py
from __future__ import absolute_import

#from djproj.celery import app
from celery import shared_task
import datetime

#@shared_task
#def add(x, y):
#    return x + y

#@shared_task
#def mul(x, y):
#    return x * y

#@shared_task
#def xsum(numbers):
#    return sum(numbers)

@shared_task
def tuantask1():
    currt = datetime.datetime.now()
    with open("files/tuantask1.txt", "w") as fo:
        print >> fo, currt.isoformat()+"tuantask_1"
    return currt.isoformat()

@shared_task
def tuantask2():
    print "stest===="

djproj/run.sh
celery -A djproj worker -B -l debug

A: Well, I know what happen. I need modify tuan.py to tasks.py, since autodiscover_tasks in celery.py only can find tasks in apps in file named tasks.py. If do not modify file name, just import tasks manually using CELERY_IMPORTS in settings.py using absolute path (e.g. 'apps.app1.tuan' ) works either. see DOC
a common practice for reusable apps is to define all tasks in a separate
tasks.py module, and Celery does have a way to autodiscover these modules

|
This way you do not have to manually add the individual modules to the
CELERY_IMPORTS setting.


text:
Q: Fatal error: Uncaught OAuthException: (#100) Invalid parameter Hello I'm trying to make an event on behalf of my users. this is the code I am using to make the request to the API. me/feed works fine. but when I change it to me/events and change the keys and content. its messed up. even copy and pasted the parameters straight from the Facebook developers section.
    $ret_obj = $facebook->api('/me/events', 'POST',
                            array(
                                'name' => 'hill Billy',
                                'start_time' => '10pm',
                                'end_time' => '3am',
                                'description' => 'Basic Info',
                                'location' => 'street address',
                                'privacy_type' => 'OPEN'
                              ));

When it's called I get this fatal error:
Fatal error: Uncaught OAuthException: (#100) Invalid parameter thrown in base_facebook.php on line 1238

I changed the code to add the session token even tho it wasn't required for the feed call but it still shows the same error message...
       $ret = $facebook->api('/me/events', 'POST',
                                    array(
                                      'access_token' => $_SESSION['fb_00000000000000_access_token'],
                                      'name' => 'hill Billy',
                                      'start_time' => '10pm',
                                      'end_time' => '3am',
                                      'description' => 'Basic Info',
                                      'location' => 'street address',
                                      'privacy_type' => 'OPEN'

But to no Evail it still doesnt work
Then I just changed it now to
      $ret_obj = $facebook->api('/'.$_SESSION['fb_000000000000000_user_id'].'/events?access_token='.$_SESSION['fb_000000000000000_access_token'], 'POST',
                                    array(

                                      'name' => 'hill Billy',
                                      'start_time' => '10pm',
                                      'end_time' => '3am',
                                      'description' => 'Basic Info',
                                      'location' => 'street address',
                                      'privacy_type' => 'OPEN'
                                 ));

isn't that what was specified?

A: While going to ON BEHALF OF in FB Apps.... you should go for Open Graph API with AUTH AU
THENTICATION.. In that first time you will asked for permission/allow option to post ON BEHALF OF.. so if you allow you will get Auth TOKEN/AUTHENTICATION ID... after that only you can able to post/do something ON BEHALF OF...
Pass your access token like below,
$ret_obj = $facebook->api('/me/events?access_token=ACCESS_TOKEN', 'POST', array( 'name' => 'hill Billy', 'start_time' => '10pm', 'end_time' => '3am', 'description' => 'Basic Info', 'location' => 'street address', 'privacy_type' => 'OPEN' ));

Refer the followings...
http://blog.awpny.com/kaiawpny/2011/how-to-facebook-access-token.html
http://developers.facebook.com/docs/opengraphprotocol/
You need to pass Auth Token... thats why your error is,
FACEBOOK PHP API FATAL ERROR: Fatal error: Uncaught OAuthException: (#100) Invalid parameter


text:
Q: Potential Memory Leak in cv::cvtColor using CV_BGR2HSV I am seeing radically different memory usage on an iPad3 when calling cv::cvtColor with CV_BGR2GRAY vs CV_BGR2HSV repeatedly in the context of a video processing algorithm and I'd like some insight in to why this is or guidance on how to avoid linear memory growth with each call to cvtColor.
Here's the simplified code I wrote for testing and for context in this question:
- (void) processImage:(cv::Mat &)image {
    processor.process(image, output);
    image = output;
}

output is defined as part of the class this method is in.  The processor class is defined as:
class TestFrameProcessor {
public:
    cv::Mat tmp;
    cv::Scalar green;
    TestFrameProcessor(void):
        green(0,255,0) {
    }

    void process(cv:: Mat &input, cv:: Mat &output) {
        cv::cvtColor(input, tmp, CV_BGR2HSV);
        output = green;
    }
};

This code is only meant to be illustrative of the problem I am having not to do anything of value.  When I use CV_BGR2GRAY as the conversion type I get a memory profile like this:

With a max value of around 21 MB and an average that is around 10 MB.
When I use CV_BGR2HSV I get a memory profile like this:

With a peak value of around 225 MB and a min of around 12 MB.  My concern is in this linear growth of memory usage when using the BGR2HSV conversion.  In this particular run there appears to be memory cleanup happening from within OpenCV, however I have had runs (did not get a screen cap of the profile) where the memory grows unbounded until all of the system memory is used up and the application dies an ungraceful death.
Questions are:

*

*Am I misusing the cv::Mat objects or cvtColor here?  Should I call release?

*Has any one seen this type of memory usage before with cvtColor?

*If so, is there a way to avoid it?

*Are there known memory issues with the OpenCV implementation cvtColor?

(I'm hoping someone else knows the answers or has better GoogleFu skills than I apparently do)


text:
Q: If $f\in k[x]$ and $\deg f \leq n$, then $f(x)=c_1(x - a_1)^n + c_2(x - a_2)^n +\cdots+ c_{n+1}(x - a_{n+1})^n$ for distinct $a_i's$ in $k$. I have been trying the following qual question from Harvard in the year of 1991. You can find it here.
Let $V$ be the vector space of polynomials of degree at most $n$ in one variable $x$ over
a field $k$ of characteristic $0$, and let $a_1,\ldots,a_{n+1}$ be any $n + 1$ distinct elements of $k$.

Show that any polynomial $f(x)\in V$ can be written in the form
$$f(x)=c_1(x - a_1)^n + c_2(x - a_2)^n +\cdots+ c_{n+1}(x - a_{n+1})^n$$
for some elements $c_i \in k$. Also this result is false if $\text{char}(k)\neq0$.

Initially I was trying to solve applying division algorithm, but stuck at the last remainder. Then i tried to imitate Lagrange's Interpolation, i.e., tried to show the collection $\mathcal B=\{(x-a_1)^n,\ldots,(x-a_{n+1})^n\}$ form a basis for the $n+1$ dimensional space $V$. I couldn't really do much. Need some help. Thanks.

A: Since $V$ is $(n+1)$-dimensional vector space, it's enough to prove that $(n+1)$ vectors $\{(x-a_i)^n\}_{i=1}^{n+1}$ are linearly independent.
Suppose the contrary, then there are $c_1,\ldots,c_{n+1}\in k$ not all zero such that the polynomial identity
$$
\sum_{k=1}^{n+1}c_k(x-a_k)^{n}=0
$$
holds.
Differentiating this equality $m$ times gives
$$
n(n-1)\ldots(n-m+1)\cdot\sum_{k=1}^{n+1}c_k(x-a_k)^{n-m}=0.
$$
However, in our case $\operatorname{char} k=0$, so we have
$$
\sum_{k=1}^{n+1}c_k(x-a_k)^{m}=0,~m=\overline{0,n}.
$$
Now it remains to recall that since not all $c_k$ are zeros, the determinant $\det\{(x-a_k)^m\}_{k,m}$ should be equal to 0. But it's a Vandermonde determinant, so it equals
$$
\det\{(x-a_k)^m\}_{k,m}=\prod_{k<m}((x-a_k)-(x-a_m))=\prod_{k<m}(a_m-a_k)\neq 0
$$
(since all $a_k$ are distinct) and this is a contradiction.
Thus, elements $\{(x-a_i)^n\}_{i=1}^{n+1}$ span the whole $V$, as desired.


text:
Q: If $x$ is a transitive set, $\bigcup x^+ = x$, where $x^+ = x\cup\{x\}$ I can't understand a sentence in a textbook: if $x$ is a transitive set, then $\bigcup x^+=x$? Could someone help me to understand?
added: $x^+=x\cup\{x\}$

A: Let us deconstruct this:

*

*$\bigcup A = \{z\mid\exists y\in A: z\in y\}$.

*$x^+=x\cup\{x\}$

From this we have: $\bigcup x^+ = \{z\mid\exists y\in x\cup\{x\}: z\in y\}$. We then follow the definition of a transitive set:

The set $x$ is transitive if for every $y\in x$, $y\subseteq x$

Now we want to show that $x\subseteq\bigcup x^+$ and that $\bigcup x^+\subseteq x$, the axiom of extensionality will ensure equality.
For the first one, it is nearly trivial. Since $x\in x^+$ we have that $y\in x$ then $y\in\bigcup x^+$ immediately (recall the definition of this union).
For the second one, we recall that $y\in x^+$ then $y\in x$ or $y=x$. Therefore $y\subseteq x$. So for every $z\in\bigcup x^+$ we have some $y\subseteq x$ such that $z\in y$, therefore $z\in x$ as wanted.

A: The set $x$ is transitive if $z\in y \in x$ implies $z\in x$. Moreover, $x^+=x\cup\{x\}$. So let $x$ be a transitive set.
We have $x\subseteq\bigcup x^+$ since $x\in\{x\}$. Now let $z\in \bigcup x^+$. Then $z\in\bigcup x\cup x$. If $z\in\bigcup x$, then there exists $y\in x$ with $z\in y$. But since $x$ is transitive, $y\subseteq x$ and hence $z\in x$.


text:
Q: Use send_dbmail to send an email for each row in sql table I am having difficulties figuring out how to make send_dbmail loop through my table and send a new email for each record.  My table is dropped and re-created each time this package runs, sometimes it will have zero records, other times it may have a few (never anything significant, always < 10).
This works fine when I have a single row but when I add a second row the subquery fails as it doesn't produce a unique result, so my question is how can I make this send a separate email for each row that might exists and how do I make it not send a message if no rows exists?
I have to send this via a TEXT body format as it is being grabbed by a third party mail eater that only supports text.
Thanks for any suggestions!
use automationdb
declare @bodytext as nvarchar(max)

set @bodyText = ( SELECT
N'%z_Curr_Contact_Number =
%string1 = na
%string1 = na
%string2 = na
%zneed_by_date = '+ CONVERT(VARCHAR(20), dateadd(day,1,GETDATE()),100) + N'
' + '%Description=' + 'ID:  ' + isnull(id,'Unknown') +  N'
' + '%Description=' + 'Name:  ' + isnull(name,'Unknown') + N'
' + '%Description=' + 'Login:  ' + isnull(login,'Unknown') + N'
' + '%Description=' + 'Status:  ' + isnull(status,'Unknown') + N'
' + '%Description=' + 'Note One:  ' + isnull(note_one,'Unknown') + N'
' + '%Description=' + 'Role:  ' + isnull(role_id,'Unknown') + N'
' + '%Description=' + 'Role Name:  ' + isnull(role_name,'Unknown') + N'
' + '%Description=' + 'Location:  ' + isnull(Location,'Unknown') + N''

     FROM dbo.mpt)

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'test',
@body = @bodyText,
@body_format ='TEXT',
@recipients = 'random@email.com',
@subject = 'send_dbmail test' ;

A: 1) You could use a LOCAL FAST_FORWARD cursor to read every row and then to execute sp_send_dbmail
or
2) You could dynamically generate a sql statement that includes the list of EXEC sp_send_dbmail statements like this:
DECLARE @SqlStatement NVARCHAR(MAX) = N'
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest01@domain.com'', ...;
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest02@domain.com'', ...;
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest03@domain.com'', ...;
    ...';
EXEC(@SqlStatement);

or
DECLARE @bodyText NVARCHAR(MAX);
SET @bodyText = ...;

DECLARE @SqlStatement NVARCHAR(MAX) = N'
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest01@domain.com'', @body = @pBody, ...;
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest02@domain.com'', @body = @pBody, ...;
    EXEC msdb.dbo.sp_send_dbmail @recipients=''dest03@domain.com'', @body = @pBody, ...;
    ...';
EXEC sp_executesql @SqlStatement, N'@pBody NVARCHAR(MAX)', @pBody = @bodyText;


text:
Q: I look for a jQuery plugin that can manage a photo gallery I look for a jQuery plugin that can manage a photo gallery.
I want to choose and move some thumbnails from one category (subcategory) to another.
I need the pagination function because some category can have many photos (thumbnails).


text:
Q: Error 1 Non-invocable member 'System.IO.SearchOption.AllDirectories' cannot be used like a method String[] files = Directory.GetFileSystemEntries(directoryToSearch, fileNameToFind, SearchOption.AllDirectories());

A: Just like the error says, you can't invoke SearchOption.AllDirectories as a method, because it isn't a method.  I think you want this:
String[] files = Directory.GetFileSystemEntries(directoryToSearch, fileNameToFind, SearchOption.AllDirectories);

Putting parentheses after something tells the compiler that it should execute that something as a method.  So you were essentially just confusing the compiler.  SearchOption.AllDirectories is a value, not a method.


text:
Q: how to extract files (named with numbers) from a directory in unix I have a folder which consists files numbered 1, 2, 3, 4, 5 and so on. These files are named as numbers only. Along with these files, I also have two folders in the same directory.
Am trying to extract the last five files from the directory (excluding folders and also files without numbers) whose file name is a number. So am trying to do something like this:
ls /var/lib/myFolder/prog/TEST_DEV/builds/ -t | head -n5

But this returns files along with my two directories.
Then i tried something like:
ls /var/lib/myFolder/prog/TEST_DEV/builds/ -p | tail -5

Which doesn't work as well.
Any suggestions on how to proceed?

A: You may use shell globbing or a script that interprets Regular Expressions, like grep.
For example, in order to list all the files whose file names only contain numbers (one or more digits) you can go like this:
ls -1 | egrep '\b[0-9]+\b'

In order to retrieve the last 5 files, as you say, you need:

*

*to make sure you use a sorting rule of ls like ls -t for sort by last modified date

*to exclude the directories from the list you should exclude the filenames that include '/' at the end by using the regular expression \b[0-9]+\b that means the matches have 1 or more numeric digits from the beginning to the end. The '/' is available at the end of directory names because ls has the p option also.

*to limit the returned matches by using the tail -5 command

So, I guess something like this will work for you:
ls -1tp | egrep '\b[0-9]+\b' | tail -5

Reference to this SO question: Regular Expression usage with ls
Reference to a Grep cheat sheet.


text:
Q: SpringBoot -- ClassCastException I am trying to externalise the configuration properties by using YAML files. I am  successfull in reading the properties and run it individually using Spring Boot application.
But when I integrate the same classes in my Spring batch job project, and I try to deploy the job, I get the below exception. What does the exception mean ? How do I disable the improper class casting ??
These are my maven dependencies:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.1.RELEASE</version>
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.batch</groupId>
     <artifactId>spring-batch-core</artifactId>
     <version>${springbatch.version}</version>
     <scope>provided</scope>
</dependency>

[2014-08-20 15:14:13.511] boot - 5604 ERROR [DeploymentsPathChildrenCache-0] --- ContainerRegistrar: Exception deploying module
java.lang.IllegalStateException: java.lang.ClassCastException: org.springframework.boot.logging.logback.LogbackLoggingSystem cannot be cast to org.springframework.boot.logging.LoggingSystem
        at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:85)
        at org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:160)
        at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:122)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:98)
        at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:92)
        at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:58)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:275)
        at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
        at org.springframework.xd.module.core.SimpleModule.initialize(SimpleModule.java:191)
        at org.springframework.xd.dirt.module.ModuleDeployer.deploy(ModuleDeployer.java:127)
        at org.springframework.xd.dirt.module.ModuleDeployer.deployAndStore(ModuleDeployer.java:117)
        at org.springframework.xd.dirt.module.ModuleDeployer.deployAndStore(ModuleDeployer.java:107)
        at org.springframework.xd.dirt.server.ContainerRegistrar.deployModule(ContainerRegistrar.java:237)
        at org.springframework.xd.dirt.server.ContainerRegistrar.deployJob(ContainerRegistrar.java:512)
        at org.springframework.xd.dirt.server.ContainerRegistrar.onChildAdded(ContainerRegistrar.java:442)
        at org.springframework.xd.dirt.server.ContainerRegistrar.access$800(ContainerRegistrar.java:96)
        at org.springframework.xd.dirt.server.ContainerRegistrar$DeploymentListener.childEvent(ContainerRegistrar.java:807)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:509)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:503)
        at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92)
        at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
        at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:83)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:500)
        at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$10.run(PathChildrenCache.java:762)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: org.springframework.boot.logging.logback.LogbackLoggingSystem cannot be cast to org.springframework.boot.logging.LoggingSystem
        at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:81)
        ... 31 more
[2014-08-20 15:14:13.601] boot - 5604  INFO [DeploymentsPathChildrenCache-0] --- ContainerRegistrar: Path cache event: /deployments/modules/a6acf7b1-32de-408a-ab96-4ece1df91115/NewJob3.job.database-sy
nchronizer-0, type: CHILD_REMOVED
[2014-08-20 15:14:13.602] boot - 5604  INFO [DeploymentsPathChildrenCache-0] --- ContainerRegistrar: Undeploying module [ModuleDescriptor@6436d9c4 moduleName = 'database-synchronizer', moduleLabel = [
null], group = 'NewJob3', sourceChannelName = [null], sinkChannelName = [null], sinkChannelName = [null], index = 0, type = job, parameters = map[[empty]], children = list[[empty]]]
[2014-08-20 15:14:13.605] boot - 5604 ERROR [JobDeploymentsPathChildrenCache-0] --- PathChildrenCache:
java.lang.IllegalStateException: Container a6acf7b1-32de-408a-ab96-4ece1df91115 experienced the following error deploying module database-synchronizer-0 of type job: java.lang.IllegalStateException: j
ava.lang.ClassCastException: org.springframework.boot.logging.logback.LogbackLoggingSystem cannot be cast to org.springframework.boot.logging.LoggingSystem
        at org.springframework.xd.dirt.server.ModuleDeploymentWriter.validateResults(ModuleDeploymentWriter.java:543)
        at org.springframework.xd.dirt.server.JobDeploymentListener.deployJob(JobDeploymentListener.java:146)
        at org.springframework.xd.dirt.server.JobDeploymentListener.onChildAdded(JobDeploymentListener.java:113)
        at org.springframework.xd.dirt.server.JobDeploymentListener.childEvent(JobDeploymentListener.java:97)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:509)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:503)
        at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92)
        at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
        at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:83)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:500)
        at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35)
        at org.apache.curator.framework.recipes.cache.PathChildrenCache$10.run(PathChildrenCache.java:762)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)


text:
Q: WPF binding listview to Dictionary> I've got a problem, I have to take List<string> from database, create Dictionary<Dictionary<string, bool>> on it and fill listview with it.
Here is my code:
xaml:
    <ListView x:Name="PlanningDataGrid"
              Grid.Row="0"
              Width="{Binding Path=ActualWidth, ElementName=grid}"
              ItemsSource="{Binding EventTypesCombinerCollection}"
              VerticalAlignment="Stretch"
              HorizontalContentAlignment="Stretch"
              VerticalContentAlignment="Stretch">
    </ListView>

model:
public class MainViewModel_Combiner : BindableBase // модель по событиям работы скважины
{
    private Dictionary<string, Dictionary<string, bool>> _eventTypesCombinerCollection;

    /// <summary>
    /// Именованный двумерный массив совмещения мероприятий. Совмещение определяется как EventTypesCombinerCollection["type1"]["type2"]
    /// </summary>
    public Dictionary<string, Dictionary<string, bool>> EventTypesCombinerCollection
    {
        get { return _eventTypesCombinerCollection; }
        set
        {
            _eventTypesCombinerCollection = value;
            OnPropertyChanged("EventTypesCombinerCollection");
        }
    }
    public MainViewModel_Combiner()
    {
        EventTypesCombinerCollection = new Dictionary<string, Dictionary<string, bool>>();
        GenerateEventTypesCocllectionFrameFromDataBase();
    }

    /// <summary>
    /// Заполняет двумерный словать типов мероприятий (абстракция для получения квадратной таблицы с одинаковыми заголовками строк и столбцов)
    /// </summary>
    private void GenerateEventTypesCocllectionFrameFromDataBase()
    {
        var EventTypesList = GetEventTypesList();
        foreach (string eventTypeCombiner in EventTypesList)
        {
            Dictionary<string, bool> combiningItems = new Dictionary<string, bool>();
            foreach (string eventTypeCombining in EventTypesList)
            {
                combiningItems.Add(eventTypeCombining, false);
            }
            EventTypesCombinerCollection.Add(eventTypeCombiner, combiningItems);
        }
    }

    /// <summary>
    /// Собирает список типов мероприятий из БД
    /// </summary>
    /// <returns></returns>
    private List<string> GetEventTypesList()
    {
        using (var db = new IP_dbEntities())
        {
            return db.EVENTS_TYPE.Select(e => e.event_type.Trim()).ToList();
        }
    }
}

and xaml.cs file:
public partial class Combiner : Window
{
    public Combiner()
    {
        InitializeComponent();
        CreateDataGridColumns();
    }

    private void CreateDataGridColumns()
    {
        var gridView = new GridView();
        PlanningDataGrid.View = gridView;
        gridView.Columns.Add(new GridViewColumn() { Header = "Тип мероприятия", DisplayMemberBinding = new Binding("Key") }); // Создаем первый столбец
        var eventTypeList = GetEventTypesList();
        foreach (string eventType in eventTypeList)
        {
            var listViewColumn = new GridViewColumn
            {
                Header = eventType,
                DisplayMemberBinding = new Binding("Value[" + eventType + "]"),
                Width = 30,
                CellTemplate = GenerateCellTemplate(eventType),
            };
            gridView.Columns.Add(listViewColumn);
        }
    }

    private DataTemplate GenerateCellTemplate(string eventType)
    {
        var template = new DataTemplate();
        FrameworkElementFactory factory = new FrameworkElementFactory(typeof(CheckBox));
        factory.SetBinding(ToggleButton.IsCheckedProperty, new Binding("Value[" + eventType + "]"));
        template.VisualTree = factory;
        return template;
    }

    /// <summary>
    /// Собирает список типов мероприятий из БД
    /// </summary>
    /// <returns></returns>
    private List<string> GetEventTypesList()
    {
        using (var db = new IP_dbEntities())
        {
            return db.EVENTS_TYPE.Select(e => e.event_type.Trim()).ToList();
        }
    }
}

Have you know any way, how to fix this, or do smth new?

A: Thanks a lot to StepUp and Ilan for helping. I just need to delete this row is code behind:
DisplayMemberBinding = new Binding("Value[" + eventType + "]"),

so, there is a solution:
    public partial class Combiner : Window
{
    public Combiner()
    {
        InitializeComponent();
        CreateDataGridColumns();
    }

    private void CreateDataGridColumns()
    {
        var gridView = new GridView();
        PlanningDataGrid.View = gridView;
        gridView.Columns.Add(new GridViewColumn() { Header = "Тип мероприятия", DisplayMemberBinding = new Binding("Key") }); // Создаем первый столбец
        var eventTypeList = GetEventTypesList();
        foreach (string eventType in eventTypeList)
        {
            Binding binding = new Binding();
            var listViewColumn = new GridViewColumn
            {
                Header = eventType,
                Width = 30,
                CellTemplate = GenerateCellTemplate(eventType),
            };
            gridView.Columns.Add(listViewColumn);
        }
    }

    private DataTemplate GenerateCellTemplate(string eventType)
    {
        FrameworkElementFactory checkbox = new FrameworkElementFactory(typeof(CheckBox));
        checkbox.SetBinding(ToggleButton.IsCheckedProperty, new Binding("Value[" + eventType + "]") {Mode = BindingMode.TwoWay});
        return new DataTemplate() {VisualTree = checkbox};
    }

    /// <summary>
    /// Собирает список типов мероприятий из БД
    /// </summary>
    /// <returns></returns>
    private List<string> GetEventTypesList()
    {
        using (var db = new IP_dbEntities())
        {
            return db.EVENTS_TYPE.Select(e => e.event_type.Trim()).ToList();
        }
    }
}

A: Your DataTemplate looks good. Try to write:
factory.SetBinding(ToggleButton.IsCheckedProperty, new Binding(eventType));

The work example looks like the following code snippet:
 FrameworkElementFactory checkbox = new FrameworkElementFactory(typeof(CheckBox));
 checkbox.Name = "aCheckBox";
 checkbox.SetBinding(ToggleButton.IsCheckedProperty, new Binding("YourBoolProperty"));
 DataTemplate dataTemplate = new DataTemplate() { VisualTree = checkbox };

Update:
To get a value from Dictionary, you should use the following syntax:
Dictionary<int, string> dictionary = new Dictionary<int, string>();
string str = dictionary[1];

So your code should look like this:
factory.SetBinding(ToggleButton.IsCheckedProperty, new Binding(dictionary[1]));


text:
Q: Where in a virtualenv should I put a custom library? I have a virtualenv that serves a few separate projects. I'd like to write a utility library that each of these projects can use. It seems to make sense to stick that in the virtualenv. By all means shoot me down now but please give an alternative if you do.
Assuming I'm not completely crazy though, Where's the best place to stick my library?
My virtualenv sticks everything I install with pip in lib/pyton2.7/site-packages. I wonder if it would make more sense to follow suit or to hack in a separate home (further up the directory tree) so if things do ever clash, my work isn't overwritten by pip (et al).

A: If your project follows the standard packaging practices with setuptools, then all you have to do is run python setup.py develop inside the virtualenvs that you want the library to be used for.  A .egg-link file will be created pointing to your package from which your other libraries will use much like any other packages, with the added benefit that your latest changes will be available to all packages at the same time (if that's your intention).  If not, then either you could call python setup.py install or use multiple versions at different locations on the file system.
To get yourself started, take a look at Getting Started With setuptools and setup.py (you can skip the part on registering your package on pypi if this is your private work).
Another relevant stackoverflow thread: setup.py examples?  The Hitchhiker's Guide to Packaging can also be quite useful.


text:
Q: varbinary(max) capture and store OLE image I support an application that has a SQL Server backend and an Access front end.  A signature image is stored in a varbinary(max) column in a table in SQL Server, the Users table.  The value in this field is displayed in various Access reports.
Periodically, a new User is added to the system.  I have not succeeded in finding a way to perform this task programmatically.  No matter how I load the image into the field in SQL, it will not display in the Access reports.  I have to perform the following steps to get the image loaded and displaying correctly:
1.  Open Doc.
2.  Copy signature to clipboard.
3.  Open Word.
4.  Paste signature into Word.
5.  Copy signature from Word to clipboard.
6.  Open Access.  Open linked Users table.
7.  Paste into OLE signature field.
8.  Update record.
I suspect the magic is in the copy of the image from Word to the clipboard, that it somehow creates an OLE object of some kind that is copied to the clipboard, then is able to be pasted into the varbinary(max) field via Access.
Can anyone shed any light on how one can programmatically (C#, Access, or?) load an image into a varbinary(max) field that Access can display as an image?  I want to create an application that the end user can use to upload the signature image.

A: How do I display an image from Sql Server with Microsoft Access?
When an OLE field is bound to a 'Bound OLE Control' in a form, and a file is pasted into the control, the file is stored in a binary access-specific OLE wrapper.
The control also expects the wrapper when displaying files/images, but if the file was saved into the table with code rather than pasting, the wrapper is not there.
Using unbound controls bypasses the issue as these controls don't require the OLE wrapper.


text:
Q: How to extract only Min Max and Average of thread groups I have a scenario, where I have an api where 50, 100 and 500 users are hitting the api at the ramp up period of 1 second as in -
50 users - 1 rampup
   + Duration assertion - 100
100 users - rampup
   + Duration assertion - 200
500 users - 1 rampup
   + duration assertion - 300

Now I run the command in Jenkins
path/jMeter/bin/jmeter -n -R {remoteIP} -t test.jmx -l path/${BUILD_NUMBER}_result.jtl -e -o path/${BUILD_NUMBER}_report/

Now in Jmeter how to calculate min, max and average of 50, 100 and 500 users each and save in a file say resultminmaxavg.csv so that I can pick the file and publish through mail.
Like below -
Users     Min    Max   Avg
50        378    455
100       333    655
500       322    344

How to calculate the data in JMeter? Attaching image:

A: One way to achieve this is aby adding an SummaryReport listener which you need to configure as following:

*

*Define a rootPath in the testPlan variables;

*Define 3 variables: 50maxThreads, 100maxThreads, and 500maxThreads

*In each ThreadGroup, define each value of the 3 variables above as number of threads,

In each SummaryReport listener of the X users thread grup, the filename is to be configured as following:
${rootPath}/${50maxThreads}_test_outcome.csv

Good luck, I have not tried this, but it should work


text:
Q: Microsoft App Submission Dashboard page sets AdUnitId to "none"? I have submitted a application for Windows Phone 8 / 8.1. I have created a pubCenter account from Microsoft Pubcenter and generated the ApplcationId and adUnitId too.
This two fields I have set in the mainPage.xaml so that it display advts.
Now I have submitted the app in the store and it gets published too. But When I visit the dashboard page you can see that pubCenter Application Id and Ad Units is set to none.
Is there any specifc task I forget to do? Because when I check in PubCenter it shows everything correctly, but I felt that there is some thing went wrong. Can anybody please help me, I am confused of what to do.

A: Ok, So finally I resolved this issue and I thought to post it here so that others will get benefit too.
I have noticed that its a one way process, creating app id in PhoneSubmission page informs Pubcenter, but creating appId in Pubcenter may or may not informs Microsoft's In-App purchase, even if you give the correct app alias name, so its better to follow this technique.
In Windows Phone app submission before you submit the apps, you create the AppUnitId and applicationId in this stage.
I have added two self- describing images of how to do this in step by step ways.
Step 1:

Step 2:

After clicking on Generate ad unit, two values will be auto generated, Application id  and AdUnit ID, copy this two values.
Remember that these information ( App alias name etc) will be auto populated to Microsoft pub center, you can visit and check.
Those who started developing their apps thinking that it will display advt they can follow this steps and after that application Id and app unit id is generated they can put those in the xaml, or in code behind and ad will start displaying.
For more helps how to integrate ad in the apps Click here


text:
Q: Intermittent slowness Spring Webflux application deployed on tomcat 8.5.5 We are using tomcat 8.5.5 to deploy the spring webflux application,
When making Get Rest call to service then it makes select on MongoDB and returns Flux.
Frequently it's giving a slow response sometimes return in 1-2 seconds, but sometimes it took around 1 minute.
I am not getting any errors in the logs.


text:
Q: What's the best way of making clickable tiles in HTML/JS? I want to make clickable tiles with people's names and pictures, for them to choose who they are.  I would like all the tiles to redirect to the same page, just with different query params.  Would it be best to just make div's that are hyperlinks? Or I was thinking maybe I should make it a form, where the action is the page to redirect to, with method=GET, and clicking any of the tiles would submit the form somehow with that tile as the form value?
Any suggestions for best way to do this? Thanks!

A: This doesn't require any javascript unless that's how you're rendering the HTML. You just need need an anchor tag () with your img and text inside.
s can't be hyperlinks, and technically shouldn't be wrapped with anchor tags. (With a little CSS you can make s behave like divs if that's what your design needs.) You COULD use javascript to attach a click event to a div, but an anchor is cleaner and easier.

 Bozo


text:
Q: Return range (real) dimensions following DELETE action (clear contents only) in Google Sheets I'm writing a script in Google Sheets that will register the email and timestamp of the latest modification made on a pre-determined column (only this column will be made available for editing). For that I'm using onEdit() trigger. The script will get the active range, get rowStart and rowEnd and write in the adjacent cells email and timestamp. I've already handled input data. However, I'm struggling to manipulate the "DELETE" action in a range with multiple rows, since e.range returns only one row following a "clear contents" method.
I want my script to be able to identify how many cells have been selected before a DELETE press (clear contents) and to write email and timestamp on adjacent cells just like it does for entered values (copy / paste operation).
An example:
There are 4 rows (say C2, C3, C4 and C5) with a "YES" stamp in column C, email of current user in column D and timestamp in column E. I select the last 3 (C3, C4 and C5) and press DELETE. With my script, only cells D3 and E3 are filled with email and date/time since e.range returns range as if it contained only one cell as opposed to 3.
This is the script
function onEdit(e) {
    // Prevent changes in columns different than the used one.
    if (e.range.getColumn() != 3) return;

    for (var i = e.range.rowStart; i <= e.range.rowEnd ; i++) {
      e.source.getActiveSheet().getRange(i, 4).setValue(e.user.getEmail());

      e.source.getActiveSheet().getRange(i, 5).setValue(new Date());
    }
}

Any ideas?


text:
Q: D3.js Collapsible tree: Adding a label for each level I am working on a project which needs a label for each of the levels of the collapsible tree in D3.js(https://bl.ocks.org/mbostock/4339083). I am facing tough time in adding the same. The label I require is added in the attached screenshot. The label should populate for each level as soon as click on each level and disappear as it the tree rolls back. Could anyone help me out with this.

A: Modify the update method to track the levels from the node items. Maintain a unique sorted hash of all the depth values from the node items used to plot the chart. Once you have the sorted depthHash array, plot the text on the top of your chart. Below is a fiddle i have modified for your reference.
    http://jsfiddle.net/deepakpster/vomxqxov/3/
var margin = {top: 20, right: 120, bottom: 20, left: 120},
    width = 960 - margin.right - margin.left,
    height = 800 - margin.top - margin.bottom;

var i = 0,
    duration = 750,
    root;

var tree = d3.layout.tree()
    .size([height, width]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

flare = "http://rawgit.com/mbostock/1093025/raw/a05a94858375bd0ae023f6950a2b13fac5127637/flare.json"
d3.json(flare, function(error, flare) {
  root = flare;
  root.x0 = height / 2;
  root.y0 = 0;

  function collapse(d) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

  root.children.forEach(collapse);
  update(root);
});

d3.select(self.frameElement).style("height", "800px");

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
      links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) { d.y = d.depth * 180; });
    // Showing the labels for the level of depths.
    // Using underscore.js to do the pluck, uniq.
  var depthHash = _.uniq(_.pluck(nodes, "depth")).sort();
  svg.selectAll("g.levels-svg").remove();
  var levelSVG = svg.append("g").attr("class", "levels-svg");
    var levels =  levelSVG.selectAll("g.level");
  levels.data(depthHash)
    .enter().append("g")
    .attr("class", "level")
    .attr("transform", function(d) { return "translate(" + d*180 + "," + 10 + ")"; })
    .append("text")
    .text(function(d){
      return "level-" + d;
    });

  // Update the nodes…
  var node = svg.selectAll("g.node")
      .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .on("click", click);

  /*
  nodeEnter.append("circle")
      .attr("r", 1e-6)
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
  */
  var ww = 30, hh = 20
  nodeEnter.append("rect")
    .attr("height", 1e-6)
    .attr("width", 1e-6)
    .attr("x", -ww/2)
    .attr("y", -hh/2)
    .attr("rx", 3)
    .attr("ry", 3)
    .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeEnter.append("text")
      .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
      .text(function(d) { return d.name; })
      .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

  nodeUpdate.select("rect")
    .attr("width", ww)
    .attr("height", hh)
    .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeUpdate.select("circle")
      .attr("r", 4.5)
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeUpdate.select("text")
      .attr("dx", -10)
      .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .remove();

  nodeExit.select("circle")
      .attr("r", 1e-6);

  nodeExit.select("text")
      .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
      .data(links, function(d) { return d.target.id; });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      });

  // Transition links to their new position.
  link.transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      })
      .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
}


text:
Q: Limiting git log to commits during a certain branch The command git log origin/<branchname> does show the commits in the certain branch, but it also shows the commits that were made to the parent branch before the <branchname> was even created.
How to limit the output to contain only those entries that were commited after the branch was created?

A: Try using git merge-base:
git log $(git merge-base parent-branch branchname)..branchname
# shorter
git log parent-branch..branchname
# which stands for
git log branchname --not parent-branch

That would list all commits after the merge point between the two branches.
This syntax assumes a bash session.
See:

*

*"What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?"

*"What are the differences between double-dot ".." and triple-dot "..." in git diff commit ranges?" (which also mentions git log)

This is linked to git rev-list, where git rev-list foo..bar shows everything on branch bar that isn't also on branch foo.

A special notation "<commit1>..<commit2>" can be used as a short-hand for "^'<commit1>' <commit2>": reachable from commit2, but not from commit1.

See git revisions for more.

Note: Git has no notion of "parent" branch, only a graph of commits: see "How to find the nearest parent of a Git branch?"

A: This also works:
git log branch1..branch2


text:
Q: Sorting DataGridView based on cell Tags I have implemented sorting based on integer cell Tags this way using the SortCompare() event:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if (e.Column.HeaderText == "From")
    {
        e.SortResult = Convert.ToInt32(dataGridView1.Rows[e.RowIndex1].Cells[e.Column.Index].Tag).CompareTo(Convert.ToInt32(dataGridView1.Rows[e.RowIndex2].Cells[e.Column.Index].Tag));
        e.Handled = true;
    }
}

I wonder if there is a more efficient/compact/better way to do that?

A: Looks like there isn't.
Just simplifying how cells are referenced:
e.SortResult = Convert.ToInt32(dataGridView1[e.Column.Index,e.RowIndex1].Tag).CompareTo(Convert.ToInt32(dataGridView1[e.Column.Index,e.RowIndex2].Tag));


text:
Q: select the row between two dates in another table i have table A which has three column name,app,date
and table b which has three column name,start,end
how i could write a query  that return only the name which has the date  came between start an end in the table b ?

A: select name from A inner join B on (A.date between B.start and B.end)


text:
Q: Is it possible to bind all the struct members of an enum variant to a single variable? Let say I define and instantiate an enum as follows:
enum MyEnum {
    EmptyVariant,
    TupleVariant(u8),
    StructVariant {
        key: u8,
        value: char,
    }
}

let instance = MyEnum::StructVariant{key: 8, value: 'a'};

Is it possible to match against this variant without destructuring? For example, instead of doing:
if let MyEnum::StructVariant{key, value} = instance {
    eprintln!("key, value = {}, {}", key, value);
}

I would rather write something like:
if let MyEnum::StructVariant{VARIANT_MEMBERS} = instance {
    eprintln!("key, value = {}, {}", VARIANT_MEMBERS.key, VARIANT_MEMBERS.value);
}

In this example, writing out the members of the struct variant is benign, but in the case where the variant has many members it makes the code difficult to read.

A: I don't think it is possible as of today.
I did see the following pattern, which in practice achieves what you asked for just with an extra intermediary type:
Instead place all the desired members of the StructVariant in an actual struct type, and have your enum use that struct as the only field of the StructVariant.
struct MyVariant {
    key: u8,
    value: char
}

enum MyEnum {
    EmptyVariant,
    TupleVariant(u8),
    StructVariant(MyVariant)
}

if let MyEnum::StructVariant(x) = instance {
    eprintln!("key, value = {}, {}", x.key, x.value);
}

This also proves handy when you want to pass the members of StructVariant around, to other functions or types.


text:
Q: Use Spring annotations to automatically apply Hibernate Interceptor? In my service class I need the hibernate session available. I currently do this in the beans.xml:
<bean id = "userDao" class="org.springframework.aop.framework.ProxyFactoryBean">
 <property name="target">
   <ref bean="userDaoTarget" />
 </property>

 <property name="proxyInterfaces">
   <value>com.app.dao.UserDao</value>
 </property>

 <property name="interceptorNames">
   <list>
     <value>hibernateInterceptor</value>
   </list>
 </property>

 <qualifier value="proxy" />
</bean>

...

<bean id="hibernateInterceptor"
   class="org.springframework.orm.hibernate3.HibernateInterceptor">
 <property name="sessionFactory">
   <ref bean="sessionFactory" />
 </property>
<bean>

(copied by hand, may be some typos..)
I'm moving to using annotations over XML, I was wondering if there was a way to use them to configure the proxy as I have above including the hibernate interceptor? If not - is there a way that I can reduce the amount of XML (with about 7 DAOs it makes it very cluttered)

A: Ok, Let's go. You said

I am moving to using annotations over XML

Enable an aspect as follows
package br.com.ar.aop;

@Aspect
public class HibernateInterceptorAdvice {

     @Autowired
     private HibernateInterceptor hibernateInterceptor;

     /**
       * I suppose your DAO's live in com.app.dao package
       */
     @Around("execution(* com.app.dao.*(..))")
     public Object interceptCall(ProceedingJoinPoint joinPoint) throws Throwable {
         ProxyFactory proxyFactory = new ProxyFactory(joinPoint.getTarget());
         proxyFactory.addAdvice(hibernateInterceptor);

         Class [] classArray = new Class[joinPoint.getArgs().length];
         for (int i = 0; i < classArray.length; i++)
             classArray[i] = joinPoint.getArgs()[i].getClass();

         return
             proxyFactory
                 .getProxy()
                 .getClass()
                 .getDeclaredMethod(joinPoint.getSignature().getName(), classArray)
                 .invoke(proxyFactory.getProxy(), joinPoint.getArgs());
     }

}

But keep in mind It just works if your DAO's implements some interface (For instance, UserDAOImpl implements UserDAO). Spring AOP uses JDK dynamic proxy in this case. If you does not have any interface, you can rely on your IDE To refactor your code by using Extract interface
Declare your xml as follows (Be aware i am using Spring 2.5 xsd schema)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-2.5.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <!--SessionFactory settings goes here-->
    <bean class="org.springframework.orm.hibernate3.HibernateInterceptor">
        <property name="sessionFactory" ref="sessionFactory"/>
    <bean>
    <!--To enable AspectJ AOP-->
    <aop:aspectj-autoproxy/>
    <!--Your advice-->
    <bean class="br.com.ar.aop.HibernateInterceptorAdvice"/>
    <!--Looks for any annotated Spring bean in com.app.dao package-->
    <context:component-scan base-package="com.app.dao"/>
    <!--Enables @Autowired annotation-->
    <context:annotation-config/>
</beans>

Do not forget To put in the classpath besides Spring libraries
<SPRING_HOME>/lib/asm
<SPRING_HOME>/lib/aopalliance
<SPRING_HOME>/lib/aspectj

A: Have a look at the @Autowired annotation.


text:
Q: How to view an MSSQL layer/table with mixed geometry types using QGIS (2.18)? I have a connection to data in an MSSQL database. The key (spatial) table records points, polygons, and lines all within the one table. Is there a more graceful way to handle this data on QGIS - which is more advanced than setting up three separate filtered views on the database, one for lines, one for polygons and one for points?
....
The following are details which may or may not be relevant:
- QGIS 2.18
- MSSQL / SQL Server 2014 (12)
- there are no multi-polygons/multi-lines/multi-points
- The database administrator has successfully set me up with filtered views (I don't have direct database access, but close communication)
- I'd actually like to be able to filter the raw data myself using tools at the QGIS end of this connection.
- QGIS seems to decide on one of the three geometry types (I'm guessing based on something like the first entry in the table) and I can't find any way to change this, so from the raw data I can render only lines.
- I tried some basic edits with a text file to the QGIS project to see if I could force QGIS to recognise the layer as being points/polygons but failed.
I note that there are a selection of somewhat similar questions already asked, but these are I think either very old (referring to old versions of QGIS) or unanswered.