Q: C# - Replacing an item in the backpack I'm trying to create a simple backpack-program. It is an assignment for school and I'm almost finished except I cannot manage to replace the item in my backpack with a new one.
My guess for why it might not be working is that I cannot replace item because it is in the global scope but I have no idea how to fix it. Here is the code:
static void Main(string[] args)
    {
        bool isRunning = true;
        while (isRunning)
        {
            Console.WriteLine("\n\tWelcome to the backpack!");
            Console.WriteLine("\t[1]Add an item");
            Console.WriteLine("\t[2]Show contents");
            Console.WriteLine("\t[3]Clear contents");
            Console.WriteLine("\t[4]Exit");
            Console.Write("\tChoose: ");

            int menyVal = Convert.ToInt32(Console.ReadLine());

            string item;
            item = "Empty space";

            switch (menyVal)
            {
                case 1:
                    Console.WriteLine("\n\tContents of backpack:");
                    Console.WriteLine("\n\t" + item);
                    Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
                    item = item.Replace(item, Console.ReadLine());
                    Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
                    break;
                case 2:
                    Console.WriteLine("\n\tContents of backpack:");
                    Console.WriteLine("\n\t" + item);
                    Console.WriteLine("\n\tPress any key...");
                    Console.ReadKey();
                    break;
                case 3:
                    item = "Tom plats";
                    Console.WriteLine("\n\tYou have emptied the backpack!");
                    break;
                case 4:
                    isRunning = false;
                    break;
                default:
                    Console.WriteLine("Incorrect input!");
                    break;
            }
        }
    }

Any ideas on how to fix this? Tips are much appreciated!
Thanks!

A: Move the assignment of
string item;
item = "Empty space";

Before the while loop.
Right now, every time you loop you overwrite the item value.
Here's how the whole code would look after the change:
static void Main(string[] args)
    {
        bool isRunning = true;
        string item = "Empty space";

        while (isRunning)
        {
            Console.WriteLine("\n\tWelcome to the backpack!");
            Console.WriteLine("\t[1]Add an item");
            Console.WriteLine("\t[2]Show contents");
            Console.WriteLine("\t[3]Clear contents");
            Console.WriteLine("\t[4]Exit");
            Console.Write("\tChoose: ");

            int menyVal = Convert.ToInt32(Console.ReadLine());

            switch (menyVal)
            {
                case 1:
                    Console.WriteLine("\n\tContents of backpack:");
                    Console.WriteLine("\n\t" + item);
                    Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
                    item = Console.ReadLine());
                    Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
                    break;
                case 2:
                    Console.WriteLine("\n\tContents of backpack:");
                    Console.WriteLine("\n\t" + item);
                    Console.WriteLine("\n\tPress any key...");
                    Console.ReadKey();
                    break;
                case 3:
                    item = "Tom plats";
                    Console.WriteLine("\n\tYou have emptied the backpack!");
                    break;
                case 4:
                    isRunning = false;
                    break;
                default:
                    Console.WriteLine("Incorrect input!");
                    break;
            }
        }
    }


Q: how to make firewall changes permanent via firewall-cmd? I am trying to open some ports in CentOS 7.
I am able to open a port with the following command:
firewall-cmd --direct --add-rule ipv4 filter IN_public_allow 0 -m tcp -p tcp --dport 7199 -j ACCEPT

By inspecting via iptables -L -n, I get the confirmation that the setting was successful:
Chain IN_public_allow (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:7199

Unfortunately, I cannot make the changes permanent. Even by using the --permanent option like this:
firewall-cmd --direct --permanent --add-rule ipv4 filter IN_public_allow 0 -m tcp -p tcp --dport 7199 -j ACCEPT

Any idea on how to fix this? Why is the --permanent option not working correctly?

A: --direct commands cannot be made permanent. Use equivalent zone command:
   sudo firewall-cmd --zone=public --add-port=7199/tcp --permanent
   sudo firewall-cmd --reload

and to check the result:
   sudo firewall-cmd --zone=public --list-all

A: You can also do something like this:

sudo firewall-cmd --zone=public --add-port=7198/tcp
sudo firewall-cmd --zone=public --add-port=7199/tcp
sudo firewall-cmd --runtime-to-permanent

... which will make the current firewall settings perman

A: there are a lot of ways.. but i am introducing today a method not mentioned here :
# firstly run it without --permanent
sudo firewall-cmd --zone=public --add-port=7199/tcp
# then run it again with adding --permanent
sudo firewall-cmd --zone=public --add-port=7199/tcp --permanent

it must work


Q: Does people train object detection methods with early stopping and what were their settings? I'm working on some stuff related to object detection methods (YOLOv3, Faster-RCNN, RetinaNet, ... ) and I need to train on VOC2007 and VOC2012 (using pretrained models of course). However when I read the relevant papers I do not see people describe if they trained using early stopping or just fixed number of iterations. And if they used early stopping, how many steps were set before stopping ? Because when I tried 100 steps before stopping, it got really poor results . Please help me, thank you very much.

A: I found an implementation of the PASCAL VOC2012 dataset trained for semantic segmentation that uses the following early stopping parameters:
earlyStopping = EarlyStopping(
    monitor='val_loss', patience=30, verbose=2, mode='auto')


Q: See if Input Has Spaces with jQuery I'm trying to write a function that reads a inputs value, and determines if a space has been used in it's creation. I'm not trying to trim anything -- just see if it would have needed the ability to trim.
I'm not even sure where to begin on this, so I don't have any code to look at. Please help if you can!
I was trying this solution but it doesn't seem to work (I don't think I'm using .has() correctly)
if ($('#id').val().has(" ")) {
            alert('has spaces')
        }

A: Use val and indexOf :
var hasSpace = $('#myInputId').val().indexOf(' ')>=0;

If you want to test other types of "spaces" (for example a tabulation), you might use a regex :
var hasSpace = /\s/g.test($('#myInputId').val());

Demonstration

A: Use contains for include space:
var value = $('#myInputId').val();
if(value.contains(' ')){
   console.log("has space");
}

Or you can find with these ascII code &nbsp and \xA0
if(value.contains(' ')){
   console.log("has space");
}

A: use val and space:
$('#name').val().length <= 0 || $('#name').val(" ")


Q: SQL Rounding Query I have been doing alot of research attempting to find an answer to my question.
I am trying to work out which syntax is needed to round when the figure is less than one.
For example
             SELECT 17/26
When running this in SQL, it bring up zero, however i am attempting to get it to return me an answer of 0.65.
I have tried using ROUND, CAST AS Numeric,Decimal and also Money.
So far.... no luck
Any help would be appreciated.

A: try this
SELECT round(convert(float,17)/26,2)

A: For whatever it's worth, when I'm doing something like this with an actual hard-coded value I just add a decimal place to one of the elements. A CAST() is better for a database field, but if you're typing something in just use a decimal ...
 SELECT 17/26, 17/26.0, 17.0/26

A: try force engine to manage floats (multiplying with float number '1.0') like this...
SELECT (1.0*17/26) as x;

also to round... you can write it like
SELECT round((1.0*17/26),2) as x;

(tried on PostgreSQL and worked)


Q: How to fix a unexisting Reactive Forms error I'm building a form but, for whatever reason, the compiler is complaining about it.
Can anybody spot something wrong here?
This is what I get:

ERROR Error: No value accessor for form control with name: 'email'
ERROR Error: No value accessor for form control with name: 'password'

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EmailLoginComponent } from './email/email-login.page';
import { LoginComponent } from './login.page';
import { RouterModule } from '@angular/router';
import { RegisterComponent } from './registration/register.page';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [
        EmailLoginComponent,
        LoginComponent,
        RegisterComponent
    ],
    imports: [
        CommonModule,
        RouterModule.forChild([
            { path: '', component: LoginComponent },
            { path: 'emailLogin' , component: EmailLoginComponent },
            { path: 'register' , component: RegisterComponent }
        ]),
        ReactiveFormsModule
    ],
    exports: [],
    providers: [],
})
export class LoginModule {}

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
    selector: 'app-register',
    templateUrl: './register.page.html',
    styleUrls: ['./register.page.scss']
})
export class RegisterComponent implements OnInit {
    platform: string;
    registerForm: FormGroup;

    constructor() { }

    ngOnInit() {
        this.registerForm = new FormGroup({
            email: new FormControl(''),
            password: new FormControl('')
        });
    }
}

<form [formGroup]="registerForm" (ngSubmit)="onRegisterUser()">
    <ion-item lines="full" color="secondary">
        <ion-input placeholder="Email" type="email" formControlName="email"></ion-input>
    </ion-item>
    <ion-item lines="full" color="secondary">
        <ion-input placeholder="Password" type="password" formControlName="password"></ion-input>
    </ion-item>
</form>

A: I copied your code into an ionic stackblitz project and was unable to reproduce your issue.
https://stackblitz.com/edit/ionic-ojdypw
Maybe there is something there that can help you.


Q: Copied data paste into String function Can anyone tell me how to store copied data into String in selenium?
example:
driver.findElement(By.xpath("//*[@id="x")).sendKeys(Keys.CONTROL, "a"));
driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "c"));
driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "v"));

I need put the copied data into String
Something like this
String text = driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "v"));

A: It seems you want to send ctrl + c keys, which will copy some data in clipboard.. want to store that data in String variable..right?
You have to use Clipboard class to do so..See implementation below...
package resources;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class One {

    @Test
    public void getClipboardContents() {
        String result = "";

        System.setProperty("webdriver.chrome.driver", "C://WebDrivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com");
        String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
        driver.findElement(By.linkText("Images")).sendKeys(copy);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        Transferable contents = clipboard.getContents(null);
        boolean hasTransferableText = (contents != null)
                && contents.isDataFlavorSupported(DataFlavor.stringFlavor);
        if (hasTransferableText) {
            try {
                result = (String) contents.getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException | IOException ex) {
                System.out.println(ex);
                ex.printStackTrace();
            }
        }
        System.out.println(result);
    }
}

@Starlord ..modify locators as per your need.

A: @Gaurav Thanks for the code.. I have modified some part of the code.. now I am getting what i want exactly
public void getClipboardContents()
throws UnsupportedFlavorException, IOException {
String result = "google.com";
System.setProperty("webdriver.chrome.driver", "E:\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys("google.com");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(Keys.CONTROL+"a");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(copy);

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
String x = (String) contents.getTransferData(DataFlavor.stringFlavor);
System.out.println(x);
int a= result.length();
int b = x.length();
System.out.println(a);
System.out.println(b);
if(a<=b)
{
System.out.println("Matched Character length")
}else
{
 System.out.println("Issue In Character length");
}
 }

    }


Q: print value on console Looking for solution round this .
i have a script
a.bsh

#!/bin/bash
a=5
echo $a

this prints 5 when ever executed .

./a.bsh
5

i need to either look to update this script or use another away to get value 5 when i do on console

echo $a

i tried updating .bashrc with
alias a=5

but it didnt work . Also we can use set in this somehow ?
please advice

A: If you want to echo the value which you provide via command line you can use something like:
./a.bsh 5

and the script itself:
#! /bin/sh -
printf '%s\n' "$1"

Also remember:

*

*parameter expansions must be quoted in sh / bash

*no need for bash for such a simple script, using sh makes it more portable (to systems that don't have bash or don't have it in /bin) and likely more efficient.

*echo can't be used to output arbitrary data.


Q: Extract all function from source file without evaluating it For my package I am looking for a method to identify all function assignments in a user supplied R script, without executing it.
So let's assume the following example script (ex.R):
ex.R
## user supplied script
a <- function(x) 1
b1 = b2 <- function() {
   y <- 1
   2 -> j
   j
}
d <<- function(x) {
   k <- function(l) 1
   k(x)
}
(function(x) 2) -> e
(function() {
   y <- 1
   2 -> j
   j
}) -> f1 -> f2
(function() 1)()
g <- 4
5 -> h
i <- lapply(1:3, FUN = function(x) x + 1)
assign('j', function() 1)
k1 <- (function() {1}) -> k2

The function should return c("a", "b1", "b2", "d", "e", "f1", "f2", "j", "k1", "k2")
I came up with the following solution:
library(dplyr)
code <- parse("ex.R")

get_identifier <- function(nm) {
   if (is.symbol(nm)) {
      deparse(nm)
   } else if (is.character(nm)) {
      nm
   } else {
      stop(paste0("unknown type", typeof(nm), "for `nm`"))
   }
}

get_fns <- function(expr) {
   assignment_ops <- c("<-", "=", "assign", "<<-")
   is_assign <- deparse(expr[[1L]]) %in% assignment_ops
   is_call <- is_assign && is.call(expr[[3L]])
   if (is_call) {
      next_call <- deparse(expr[[3L]][[1L]])
      if (next_call == "function") {
         get_identifier(expr[[2L]])
      } else if (next_call %in% c(assignment_ops, "(")) {
         c(get_identifier(expr[[2L]]), Recall(expr[[3L]]))
      } else {
         NULL
      }
   } else {
      NULL
   }
}

unlist(lapply(code, get_fns))
# [1] "a"  "b1" "b2" "d"  "e"  "f2" "f1" "j"  "k1" "k2"

Which is correct for at least this use case.
But adding just two other nasty edge cases will break the code:
l1 <- (1 + (l2 <- function(x) 2 * x)(3))
(m <- function(x) x)

should return c("l2", "m"), but it does not. My recursion is somewhere at fault, but I cannot spot the problem. How would I fix the code?

Update
The comment showed that I should explain a bit what I want to achieve eventually:

*

*I want to develop a package which takes an "arbitrary" R script (script.R say) and transforms this script into a script which has a Command Line Interface (script_ammended.R say), that is which can be eventually called via Rscript ammended_script.R [ARGS].

*The idea is that user script contains some functions with some special comments and via those the CLI is auto-generated.

*I know that there a couple of libraries, which enable a decent command line parsing already, but all of them require of course that the user spends some time on CLI programming.

*My use case is somewhat different. I want a standalone script, which simply uses some functions to do what it is meant to do. If the user later wants to create a CL tool out of it, it should be as easy as pressing a button (assuming that the user add some minimal comments to the original functions).

*The auto generated script will always add extra code, to log, to make sure that needed libraries are installed and so on.

A contrived example may look like this:
script.R
greet <- function(msg, from = "me") {
   #! short: -g
   #! params: [., -f]
   #! description: greeting <msg> from user <me> is shown
   print(paste0("Message from <", from, ">: ", msg))
}

bye <- function() {
   #! short: -b
   greet("Good Bye", "system")
}

greet("Test")

This would be a typical user script, which can be quite conveniently used interactively. Now, my package should take this script and turn it into the following script:
script_amended.R
library(optigrab)

greet <- function(msg, from = "me") {
   print(paste0("Message from <", from, ">: ", msg))
}

bye <- function() {
   greet("Good Bye", "system")
}

msg <- opt_get("g", default = NA_character_,
               description = "greeting <msg> from user <me> is shown")
from <- opt_get("f", default = "me")
bye_flag <- opt_get("b", default = FALSE)

if (!is.na(msg)) {
   greet(msg, from)
   quit(status = 0)
} else if (bye_flag) {
   bye()
   quit(status = 0)
}

A: Credits to Allan Cameron's comments to run the script, below a function to use exactly that approach.
functions_from_source <- function(source) {

  myEnv <- new.env()

  source(source, local = myEnv)

  objects <- ls(envir = myEnv)

  funs <- sapply(objects, \(x){
    is.function(eval(parse(text = x), envir = myEnv))
  })

  objects[funs]

  rm(envir = myEnv)

}

functions_from_source("ex.R")

# [1] "a"  "b1" "b2" "e"  "f1" "f2" "j"  "k1" "k2" "m"

ex.R including m and l1 (note R does not interpret l2 as a function but as a value)
a <- function(x) 1
b1 = b2 <- function() {
  y <- 1
  2 -> j
  j
}
d <<- function(x) {
  k <- function(l) 1
  k(x)
}
(function(x) 2) -> e
(function() {
  y <- 1
  2 -> j
  j
}) -> f1 -> f2
(function() 1)()
g <- 4
5 -> h
i <- lapply(1:3, FUN = function(x) x + 1)
assign('j', function() 1)
k1 <- (function() {1}) -> k2

l1 <- (1 + (l2 <- (function(x) 2 * x)(3)))
(m <- function(x) x)

A: Tried reducing the function: Though might have some edge cases. Not sure.
get_fun <- function(x){
  dp <- deparse1(x[[1]])
  if( dp %in% c('<-', '=', '<<-'))  c(x[[2]], get_fun(x[[3]]))
  else if(dp == c('(')) get_fun(x[[2]])
  else if(dp == 'assign') as.list(x[-1])
  else if(dp == 'function') x
  else if(any(i<-grepl("<<?-",x))) c(NA, get_fun(x[[which(i)]]))
}

get_name <- function(y){
  x <- head(get_fun(y), -1)
  if (length(x) > 1 & any(i <- is.na(x))) x <- tail(x,-max(which(i)))
  as.character(x)
}

get_fns <- function(file){
  unlist(lapply(parse(file), get_name))
}

get_fns('ex.R')
 [1] "a"       "b1"      "b2"      "d"       "e"       "f2"
 [7] "f1"      "j"       "k1"      "k2"      "l2"      "m"

The usage of get_fun is quite simple. eg:
suppose we have:
 z <- alist(   l1 <- (1 + (l2 <- function(x) 2 * x)(3)),
               (s = (m <- function(x) x))->k,
              d <- (((function(x)x+2))),
              i <- lapply(1:3, FUN = function(x) x + 1),
              j <- lapply(1:3, FUN <- function(x) x + 1))

Notice that we have l2, m, d, FUN. The FUN is from j and not i since we used <- meaning we assigned the function and not merely a parameter:
From l1 we get:
get_fun(z[[1]])
[[1]]
l1

[[2]]
[1] NA

[[3]]
[1] NA

[[4]]
l2

[[5]]
function(x) 2 * x

We only pick everything after all the NAs:
get_fun(z[[2]])
[[1]]
k

[[2]]
s

[[3]]
m

[[4]]
function(x) x

get_fun(z[[3]])
[[1]]
d

[[2]]
function(x) x + 2

get_fun(z[[4]])
[[1]]
i

For z[[4]] although there is a name, there is no function associated with the name. Thus not a valid function
get_fun(z[[5]])
[[1]]
j

[[2]]
[1] NA

[[3]]
FUN

[[4]]
function(x) x + 1

A: After a good sleep, I could reduce the (recursive) problem to 5 simple cases:

*

*If the expression under investigation (expr) is not a call, we stop and return NULL.

*If we hit a bracket, simply recurse into the expression and keep the current list of potential identifiers.

*If we hit a function, we simply return the vector of potential identifiers collected so far.

*If we hit an assignment operator, add the identifier to the list of potential identifiers and recurse into the RHS of the assignment.

*In any other case, we loop through all elements of the call, but reset the list of potential identifiers to NULL.

extract_function <- function(expr, identifiers = NULL) {
   .OP <- 1L
   .LHS <- 2L
   .RHS <- 3L
   .ASGNM <- c("<-", "<<-", "=", "assign")
   if (is.call(expr)) {
      op <- deparse(expr[[.OP]])
      if (op == "(") {
         ## bracket case: simply recurse into the call and keep identifiers
         res <- Recall(expr[[-.OP]], identifiers)
      } else if (op == "function") {
         ## function case: we can stop and return stored identifiers
         res <- identifiers
      } else if (op %in% .ASGNM) {
         ## assignment case: add LHS to potential list of identifiers
         res <- Recall(expr[[.RHS]], c(as.character(expr[[.LHS]]), identifiers))
      } else {
         ## else case: drop identifiers and recurse into function
         res <- lapply(expr, extract_function, identifiers = NULL) |>
            unlist()
      }
   } else {
      res <- NULL
   }
   res
}

unlist(lapply(parse("ex.r"), extract_function))
# [1] "a"  "b2" "b1" "d"  "e"  "f1" "f2" "j"  "k2" "k1" "l2" "m"


Q: having trouble compiling old VC++ 6 c++ code I am trying to compile MSVC 6 C++ code using MSVC 2008 Express on 64 bit windows 7. When I tried to open the .sln file, I get the error "project file dpcwebcfx.vproj could not be loaded". I don't have the .vproj file, but I do have dpcwebcfx.dsw file. So in the .sln file I changed
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dpcwebcfx", "dpcwebcfx.vcproj", "{355F3EB4-3B37-4272-B454-340E9B3BD9D3}"

to
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dpcwebcfx", "dpcwebcfx.dsw", "{355F3EB4-3B37-4272-B454-340E9B3BD9D3}"

Now I get an error converting the dsw file: Cannot load the project due to a corrupt project file. What should I do? Am I missing a file so that I can't open this project?


Q: Exception in VOCE sample C++ app I've been playing around with the C++ api of Voce for speech recognition in one of my projects. So far, I've been able to compile the C++ version of one of the sample apps provided by Voce named recognitionTest (provided under the samples directory in voce-0.9.1).
However, when I try running recognitionTest.exe, I hit an IndexOutOfBoundsException (console output is provided below).
[Voce] Java virtual machine created
[Voce] Initializing recognizer. This may take some time...
[Voce] Initialization complete
This is a speech recognition test. Speak digits from 0-9 into the microphone. Speak 'quit' to quit.
Exception in thread "Recognition thread" java.lang.IndexOutOfBoundsException: Index: 110,Size: 109
    at java.util.SubList.rangeCheck(Unknown Source)
    at java.util.SubList.get(Unknown Source)
    at edu.cmu.sphinx.decoder.scorer.ScoreableJob.getFirst(ThreadedAcousticScorer.java:516)
    at edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer.scoreScoreables(ThreadedAcousticScorer.java:310)
    at edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer.calculateScores(ThreadedAcousticScorer.java:276)
    at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.scoreTokens(SimpleBreadthFirstSearchManager.java:337)
    at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.recognize(SimpleBreadthFirstSearchManager.java:258)
    at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.recognize(SimpleBreadthFirstSearchManager.java:226)
    at edu.cmu.sphinx.decoder.Decoder.decode(Decoder.java:94)
    at edu.cmu.sphinx.recognizer.Recognizer.recognize(Recognizer.java:116)
    at edu.cmu.sphinx.recognizer.Recognizer.recognize(Recognizer.java:135)
    at voce.SpeechRecognizer.run(SpeechRecognizer.java:129)
    at java.lang.Thread.run(Unknown Source)

I'm using Windows 8 and 32-bit version of java 1.5.
Question: Has someone encountered a similar error before? The exception seems to be thrown by the underlying cmusphinx library. So, I'm unable to debug the issue.
Any help would be greatly appreciated!
Please let me know if any additional info would be helpful in figuring out the issue.
Thanks in advance!


Q: How does this function traverse Binary Tree? I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.
The prompt is
Given a binary tree, find the leftmost value in the last row of the tree.

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Tree is defined:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

This function works (I did not come up with it):
var findBottomLeftValue = function(root) {
    var result = root.val;
    var resultHeight = 0;
    (function recurse (node, height) {
        if (node === null) {
            return;
        }
        if (node.left !== null) {
            recurse(node.left, height + 1);
        }
        if (height > resultHeight) {
            result = node.val;
            resultHeight = height;
        }
        if (node.right !== null) {
            recurse(node.right, height + 1);
        }
    })(root, 1);
    return result;
};

I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.
What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.
Where on the solution did it check for nodes 3, 5, 6, and 7?

A: Your function descents to the left in the first call of recurse() (line 9).
If it is done with the left node, it'll go to the right in the second call to recurse() (line 16).
The sequence of the nodes will be 1 -> 2 -> 4 -> (2) -> (1) -> 3 -> 5 -> 7 -> (5) -> (3) -> 6 -> (3) -> (1).
The nodes in braces show where the call stack is reduced.

A: If you imagine what is happening as a stack,it's much easier to understand.
It starts on the node with value 1. When it checks the left node,it's left on hold as the first item of the stack(to be called again when it's the topmost item of the stack again)
It would look something like this when it starts on the second iteration:
2
---
1

Then,it would keep executing and adding to the stack until it check that the node 4 has no left or right node.
At this moment,it would look like this:
4
---
2
---
1

Then,since there's nothing else to do on the node with value 4,it gets removed out of the stack,and then it executes the next topmost of the stack from where it left off:checking the right node of it.
I hope this helped you visualise and understand what really happens because that really helped me and some college coleagues to understand binary trees.


Q: Why is AWS Lambda resetting every ~2hrs even with regular ping from EventBridge? I have a Lambda function that has an unacceptably long start-up time due to large files being transferred on initialisation.  Once this is done, the actual data processing is very quick
I've set up a rule with EventBridge that keeps the function warm by sending a dummy request every 4 minutes.  I've set these dummy requests up such that they only take a few ms after the initial request.
For this most part this seems to be working well - on the logs I see one long request and then all of the ones afterwards are quick.
However, I notice that every 128 minutes I get another long request, as if the Lambda function is 'resetting', despite the warming rule.
Does anyone know why this is happening?  I don't understand why I'm getting these intermittent long requests if the function is being kept warm..

A: A lambda function instance has a maximum lifetime of about 2 hours even if it's in use.  If you want to keep an instance alive then you should use provisioned concurrency.

A: What Matt said above is true, you should use provisioned concurrency. But you can also speed up the cold start by using lambda layers to include files there, instead of downloading on initialization (if the files you need to download don't change frequently).


Q: Handling large JSON web response in VBA I need to create a program that accesses a REST API and imports the JSON response into Excel. I am using XMLHTTP WebRequest to get the response into an string and then use the VBA-JSON Library to parse it.
Sample code:
Dim Url As String
Dim Response As String
Dim HttpReq, ResponseObj As Object
Url = "https://jsonplaceholder.typicode.com/posts"

'Download JSON response and Parse it into an object
Set HttpReq = CreateObject("WinHttp.WinHttprequest.5.1")
HttpReq.SetTimeouts -1, -1, -1, -1
HttpReq.Open "GET", Url, False
HttpReq.Send
Response = HttpReq.ResponseText        'Line with Out of Memory Error
ResponseObj = ParseJson(Response)

'This is followed by further code that places the response rows into Excel Cells

The input is well structured array, similar to the URL used here and the current code works well for majority of requests. However there are some requests where the response is approximately 40 MB where I get an "Out of Memory" error on retrieving the response (Line with reference to HttpReq.ResponseText). I have tried restarting the machine, closing other programs, Excel Safe Mode, etc but the error persists.
The question I have is, is there any way that I can download, parse and import data into Excel in a more memory efficient manner so that I do not run into the memory error above. For reference, I need to use Excel 2010 32 bit as that's the only approved and installed version at my workplace.

A: Try the below approach to get the Id,Title and body from that webpage.
Sub Get_data()
    Dim HTTP As New XMLHTTP60, res As Variant
    Dim r As Long, v As Long

    With HTTP
        .Open "GET", "https://jsonplaceholder.typicode.com/posts", False
        .setRequestHeader "User-Agent", "Mozilla/5.0"
        .send
        res = Split(.responseText, "id"":")
    End With

    r = UBound(res)

    For v = 1 To r
        Cells(v, 1) = Split(res(v), ",")(0)
        Cells(v, 2) = Split(Split(Split(res(v), "title"":")(1), """")(1), """,")(0)
        Cells(v, 3) = Split(Split(Split(res(v), "body"":")(1), """")(1), """,")(0)
    Next v
End Sub

Reference to add to the library:
Microsoft XML, V6.0


Q: How to write this sql query efficiently in this case Here I have a query like below and am looping the child id and passing it to this query and getting the appropriate result. Here I have 33 child ids so the result for this query contains 33 rows
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7

SELECT COUNT(1) FROM  BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
                      WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
                      AND CHE.CHILDID = @CHILDID AND CHE.ADDDATE BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
                      DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7) AS PREVIOUSWEEKACCIDENTS

here instead of looping the childid I have tried using join in this query but am getting the result in a single row. what I am doing wrong in this
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7
SELECT COUNT(1) FROM  BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP
                      ON CHEP.EVENTID = CHE.EVENTID
                      JOIN  BKA.CHILDINFORMATION CHINFO
                      ON CHE.CHILDID = CHINFO.CHILDID
                      WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
                      AND CHE.ADDDATE
                      BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
                      DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7)

Any suggestion?

A: You need to add a GROUP BY clause:
SELECT  CHINFO.CHILDID
      , COUNT(1)
FROM    BKA.CHILDEVENTS CHE
        JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
        JOIN BKA.CHILDINFORMATION CHINFO ON CHE.CHILDID = CHINFO.CHILDID
WHERE   ( CHE.TYPE = 'ACCIDENT'
          OR ( CHE.TYPE = 'BREAK'
               AND CHEP.PROPERTY = 'SUCCESS'
               AND CHEP.PROPERTYVALUE = 'FALSE'
             )
        )
        AND CHE.ADDDATE BETWEEN DATEADD(DD,
                                        -( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
                                        @DATETIMENOW - 7)
                        AND     DATEADD(DD,
                                        7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
                                        @DATETIMENOW - 7)
GROUP BY CHINFO.CHILDID

A: A value in the where will invalidate an outer join
SELECT CHE.CHILDID
     , COUNT(1)
  FROM BKA.CHILDEVENTS CHE
  LEFT JOIN BKA.CHILDEVENTPROPERITIES CHEP
    ON CHEP.EVENTID = CHE.EVENTID
   AND ( CHE.TYPE = 'ACCIDENT'
          OR ( CHE.TYPE = 'BREAK'
               AND CHEP.PROPERTY = 'SUCCESS'
               AND CHEP.PROPERTYVALUE = 'FALSE'
             )
       )
   AND CHE.ADDDATE BETWEEN DATEADD(DD,
                                        -( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
                                        @DATETIMENOW - 7)
                       AND DATEADD(DD,
                                        7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
                                        @DATETIMENOW - 7)
GROUP BY CHE.CHILDID

A:           DECLARE @DATETIMENOW DATETIME
          SET @DATETIMENOW = GETDATE()

              SELECT  B.WEEK FROM BKA.CHILDINFORMATION CI LEFT OUTER JOIN

              (SELECT Distinct CHINFO.CHILDID,COUNT(*)  as week FROM  BKA.CHILDINFORMATION CHINFO
               JOIN  BKA.CHILDEVENTS CHE
                            ON CHE.CHILDID = CHINFO.CHILDID
               JOIN BKA.CHILDEVENTPROPERITIES CHEP
                            ON  CHE.EVENTID = CHEP.EVENTID
              WHERE
                          (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'POTTYBREAK' AND CHEP.PROPERTY = 'SUCCESS'
                          AND CHEP.PROPERTYVALUE = 'FALSE'))
                            AND
                            CHE.ADDDATE
                            BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-14)-1), @DATETIMENOW-14) AND
                            DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-14)), @DATETIMENOW-14)      group by CHINFO.CHILDID) b
                            on CI.ChildID = b.ChildID


Q: Worst Case Binary Search? The question is:

In order to distinguish ordinary emails from spam,
  an algorithm with several features has been designed. Every feature provides
  information about the message, for instance number of suspicious words, the
  length of the message, degree of matching with spam templates etc. Every feature is a discrete variable with two values, for example, low/high, short/long, and similar/dissimilar. A tree with 255 nodes has been employed to make the decision whether to reject an email. How many operations/steps/time units
  are required at most to process each email?

I was thinking that this would be a perfect binary tree, so 2^n - 1 = 255, thus n = 8. However, I was starting to consider the following "worst-case" scenario:
...O
../\
.O..O
..../\
...O..O
and so forth.

So would this use a binary search recurrence relation. T(n)=T(n/2)+1?

A: I think you have the right answer Jay. From the question, I would draw the tree to look like this:
>                     o
>                    /\
> feature 1:        o  o
>                  /\  /\
> feature 2:      o  o o o
>
                   ...

So you start with a root value. Then you ask if the feature has been successfully met by the email or not, so it breaks into 2 nodes, Y or N. For Y (left-subtree), you ask if the email has met the 2nd feature, Y or N and this breaks off into 2 more node and the same is repeated on the N side (right-subtree). Repeat for all features.
We know that the big-Omega (worst case) for a perfect binary tree is log(n) [base 2]. So log(255) [base 2] is approximately 8, & that must be the max number of steps required.

A: If your tree is a balanced binary tree, then the answer would be 8.
The wording of the problem doesn't seem to call that out though. So that being said, we could make a tree that is a chain (only right children), which would make 255 the worse case.


Q: Externalize angular configuration file ( config.json ) I have an angular application (war format) that run on a jboss application server. My actual architecture is: Front app ( angular ) and back app ( java ), the front calls back services using the rest api link, that is provided in the src/conf/config.json file.
This is my app config file :
{
"restApiUrl": "https://jboss_host:8443/back/rest/",
"ldapAuthentication" : true
}

So, my needs for now ( the client need) is to externalize this config file to change the rest api link easily, without make a rebuild or redeploiment process.
I can't use any further elements in my architecture ( revers-proxy, conf server ) because it going to be a brain teaser for the client production, or api database ( the DB connection is provided by the back service ).
Please can you advise.

A: If you do not want load config file over http, try to use config.js file.
Rename config.json to config.js and change content to this:
var config = {
  "restApiUrl": "https://jboss_host:8443/back/rest/",
  "ldapAuthentication" : true
}

Then include config file into index.html in your application:
<script type="text/javascript" src="config.js"></script>

In angular application you can access to this config via (<any>window).config.
For more convenient use create ConfigService like:
@Injectable({providedIn: 'root'})
export class ConfigService {
  getConfig(): Config { // You should create some model of your config too or you can use 'any'
    return (<any>window).config;
  }
}

A: @mpstv thank you for your replay.
I was able to solve this, by using the power of java servlet. The solution was adding to the project war the WEB-INF folder ( servlet.class + web.xml ) that will charge the config file from the filesystem and serve it to the angular, while HTTP call.


Q: Calling NSXMLParser from static method does not parse I'm trying to build a nice little class with NSXMLParser for my needs.
I'm calling the class this way:
ViewController.m:
[IDAN_XML_Parser setXmlString:soapMsg];
[IDAN_XML_Parser setStringToFind:@"userID"];
[IDAN_XML_Parser setHeader:kAPP_PASSWORD andHeaderValue:kAPP_HEADER];
[IDAN_XML_Parser setSetupXml:kWEB_SERVICE_URL];
[IDAN_XML_Parser prepareParsingAndGetResponse];

NSString *answer = [IDAN_XML_Parser getResponse];
NSLog(@"Response: %@", answer);

And my class is this:
.h file:
#import <Foundation/Foundation.h>

@interface IDAN_XML_Parser : NSObject <NSXMLParserDelegate, NSURLConnectionDelegate>

+ (void)setXmlString:(NSString *)theXML;
+ (void)setStringToFind:(NSString *)stringToFind;
+ (void)setSetupXml:(NSString *)webServicesURL;
+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue;
+ (BOOL)prepareParsingAndGetResponse;
- (NSInteger)startParsing;
+ (BOOL)isParsingOK;
+ (IDAN_XML_Parser *)sharedXML;
+ (NSString *)getXMLString;
+ (NSString *)getResponse;

@end

.m file
#import "IDAN_XML_Parser.h"

@implementation IDAN_XML_Parser

NSString *matchingElement;
NSString *xmlString;
NSMutableData *webData;
NSURLConnection *conn;
NSString *soapHeader_key;
NSString *soapHeader_value;
NSURL *url;
BOOL isHeader = NO;
NSInteger didGetError = 0;
BOOL elementFound;
NSMutableString *soapResults;
NSString *returnedString;
NSXMLParser *xmlParser;
NSString *exceptionReason;
NSString *resultXML;

#pragma mark - Setup Parsing

+ (IDAN_XML_Parser *)sharedXML
{
    static IDAN_XML_Parser *theParser;
    @synchronized(self) {
        if (!theParser)
            theParser = [[self alloc] init];
    }
    return theParser;
}

+ (void)setXmlString:(NSString *)theXML
{
    xmlString = theXML;
    NSLog(@"\n\nXML TO SEND: %@", xmlString);
}

+ (void)setStringToFind:(NSString *)stringToFind
{
    matchingElement = stringToFind;
}

+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue
{
    isHeader = YES;
    soapHeader_key = headerKey;
    soapHeader_value = headerValue;
}

+ (void)setSetupXml:(NSString *)webServicesURL
{
    url = [NSURL URLWithString:webServicesURL];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [xmlString length]];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [xmlString dataUsingEncoding:NSUTF8StringEncoding]];

    if (isHeader) {
        [req setValue:soapHeader_value forHTTPHeaderField:soapHeader_key];
    }

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];

    if (conn)
    {
        webData = [NSMutableData data];
    }
}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response
{
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data
{
    [webData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error
{
    didGetError = 1;
    NSLog(@"\n\nConnection Error: %@", error);
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    resultXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
                                                length:[webData length]
                                              encoding:NSUTF8StringEncoding];
    didGetError = 0;
    NSLog(@"\n\nRESPONSE XML: %@", resultXML);
}

+ (BOOL)prepareParsingAndGetResponse
{
    NSInteger isParsingOK;
    isParsingOK = [[self sharedXML] startParsing];

    if (isParsingOK == 1) {
        return YES;
    } else {
        return NO;
    }
}

- (NSInteger)startParsing
{
    @try {
        xmlParser = [[NSXMLParser alloc] initWithData:webData];
        [xmlParser setDelegate:self];
        [xmlParser setShouldResolveExternalEntities:YES];
        [xmlParser parse];
    }
    @catch (NSException *exception) {
        didGetError = 1;
        exceptionReason = exception.reason;
        NSLog(@"Exception Reason: %@", exception.reason);
    }

    if (didGetError != 1) {
        didGetError = 0;
    }

    return didGetError;
}

+ (NSString *)getXMLString
{
    return resultXML;
}

+ (BOOL)isParsingOK
{
    if (didGetError == 1) { // We have error
        return 1;
    } else { // We don't have error
        return 0;
    }
}

+ (NSString *)getResponse
{
    return returnedString;
}

#pragma mark - Start Parsing

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"START PARSING!");
    if ([elementName isEqualToString:matchingElement]) {
        if (!soapResults) {
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (elementFound) {
        [soapResults appendString:string];
        NSLog(@"\n\nsoapResults: %@", soapResults);
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:matchingElement]) {
        returnedString = soapResults; // Save the element we found
        elementFound = NO;
    }
}

@end

I manage to send and get back the correct xml but it's actually doesn't start the parsing.
Any idea how can I solve it?

A: You are initiating an asynchronous NSURLConnection and then immediately starting the parsing process. You need to defer the initiation of the parsing until connectionDidFinishLoading, or you should do a synchronous NSURLConnection (but obviously, not from the main queue). Thus, while you're eventually getting a response, the parsing is undoubtedly initiated before the response has been received.


Q: Best way to transfer struct from one process to another? I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:
typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

A: In my understanding you can solve this issue by implementing a shared queue. The pattern of your problem is more towards Producer Consumer Problem
You can also take these examples

*

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

*How should i write producer /consumer code in C#?

A: Are the server and clients on different hosts? If so, why don't you take UDP and to methods to serialize your structure to send via network and the second one to get it back to structure? ...

A: WM_COPYDATA is specifically meant for transferring structs between processes. Check it out.
You mentioned pointers though - and no, you cannot expect pointers to work between processes. If you have variable-length arrays or pointers, it's probably necessary to serialize the data, for example with BSON or XML.

A: It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit.

A: ReadProcessMemory and WriteProcessMemory ought to be able to do the trick for you.


Q: Accordion animation in ui-bootstrap is different from the original bootstrap (size of the accordion is increased, visually it "jumps") The default animation in bootstrap does not change the size of the full accordion in the process. For some reason in the ui-bootstrap that is not the case and while it animates it does a strange increase in size which looks like it "jumps" (easy to notice if you look at the bottom of control). I think that the original behaviour is way more pleasant to the eye as the ui-bootstrap may even change the scrollbar size while it's animating.
Why is it doing it differently and is there an easy way to fix it? E.g. by changing the template.

A: The accordion-group template uses the uib-collapse directive to open/close the panels, see here  Removing the uib-collapse directive will bypass some of the unexpected behavior you are seeing, but I think you will need to manage closing/opening the panels.


Q: How to prevent reordering of loads after stores using the C++11 atomics API? I know that you can use the C++11 atomics API in a producer-consumer context to make sure that a consumer sees the "done writing" flag only after some produced record has been completely written out, i.e.
producer:
data[write_index] = <something>
status[write_index].store(READABLE, std::memory_order_release)

consumer:
if (status[read_index].load(std::memory_order_acquire) == READABLE)
  //do something with data[read_index]

My question is what happens next - how does the consumer safely tell the producer that it has finished reading from data[read_index], so that the producer can write to data[read_index] for some other purpose?
On x86, I can do (I think?)
consumer:
//do something with data[read_index] //LINE A
asm volatile("" : : : "memory"); //compiler barrier
status[read_index].store(AVAILABLE, std::memory_order_relaxed) //LINE B

and
producer:
if (status[write_index].load(std::memory_order_relaxed) == AVAILABLE)
  //write_index is available for writing

My impression is that on an architecture where loads can be reordered after stores, the writer could observe LINE B before LINE A has finished, which would cause a problem.
Is there a way to do this using the C++11 atomics API? The atomic_thread_fence instructions seemed promising but after reading the documentation I don't see that it gives the guarantee I need here.
Thanks!

A: Always use sequential consistency if in doubt :)

memory_order_seq_cst
  The operation is ordered in a sequentially consistent manner: All operations using this memory order are ordered to happen once all accesses to memory that may have visible side effects on the other threads involved have already happened.
  This is the strictest memory order, guaranteeing the least unexpected side effects between thread interactions though the non-atomic memory accesses.

It applies either to the consumer's store which sends the signal back to the producer or the std::atomic_thread_fence before it.
void producer() {
  for(;;) {
    data[write_index] = <something>;
    status[write_index].store(READABLE, std::memory_order_release);
    // do something else while consumer reads it

    // producer knows for sure that reader will consume it and signal back
    while( status[write_index].load(std::memory_order_acquire) != WRITEABLE)
        _mm_pause(); // or at least std::this_thread::yield();
  }
}
void consumer() {
    while (status[read_index].load(std::memory_order_acquire) != READABLE)
        _mm_pause(); // or at least std::this_thread::yield();
    //do something with data[read_index]

    // signal back and prevent loads from reorder below
    status[read_index].store(WRITEABLE, std::memory_order_seq_cst);
}

I'm afraid that this will result in excessive synchronization on x86.. but until someone else comes up with more tricky (but still portable C++11) approach, consider this as the price of portability.


Q: Getting "TypeError: cannot pickle '_thread.RLock' object" when using Broadcast Variable in Spark Cluster The Spark Cluster has one Master and four Slaves. I have a small table in the database, so I read the table in Master node and set it as a Broadcast variable like this:
def checkTableExists(tablename, connection):
try:
    query = 'SELECT * FROM {0}'.format(str(tablename))
    print(query)
    connection.cursor.execute(query)
    return True
except odb.DatabaseError as e:
    x = e.args[0]
    if x.code == 942:  ## Only catch ORA-00942: table or view does not exist error
        return False
    else:
        raise e

def read_cheque_paper(spark, connection):
   if create_tables.checkTableExists(small_table, connection) == True:
     query_cheque = '''select * from {}'''.format(small_table)
     df = connection.read_sql(query_cheque)
     broadcastStates = spark.sparkContext.broadcast(df)
   else:
     df = spark.createDataFrame([], StructType([]))
     broadcastStates = spark.sparkContext.broadcast(df)
return broadcastStates

def trx_features(dataframe, broadcast_df):
  df_small = broadcast_df.value
  if df_small.empty:
    df = df.withColumn('field_check', lit(None).cast(StringType()))
  else:
    df = calculate_field_check(dataframe, df_small)
    df.select('field_check').where('field_check==1').show()
return df

def distribute_data(spark):
   connection = cx_Oracle.connect(
    config.username,
    config.password,
    config.dsn,
    encoding=config.encoding)
   if gf.flag_trx:
      source_table_name, table_name = gf.create_query('trx')
      broadcast_df = read_cheque_paper(spark, connection)
      predicates = list_predicates(connection, source_table_name, date_field)
      dataframe = gf.read_spark(spark, table_name, predicates, connection)
      df_trx = trx_features(dataframe, broadcast_df)
      write_spark(dist_table_name_trx, df_trx)
return

if __name__ == '__main__':
   master = "spark://IP master:7077"
   conf = SparkConf() \
    .setAppName('ETL') \
    .setMaster(master) \
    .set("spark.jars", "ojdbc8.jar")

   sc = SparkContext.getOrCreate(conf=conf)
   sqlContext = SQLContext(sc)
   spark = sqlContext.sparkSession
   spark.sparkContext.setLogLevel('ERROR')
   start_time = datetime.datetime.now().timestamp()
   distribute_data(spark)
   end_time = datetime.datetime.now().timestamp()
   duration = end_time - start_time

When this program run in local mode,I get the result without any errors. But, while I run that in the cluster,when it reach to the df_small = broadcast_df.value it was stopped with this error:
TypeError: cannot pickle '_thread.RLock' object

Would you please guide me what is wrong with defining the broadcast varible?
Any help is really appreciated .


Q: How to draw perfect straight line passing through majority of given points in MATLAB? Can someone help me figure out how to draw a perfect straight line from given set of points passing through majority (may be 5-6 point out of 20) of these points? Please note that this is not a line fit problem, but perfect line should be drawn (horizontal, vertical or somewhat slanted) between majority of the given points.
Here is MATLAB code:

e=[161    162   193   195   155    40   106   102   125   155   189   192   186   188   185   186   147   148   180   183];

f =[138    92    92   115   258   124   218   114   125   232   431   252   539   463   643   571   582   726   726   676];

figure;scatter(f, e, 5, 'red');

axis ij;

and here is image:

A: Since you want the line to go through the majority of points, it sounds quite like a line fitting problem even though you say it isn't. Have you looked at the Theil-Sen estimator (for example this one on fex), which is a linear regression ignoring up to some 30% of the outliers.
If you simply want a line through the extrema you might do something like this:
% Setup data
e = [161    162   193   195   155    40   106   102   125   155   189   192   186   188   185   186   147   148   180   183];
f = [138    92    92   115   258   124   218   114   125   232   431   252   539   463   643   571   582   726   726   676];
% Create scatterplot
figure(1);
scatter(f, e, 5, 'red');
axis ij;

% Fit extrema
[min_e, min_idx_e] = min(e);
[max_e, max_idx_e] = max(e);
[min_f, min_idx_f] = min(f);
[max_f, max_idx_f] = max(f);
% Determine largest range and draw line accordingly
if (max_e-min_e)>(max_f-min_f)
    line(f([min_idx_e, max_idx_e]), e([min_idx_e, max_idx_e]), 'color', 'blue')
    text(f(max_idx_e), e(max_idx_e), ' Extrema')
else
    line(f([min_idx_f, max_idx_f]), e([min_idx_f, max_idx_f]), 'color', 'blue')
    text(f(max_idx_f), e(max_idx_f), ' Extrema')
end

% Fit using Theil-Sen estimator
[m, e0] = Theil_Sen_Regress(f', e');
line([min_f, max_f], m*[min_f, max_f]+e0, 'color', 'black')
text(max_f, m*max_f+e0, ' Theil-Sen')

However, as you'll notice neither solution automatically fits the points automatically, simply because there are too many outliers, unless you filter those beforehand. Therefore you probably are better off using the RANSAC algorithm as proposed by Shai and McMa.

A: That's a textbook example for the RANSAC algorithm. This free toolbox for Matlab actually has some very nice examples of line fitting.

A: An easy but not very efficient solution would be to compute slope between each two points and if a set of points lie on a straight line, all pairs of these set would have the same slope. So one algorithm could pick all the poirs with same slope and connect them if they have one point in common. finally you have to choose the largest set. The time complexity of this algorithm will be O(N^2 log N) which N is number of points.
As I see in your figure there is not a real perfect line going through all the points, rather there is a tolerance which in this algorithm could be defined as the criteria by which you connect two pairs. say if two slopes are different by less than 2 percent we connect the pairs.


Q: Unexpected binding behaviour I have select list i set default option to be chosen. what happen is for few second it works then it disappear and the blank option in the list is chosen as default.
 <div class="form-group">
              <select class="form-control" ng-model="item.action" ng-options="option.value as option.title for option in options">
              </select>
            </div>

i want to set defualt option to be chosen :
so my controller look like this:
$scope.item = {};
  $scope.options = [{
    title: 'On entering',
    value: 'enter'
  }, {
    title: 'On exiting',
    value: 'exit'
  }];
  $scope.item.action= $scope.options[0].value;

  $scope.profile = me.getUser();
  $scope.profile.then(
    function(user) {
      $scope.owner = user;
      $scope.item = {};
      $scope.item.data = '';
      $scope.item.published = true;
      $scope.item.action= $scope.action;
      $scope.item.owner = $scope.owner.displayName;
    },
    function(response) {
      console.log(response);
    }
  );

me is a service that fecth the user data.
the reason why am defining $scope.item = {}; again is because i can't apend the displayName to the $scope.item out of the scope.
I commented this part of the code and it works well:
  $scope.profile = me.getUser();
  $scope.profile.then(
    function(user) {
      $scope.owner = user;
      $scope.item = {};
      $scope.item.data = '';
      $scope.item.published = true;
      $scope.item.action= $scope.action;
      $scope.item.owner = $scope.owner.displayName;
    },
    function(response) {
      console.log(response);
    }
  );

But now i can't figure out how to build my item object to send it in HTTP request


Q: Simplify PHP for SQL data retrevial I'm new to PHP and SQL queries but trying to learn. Anyway, I have the following code which I'm sure there will be a simpler way of doing (hopefully as I intend to do the same for day of year not just month).
My current code is;
//Get jan power consumption
$janquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 1");
$janresult = mysql_fetch_array($janquery);
$jankwm = $janresult[0] / 60;
$jankwh = round($jankwm / 60,2);

//Get feb power consumption
$febquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 2");
$febresult = mysql_fetch_array($febquery);
$febkwm = $febresult[0] / 60;
$febkwh = round($febkwm / 60,2);

and so on then...
$values=array(
    "Jan" => $jankwh,
    "Feb" => $febkwh,
    "Mar" => $markwh,
    "Apr" => $aprkwh,
    "May" => $maykwh,
    "Jun" => $junkwh,
    "Jul" => $julkwh,
    "Aug" => $augkwh,
    "Sep" => $sepkwh,
    "Oct" => $octkwh,
    "Nov" => $novkwh,
    "Dec" => $deckwh
);

I want to avoid having 12 queries so any help would be appreciated.

A: SELECT
    month(time) as `month`,
    SUM(kw*tdsecs) as `sum`
FROM data
WHERE year(time) = year(CURDATE())
group by month(time)
order by month(time)

A: SELECT month(time), SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) group by month(time);

A:   mysql_query("SELECT month(time),SUM(kw*tdsecs) FROM data WHERE
  year(time) = year(CURDATE()) AND month(time) in
  (1,2,3,4,5,6,7,8,9,10,11,12) group by month(time)")

A: A simple solution (not the best) would be to loop through the months and store the results in a array:
for($month=1; $month<=12; $month++) {
  $query = mysql_query(
    "SELECT SUM(kw*tdsecs) FROM data
     WHERE year(time) = year(CURDATE()) AND month(time) = $month");
  $result = mysql_fetch_array($query);
  $kwm[$month] = $result[0] / 60;
  $kwh[$month] = round($kwm[$month] / 60,2);
}


Q: The conformal map from interior of ellipse to interior of the unit disk (property check) Based on example 5 (page 546) and example 7 (page 550) of the book "Applied and computational complex analysis. Volume 3, Wiley, 1986" written by Peter Henrici, if $a,b>0$ satisfies $a^2-b^2 = 1$ and we define $\rho>1$ through $\rho+\rho^{-1} = 2a$ (or through $\rho - \rho^{-1} = 2b$), the conformal map sending the interior of the ellipse $R:=\{(x,y)\in \mathbb{R}^2 \mid \frac{x^2}{a^2}+\frac{y^2}{b^2} \leq 1\}$, which in polar coordinates reads $$R = \left\{(\theta,r) \mid r \leq \frac{ab}{\sqrt{a^2\sin^2\theta + b^2\cos^2\theta}}:=r(\theta)\right\},$$ to the interior of the unit circle is given by
\begin{equation}\label{E2D}
h(z) = \frac{4}{h'(0)}\sum_{m=0}^\infty \frac{(-1)^mT_{2m+1}(z)}{\rho^{4m+2}-\rho^{-4m-2}},\quad z\in R,
\end{equation}
where $(T_n)_{n\geq 0}$ are the Chebyshev polynomials of the first kind and $$h'(0) = \left(4\sum_{m=0}^\infty \frac{2m+1}{\rho^{4m+2}-\rho^{-4m-2}}\right)^{\frac 12}.$$ But I get stuck when trying to check this is indeed the correct conformal map. Specifically, I do not know how to show $$|h(z)| < 1 \quad \text{for $z = re^{i\theta} \in R$}.$$ Also, another key question that is of my interest concerns the boundary behavior of $h$: what is the image under $h$ of the boundary "elliptical" arc $\{(\theta,r(\theta)) \in E \mid |\theta| \leq \delta \}$ (where $E$ is boundary of the elliptical region enclosed by $R$ and $\delta$ is small)? Thanks for any help or suggestions!


Q: Summation of Functional equation Let $ f(k)$= $\dfrac{k}{2009}$ and $g(k)$ =$\dfrac{f^4(k)}{(1-f(k))^4+(f(k))^4}$ then the sum of
$$
\sum_{k=0}^{2009} g(k)\
$$ is equal to
My Approach : I substituted the values of $f(k)$ in $g(k)$ and formed the series .
And I saw that the series was repeating after $1004$ , so I did twice. But still I cannot get any perfect answer.
The series is $$
\sum_{k=0}^{2009}\frac{k^4}{(2009-k)^4+k^4}
$$
So it repeats after 1004 but I am not able to proceed ..
Please help...

A: Let
$$ M_1=\sum_{k=0}^{2009}g(k)=\sum_{k=0}^{2009}\frac{k^4}{(2009-k)^4+k^4}, M_2=\sum_{k=0}^{2009}\frac{(2009-k)^4}{(2009-k)^4+k^4}. $$
Clearly $M_1=M_2$ by letting $n=2009-k$. Note $M_1+M_2=2010$ and hence $M_1=1005$.


Q: How to convert Object to List in c#? I have a List<string> in Model.
When I write a html helper, I can get the data from metadata.Model, which is an object
// this is from MVC3 (namespace System.Web.Mvc -> ModelMetadata), I did not write this
// Summary:
//     Gets the value of the model.
//
// Returns:
//     The value of the model. For more information about System.Web.Mvc.ModelMetadata,
//     see the entry ASP.NET MVC 2 Templates, Part 2: ModelMetadata on Brad Wilson's
//     blog
public object Model { get; set; }

My question is: how to get List<string> from an Object?

A: If the underlying type of the object variable is List<string>, a simple cast will do:
// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model;

or
// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;


Q: How can I tell if a file has changed through .NET? I am looking for a way to determine when a particular file has changed, through .NET. (What I ultimately want is functionality that makes a copy of the file as soon as it has changed.) How can this be done?

A: class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher(@"c:\temp");
            fsw.Changed += new FileSystemEventHandler(fsw_Changed);
            fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
            fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
            fsw.Created += new FileSystemEventHandler(fsw_Created);
            fsw.EnableRaisingEvents = true;
            Console.ReadLine();
        }

        static void fsw_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was created", e.FullPath);
        }

        static void fsw_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("{0} was Renamed", e.FullPath);
        }

        static void fsw_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was Deleted", e.FullPath);
        }

        static void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was Changed", e.FullPath);
        }
}

A: Microsoft Windows, and its ultimate ancestor MS-DOS, has always had an attribute on its files that indicates whether that file was changed since the last time that attribute was cleared, sort of a "dirty flag". It was used in the past by backup programs to find those files that needed to be backed up incrementally, and then cleared when a copy of that file had been made.
You can use File.GetAttributes to get the attributes on a file, and use File.SetAttributes to clear that "Archive" attribute. The next time that file is opened for writing, that archive flag will be set again.
Be careful about copying files that have been changed, as those files may still be open. You probably want to avoid concurrency problems by opening them for read exclusively when copying, and if that fails you know that file is still open for writing.

A: To all who responded with, use FileSystemWatcher, how do you deal with the time your app isn't running? For example, the user has rebooted the box, modified the file you are interested in, and then starts up your app?
Be sure to also read the docs on FileSystemWatcher Class carefully specially the section about Events and Buffer Sizes.

A: You can use a FileSystemWatcher object.  This raises events on changes to files within the specified watched folder.

A: You're likely to run into issues with FileSystemWatcher (not getting events, too many events, etc.)  This code wraps it up and solves many of them:
http://precisionsoftware.blogspot.com/2009/05/filesystemwatcher-done-right.html

A: You will have to note the modified date of files which you want to check.
After certain period you can check if the file was modified later.
If the file is modified with different date and time, you can make the copy.


Q: При попытке переустановить Ubuntu попадаю в grub-меню Всем привет.
Слетела Убунта.
Хочу переустановить.
Создал загрузочную флешку с помощью утилиты "Создать загрузочный диск" (из другой Убунты) и образа "ubuntu-20.10-desktop-amd64.iso", который скачал с официального сайта.
Ноутбук DELL Inspirion 15 3000 Series.
При запуске нажимаю F12, выбираю в качестве источника загрузки мою загрузочную флешку.
Попадаю в grub-меню.
Как запустить установку ОС?
С уважением, Александр.

A: По идее, если выбрать первый пункт меню, ОС должна загрузиться с флешки и на рабочем столе должна быть программа установки. Но рабочий стол загружался пустым. Ничего нельзя было сделать, просто шевелить мышкой. Подозреваю, что скачал кривой образ.
Скачал образ "linuxmint-20-cinnamon-64bit.iso". Первый пункт grub-меню отработал. Загрузился функциональный рабочий стол и я запустил установку ОС. Давно хотел попробовать Mint, вот представилась такая возможность :)


Q: Linux: how to check the largest contiguous address range available to a process I want to enter the pid at the command line and get back the largest contiguous address space that has not been reserved.  Any ideas?
Our 32 bit app, running on 64 bit RHEL 5.4, craps out after running for a while, say 24 hours.  At that time it is only up to 2.5 gb of memory use, but we get out of memory errors.  We think it failing to mmap large files because the app's memory space is fragmented.  I wanted to go out to the production servers and just test that theory.

A: Slighly nicer version of my above comment:
#!perl -T

use warnings;
use strict;

scalar(@ARGV) > 0 or die "Use: $0 <pid>";

my $pid = $ARGV[0];
$pid = oct($pid) if $pid=~/^0/;         # support hex and octal PIDs
$pid += 0; $pid = abs(int($pid));       # make sure we have a number

open(my $maps, "<", "/proc/".$pid."/maps") or
        die "can't open maps file for pid ".$pid;

my $max = 0;
my $end = 0;
while (<$maps>) {
        /([0-9a-f]+)-([0-9a-f]+)/;
        $max = hex ($1) - $end if $max < hex ($1) - $end;
        $end = hex ($2);
}

close ($maps);

END {
        print "$max\n";
}

A: Probably not exactly what you want, but from inside a process it is possible to do binary search by mmaping without allocating. I.e. mmap(4GB), if that fails mmap(2GB), if that succeeds mmap(3GB), and so on.

A:
we get out of memory errors. We think it failing to mmap large files because the app's memory space is fragmented.

However, one can also get OOM errors while still having lots of free virtual address ranges on paper, for example by sufficient lack of RAM+swap. Furthermore your system and/or program(s) may have overcomitting turned off (sysctl -a), or have swapping inhibited (mlock(2)), or you actually have a very blunt limit on mappings (ulimit -v) — the latter is easy to run in given some distributions set such ulimits one way or another.


Q: REDIS-Python -> get all keys and respective values from 1 database I am trying to get all keys and values from a REDIS db. There are about 35000+ open connections on REDIS by the other users. I am using r.scan_iter()to get all the keys and I am appending them to a list. I am currently using pipeline.execute() to get all the values for these list of keys. Is this necessary to get the values for keys from redis? Or is there some way to access values of keys from r.scan_iter() loop.
Key = a|b|c
Value = V1:X1 V2:X2 V3:X3
My code is as below:
r = redis.Redis(host,port,db)
#To get all the keys and then use pipeline to get corresponding values
for key in r.scan_iter():
    pipe.hgetall(key.decode('utf-8'))
values = pipe.execute()
#To  loop through the values and read
for value in values:
     # Get all the values for each key
     for name, value in value.items():


Q: Facebook and Whatsapp sharing buttons I have an PHP page showing an image to the user, and I want them to share via Facebook or WhatsApp,
Here the code for the head part:
<meta name="description" content="<?php echo $Rowdati['metadescrizione'];?>">
<meta name="keywords" content="<?php echo $Rowdati['keywordsapp'];?>">
<meta property="og:image" content="<?php echo $urlimmagineuser; ?>">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="400">
<meta property="og:image:height" content="400">
<meta property="og:title" content="<?php echo $Rowdati['titolo_fb_share'];?>">
<meta property="og:description " content="<?php echo $Rowdati['descr_fb_share'];?>">

Here the code for getting the image to share and display on the web page:
<?php echo "

    ";
?>

Here the share buttons:
<div class="col-sm-4" data-href="<?php echo $actual_link;?>" data-layout="button" data-size="large" data-mobile-iframe="true">
    <button class="btn col-xs-12 scroll_effect shadow-top-down">
        <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $actual_link;?>;src=sdkpreparse">

share on FB
    </button>

    <button class="btn col-xs-12 scroll_effect shadow-top-down">
        <?php
            $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") .
            "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ?>
        <a href="whatsapp://send?text=<?php echo $Rowdati['testo_whatsapp'] . "http://mydomain.it";?>" data-action="share/whatsapp/share">

share on Whatsapp

    </button>

The page works fine, except that when i share it on Facebook or WhatsApp it does not return the image preview...
I cannot figure out why after checking and rechecking the code.


Q: python сделать синхронную функцию асинхронной Есть долгая функция long_sync_func()
Как ее выполнить асинхронно, чтоб можно было это запустить в цикле событий?
Есть вариант сделать асинхронное выполнение через threading.Thread, но мне нужно, чтоб можно было применить await, например:
async def new_function():
    # do smth
    await make_function_async(long_sync_func)
    # do smth

Вот как реализовать эту make_function_async?
UPD
Пришел на ум вот такой костыль, насколько так делать правильно?
import asyncio
from threading import Thread

class Runner(Thread):
    def __init__(self, func, *args, **kwargs):
        super().__init__()
        self.func = func
        self.args = args
        self.kwargs = kwargs

    def run(self):
        self.result = self.func(*self.args, **self.kwargs)

async def make_async(func, *args, **kwargs):
    r = Runner(func, *args, **kwargs)
    r.start()
    while r.is_alive():
        await asyncio.sleep(0)


Q: Making a V-shaped pattern with Python I wanna make  pattern　by　algorithm.
Result is the pattern like
..........
..........
..........
..........
..........
..........
.########.
.########.
##########
##########

But my ideal pattern is
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....

So,I cannot understand why I cannot do it in my code.
By comparing current pattern & ideal one,I think  data cannot use correctly. But I cannot know how to fix this. What should I do to do it?

A: A different approach:
final = []
for i in range(10):
    temp = ["." for j in range(10)]
    temp[int(i / 2)] = "#"
    temp[int(i / 2) + 1] = "#"
    temp[-int(i / 2) - 1] = "#"
    temp[-int(i / 2) -2] = "#"
    final.append(temp)

for a in final:
    print("".join(a))

Will print:
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....

This can be made even cleaner, but here you can see all the different steps, so I hope it helps

A: # 10x10
#             first # start position  second # start position from last
# LN 0 1:     0                       -1
# LN 2 3:     1                       -2
# LN 2k 2k+1: k                       -k-1
# LN 8 9:     4                       -5

# dw: dot '.' width
# sw: sharp '#' width
# if k == 0 part is ugly, for list slicing
def draw(dw, sw):
    for k in range(dw//2):
        row = [ '.' for _ in range(dw) ]
        row[k:k+sw] = '#' * sw
        if k == 0:
            row[-sw:] = '#' * sw
        else:
            row[-k-sw:-k] = '#' * sw
        print("".join(row))
        print("".join(row))

draw(10, 2)

with draw(20, 2) got
##................##
##................##
.##..............##.
.##..............##.
..##............##..
..##............##..
...##..........##...
...##..........##...
....##........##....
....##........##....
.....##......##.....
.....##......##.....
......##....##......
......##....##......
.......##..##.......
.......##..##.......
........####........
........####........
.........##.........
.........##.........

A: I would use itertools' product, and filter the indices that aren't relevant
def v(row):
    return set([int(row/4), row-int(row/4), int(row/4)+1, row-int(row/4)-1])

from itertools import product
indices = product(range(len(array)),range(len(array[0])))
indices = filter(lambda i: i[1] in v(i[0]), indicies)
for r,c in indices:
    array[r][c] = "#"

A: Don't know what you're trying to accomplish here, but I can do it, too:
a = "##..."
for i in range(10):
    b = ("."*int(i/2) + a)[:5]
    print(b + b[::-1])

A: Slightly more concise:
width = 10

for i in range(width):
    line = ['.'] * width
    m = i//2
    line[m] = line[m+1] = line[-m-1] = line[-m-2] = "#"
    print(''.join(line))


Q: Selenium Python Windows Chrome. Как загрузить файл(ы) из компьютера по относительному или полному пути
#элемент отвечающий за открыть окно "вставку изображения из компьютера"

driver.find_element_by_xpath("//div[@id='SHORTCUT_FOCUSABLE_DIV']/div[2]/div/div/div/div[2]/div[3]/div/div[2]/div[3]/div[2]/div[2]/div/div/div/div[16]/div").click()

Каким образом можно вставить файлы или файлы указав полный путь или относительный? И нажать на кнопку открыть.

A: Используй класс Robot, который будет вводить путь и нажимать кнопку "Открыть".

A: Можно воспользоваться automate 7 (или 10) упростить задачу, но не для фоновых задач


Q: Do custom networks replace default network in docker-compose.yml Does specifying custom networks in docker-compose remove services from the default network? I can't find any information about this.
example
version: '3'
services:
  nginx:
    image: 'nginx:alpine'
    restart: always
    networks:
      - web
      - internal_network
    labels:
      - "traefik.docker.network=traefik"
      - "traefik.backend=blog"
      - "traefik.frontend.rule=Host:test.ondrovo.com"
      - "traefik.port=80"
      - "traefik.frontend.passHostHeader=true"
      - "traefik.protocol=http"
    volumes:
      - ./www:/srv/www
      - ./config/nginx.conf:/etc/nginx/nginx.conf
      - ./config/conf.d:/etc/nginx/conf.d

  php:
    image: php:7-fpm
    volumes:
      - ./www:/srv/www
    networks:
      - internal_network

networks:
  web:
    external:
      name: traefik

  internal_network:
    internal: true

in this case, is internal_network needed or can i just leave it out?

A: The answer is yes, the default network is removed if you specify them manually.
I went ahead and tried it.
You can specify 'default' in the networks list, however, and it apparently does not need to be declared in the top-level list.


Q: How to create filterable and sortable div elements I am using rails 3 and ruby 1.9 to develop a ecommerce app. I currently have a loop pulling product info from the database into a div for each product to populate the storefront.
Problem is I have been been trying without any luck to figure out how to make the products sortable and filterable. Basically i want potential customers to be able to filter and/or sort the products listing by some of the data associated with the products (e.g., sort by date added or filter by manufacturer).
So far i've come across some templates using jquery to accomplish this, but i haven't been able to find anything leveraging the rails framework. Ive included the code below. any assistance would be much appreciated.

Today's

Offers

<% @products.each do |product| %>

 <%= product.title %>

<%= image_tag(product.image_url, :alt =>product.title,  :class=>"product-image")%>


Q: Parse data from php to jsquery.flot.pie I've seen some questions about this already but I still couldn't clear the fog around this...
I have this sql statement to get data:
<script type="text/javascript">

<?php

$query = "SELECT rel_id, SUM(suma) FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]'";
$result = mysql_query ($query);
while($row = mysql_fetch_array($result)){
    echo 'var some_data = ' . json_encode( $viso );
}

?>

Next is the js part:
    $(function () {

   $.plot($("#placeholder"), [some_data],
{
        series: {
            pie: {
                show: true
            }
        },
        legend: {
            show: false
        }
});
});
</script>

I was thinking I could reach the data in some_data and use it to display it in the pie chart, unfortunately this is not the way to go.
Any help and suggestions are greatly appriciated ! :)

A: The most likely problem is that your numeric data is being interpreted as a string.
From the API.txt:

Note that to simplify the internal
  logic in Flot both the x and y values
  must be numbers (even if specifying
  time series, see below for how to do
  this). This is a common problem
  because you might retrieve data from
  the database and serialize them
  directly to JSON without noticing the
  wrong type. If you're getting
  mysterious errors, double check that
  you're inputting numbers and not
  strings.

So either force your data to numeric types on the PHP side, or do it in javascript, perhaps with .Number(some_data)


Q: dotnet restore: An error occurred while retrieving package... metadata Root element is missing I have a nuget/docker build issue that I’ve spent a couple of days debugging and am running out of ideas: Do you know why I am getting the below error?
The issue is with one asp.net core solution (others that are very similar are unaffected): Although I can build the affected solution in visual studio 2019 using the docker compose file, it will not work using the dockerfile and so the docker build command can’t be run.
If I run the dockerfile by doing a build as below in command prompt:
docker build -f MStoreBosGateway/MStoreBosGatewayApi/Dockerfile --pull --no-cache -t mstorebosgateway:0.041 .

then I get the following error:
Step 11/26 : RUN dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"
>  ---> Running in 30819cb5db4f
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error
> occurred while retrieving package metadata for
> 'System.Text.Encodings.Web.4.5.0' from source
> '/usr/share/dotnet/sdk/NuGetFallbackFolder'.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root
> element is missing.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> The command '/bin/sh -c dotnet restore
> "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"'
> returned a non-zero code: 1

I’ve put RUN echo commands after each line in the dockerfile so it looks like it is the dotnet restore that is causing this issue. If I run the dotnet restore command by itself it runs ok.
To try to resolve this I’ve done quite a few things e.g.

*

*-Deleted the obj and bin folders from this solution and projects,

*-Uninstalled and reinstalled nuget,

*-Deleted the nuget caches to force the packages to be redownloaded,

*-uninstalled and reinstalled the dotnet core sdks,

*-Removed the package mentioned in the error message ('System.Text.Encodings.Web.4.5.0) from the project file (this did
not cause any errors so must have been redundant anyway). That did
not affect this error and it restores this package so there must be
something else saying to use this package or possibly system packages
are all included by default anyway.

My colleague can build this project and has sent me a copy of it that he can build; I get the same issue building his copy so assume it’s something external to the project.
I have added below the output if I add ‘ –verbosity detailed’ to the dotnet restore command in the docker file.
           GET https://api.nuget.org/v3-flatcontainer/microsoft.extensions.dependencyinjection.abstractions/index.json
           OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/index.json 342ms
           GET https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg
           OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg 52ms
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.authentication/index.json
           GET https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
     1>/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/index.json 156ms
           GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/index.json 160ms
           GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg
           OK https://api.nuget.org/v3-flatcontainer/automapper/index.json 155ms
           GET https://api.nuget.org/v3-flatcontainer/automapper/8.0.0/automapper.8.0.0.nupkg
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg 44ms
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg 49ms
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.apiexplorer/index.json
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.core/index.json
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.dataannotations/index.json
         NuGet.Protocol.Core.Types.FatalProtocolException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> NuGet.Packaging.Core.PackagingException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> System.Xml.XmlException: Root element is missing.
            at System.Xml.XmlTextReaderImpl.Throw(Exception e)
            at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
            at System.Xml.XmlTextReaderImpl.Read()
            at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
            at NuGet.Packaging.Core.NuspecCoreReaderBase.LoadXml(Stream stream, Boolean leaveStreamOpen)
            at NuGet.Packaging.Core.NuspecCoreReaderBase..ctor(Stream stream, Boolean leaveStreamOpen)
            at NuGet.Packaging.NuspecReader..ctor(Stream stream)
            at NuGet.Protocol.LocalPackageFileCache.GetNuspec(String manifestPath, String expandedPath)
            at NuGet.Protocol.LocalPackageFileCache.<>c__DisplayClass6_1.<GetOrAddNuspec>b__1()
            at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
            at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
            at System.Lazy`1.CreateValue()
            at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
            --- End of inner exception stack trace ---
            --- End of inner exception stack trace ---
            at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
            at NuGet.Protocol.LocalV3FindPackageByIdResource.GetDependencyInfoAsync(String id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesCoreAsync(LibraryIdentity match, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass21_0.<<GetDependenciesAsync>b__0>d.MoveNext()
         --- End of stack trace from previous location where exception was thrown ---
            at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesAsync(LibraryIdentity libraryIdentity, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.CreateGraphItemAsync(RemoteMatch match, NuGetFramework framework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
            at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity)
            at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
            at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
            at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
       Done executing task "RestoreTask" -- FAILED.
     1>Done building target "Restore" in project "MStoreBOSGatewayApi.csproj" -- FAILED.
     1>Done Building Project "/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target(s)) -- FAILED.

Build FAILED.

       "/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target) (1) ->
       (Restore target) ->
         /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
       /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:04.70
The command '/bin/sh -c dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" --verbosity detailed' returned a non-zero code: 1

C:\Applications\VB2017Apps\MStoreBOSGateway>


Q: Find "complete cases" with awk Using awk, how can I output the lines of a file that have all fields non-null without manually specifying each column?
foo.dat
A||B|X
A|A|1|
|1|2|W
A|A|A|B

Should return:
A|A|A|B

In this case we can do:
awk -F"|" -v OFS="|" '$1 != "" && $2 != "" && $3 != "" && $4 != "" { print }' foo.dat

But is there a way to do this without specifying each column?

A: You can loop over all fields and skip the record if any of the fields are empty:
$ awk -F'|' '{ for (i=1; i<=NF; ++i) { if (!$i) next } }1' foo.dat
A|A|A|B

if (!$i) is "if field i is not non-empty", and 1 is short for "print the line", but it is only hit if next was not executed for any of the fields of the current line.

A: Another in awk:
$ awk -F\| 'gsub(/[^|]+(\||$)/,"&")==NF' file
A|A|A|B

print record if there are NF times | terminating (non-empty, |-excluding) strings.

A: awk '!/\|\|/&&!/\|$/&&!/^\|/' file

A|A|A|B


Q: Prevent Popup template to shows multiple feature in ArcGIS 4.16 Angular 10 I have integrated a popup on the map for a specific layer. Some time the poup shows pagination (featureNavigation) multiple data. Sometimes it fails to show the data, or mismatch in the data that actually the service returns.
    var popupTrailheads = {
            title: "ID: {ID}",
            content: this.getcustomcontent.bind(this),
          };
          // Add layer special layer
          this.layer_fifteen = new FeatureLayer({
            url: `${this.esriURL}/15`,
            visible: true,
            outFields: ['*'],
            popupTemplate: popupTrailheads,
          });

     getcustomcontent(feature) {
    // The popup content will become here from angular service
return `<div>content</div>`;
    }

I have a few options to fix the issue.
1)Popup for this layer enables only at a specific Zoom level. Else the popup won't appear.
2)The click on the map should trigger only for a point. (I believe when click on the layer it triggers multiple points that is the reason it shows multiple feature details.)
Can you please suggest an idea, how to enable a popup in specific zoom level, or select only one feature in one click on the map.
Thanks in advance.

A: So, there are a number of possible ways to enable the popup under certain conditions, like the zoom level of the view.
In the example that I made for you popup only opens if zoom is greatest than 10.

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
  <title>PopupTemplate - Auto Open False</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css" />

Related to only display one result in the popup, you could hide the navigation like this,
view.popup.visibleElements.featureNavigation = false;
Now if what you actually want is to get only one result, then I suggest to use view method hitTest, that only gets the topmost result of the layers. You could do this after inside the click handler and only open if any result of desire layer. For this you need to set featFeatures: false, and set the features with the hit one.
Just as a comment it could result weird or confusing to the user retrieve just one of all possible features. I think probable you may have a problem with the content.


Q: A first-order differential equation A function $y=f(x)$ satisfies the first-order differential equation
$$y'(y-x+a)=b,\,\,\,x\in [0,1]$$
where $a\in (0,1)$ and $b>0$ are known constants.
It is more or less clear that the function has an affine solution $f(x)=x+(b-a)$, which is indeed the only affine function that satisfies the differential equation
However, it seems hard to pin down the general solution, which should be obtained in a systematic way rather than "guess-and-verify''. The special affine solution gives no hint for what the general solution should look like.
Can anyone give some suggestions/hints? Thanks~

A: After the change of variables
$$
u=y-x+a,\qquad u'=y'-1
$$
the equation becomes separable:
$$
(u'+1)u=b
$$
$$
u'=\frac{b}{u}-1
$$

A: Hint:
$$y'=\frac{1}{y-x+a}$$
Let $y-x+a=v \implies y'-1=v'$, then the ODE is
$$v'=2/v-1\implies \int \frac{vdv}{2-v}=\int dx+C$$

A: Hint:
$$y'(y-x+a)=b,\,\,\,x\in [0,1]$$
$$y-x+a=bx'$$
This is a first order linear DE.