text:
Q: Regarding hardware requirements for freeswitch I have a ubuntu 16.04 desktop version installed on 64 bit 4GB RAM, intel core i3 processor 2.13 GHz.
I need to install freeswitch for doing a small project. It will take only one call at a time. I tried looking up the hardware requirements for freeswitch on their wiki. But i am not able to find the hardware requirements.
Will freeswitch run fine on my laptop? Is there a page giving details about minimum  hardware requirements for freeswitch? Thanks.
Update: I got some more info on another website: Section Hardware and Software Requirements freeswitch versus asterisk

A: Min Requirement
System Tuning
Minimum/Recommended System Requirements:
32-bit OS (64-bit recommended)
512MB RAM (1GB recommended)
50MB of Disk Space
System requirements depend on your deployment needs.
If you just want group video calling feature then go for 1.6.x version, else just use only 1.4.x


text:
Q: What does Clojure's bit-and-not do? From the docs:

bit-and-not
function
Usage: (bit-and-not x y)
       (bit-and-not x y & more)

Bitwise and with complement

Added in Clojure version 1.0

Clojure's other bit- functions make sense to me, but I don't understand this one.

A: It is equivalent to this:
(bit-and x (bit-not y))
This function can be used to do subset tests. The set a (represented as a bitmask) is a subset of the set b if and only if (bit-and-not a b) is zero.

A: Interesting question. It looks like when your Clojure code is compiled to JVM bytecodes, calls to (bit-and-not) are converted to calls to clojure.lang.Numbers.andNot(), which looks like this:
static public long andNot(long x, long y){
     return x & ~y;
}

So perhaps this is for performance, if you need to do a bitwise AND with complement inside an inner loop?
The most common use case for a bitwise AND with complement is when you are working with bitmasks -- to clear all the bits in x which are set in y. Or perhaps there is some other reason why this is a particularly useful operation?

redpajama_set_name: RedPajamaStackExchange


text:
Q: GTK++ Window Confusion I am experimenting with GTK++ on Ubuntu and I'm not having much luck. Just for testing purposes, I wanted to see if I could get a Boolean describing whether or not a window is resizable. Here is my code:
  #include <gtkmm.h>
  #include <iostream>
  #include "config.h"

 int  main (int argc, char *argv[])
 {
    gboolean isResizable;
    Gtk::Main kit(argc, argv);

    Gtk::Window* main_win = new Gtk::Window (Gtk::WINDOW_TOPLEVEL);
    main_win->set_title ("gtk-test");
    isResizable = gtk_window_get_resizable(main_win);
    if (main_win)
    {
        kit.run(*main_win);
    }
    return 0;
 }

I am getting an error on the line where I set isResizable to gtk_window_get_resizable.
The error says:
    cannot convert 'Gtk::Window*' to GtkWindow* {aka_Gtk_window*} for argument 1

Is there a difference between Gtk::Window and GtkWindow* ? And if so, how would I go about passing in Gtk::Window ?
Thanks

A: Instread of:
gtk_window_get_resizable(main_win);

Call:
main_win->get_resizable();

Is there a difference between Gtk::Window and GtkWindow* ?

Gtk::Window ( and main_win->get_resizable() ) is C++ (gtkmm)
GtkWindow ( and gtk_window_get_resizable ) is C (gtk)
It's easy to cross the two, since gtkmm is a wrapper for gtk, so you have both codebases.


text:
Q: Doctrine isn't saving my entities? I have the following model, or as you call them entity, and I also have a controller, everything works in this action, but when I check the database there is no user. So I am curious as what I am missing. So lets start at the beginning as to what I have:
bootstrap.php contains the following code, among other things.
...
/** ---------------------------------------------------------------- **/
// Lets Setup Doctrine.
/** ---------------------------------------------------------------- **/
require_once 'vendor/autoload.php';

$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

/**
 * Set up Doctrine.
 */
class DoctrineSetup {

    /**
     * @var array $paths - where the entities live.
     */
    protected $paths = array(APP_MODELS);

    /**
     * @var bool $isDevMode - Are we considered "in development."
     */
    protected $isDevMode = false;

    /**
     * @var array $dbParams - The database paramters.
     */
    protected $dbParams = null;

    /**
     * Constructor to set some core values.
     */
    public function __construct(){
        if (!file_exists('db_config.ini')) {
            throw new \Exception(
                'Missing db_config.ini. You can create this from the db_config_sample.ini'
            );
        }

        $this->dbParams = array(
            'driver' => 'pdo_mysql',
            'user' => parse_ini_file('db_config.ini')['DB_USER'],
            'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
            'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
        );
    }

    /**
     * Get the entity manager for use through out the app.
     *
     * @return EntityManager
     */
    public function getEntityManager() {
        $config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
        return EntityManager::create($this->dbParams, $config);
    }
}

/**
 * Function that can be called through out the app.
 *
 * @return EntityManager
 */
function getEntityManager() {
    $ds = new DoctrineSetup();
    return $ds->getEntityManager();
}

/**
 * Function that returns the conection to the database.
 */
function getConnection() {
    $ds = new DoctrineSetup();
    return $ds->getEntityManager()->getConnection();
}
...

So now that we have doctrine set up its time to create a model (entity) and set which fields can and cannot be blank and so on and so forth.
Note At this point, you should know that I am not using Symfony other then its components on top of Doctrine. I am using Slim Framework. So if any suggestion is to use x or y from symfony, please make sure its a component.
Models/User.php
<?php

namespace ImageUploader\Models;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="users", uniqueConstraints={
 *   @ORM\UniqueConstraint(name="user", columns={"userName", "email"})}
 * )
 */
class User {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=32, nullable=false)
     * @Assert\NotBlank()
     */
    protected $firstName;

    /**
     * @ORM\Column(type="string", length=32, nullable=false)
     * @Assert\NotBlank()
     */
    protected $lastName;

    /**
     * @ORM\Column(type="string", length=100, unique=true, nullable=false)
     * @Assert\NotBlank(
     *    message = "Username cannot be blank"
     * )
     */
    protected $userName;

    /**
     * @ORM\Column(type="string", length=100, unique=true, nullable=false)
     * @Assert\NotBlank(
     *   message = "Email field cannot be blank."
     * )
     * @Assert\Email(
     *    message = "The email you entered is invalid.",
     *    checkMX = true
     * )
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=500, nullable=false)
     * @Assert\NotBlank(
     *  message = "The password field cannot be empty."
     * )
     */
    protected $password;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $created_at;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $updated_at;

    /**
     * Get the value of Created At
     *
     * @return mixed
     */
    public function getCreatedAt()
    {
        return $this->created_at;
    }

    /**
     * Set the value of Created At
     *
     * @param mixed created_at
     *
     * @return self
     */
    public function setCreatedAt(\DateTime $created_at = null)
    {
        $this->created_at = $created_at;

        return $this;
    }

    /**
     * Get the value of Updated At
     *
     * @return mixed
     */
    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    /**
     * Set the value of Updated At
     *
     * @param mixed updated_at
     *
     * @return self
     */
    public function setUpdatedAt(\DateTime $updated_at = null)
    {
        $this->updated_at = $updated_at;

        return $this;
    }

    /**
     * Get the value of First Name
     *
     * @return mixed
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set the value of First Name
     *
     * @param mixed firstName
     *
     * @return self
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get the value of Last Name
     *
     * @return mixed
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set the value of Last Name
     *
     * @param mixed lastName
     *
     * @return self
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get the value of User Name
     *
     * @return mixed
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * Set the value of User Name
     *
     * @param mixed userName
     *
     * @return self
     */
    public function setUserName($userName)
    {
        $this->userName = $userName;

        return $this;
    }

    /**
     * Get the value of Email
     *
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set the value of Email
     *
     * @param mixed email
     *
     * @return self
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Set ths password.
     *
     * @param string password
     *
     * @return self
     */
    public function setPassword($password) {
        $this->password = password_hash($password, PASSWORD_DEFAULT);
        return $this;
    }

    /**
     * Check the users password against that which is enterd.
     *
     * @param string password
     *
     * @return bool
     */
    public function checkPassword($password) {
        if (password_hash($password, PASSWORD_DEFAULT) === $this->getPassword()) {
            return true;
        }

        return false;
    }

    /**
     * Return the password value.
     *
     * @return hash
     */
    private function getPassword(){
        return $this->password;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAtTimeStamp() {
        if (is_null($this->getCreatedAt())) {
            $this->setCreatedAt(new \DateTime());
        }
    }

    /**
     * @ORM\PreUpdate
     */
    public function setUpdatedAtTimeStamp() {
        if (is_null($this->getUpdatedAt())) {
            $this->setUpdatedAt(new \DateTime());
        }
    }
}

The above model is correct, as far as I know, I mean when I run "vendor/bin/doctrine migrations:migrate" a database table is created.
Now, where is all this used? it's used in a controller called SignupController under an action called createAction($params)
**createAction($params)**
public static function createAction($params){
  $postParams = $params->request()->post();
  $flash = new Flash();

  if ($postParams['password'] !== $postParams['repassword']) {
    $flash->createFlash('error', 'Your passwords do not match.');
    self::$createEncryptedPostParams($postParams);
    $params->redirect('/signup/error');
  }

  $user = new User();

  $user->setFirstName($postParams['firstname'])
       ->setLastName($postParams['lastname'])
       ->setUserName($postParams['username'])
       ->setEmail($postParams['email'])
       ->setPassword($postParams['password'])
       ->setCreatedAtTimeStamp();

  $validator = Validator::createValidatorBuilder();
  $validator->enableAnnotationMapping();

  $errors = $validator->getValidator()->validate($user);

  if (count($errors) > 0) {
      foreach($errors as $error) {
        $flash->createFlash(
            $error->getPropertyPath() . 'error',
            $error->getMessage()
        );
    }

    self::createEncryptedPostParams($postParams);
    $params->redirect('/signup/error');
  }

  $anyEncryptedErors = self::getEncryptedPostParams();
  if ($anyEncryptedErors !== null) {
    $anyEncryptedErors->destroy('error');
  }

  getEntityManager()->flush();
  getEntityManager()->persist($user);

  $flash->createFlash('success', ' You have signed up successfully! Please sign in!');
  $params->redirect('/signin');
}

Now should you enter everything in correctly I show a flash of success and redirect you. THIS WORKS it redirects, it shows a flash message. But its the:
  getEntityManager()->flush();
  getEntityManager()->persist($user);

That I don't think is working. Why? Because doing a select * from users on the database in question comes back with no records.
Why?

A: Flush statement should be execute after persist. So Code should be:
getEntityManager()->persist($user);
getEntityManager()->flush();

A: I had a similar issue and thought I would post it here. I was creating an entity and everything was responding correctly, but when I checked the database no record had been created.
Just wrapped the flush in a try-catch and logged the error.
$this->em->persist($insectLifeCycle);
try {
    $this->em->flush();
} catch (\Exception $error) {
    $this->logger->debug($error);
}

It turns out that one of properties was exceeding its character limit and the database was throwing an error. Also found out I need to improve my error handling....

A: As Samiul Amin Shanto said:
getEntityManager()->persist($user);
getEntityManager()->flush();

will be correct way, because persist action prepare the data to be stored in DB and flush "Flushes all changes to now to the database."

A: If you have the object id and then, the database is not showing it, you might have a "START TRANSACTION" and then you have your insert, after this insert you will have a "COMMIT". If any error appears between your persist and the COMMIT, object won't be stored in your database.
Check your Symfony request profiler information.
You can find it using the developer tool and checking your response for it.


text:
Q: Reorganizar index do meu array Tenho dois cards na minha aplicação.
O primeiro card possui index 0, o segundo card possui index 1.
Existe uma variável chamada listAtributos que possui a seguinte estrutura:
0: {indexvariacaoatributo: 0, id: 5, tipovariacao: "Cor", valorvariacao: "Azul"}
1: {indexvariacaoatributo: 0, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}
2: {indexvariacaoatributo: 1, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"}
3: {indexvariacaoatributo: 1, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}

Existe uma relação entre o index do card e o indexvariacaoatributo, através dele são mostrados nos meus cards os itens.
Exemplo:
No card 0, por ter index 0, será mostrado através do ngfor os seguintes itens:
0: {indexvariacaoatributo: 0, id: 5, tipovariacao: "Cor", valorvariacao: "Azul"}
1: {indexvariacaoatributo: 0, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}

No card 1, por ter index 1, será mostrado através do meu ngfor, os seguintes itens:
2: {indexvariacaoatributo: 1, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"}
3: {indexvariacaoatributo: 1, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}

Em um determinado momento da minha aplicação eu preciso remover um desses cards, e é nesse momento que os index da minha variável listAtributos fica perdidos.
Tentei fazer um algoritmo para que quando é excluido um card, o indexvariacaoatributo seja atualizado para aparecer no card que sobrou.
Exemplo:
Se eu excluir o card 0, o indexvariacaoatributo dos que estavam 1 devem passar a ser 0.
Se eu excluir o card 1, o indexvariacaoatributo dos que estavam 0 deve passar a ser 1.
Tentei algo como:
for(let i=0;i<this.listAtributos.length;i++){
  if(this.listAtributos[i].indexvariacaoatributo == index){
    this.listAtributos[i].indexvariacaoatributo = index - 1;
  }
}

a variável index é recebida como parâmetro dessa função, é o index do card a ser excluido.

A: Vê se isso te atende. Essa função remove os elementos cujo o indexvariacaoatributo for igual ao parâmetro index passado e em seguida pega os elementos que possuem indexvariacaoatributo a frente do index removido e decrementa 1.
var array = [
    {indexvariacaoatributo: 0, id: 5, tipovariacao: "Cor", valorvariacao: "Azul"},
    {indexvariacaoatributo: 0, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"},
    {indexvariacaoatributo: 1, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"},
    {indexvariacaoatributo: 2, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}];

function remover(index, array) {

    let arrayElemRemovido = array.sort((v1, v2) => v1.indexvariacaoatributo > v2.indexvariacaoatributo)
                                 .filter(e => e.indexvariacaoatributo != index)
                                 .map(e => { if (e.indexvariacaoatributo > index) {
                                               e.indexvariacaoatributo -= 1;
                                             }

                                             return e;
                                     });
    // Reorganiza os índices para que o primeiro elemento do array seja sempre zero
    while(arrayElemRemovido.length > 0 && arrayElemRemovido.filter(v => v.indexvariacaoatributo == 0).length == 0) {
        arrayElemRemovido.map(v => { v.indexvariacaoatributo -= 1; return v });
    }

    return arrayElemRemovido;

}

var array = remover(0, array);
console.log(array);

/* Saída:
    0: {indexvariacaoatributo: 0, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"}
    1: {indexvariacaoatributo: 1, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}
*/

var array = remover(1, array);
console.log(array);

/* Saída:
    0: {indexvariacaoatributo: 0, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"}
*/

var array = [
    {indexvariacaoatributo: 1, id: 5, tipovariacao: "Cor", valorvariacao: "Azul"},
    {indexvariacaoatributo: 2, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"},
    {indexvariacaoatributo: 1, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"},
    {indexvariacaoatributo: 2, id: 7, tipovariacao: "Tamanho", valorvariacao: "P"}];

var array = remover(2, array);
console.log(array);

/* Saída:
    0: {indexvariacaoatributo: 0, id: 5, tipovariacao: "Cor", valorvariacao: "Azul"}
    1: {indexvariacaoatributo: 0, id: 6, tipovariacao: "Cor", valorvariacao: "Amarelo"}
*/


text:
Q: Prisma findMany() - Ordering by count orders 0 count as positive infinity I am trying to findMany() users and orderBy their post count. I found exactly how to do it in the docs and it works except it counts users with 0 posts as +infinity.  orderBy: {posts: {count: asc}}
For example, the ordering works in ascending starting with users with 1 post up until the users with a lot of posts, but the last users have 0 posts. Vice versa when descending.
I am using postgres as the provider, I really don't know how to even google for this problem, and title this question. Please help.
model User {
  id     Int    @id @default(autoincrement())
  posts  Post[]
}

model Post {
  id      Int   @id @default(autoincrement())
  user    User  @relation(fields: [userID], references: [id])
  userID  Int
}

  await prisma.user.findMany({
    orderBy: {
      posts: {
        count: 'desc',
      },
    },
  });

Output of a small test in descending order. You can see the post count is ordered 0 2 1 (in ascending order its output order is 1 2 0):
[
  { id: 3, _count: { posts: 0 } },
  { id: 1, _count: { posts: 2 } },
  { id: 2, _count: { posts: 1 } }
]


text:
Q: How do I create a google form template using google script? I have created a google form which I would like to convert to a template. The objective is to to distribute this template to other people so they can amend the form as they see fit. I also need these amended forms to sit inside a directory in the google drive.
How can I construct a google script to convert the original form into a template?
Thus far I have
var form = FormApp.openById('asdfasdfasdfasdfasdfasdfFORMIDGOESHEREfasdfasdfa');

I am stuck on how to take this form and now convert it to a template.

A: If you want to get the whole form and then transform it into a template to modify it at will, it is not feasible. But instead, if you want to get certain elements and modify them or create a new form using Apps Script you can check the Class Form, which gives you several methods that will allow you to insert or removes elements.


text:
Q: How to delete default themes Is it possible to delete the default Themes (Twenty Eleven, Twenty Twelve, Twenty Thirteen …) automatically … or - even better - disable the automatic re-installation on when updating WordPress?
I've read this question and i know that many consider it useful to have at least on of this themes. But i never used one of these and just want them gone ;)

A: The best thing you can do to "automate" the process to delete themes is to use WP-CLI, namely the delete command. like so:
$ wp theme delete twentytwelve

A: My approach is to delete the default themes using ftp or your control panel file-manager once you have your site up and running.
These themes will not be re-installed when you update Wordpress, and will not show up in your update notifications.
I usually keep the TwentySixteen theme on the system as this is the fallback theme in case you have problems with your installed theme.


text:
Q: Finding $\lim_{n\rightarrow \infty}\sum^{n}_{r=1}\frac{1}{f(r)g(r)}$
If $f,g:\mathbb{N}\rightarrow \mathbb{N}$ are defined as $f(n)=\{$ smallest prime $>n+1\}$
  and $g(n)=\{$ greatest prime $\leq n+1\}.$ Then $\displaystyle \lim_{n\rightarrow \infty}\sum^{n}_{r=1}\frac{1}{f(r)g(r)}$

Try: $\displaystyle \lim_{n\rightarrow \infty}\sum^{n}_{r=1}\frac{1}{f(r)g(r)}=\lim_{n\rightarrow \infty}\bigg[\frac{1}{f(1)g(1)}+\frac{1}{f(2)g(2)}+\cdots +\frac{1}{f(n)g(n)}\bigg]$
Could some help me to solve it, thanks

A: Let $p_k$ be the $k^{th}$ prime.
The key is we can partition the integers $\ge 2$ into a disjoint union of intervals of the form $[p_k,p_{k+1}-1]$ and whenever $n + 1 \in [p_k,p_{k+1} - 1]$, we have
$f(n) = p_{k+1}$ and $g(n) = p_{k}$.
This leads to
$$\sum_{n=1}^\infty \frac{1}{f(n)g(n)}
= \sum_{k=1}^\infty \sum_{p_k \le n+1 < p_{k+1}} \frac{1}{p_{k+1} p_k}
= \sum_{k=1}^\infty \frac{p_{k+1}-p_k}{p_{k+1}p_k}\\
= \sum_{k=1}^\infty\left(\frac{1}{p_k} - \frac{1}{p_{k+1}}\right)
= \frac{1}{p_1} - \lim_{k\to\infty} \frac{1}{p_{k+1}}
= \frac12$$


text:
Q: syslog-ng viewer that can display many log files of different IDS I have three Intrusion detection systems installed (snort, modsecurity,ossec) and I want to visualize the generated log files of these IDS.
Is there a Graphical User Interface that can display the log files?
Thanks,

A: ELSA has parsers for many IDS, firewall etc. log messages and can create nice visualizations: https://github.com/mcholste/elsa
Actually there is also an Ubuntu based security distro which has all of these integrated: https://security-onion-solutions.github.io/security-onion/


text:
Q: how to get top 2 values for specific year from a dataframe? I would like to obtain the top 2 values for specific year, but the following code doesn't work:
library(tidyverse)
mpg
mpg %>% group_by(year, class, model) %>% summarize (n= n()) %>% top_n(2)

How can I modify my code?

A: To print and understand the "top n", it's better first to arrange your data in ascending or descending order according to n, but maybe your problem is that (it's not 100% clear in your question) you have to specify for which tuple you want top n, just top 2 by {year}, or by {year,class} ?
In your code you have top 2 for each {year, class} depending if dplyr ungroup the last grouping variable after summarise.
Another thing to consider is: if there are multiple car with same n value in the top 2, they all will be keepted by top n, not just the top 2.
By year like this with slice_max
mpg %>%
  group_by(year, class, model) %>%
  summarize (n= n()) %>%
  arrange(year, desc(n)) %>%
  group_by(year) %>%
  slice_max(n, n = 2)

# Groups:   year [2]
   year class      model                   n
  <int> <chr>      <chr>               <int>
1  1999 minivan    caravan 2wd             6
2  1999 compact    jetta                   5
3  1999 pickup     f150 pickup 4wd         5
4  1999 subcompact civic                   5
5  2008 pickup     ram 1500 pickup 4wd     7
6  2008 suv        grand cherokee 4wd      6


text:
Q: Discovering API Limits via Custom APEX Rest API According to the documentation, the Salesforce REST API returns a Limit Info Header with each request. So each REST API call gets a Sforce-Limit-Info: api-usage=18/5000 line returned in the response header.
When I make a call to a custom Apex REST API endpoint, this header is not automatically included in the response. The only other way I can find to programmatically determine the limit for an organization is to ping the /limits REST endpoint. But, according to a SF employee:

This feature is still in pilot mode, and just "might" become generally
  available with the winter 15 release (november).

So if Sforce-Limit-Info isn't being returned in the header, and /limits endpoint isn't in production yet, how can my custom APEX REST endpoint programmatically determine the limits for the authorized organization today, and, how many requests have been made towards those limits?
It doesn't solve the issue, but what would be great/helpful is if Salesforce added a daily_limit return parameter to the OAuth connection so you at least know the organizations max daily usage at the time you authorize them.

A: Well, you could make a Force.com REST call after your custom call. Something like a trivial select. This is not an efficient solution. It will increase the speed at which you use up calls and will slow down whatever is consuming this info as it now needs to call your custom endpoint, then this trivial one as well. I will continue to research since this is a bucket of nope but it does get you the information you are looking for.

A: I would create a static method which puts all needed information to header.
RestContext.response.addHeader(REST_Manager.ERROR_MESSAGE_HEADER_NAME, errorMessage);

In this way you can put all needed limits.
RestContext.response.addHeader(CIO_REST_Toolbox.DML_STATEMENTS_HEADER_NAME, Limits.getDMLStatements());

And then extract values on your application by getting data from response header.
This method can be included in needed REST services in the end of the REST method.
Edit.
Please, check this API Usage Limits. Particularly, I'm referring to

You can configure your organization so that email is sent to a designated user when the number of API requests has exceeded a specified percentage of the limit. You can perform this configuration in from Setup by clicking Monitoring | API Usage Notifications.

I totally understand, that this is not what you wanted; but this is the only way right to be notified about API Limits.


text:
Q: How to send real time sensor data from the Samsung Galaxy Note 3 to the Galaxy Gear? I have connected a Wireless sensor network to the Samsung Galaxy Note 3 via an OTG cable and I am tracking the real time sensor data on the phone.
Will it be possible to see this data on the Galaxy Gear? What should I do to see this data on the Gear?
I tried opening a Bluetooth socket connection using Eclipse but I am not successful in sending/receiving data. Is this the right approach or should I use the Samsung SDK for this?


text:
Q: How can I programmatically trigger an event with PySimpleGUI? For example, the "Show" event in the example below is tied to clicking the "Show" button. Is there a way to programmatically fire off the "Show" event without actually clicking the button? The goal is to automate clicking a series of buttons and filling text boxes by just clicking one other button instead, like a browser autofill.
import PySimpleGUI as sg

sg.theme("BluePurple")

layout = [
    [sg.Text("Your typed chars appear here:"), sg.Text(size=(15, 1), key="-OUTPUT-")],
    [sg.Input(key="-IN-")],
    [sg.Button("Show"), sg.Button("Exit")],
]

window = sg.Window("Pattern 2B", layout)

while True:  # Event Loop
    event, values = window.read()
    print(event, values)
    if event == sg.WIN_CLOSED or event == "Exit":
        break
    if event == "Show":
        # Update the "output" text element to be the value of "input" element
        window["-OUTPUT-"].update(values["-IN-"])

window.close()

A: From martineau's comment above:

You can generate a click of the button as if the user clicked on it by calling its click() method. See the docs.

Aditionally, you can fire a specific event with:
write_event_value(key, value)


text: Q: Android Amplify connection drop listener I am uploading a file using Amplify.Storage.uploadFile(). The problem is when the internet connection drops, the uploadFile method hangs so I don't have a way to figure it out and to re-upload the file. I saw https://github.com/aws-amplify/amplify-android/issues/1419 but there is no clear way to overcome the problem. Can someone provide a clear path to fix it, other then monitor the progress?


text:
Q: Adding keys to a dict gives TypeError: 'str' object does not support item assignment I'm trying to edit a YAML file with my own variables.
This is my YAML template that I'm editing:
Mappings:
  PrivateLink:
    EndPointService:
      EndPointService: hostname1
      PrincipalName: ""
  NLBName:
    NLBName:
      Name: hostname1
  TargetName:
    hostname1-22:
      Name: hostname1-22
      VpcId: vpc-123
      Id: "i-123"

My goal is to loop over a list port numbers I have and use them to create new Target Groups.
For example, if my ports list is [22, 80, 443], the output YAML will look like this:
Mappings:
  PrivateLink:
    EndPointService:
      EndPointService: hostname1
      PrincipalName: ""
  NLBName:
    NLBName:
      Name: hostname1
  TargetName:
    #Editing is done here
    hostname1-22:
      Name: hostname1-22
      VpcId: vpc-123
      Id: "i-123"
    hostname1-80:
      Name: hostname1-80
      VpcId: vpc-123
      Id: "i-123"
    hostname1-443:
      Name: hostname1-443
      VpcId: vpc-123
      Id: "i-123"

So for my function looks like this:
def editEndpointServiceTemplate(endpoint_service_template_path):
    yaml = YAML()
    yaml.indent(mapping=3)
    ports_list = ast.literal_eval(configParser.get("Ports", "Ports"))

    #Load yaml file
    with open(endpoint_service_template_path) as fp:
        data = yaml.load(fp)

    for i in range(0, len(ports_list)):
        tg_name = service_name + "-" + str(ports_list[i])
        data['Mappings']['TargetName'][tg_name] = None
        data['Mappings']['TargetName'][tg_name]['Name'] = "test"

    #Write new yaml file
    with open(endpoint_service_template_path, 'w') as fp:
        yaml.dump(data, fp)

I'm failing on this error:
data['Mappings']['TargetName'][tg_name]['Name'] = "test"
TypeError: 'str' object does not support item assignment

I guess I can't access a key I just created for some reason but I'm not sure how to fix this.

A: Fixed it by changing:
data['Mappings']['TargetName'][tg_name] = None

To this:
data['Mappings']['TargetName'][tg_name] = {}

Now it's fixed. Guess I had to set it to a dict object.


text:
Q: WAN port 1 is for internet but it's IPv6. Will a device that is not IPv6 compatible be affected if I connect to this port? Encapsulation mode: PPPoE,
Protocol type: IPv6,
WAN mode: Route WAN,
Service type: Internet.
WAN port 1 is for internet but it's IPv6. I have a device that is not compatible with IPv6. Will it be affected?
Should I call my ISP to change the protocol to IPv4 or just ignore it?

A: You should be able to use IPv4 and IPv6 simultaneously. Nothing about IPv6 prevents IPv4 from working and, in fact, IPv6 specifically makes allowances for converting IPv4 addresses to IPv6 address syntax.
That said, newer OSes default to trying to communicate via IPv6 anytime it appears to be available and if your isp does not fully and properly have IPv6 implemented this can cause your computer to assume the sites you are looking for don't exist... rather than they simply aren't reachable via IPv6. You OS likely provides a means of forcing the use of IPv4 regardless of detected IPv6 support.
In windows, you would simply disable the TCP/IPv6 module for the network adapter in question. For Ubuntu (and likely other Debian-based Linux distros) there is a setting you can change in a file in /etc to tell the OS to prefer IPv4 over IPv6.


text:
Q: Does voltage drop with discharge? Does voltage drop with discharge? Since voltage is the potentiality between two charges to re-balance (from my understanding).
I mean, once all charges are equally shared between both capacitor sides, there is no potentiality between the charges to re-balance since they are now balanced.

*

*Can we tell that voltage drops when a capacitor discharges?

*If yes, does this mean that my 9V lithium battery
loses voltage while being used?

*That would also mean that a LED would lose brightness over time, is that the case?

A: To answer your questions:

*

*Correct, as you discharge a capacitor the voltage drops. This is due to the relationship of \$Q = VC\$ - the charge stored in a capacitor is proportional to the voltage for a given capacitance. As you discharge the capacitor, the charge on the capacitor is reduced, and so the voltage reduces.
However this has nothing to do with batteries.

*A battery terminal voltage will drop as you discharge it, mainly because the chemical reactions slow down due to depletion.
This is nothing to do with the principal of capacitance.
At its simplest, you can think of a battery as an ideal voltage source, and a series resistor. As you discharge the battery, the reactions slow down, which increases the value of the representative series resistance. As a result for the same load, the terminal voltage will drop (see also: potential dividers).
However in practice it is much more complex. For one there is no such thing as an ideal voltage source. The change in terminal voltage is also not linear. It depends on the chemistry of the battery, and also the current draw.
Here is an example Lithium Primary 9V PP3 battery, the discharge curve for which is shown below:

Notice how the voltage varies over time, and in a non-linear nor exponential fashion. This is very different to how a capacitor would discharge (exponential decay).

*For a simple LED circuit, you would have a resistor in series with your LED. If you decrease the voltage across the circuit (regardless of whether you use a battery, a capacitor, or other power supply), you will reduce the current flow. Therefore you reduce brightness of the LED as the battery discharges.
If however your LED circuit used, say, a DC-DC converter rather than (or in addition to) a series resistor, you may find that the converter will keep the LED voltage constant as the input voltage varies. As a result the brightness stays constant even as the battery discharges. At some point the battery voltage would be too low for the DC-DC converter, and switch off, turning the LED off. Basically you end up with constant brightness until it turns off.


text:
Q: Obter o array mais interno de array multidimensional Tenho o seguinte json
{
  "data": {
    "card": {
      "current_phase": {
        "id": "3134719",
        "name": "Phase Final"
      },
      "child_relations": [
        {
          "cards": [
            {
              "id": "6405893",
              "current_phase": {
                "id": "3147728",
                "name": "Concluído 2"
              },
              "child_relations": [
                {
                  "pipe": {
                    "id": "458138"
                  },
                  "name": "Pipe 3 Conexão",
                  "cards": [
                    {
                      "id": "6407049",
                      "current_phase": {
                        "id": "3151152",
                        "name": "pipe 3 phase 1"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  }
}

Preciso obter sempre o array mais interno ( oque esta mais para dentro ), neste caso seria:
"current_phase": {
   "id": "3151152",
   "name": "pipe 3 phase 1"
}

Eu ja tentei varias coisas,como a função end etc, o mais proximo que cheguei foi isso com array_column:
  $resultarray = json_decode($response, true);
  // print_r($resultarray);
  $current_phase = array_column($resultarray['data'], 'current_phase');
  print_r($current_phase);
  die();
  /*

  Array
  (
    [0] => Array
    (
      [id] => 3134719
      [name] => Phase Final
    )
  )

  */

--
Usando array_walk_recursive foi o mais proximo que cheguei do que preciso:
array_walk_recursive($resultarray, function($item, $key) {
    echo "$key holds $item\n";
  });

Retorno:
    title holds 9YEOCC
id holds 3134719
name holds Phase Final
name holds Pipe 2 Conexao
id holds 6405893
id holds 3147728
name holds Concluído 2
id holds 458138
name holds Pipe 3 Conexão
id holds 6407049
id holds 3151152
name holds pipe 3 phase 1

A: Tente este código (a variável $json deve conter sua string literal conforme seu post):
$nivel = 0;
$nivelMax = 0;
$posLim = 0;
for ($i = 0; $i < strlen ($json); $i++) {
    $car = substr($json, $i, 1);
    if ($car == '{') {
        $nivel++;
        if ($nivel > $nivelMax) {
            $nivelMax = $nivel;
            $posIniNivelMax = $i;
        }
    }
    if ($car == '}') {
        if ($nivel == $nivelMax)
            $posFimNivelMax = $i;
        $nivel--;
    }
    if ($car == ',') {
        $posLimAnt = $posLim;
        $posLim = $i;
    }
};
echo substr($json, $posLimAnt+1, $posFimNivelMax - $posLimAnt + 1) . '<br>';

Mostrará:
 "current_phase": {
    "id": "3151152",
     "name": "pipe 3 phase 1"
 }

Confira também o resultado no Ideone.com


text:
Q: Executing 1000+ pages/min in a browser environment How would I go about downloading and executing (i.e evaluate Javascript, build DOM) in excess of 1000 XHTML documents per minute?
Some outlines/constraints:

*

*URLs to be downloaded are on different servers.

*I need to traverse - and ideally modify the resulting DOM.

*No interest in rendering the graphics.

*Bandwidth is not an issue.

*Overly massive hardware parallelization would be more of a problem.

*Production enviroment is .NET.

I am not so concerned about downloading the pages. I estimate that actually excuting the page is a bottleneck. .NET has a built in Web Browser object but I have no idea if it would scale up on a single machine. Also, .NET is not an absolute requirement but it would make integration around here easier.
I'd be grateful for any comments/pointers regarding:

*

*Which browser API is most suited to do this?

*Is a browser the right way to go - maybe there's a more lightweight way to execute the Javascript which is the most important part (... but does not provide a DOM)?

*What existing products/services - be they open source or commerical - may accomplish the task?

*Roughly how many pages per minute I can expect to handle on a single machine (3ms Chrome rendering commercial anyone)?

*Any pitfalls one is likely to encounter...

Thank you in advance,
/David

A: Look at one of the headless browsers for .NET - they will be faster than the BrowserControl as they don't need to render a graphical view.
I don't know if this will allow you to execute 1000 pages per minute, but should be much faster than the control.
Here is one.
Here is a blog post about using HtmlUnit as a headless browser.
And an SO question about headless browsers.

A: I have an application that is implemented in WinForms that processes ~7,800 URLs in approximately 5 minutes (downloads the URL, parses the content, looks for specific pieces of data and if it finds what its looking for does some additional processing on that page.
This specific application used to take between 26 to 30 minutes to run, but by changing the code to the TPL (Task Parallel Library in .NET v4.0) it executes in just 5.  The computer is a Dell T7500 workstation with dual quad core Xeon processors (3 GHz), running with 24 GB of RAM, and Windows 7 Ultimate 64-bit edition.
I simply use WebClient, Stream, and StreamReader objects within a Parallel.ForEach() loop, and it's extremely fast.
Probably not the exact solution you're looking for, but unlike most of the other postings I see here this actualy does "process 1,000 pages / minute" [and more].
Food for thought ...

A: I think node.js can do a lot of what you want and do it fast if you are not married to the .net solution. It definitly has a dom implementation.


text:
Q: Give input to stdio in gdb with python I want to debug app with gdb which gets two inputs from stdin, to understand my situation, This is example program which i want to debug.

*

*Program prints something like "Hello world", then asks for input.

*from python script, inputs 5 to stdin. ( This is static )

*The program prints "123"

*The python script inputs "123" ( inputs what program printed )

*Program exits


text:
Q: How to calculate the number of times a particular letter is typed on a cell in Excel? I know the title looks enormous but I don't know how to put the title to the question I want to ask.
Ok, basically this is what I have so far:
On the spreadsheet I a column asking a question and the you fill up the row and according what you have there you have to put a Y (yes) or N (no).
On the end of the month we need to know how many Y (yes) we have, I need to do this manually. I was wondering, if there is a way to use a separate cell to count how many Y's we have on that column?
If someone could help on that I will very much appreciate.

A: This is completely possible. Depending upon which version of Excel you're using (2007 and later should work), try pressing Functions, and then choose AddCount, which counts the amount of something in a certain space.
If this does not work for you, you can also create drop-down menus inside of the Data Validation feature of Excel.
If you're making a form these two options will work.

A: If you have a column (say column A) containing either Y or N,  then in a cell outside that column enter:
=COUNTIF(A:A,"y")

This will perform the counting and will count either upper case or lower case letters.

A: Select the excel cell where you want the output. Then go to function box and type =COUNTIF(CL1:CL100,"Y")
where CL1 is your stating column Index and
CL100 is your last column index till where you want to search.


text:
Q: How do I run a dockerized 'Hello World' web job deployed into Virtual Kubelet within Azure Kubernetes Service (AKS) I did create a simple 'Hello World' Web Job and placed that Web Job inside a Docker Windows Container/Nanoserver
I did push that Docker Windows Container into an Azure Container Registry
I did follow this article and successfully created Virtual AKS pods/nodes
When I run 'get pods' I do see the pods created and running
I do see IP's generated reflected in the 'get pods' command
My question is how do I run the container inside these pods/nodes?
I did try to reference the IP's but those IP's don't load anything
How can I run those containers that I successfully placed into Virtual Kubelet pods/nodes
If the containers in the get fired up by themselves, do they fire up/get invoked only once or every n number of minutes?
Is there a way to check on how the last run went, like log files?
Thank you very much for your help

A: First of all, I see you create your web job inside a Windows-based Docker. If so, you cannot run the container in the AKS while it does not support Windows nodes, at least current. For window container, I suggest you could use the Azure Container Instance or Web App for Container.
For Linux containers, the pod in AKS is a group of one or more containers (such as Docker containers), with shared storage/network, and a specification for how to run the containers. If you already have the Docker image, you can create the container inside the pod follow the steps in Running the application in AKS.
In addition, you can set the restart policy for your container. See Restart Policy for the container in Kubernetes. For the logs, I suggest you could use the persist volumes. If not, the files will be lost if the container crash.\
Update
If you really want to run windows container in AKS cluster, there is also a way for you. You can use the virtual Kubelet and Azure Container Instance in AKS. Follow the steps Run Windows container in AKS.


text:
Q: How to display scrollbar in UITableView I want to display some kind of indication to guide user to scroll.
Usually when we touch the UITableView scrollbar appears if needed. But I want this scrollbar indication already displayed on my tableview.
How is it possible to do so?

A: If you have a table view that goes offscreen, you can call
[self.tableView flashScrollIndicators];
and they will flash to show the user that they are there. This is usually put in viewDidAppear.
(If you inherit from UITableViewController then you will have a self.tableView instance variable, if not then substitute another UITableView.)
If you a scroll view's entire contents fit within its view then no scroll bars are displayed; to test this display a table view with only one cell. If the content size is larger than the view's frame then scroll bars will be displayed; only then will [self.tableView flashScrollIndicators]; actually flash scroll indicators.

A: There's no way to force the scrollbar to appear, short of messing with the internals of UITableView(which you shouldn't do), or redesigning your own table view class.
Per the documentation of UIScrollView's showsVerticalScrollIndicator property: "The indicator is visible while tracking is underway and fades out after tracking."


text:
Q: kartik datepicker Yii2 Bootstrap 4
use kartik\field\FieldRange;
use kartik\form\ActiveForm;
use kartik\datecontrol\DateControl;

                        Create new budget

                    <?php $form = ActiveForm::begin(['options' => ['class' => 'user mt-5']]); ?>
                    <?= $form->field($model, 'name')->textInput(['style' => 'height: 50px; border-radius: 10rem;', 'class' => 'form-control', 'placeholder' => 'Budget name'])->label(false); ?>
                    <?= $form->field($model, 'amount')->input('number', ['style' => 'height: 50px; border-radius: 10rem;', 'class' => ' form-control mb-4', 'step' => '0.01',  'placeholder' => 'Amount'])->label(false); ?>
                    <?= $form->field($model, 'wallet')->dropDownList($wItems, ['prompt' => 'Select wallet', 'style' => 'height:50px; border-radius: 10rem;', 'class' => 'custom-select'])->label(false); ?>
                    <?= FieldRange::widget([
                        'form' => $form,
                        'model' => $model,
                        'label' => 'Enter date range',
                        'attribute1' => 'date_start',
                        'attribute2' => 'date_end',
                        'type' => FieldRange::INPUT_WIDGET,
                        'widgetClass' => DateControl::class,
                        'widgetOptions1' => [
                            'saveFormat' => 'php:U'
                        ],
                        'widgetOptions2' => [
                            'saveFormat' => 'php:U'
                        ],
                    ]);?>

                        <?= Html::submitButton('', ['class' => 'btn fa fa-check fa-lg mt-2']) ?>

                    <?php ActiveForm::end(); ?>

Не работает выбор дат, получается вот так

Также выбрать дату не получается, почему-то таблица с выбором просто не появляется (только края, видно на 2 скриншоте)

A: Можно использовать другой datapicker. Загрузите в composer
"moonlandsoft/bootui-datetimepicker": "*"
В форме выглядит так:

use bootui\datetimepicker\Datepicker;

<?= $form->field($model, 'birthdate')->widget(DatePicker::className(), [
           'options' => ['class' => 'form-control'],
           'daysOfWeekDisabled' => [0-6],
           'pluginOptions' => [
               'dateFormat'=> date('Y-m-d'),
               'defaultDate' => $model->birthdate,
               'autoClose' => true,
               'format' => 'yyyy-mm-dd',
               'firstday'=>1,
           ],
       ]);?>

Могу поискать еще решения, поскольку для меня пока еще актуальна эта тема.


text:
Q: Advanced symbol-macrolet Suppose I have a class class with slots first and second. Inside my function I can bind a variable to one of those slots like
(symbol-macrolet ((var (first cls)))
 ....)

Obviously I can also bind the second slot to smth.
Questions is, let's say that first and second are either some number or nil. Let's also say that if second is non-nil, first is always nil. Now, can I bind my var to a non-nil one with just one macro? So it just looks at instance of the class given and then check if second is nil. If no, it binds var to second, otherwise to first.
Seems complicated, but I'm pretty sure it can be done, just don't know where to start.
To further generalize -- is it possible to bond a variable not to a single place, but to one of a specific set, depending on some state?

A: I think this is not quite simple.  You could do something like this which works for reading only (I've used a fake toy structure so my code works, which is given here):
(defstruct toy
  (first nil)
  (second nil))

(defun foo (a-toy)
  (symbol-macrolet ((x (or (toy-first a-toy) (toy-second a-toy))))
    ...))

But now (setf x ...) is horribly illegal.  You can get around this, once you've decided what (setf x ...) should do, by defining some local functions.  I've decided here that it should set the non-nil slot, as that makes sense to me.
(defun bar (a-toy)
  (flet ((toy-slot (the-toy)
           (or (toy-first the-toy) (toy-second the-toy)))
         ((setf toy-slot) (new the-toy)
           (if (toy-first the-toy)
               (setf (toy-first the-toy) new)
             (setf (toy-second the-toy) new))))
    (symbol-macrolet ((x (toy-slot a-toy)))
      (setf x 2)
      a-toy)))

And now you can wrap this all in a single macro:
(defmacro binding-toy-slot ((x toy) &body forms)
  (let ((tsn (make-symbol "TOY-SLOT")))
    `(flet ((,tsn (the-toy)
              (or (toy-first the-toy) (toy-second the-toy)))
             ((setf ,tsn) (new the-toy)
               (if (toy-first the-toy)
                   (setf (toy-first the-toy) new)
                 (setf (toy-second the-toy) new))))
       (symbol-macrolet ((,x (,tsn ,toy)))
         ,@forms))))

(defun bar (a-toy)
  (binding-toy-slot (x a-toy)
    (setf x 3)
    a-toy))

Obviously you might want to generalise binding-toy-slot, so it, for instance, takes a list of slot accessor names or something like that.
There may also be better ways of doing this I haven't thought of: there might be clever tricks with setf-expansions that let you do it without the little helper functions.  You could also have global helper functions which get passed an object and a list of accessors to try which would make the code slightly smaller (although you can probably achieve similarly small code in any serious implementation by declaring the helpers inline which should cause them to be completely compiled away).

An alternative, and perhaps better, approach, is to define the protocol you want to achieve using generic functions.  This means things are defined globally, and it's related to but not quite the same as Kaz's answer.
So again, let's say I have some class (this can be a structure, but making it a fully-fledged standard-class lets us have unbound slots, which is nice):
(defclass toy ()
  ((first :initarg :first)
   (second :initarg :second)))

Now you could either define generic functions with names like appropriate-slot-value & (setf appropriate-slot-value), or you could define GF which returns the name of the appropriate slot, like so:
(define-condition no-appropriate-slot (unbound-slot)
  ;; this is not the right place in the condition heirarchy probably
  ()
  (:report "no appropriate slot was bound"))

(defgeneric appropriate-slot-name (object &key for)
  (:method :around (object &key (for ':read))
   (call-next-method object :for for)))

(defmethod appropriate-slot-name ((object toy) &key for)
  (let ((found (find-if (lambda (slot)
                          (slot-boundp object slot))
                        '(first second))))
    (ecase for
      ((:read)
       (unless found
         (error 'no-appropriate-slot :name '(first second) :instance object))
       found)
      ((:write)
       (or found 'first)))))

And now the accessor function pair can be plain functions which will work for any class where there is a method for appropriate-slot-name:
(defun appropriate-slot-value (object)
  (slot-value object (appropriate-slot-name object :for ':read)))

(defun (setf appropriate-slot-value) (new object)
  ;; set the bound slot, or the first slot
  (setf (slot-value object (appropriate-slot-name object :for ':write)) new))

Finally, we can now have functions which just use symbol-macrolet in the obvious way:
(defun foo (something)
  (symbol-macrolet ((s (appropriate-slot-value something)))
    ... s ... (setf s ...) ...))

So, that's another approach.

A: Simple, inefficient way with defsetf:
(defun second-or-first (list)
  (or (second list) (first list)))

(defun set-second-or-first (list val)
  (if (second list)
    (setf (second list) val)
    (setf (first list) val)))

(defsetf second-or-first set-second-or-first)

(defun test ()
  (let ((list (list nil nil)))
    (symbol-macrolet ((sof (second-or-first list)))
      (flet ((prn ()
               (prin1 list) (terpri)
               (prin1 sof) (terpri)))
        (prn)
        (setf sof 0)
        (prn)
        (setf sof 1)
        (prn)
        (setf (second list) 3)
        (prn)
        (setf sof nil)
        (prn)
        (setf sof nil)
        (prn)))))

If it is okay that update expressions like (incf sof) wastefully traverse the structure twice, this is adequate.
Otherwise a more sophisticated implementation is required using  define-setf-expander. The gist of such a solution is that the generated code has to calculate which of the two cons cells of the list holds the current place, storing that cons cell in a temporary variable #:temp. Then the place we are interested in is denoted by (car #:temp).  If #:temp is the second cell, avoiding two accesses to are tricky (one access to determine it's the one we want, then the other to get the prior value).  Basically what we can do is have another temp variable which holds the value of the place that we obtained as a side effect of checking whether it is not nil. Then designate that temporary variable as the access form for getting the prior value.

A: Here's how you might not use symbol macros without any huge loss:
(defgeneric firsty-secondy (thing))
(defgeneric (setf firsty-secondy) (newval thing))
(defmethod firsty-secondy ((x my-class))
  (or (secondy x) (firsty x)))
(defmethod (setf firsty-secondy) (nv (x my-class))
  (if (secondy x)
      (setf (secondy x) nv)
      (setf (firsty x) nv)))

You may find that the compiler does better with these because within the methods it can be more sure about where the slots for the fields are in memory.
Here is a way to structure your object to not need to do this and enforce your invariant a bit better:
(defclass my-class
  ((is-first :initform nil)
   (thingy :initform nil)))

Here is a comparison:
first=nil,second=nil  :  is-first=nil,thingy=nil
first=123,second=nil  :  is-first=t  ,thingy=123
first=nil,second=123  :  is-first=nil,thingy=123
first=123,second=456  : unrepresentable


text:
Q: Golang: Wait x amount of time before looping again without starting new goroutine I have a loop that needs to wait a random amount of time before looping again.
What I have:
for {
    rand.Seed(time.Now().UnixNano())
    r := rand.Int()
    //Do stuff
    t, _ := time.ParseDuration(string(r) + "ms")
    time.Sleep(t)
}

Unfortunately, the loops run multiple times, just like if time.Sleep was not working.

A: You should check the error you are currently discarding from t, _ := time.ParseDuration: the time.Duration you are passing to Sleep is in its zero value, which causes the function to sleep for 0 nanoseconds.
Change #1: handle the error
    t, err := time.ParseDuration(string(r) + "ms")
    if err != nil {
        log.Println(err)
        return
    }

Resulting in:
time: invalid duration �ms
Since you are directly casting an integer to a string, you are messing with a whole lot of unicode logic you don't really want to.
Change #2: use strconv:
    t, err := time.ParseDuration(strconv.Itoa(r) + "ms")
    if err != nil {
        log.Println(err)
        return
    }

Result:
time: invalid duration 7936209096285811603ms
You get this error because time.Duration is represented using a int64 for storing nanoseconds. You are trying to pass an int representing MILLIseconds: you will be overflowing most of the time.
Change #3: directly assign to the Duration
for {
    rand.Seed(time.Now().UnixNano())
    r := rand.Int()
    log.Println(r)
    d := time.Duration(r)
    time.Sleep(d)
}

Now it works! The first integer generated by my function is 649508928394582529, which I am casting to time.Duration (again, this is an int64 of nanoseconds).
This is approximatively 649508928 seconds: just over a week.
It looks like a lot. But keep in mind that you were trying to use the generated int as milliseconds: that is 10^6 times more.
Change #4: Seed outside the loop
While we are at it, let's polish a bit:
rand.Seed(time.Now().UnixNano())
for {
    r := rand.Int()
    log.Println(r)
    d := time.Duration(r)
    time.Sleep(d)
}

Explanation: a pseudorandom number generator is a state machine. You have to feed it a seed once, and then it will work forever. Giving it a different seed every time you run it is not improving its randomness: it's applying the same algorithm over and over on a predictable value (time). You can achieve the same exact degree of randomness by directly using time.Now()Unix()

A: for loop doesn't spawn new goroutines unless you do it explicitly in cycle. By default next cycle starts only after previous is done. So you do not need any delay. Just make sure you do not use go keyword in your cycle.
If you want to launch goroutines:
for {
    rand.Seed(time.Now().UnixNano())
    r := rand.Int()
    //Do stuff in separate goroutine
    go DoStuff()
    t, _ := time.ParseDuration(string(r) + "ms")
    time.Sleep(t)
}

This way new goroutine will be launched.


text:
Q: How to create a ones of specific shape in tensorflow? I need to create a ones of shape (200,240,2).
For an example, in numpy I can do:
r = numpy.ones_like(x) # x shape is (200,240,2)
r[...,0] = 0
r[...,1] = 1.57

How can I do it in tensorflow?
Could anyone help me with this?

A: You can't do indexing and assignment at the same time in tensorflow, but otherwise, you can do the same things than in numpy. Here's one way to replicate your numpy code:
x_shape = x.shape
r0 = tf.zeros(x_shape[:-1])
r1 = tf.ones(x_shape[:-1]) + 0.57
r = tf.stack([r0,r1],axis=-1)

If you need other values than one or zero, you can do simple arithmetic:
r1 = tf.zeros(x_shape[:-1]) + 1.57


text:
Q: Ant build script executing  task using java code Any idea, why none of the debugging comments are printed once after executing the ANT build script's SQL task via java code?
The java class to execute the sql in build scirpt is
public class AntRunnerTest {
   private Project project;

   public void executeTask(String taskName) {
      try {
        project = new Project();
        project.init();
        project.setBasedir(new String("."));
        ProjectHelper helper = ProjectHelper.getProjectHelper();
        project.addReference("ant.projectHelper", helper);
        helper.parse(project, new File("build-copy.xml"));
        System.out.println("Before");
        project.executeTarget(taskName);
        System.out.println("After");
      } catch(Exception ex) {
          System.out.println(ex.getMessage());
      }
   }

   public static void main(String args[]) {
      try {
         AntRunnerTest newInst = new AntRunnerTest();
         newInst.executeTask("sql");
      } catch(Exception e) {
         System.out.println(""+e);
      }
   }
}

I dont see the debug String "After" getting printed in the console. I noticed this issue only when i try to execute a sql task using java code.
The ant script has the following simple transaction tag in it.
<transaction> <![CDATA[ select now() ]]> </transaction>

Any thoughts?
Thanks in advance.

A: The problem will be solved if you add the output attribute of  tag.

A: Example of an Ant build script executing any task using java code:

*

* direct the log to the console and byte array;

* fill in the Ant project variables;

* execute an ant task;

* add output log to swing component (javax.swing.JTextArea);

See source code: https://github.com/wellboyvg/workgear/blob/master/manager/src/manager/WorkGearManager.java
private boolean executeAntTask(String target) {
boolean success = false;
// use log output to the console
DefaultLogger conlog = new DefaultLogger();
conlog.setErrorPrintStream(System.err);
conlog.setOutputPrintStream(System.out);
conlog.setMessageOutputLevel(Project.MSG_INFO);
// use log output to the byte array
DefaultLogger strlog = new DefaultLogger();
ByteArrayOutputStream errb = new ByteArrayOutputStream();
PrintStream errp = new PrintStream(errb);
strlog.setErrorPrintStream(errp);
ByteArrayOutputStream outb = new ByteArrayOutputStream();
PrintStream outp = new PrintStream(outb);
strlog.setOutputPrintStream(outp);
strlog.setMessageOutputLevel(Project.MSG_INFO);
// prepare Ant
Project project = new Project();
File buildfile = new File(buildname);
project.setUserProperty("ant.file", buildfile.getAbsolutePath());
// add record log to the console
project.addBuildListener(conlog);
// add record log to the byte array
project.addBuildListener(strlog);
//
try {
  // fill the Ant project variables
  for (Entry m : map.entrySet()) {
    project.setUserProperty(m.getKey().toString(), m.getValue().toString());
  }
  project.fireBuildStarted();
  project.init();
  ProjectHelper helper = ProjectHelper.getProjectHelper();
  project.addReference("ant.projectHelper", helper);
  helper.parse(project, buildfile);
  // execute the ant task
  project.executeTarget(target);
  project.fireBuildFinished(null);
  success = true;
} catch (BuildException buildException) {
  project.fireBuildFinished(buildException);
}
// add output log to swing component (javax.swing.JTextArea)
jtLog.append(new String(outb.toByteArray()));
jtLog.append(new String(errb.toByteArray()));
return success;

}


text:
Q: Backbone router issue I have a router that does the site navigation nicely and also works when clicking the browsers back / forward button. However, when entering directly an URL I get 404.
Here is my router:
define(function(require) {
var $         = require('jquery'),
    _         = require('underscore'),
    Backbone  = require('backbone');

var AppRouter = Backbone.Router.extend( {

    routes: {
        'home'       : 'homeHandler',
        'webdesign'  : 'webHandler',
        'mobile'     : 'mobileHandler',
        'javascript' : 'javascriptHandler',
        'hosting'    : 'hostingHandler',
        'contact'    : 'contactHandler'
    },

    initialize: function() {
        this._bindRoutes();
        $('.link').click(function(e){
            e.preventDefault();
            Backbone.history.navigate($(this).attr("href"),true);
        });
        if(history && history.pushState) {
            Backbone.history.start({pushState : true});
            console.log("has pushstate");
        }
        else {
            Backbone.history.start();
            console.log("no pushstate");
        }
        console.log("Router init with routes:",this.routes);
    },

    homeHandler: function(e) {
        require(['../views/home-content-view', '../views/home-sidebar-view'],
            function(HomeContent, HomeSidebar) {
                var homeContent = new HomeContent();
                homeContent.render();
                var homeSidebar = new HomeSidebar();
                homeSidebar.render();
        });
    },

    webHandler: function(e) {
        require(['../views/web-content-view', '../views/web-sidebar-view'],
            function(WebContent, WebSidebar) {
                var webContent = new WebContent();
                webContent.render();
                var webSidebar = new WebSidebar();
                webSidebar.render();
        });
    },

    ...

});

return AppRouter;
});

Obviously, I'm missing something.
Any clarification would be greatly appreciated.
Thanks,
Stephan

A: Backbone operates on a web-page (that has already been loaded in the browser). When you enter a URL in the browser directly, you're making a HTTP-request for that URL to the server. The server is not managed by Backbone. You have to define on the server the behavior when such HTTP-requests are encountered.


text:
Q: How to pass variables by reference in R? I would like to ask how I can overwrite the variables v and ind in the following function:
 repcomb <- function(v,n,ind)
{
   k <- length(v)
   if(ind == 0)
   {
      for (i in 1:k) v[i] <- 1
      ind <- 1
      return
   }
   for (i in k:1)
   {
      if(v[i] != n)
      {
         for (j in k:i) v[j] <- v[i] + 1
         return
      }
   }
   ind = 0
}

What is the easiest way for updating v and ind?

A: This is the easiest way:
repcomb <- function(v,n,ind)
{
  k <- length(v)
  if(ind == 0)
  {
    for (i in 1:k) v[i] <- 1
    ind <- 1
    return(list(v=v, ind=ind))
  }
  for (i in k:1)
  {
    if(v[i] != n)
    {
      for (j in i+1:k) v[j] <- v[i] + 1
      v[i] <- v[i] + 1
      return(list(v=v, ind=ind))
    }
  }
  ind = 0
  return(list(v=v, ind=ind))
}

res <- repcomb(1:5, 4, 2)
v <- res$v
ind <- res$ind

A: If you want to get back the value of a parameter set inside a function, you can use eval.parent(substitute(val<-new_val)), for example:
f_sqr <- function(val){
     new_val <- val^2
     eval.parent(substitute(val<-new_val))
}

If you call it:
val <- 5
f_sqr(val)
val
#[1] 25

Please bear in mind that you should not change the value of the parameter inside the function, instead, you copy it to a new variable, do what you want to do in your code and finally set the value of new variable into your parameter variable as it is the case inside the function.
For your own function, this is what you have to do for your first if:
repcomb <- function(v, n, ind)
{
   k <- length(v)
   if (ind == 0)
   {
      new_v <- v
      for (i in 1:k) new_v[i] <- 1
      # ind <- 1
      new_ind <- 1
      eval.parent(substitute(ind<-new_ind))
      eval.parent(substitute(v<-new_v))
   }
}

Then if you call it, you will get the changes back:
v <- 1:5
n <- 3
ind <- 0
repcomb(v, n, ind)
v
#[1] 1 1 1 1 1
ind
#[1] 1

Correspondingly, the other part can be changed to meet what you want.


text:
Q: Azure ApiM unable to create jwt token validation policy with RSA certificate According to documentation in Azure API Management it is possible to create JWT token validation policy using certificate id of RSA certificate previously uploaded to APIM.
I am trying to build such policy as described in the docs, and it is saved without errors, but when I open the policy definition again, key element is always empty, without the certificate-id attribute I set earlier.
https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies#token-validation-with-rsa-certificate

A: I can also reproduce your issue on my side, after configuration and come back, the policy will be like below.

It looks should be a bug in UI, because if you get the policy with PowerShell Get-AzApiManagementPolicy or REST API - Api Policy - Get directly, we can get the value. So I think the policy should be applied, just ignore it and go on.
Powershell:
$ApiMgmtContext = New-AzApiManagementContext -ResourceGroupName "groupname" -ServiceName "joyapim"
Get-AzApiManagementPolicy -Context $ApiMgmtContext -ApiId 'echo-api'

REST API:


text:
Q: Connecting To Multiple MySQL Databases in Node.js I am trying to have some type of dropdown that shows a list of all the databases from the specified host. Basically, my goal is for user to be able to select one of the databases from the dropdown and be able run a report. But I am stuck on how I can connect to the host and be able to display the list into the dropdown. I have done some research, but I am not getting any clear answer of how to solve this issue.

A: To get database name, query information_schema.TABLES database.
SELECT Table_schema AS 'Databases'
FROM information_schema.TABLES
GROUP BY table_schema`;

Then do your report query for example like this:
SELECT * FROM `dbname`.`tablename` WHERE date >= 'XXXX-XX-XX' AND date <= 'XXXX-XX-XX';

Where dbname is the database name that you pass from the dropdown list to the backend query.


text:
Q: How to input Strings into a 2D array I have this code and I need to export the strings 'Name','Testav','HWav','Lows','grade' into a 2D array with the columns being the following respectively. I then need to export the 2D array into a csv file. Any help would be greatly appreciated.
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class ComputeGrades {
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.printf("Please enter the name of the input file: ");
        String input_name = in.next();
        System.out.printf("Please enter the name of the output CSV file: ");
        String csv_name = in.next();
        System.out.printf("Please enter the name of the output pretty-print file: ");
        String pretty_name = in.next();

        processGrades(input_name, csv_name, pretty_name);
        System.out.printf("\nExiting...\n");
   }
   public static void processGrades (String input_name, String csv_name, String pretty_name)
   {
       PrintWriter csv = null;
       PrintWriter pretty = null;
       String[][] data = readSpreadsheet(input_name);

       boolean resultb = sanityCheck(data);
       int length = data.length;
       ArrayList<String> test_avg = new ArrayList<String>();
       ArrayList<String> HW_avg = new ArrayList<String>();
       ArrayList<String> NAME = new ArrayList<String>();
       ArrayList<String> ColN = new ArrayList<String>();
       ArrayList<String> Hell = new ArrayList<String>();
       String[][] kill_me = new String[length][];
       for(int row = 1; row<length; row++)
       {
           String name = data[row][0];
           String name2 = data[row][1];
           String Name = name+" "+name2;
           int test1 = Integer.parseInt(data[row][2]);
           int test2 = Integer.parseInt(data[row][3]);
           int test3 = Integer.parseInt(data[row][4]);
           int Test = (test1+test2+test3)/3;
           String Testav = Integer.toString(Test);
           int hw1 = Integer.parseInt(data[row][5]);
           int hw2 = Integer.parseInt(data[row][6]);
           int hw3 = Integer.parseInt(data[row][7]);
           int hw4 = Integer.parseInt(data[row][8]);
           int hw5 = Integer.parseInt(data[row][9]);
           int hw6 = Integer.parseInt(data[row][10]);
           int hw7 = Integer.parseInt(data[row][11]);
           int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
           String HWav = Integer.toString(HW);
           int[] trying = {Test, HW};
           int low = find_min(trying);
           String Lows = Integer.toString(low);
           String grade = null;
           if(low>=90)
           {
               grade ="A";
           }
           if(low < 90 && low>= 80)
           {
               grade = "B";
           }
           if(low <80 && low>=70)
           {
               grade ="C";
           }
           if(low<70 && low>=60)
           {
               grade="D";
           }
           if(low<60)
           {
               grade = "F";
           }
           test_avg.add(Testav);
           HW_avg.add(HWav);
           NAME.add(Name);
           Hell.add(Name);
           Hell.add(Testav);
           Hell.add(HWav);
           Hell.add(Lows);
           Hell.add(grade);
      }
      System.out.println(Hell);
      System.out.printf("\n");
      File csvFile = new File(csv_name);
      try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
          Hell.stream().forEach(csvWriter::println);
      } catch (IOException e) {
      }

  }

  public static int find_min(int[] values)
  {
      int result = values[0];
      for(int i = 0; i<values.length; i++)
      {
          if(values[i]<result)
          {
              result = values[i];
          }
      }
      return result;
  }
  public static boolean sanityCheck(String[][] data)
  {
      if (data == null)
      {
          System.out.printf("Sanity check: nul data\n");
          return false;
      }
      if(data.length<3)
      {
          System.out.printf("Sanity check: %d rows\n",data.length);
          return false;
      }
      int cols= data[0].length;
      for(int row = 0; row<data.length; row++)
      {
          int current_cols = data[row].length;
          if(current_cols!=cols)
          {
              System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
              return false;
          }
      }

      return true;
  }
  public static String[][] readSpreadsheet(String filename)
  {
      ArrayList<String> lines = readFile(filename);
      if (lines == null)
      {
          return null;
      }

      int rows = lines.size();
      String[][] result = new String[rows][];

      for (int i = 0; i < rows; i++)
      {
          String line = lines.get(i);
          String[] values = line.split(",");
          result[i] = values;
      }

      return result;
  }

  public static ArrayList<String> readFile(String filename)
  {
      File temp = new File(filename);
      Scanner input_file;

      try
      {
          input_file = new Scanner(temp);
      } catch (Exception e)
      {
          System.out.printf("Failed to open file %s\n",
              filename);
          return null;
      }

      ArrayList<String> result = new ArrayList<String>();
      while (input_file.hasNextLine())
      {
          String line = input_file.nextLine();
          result.add(line);
      }

      input_file.close();
      return result;
  }
}

input file:
First,Last,Exam1,Exam2,Final,H1,H2,H3,H4,H5,H6,H7
Ping,Milledge,43,59,68,69,62,43,60,38,37,40
Elisa,Oltz,76,94,73,100,99,100,90,97,100,92
Leonard,Havers,67,95,57,69,95,71,68,61,93,61
Setsuko,Lovera,78,100,84,89,88,92,65,85,66,97
Franklyn,Degnim,54,74,50,63,78,42,42,41,67,64
Gwyneth,Marsico,61,89,81,59,59,62,88,60,66,66
Abigail,Greep,69,99,93,94,91,85,78,91,69,71
Majorie,Granvold,78,100,100,82,96,100,89,100,100,94
Daphine,Polaco,62,82,88,81,68,89,62,73,90,62
An,Corvera,44,71,37,46,57,42,59,66,54,60
Ayanna,Pensiero,64,42,56,37,53,66,69,52,43,58
Era,Deming,98,81,100,69,65,73,77,78,73,89
Michal,Slentz,73,85,81,82,74,93,81,76,69,81
Corie,Brazen,86,99,66,100,69,97,96,100,70,84
Dona,Tufte,63,54,70,71,55,68,86,66,75,63
Juan,Rohdenburg,78,89,100,91,80,97,92,100,98,100
Orville,Samit,88,63,60,88,81,56,91,76,77,80
Ricky,Knoechel,100,100,93,81,100,90,100,92,100,84
Blythe,Threet,38,68,35,61,63,51,48,72,49,51
Sammie,Wachs,46,53,52,76,50,52,56,68,46,75
Estelle,Veazey,72,87,69,98,96,77,95,91,100,91
Agatha,Keckler,100,92,90,95,85,100,94,85,92,100
Novella,Oros,85,76,100,92,84,77,77,90,86,98
Tanya,Quinlisk,47,78,71,50,79,52,69,66,51,45
Marion,Coltrin,68,68,54,39,61,44,66,58,47,74
Helene,Karow,100,100,75,79,100,100,100,92,89,96
Shonta,Bourek,100,96,90,81,97,84,91,100,100,100
Hyon,Anglemyer,81,76,43,43,47,53,44,60,57,65
Ervin,Kenison,78,53,54,75,55,46,61,75,56,69
Renato,Urch,71,64,64,84,49,57,63,69,81,64
Mikel,Burleigh,88,100,90,100,90,91,90,80,74,74
Val,Royal,100,80,100,99,100,100,76,86,100,96
Jodie,Adolfo,94,77,59,83,67,79,87,82,82,75
Roselee,Lienhard,68,75,58,82,96,62,60,94,68,58
Austin,Holznecht,76,49,79,48,58,68,67,71,70,61
Emelia,Toney,70,95,74,90,99,68,100,66,98,98
Lucy,Rhodd,71,91,100,82,100,93,100,100,71,81
Sacha,Chee,78,71,90,82,74,64,62,87,69,84
Julio,Lackner,56,86,53,88,88,73,57,59,80,85
Salvador,Gretzner,54,83,91,66,78,67,61,84,82,6

export file(csv_name)
name,exam_score,hw_score,min_score,grade
Ping Milledge,56.666667,49.857143,49.857143,F
Elisa Oltz,81.000000,96.857143,81.000000,B
Leonard Havers,73.000000,74.000000,73.000000,C
Setsuko Lovera,87.333333,83.142857,83.142857,B
Franklyn Degnim,59.333333,56.714286,56.714286,F
Gwyneth Marsico,77.000000,65.714286,65.714286,D
Abigail Greep,87.000000,82.714286,82.714286,B
Majorie Granvold,92.666667,94.428571,92.666667,A
Daphine Polaco,77.333333,75.000000,75.000000,C
An Corvera,50.666667,54.857143,50.666667,F
Ayanna Pensiero,54.000000,54.000000,54.000000,F
Era Deming,93.000000,74.857143,74.857143,C
Michal Slentz,79.666667,79.428571,79.428571,C
Corie Brazen,83.666667,88.000000,83.666667,B
Dona Tufte,62.333333,69.142857,62.333333,D
Juan Rohdenburg,89.000000,94.000000,89.000000,B
Orville Samit,70.333333,78.428571,70.333333,C
Ricky Knoechel,97.666667,92.428571,92.428571,A
Blythe Threet,47.000000,56.428571,47.000000,F
Sammie Wachs,50.333333,60.428571,50.333333,F
Estelle Veazey,76.000000,92.571429,76.000000,C
Agatha Keckler,94.000000,93.000000,93.000000,A
Novella Oros,87.000000,86.285714,86.285714,B
Tanya Quinlisk,65.333333,58.857143,58.857143,F
Marion Coltrin,63.333333,55.571429,55.571429,F
Helene Karow,91.666667,93.714286,91.666667,A
Shonta Bourek,95.333333,93.285714,93.285714,A
Hyon Anglemyer,66.666667,52.714286,52.714286,F
Ervin Kenison,61.666667,62.428571,61.666667,D
Renato Urch,66.333333,66.714286,66.333333,D
Mikel Burleigh,92.666667,85.571429,85.571429,B
Val Royal,93.333333,93.857143,93.333333,A
Jodie Adolfo,76.666667,79.285714,76.666667,C
Roselee Lienhard,67.000000,74.285714,67.000000,D
Austin Holznecht,68.000000,63.285714,63.285714,D
Emelia Toney,79.666667,88.428571,79.666667,C
Lucy Rhodd,87.333333,89.571429,87.333333,B
Sacha Chee,79.666667,74.571429,74.571429,C
Julio Lackner,65.000000,75.714286,65.000000,D
Salvador Gretzner,76.000000,71.714286,71.714286,C

export file 2(pretty_name)
                name: exam score, hw score, min score, grade
       Ping Milledge:      56.67,    49.86,     49.86, F
          Elisa Oltz:      81.00,    96.86,     81.00, B
      Leonard Havers:      73.00,    74.00,     73.00, C
      Setsuko Lovera:      87.33,    83.14,     83.14, B
     Franklyn Degnim:      59.33,    56.71,     56.71, F
     Gwyneth Marsico:      77.00,    65.71,     65.71, D
       Abigail Greep:      87.00,    82.71,     82.71, B
    Majorie Granvold:      92.67,    94.43,     92.67, A
      Daphine Polaco:      77.33,    75.00,     75.00, C
          An Corvera:      50.67,    54.86,     50.67, F
     Ayanna Pensiero:      54.00,    54.00,     54.00, F
          Era Deming:      93.00,    74.86,     74.86, C
       Michal Slentz:      79.67,    79.43,     79.43, C
        Corie Brazen:      83.67,    88.00,     83.67, B
          Dona Tufte:      62.33,    69.14,     62.33, D
     Juan Rohdenburg:      89.00,    94.00,     89.00, B
       Orville Samit:      70.33,    78.43,     70.33, C
      Ricky Knoechel:      97.67,    92.43,     92.43, A
       Blythe Threet:      47.00,    56.43,     47.00, F
        Sammie Wachs:      50.33,    60.43,     50.33, F
      Estelle Veazey:      76.00,    92.57,     76.00, C
      Agatha Keckler:      94.00,    93.00,     93.00, A
        Novella Oros:      87.00,    86.29,     86.29, B
      Tanya Quinlisk:      65.33,    58.86,     58.86, F
      Marion Coltrin:      63.33,    55.57,     55.57, F
        Helene Karow:      91.67,    93.71,     91.67, A
       Shonta Bourek:      95.33,    93.29,     93.29, A
      Hyon Anglemyer:      66.67,    52.71,     52.71, F
       Ervin Kenison:      61.67,    62.43,     61.67, D
         Renato Urch:      66.33,    66.71,     66.33, D
      Mikel Burleigh:      92.67,    85.57,     85.57, B
           Val Royal:      93.33,    93.86,     93.33, A
        Jodie Adolfo:      76.67,    79.29,     76.67, C
    Roselee Lienhard:      67.00,    74.29,     67.00, D
    Austin Holznecht:      68.00,    63.29,     63.29, D
        Emelia Toney:      79.67,    88.43,     79.67, C
          Lucy Rhodd:      87.33,    89.57,     87.33, B
          Sacha Chee:      79.67,    74.57,     74.57, C
       Julio Lackner:      65.00,    75.71,     65.00, D
   Salvador Gretzner:      76.00,    71.71,     71.71, C

A: This should do it, if you have question about the code, just ask.
public static void processGrades (String input_name, String csv_name, String pretty_name) {
    DecimalFormat decimalFormat = new DecimalFormat(".000000");

    String[][] data = readSpreadsheet(input_name);
    String[][] result = new String[data.length][];
    result[0] = new String[]{"name", "exam_score", "hw_score", "min_score", "grade"};

    // Export to 2D String array
    for(int row = 1; row < data.length; row++) {
        String name = data[row][0] + " " + data[row][1];
        double testAverage = average(data[row], 2, 5);
        double homeworkAverage = average(data[row], 5, 12);
        double min = Math.min(testAverage, homeworkAverage);
        char grade = (char) (74 - ((int) min / 10));
        grade = grade > 'D' ? 'F' : grade;

        result[row] = new String[]{
                name,
                decimalFormat.format(testAverage),
                decimalFormat.format(homeworkAverage),
                decimalFormat.format(min),
                Character.toString(grade)
        };
    }

    // Export 2D array into a csv String
    String csv = "";
    for (int y = 0; y < result.length; y++) {
        for (int x = 0; x < result[y].length - 1; x++) {
            csv += result[y][x] + ",";
        }
        csv += result[y][result[y].length - 1] + "\n";
    }

    // Save String in file
    File file = new File(csv_name);
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
        bw.write(csv);
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static double average(String[] row, int fromIndex, int toIndex) {
    double total = 0;
    for (int i = fromIndex; i < toIndex; i++) {
        total += Integer.parseInt(row[i]);
    }
    return total / (toIndex - fromIndex);
}


text:
Q: Jquery buttons to show/ hide images and text I build a website, in this website I have this two buttons by jQuery
 when I click on the bt1 the image appear and
 then I'll click on the btn2 the first image should dissapear and the second image for this button btn2 appear.
The problem is
 I click on btn1 and then click on btn2,  when I want to back to btn1 and click it, it not work.
I have to perform a double click on each other, click to open image and the other to close.
I want to click one time to see image and when i click on the second button the first image disappear and open the second image.
And I want that image** appear when I open the website but when I click on any button (btn1,btn2) the image hide disappear.
** 3rd image not for (btn1/btn2) but appear when i open my web n disappear when i click on any image
thank for help

<button onclick="showhide_menu('btn1');">Show/Hide.  </button>

 <button onclick="showhide_menu('btn2');">Show/Hide.  </button>

    text text text text text text text text text....

    text text text text text text text text text....

A: Give the btn-DIVs a class.
Then hide them before toggling:
http://jsfiddle.net/qYCUJ/
HTML

    text text text text text text text text text....

    text text text text text text text text text....

JS
function showhide_menu(id){
    $('.btn:not(#'+id+')').hide();
    $("#" + id).toggle();
}

A: You can use this too
function showhide_menu(){
    if($('#btn1').is(':visible'))
    {
        $('#btn1').hide();
        $('#btn2').show();
    }
    else
    {
       $('#btn2').hide();
        $('#btn1').show();
    }
}


text:
Q: Pandas: Split string on last occurrence I'm trying to split a column in a pandas dataframe based on a separator character, and obtain the last section.
pandas has the str.rsplit and the str.rpartition functions.
If I try:
df_client["Subject"].str.rsplit("-", 1)

I get

0 [Activity -Location ,  UserCode]
  1 [Activity -Location ,  UserCode]

and if I try
df_client["Subject"].str.rpartition("-")

I get

      0            1      2

0  Activity -Location  -   UserCode
  1  Activity -Location  -   UserCode

If I do
df_client["Subject"].str.rpartition("-")[2]

I get

0 UserCode

which is what I want.
To me, str.rsplit seems unintuitive.
After getting the list of the split string, how would I then select the single item that I need?

A: I think need indexing by str working with iterables:
#select last lists
df_client["Subject"].str.rsplit("-", 1).str[-1]
#select second lists
df_client["Subject"].str.rsplit("-", 1).str[1]

If performance is important use list comprehension:
df_client['last_col'] = [x.rsplit("-", 1)[-1] for x in df_client["Subject"]]
print (df_client)
                      Subject  last_col
0  Activity-Location-UserCode  UserCode
1  Activity-Location-UserCode  UserCode

A: Use expand=True:
df_client["Subject"].str.split('-', expand=True)[2]


text:
Q: What is the default event order in JavaScript? Top-down or Bottom-up?
Possible Duplicate:
What is event bubbling and capturing

I just learnt that in JS we have two event types: Capture and Bubble. Bubble can be used for avoiding the need of attaching the eventListener to all children; instead attach listener only to the parent and have it check the target. It sounds cool. And I tried out this example:

    span1
    span2
    span3
    span4

But I haven't attached any listeners to the child spans. Yet the events on them are bubbling! So is bubbling the default event order in JS? Then in which scenario would the capture (top-down) be used?

A: Imagine you have html that looks like this:

        <button id="target"></button>

And JS which looks like this:
function sayGrandpa (evt) { console.log("Grandpa"); }
function sayClicked (evt) { console.log("Clicked"); }

var grandparent = document.getElementById("grandparent"),
    target = document.getElementById("target");

grandparent.addEventListener("click", sayGrandpa, false);
target.addEventListener("click", sayClicked, false);

Bubbling vs Capture doesn't really have anything to do with what you're supposing, in that in both cases (on W3C-compliant browsers), you can use event listeners to attach to a parent, to listen to events which are triggered on a child.
The difference is that bubbling assumes that the chain of events starts at the target, and works its way back up through the chain of parents, like a bomb detonating at ground-zero, and sending a shockwave rippling outward.
Capturing starts at window (or at ), and goes down to the target element.
So when you use bubbling (more like rippling), any functions which are set directly on the element happen first, and any delegated functions, attached to ancestors, happen as the ripples go back up the chain.
When you use capturing, any delegated functions, attached to ancestors, happen BEFORE the event happens on the element.
So the grandparent element knows about a click, before target does.
So when you ask what order things happen in, things are pretty obvious:
When you set an event on grandparent which is captured and set a second event on grandparent which is bubbled, and set an event on target which is either, the order will be:
captured grandparent
target
bubbled grandparent
So when is it beneficial to have ancestors know about a click happening before the button that's actually being clicked?
Great question!
I'm sure somebody can think of something that isn't just a really-douchey way of making people miserable by hiding the thing they were supposed to be clicking on.
But the moral is that you expressly have to ask for it (setting the third parameter of .addEventListener to true).
Also, oldIE and others don't support capturing at all.
It's not really something which should be used in general.

A: The default event order is browser specific.
Event capturing: the event handler of outer element fires first, the event handler of inner elements fires last.
Event Bubbling: the event handler of the inner element fires first, the event handler of outer element fires last.

The two event orders are radically opposed. Explorer only supports
  event bubbling. Mozilla, Opera 7 and Konqueror support both. Older
  Opera's and iCab support neither.

In the Microsoft model you must set the event's cancelBubble property to true.
window.event.cancelBubble = true
In the W3C model you must call the event's stopPropagation() method.
e.stopPropagation()
function doSomething(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

http://www.quirksmode.org/js/events_order.html


text:
Q: null used with logical operator I have a table with name,age and address.I have totally five rows of data in the table.For some rows the age is left null.I have to display all the data where age is not null.
select * from sample_table where (age !=null);
But no output is displayed and it doesn't give an error also.Please explain this.Thanks.

A: With NULL you have to use IS or IS NOT. The following query should work:
SELECT * FROM sample_table WHERE (age IS NOT NULL)

A: The explanation from MySQL

The concept of the NULL value is a common source of confusion for
  newcomers to SQL, who often think that
  NULL is the same thing as an empty
  string ''. This is not the case.
In SQL, the NULL value is never true in comparison to any other value,
  even NULL. An expression that contains
  NULL always produces a NULL value
  unless otherwise indicated in the
  documentation for the operators and
If you want to search for column values that are NULL, you cannot use
  an expr = NULL test.
To look for NULL values, you must use the IS NULL test.

A: You have to use IS NULL or IS NOT NULL.
You can not compare directly against NULL because it is not value (no pedants please!)
NULL on Wikipedia
MySQL, Sybase, SQL Server... it's all the same


text:
Q: Count group of ones in series I have a series a=[100 200 1 1 1 243 300 1 1 1 1 1 400 1 900  600 900 1 1 1 ]
I have to count how many times 1 occur when it occurs in group.
First group of 1's, sum is 3 (lying between 200 and 243).
Second group of ones lying between 300 and 400 is 5. Sum of all ones in each group is [3 5 1 3].
Please give me some suggestions.

A: Use diff on a==1. Bracket with false to assure the count is correct no matter what the starting or ending values of a. Finally, find the start and end of each run and subract:
d = diff([false, a==1, false]);
result = find(d==-1) - find(d==1);

In your example this gives
result =
     3     5     1     3


text:
Q: 5 star Bayes Rating return in percentage Im build 5 star rating system.The problem come when user keep rate the photo and eventually the br will return more then 100%,how can i make sure it return in percentage and not more than 100%
br = ( (avg_num_votes * avg_rating) + (this_num_votes * this_rating) ) / (avg_num_votes + this_num_votes)

A: Assuming avg_rating and this_rating are both no more than 100%, and all values are non-negative, your formula will never give more than 100%.
br = ( (avg_n * avg_r) + (this_n * this_r) ) / (avg_n + this_n) <=
   <= ( (avg_n * 100%) + (this_n * 100%) ) / (avg_n + this_n) =
   = 100% * (avg_n + this_n) / (avg_n + this_n) =
   = 100%

If avg_rating and this_rating are not measured in percentage (e.g. they are the number of stars 0-5), you should convert them to percentages first.


text:
Q: libpng - crash due to memory error [iOS & Android] I'm using libpng version 1.6.15 in both my iOS and Android-NDK project to read .png image and use it for OpenGL ES 2.0 texture. I have configured libpng without errors, below is the code where I read PNG image:
uint8_t  *outputData;
FILE *fp = fopen(filename, "rb");

png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png) abort();

png_infop info = png_create_info_struct(png);
if(!info) abort();

if(setjmp(png_jmpbuf(png))) abort();

png_init_io(png, fp);

png_read_info(png, info);

width      = png_get_image_width(png, info);
height     = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth  = png_get_bit_depth(png, info);

texWidth = width;
texHeight = height;

if(bit_depth == 16)
    png_set_strip_16(png);

if(color_type == PNG_COLOR_TYPE_PALETTE)
    png_set_palette_to_rgb(png);

if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    png_set_expand_gray_1_2_4_to_8(png);

if(png_get_valid(png, info, PNG_INFO_tRNS))
    png_set_tRNS_to_alpha(png);

if(color_type == PNG_COLOR_TYPE_RGB ||
   color_type == PNG_COLOR_TYPE_GRAY ||
   color_type == PNG_COLOR_TYPE_PALETTE)
    png_set_filler(png, 0xFF, PNG_FILLER_AFTER);

if(color_type == PNG_COLOR_TYPE_GRAY ||
   color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
    png_set_gray_to_rgb(png);

png_read_update_info(png, info);
unsigned  long row_bytes = png_get_rowbytes(png,info);
outputData = (uint8_t*) malloc(row_bytes * height * 4); // Allocating memory

row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for(int y = 0; y < height; y++) {
    row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png,info));
}
png_read_image(png, row_pointers);
for(int i = 0; i < height; i++) {
    //memcpy(outputData+(row_bytes * (height-1-i)), row_pointers[i], row_bytes);
    memcpy(outputData+(row_bytes * i), row_pointers[i], row_bytes);
}
printf("Allocating memory ... ");
//png_destroy_info_struct(png, &info);
//free(row_pointers);
fclose(fp);

return  outputData;

And after that I'm using the output data returned for setting texture as below:
glGenTextures(1, &OGLTextureName);
glBindTexture(GL_TEXTURE_2D, OGLTextureName);
glTexImage2D(GL_TEXTURE_2D, 0,getOGLTextureFormat(format), width, height, 0, getOGLTextureFormat(format), getOGLTextureType(texelType), outputData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
free(outputData);

It is working sometimes in Android-NDK project, reading the images correctly so that texture is perfect, but most of the time app is getting crashed after reading the data with the message as below:
in iOS:
malloc: *** error for object 0x16884844: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

in Android
heap corruption detected by dlfree

What am I doing wrong here? I have also tried setting breakpoint in malloc_error_break but that is not helping me. Is that the issue due to chunks in images?


text:
Q: How to calculate the UTM-Latitude-band? I have to convert a coordinate from UTM to MGRS. I think I have the most of it covered, but I have some difficulties to calculate the correct Latitude-band. How can I decide which band the coordinate has?

A: I use:
zone = math.floor ((lon + 180.0) / 6) + 1

Bear with me on that, and I'll check my library
So if
lon = -35
lat = 35

Then zone will be 25, which I think is correct.  Try it and let me know if it works for you.
There is also:
andrewlesley.freeserve.co.uk/gps/convertr/UTM-MGRS.html
I am sure you can get into the JS and use the code.
var UTMzdlChars="CDEFGHJKLMNPQRSTUVWXX";
function UTMzdl(latDeg)
{
    if(-80<=latDeg&&latDeg<=84)
    {
        return UTMzdlChars.charAt(Math.floor((latDeg+80)/8));

    }else
    {
         //Not normally reached
         alert("No zdl: UTM is not valid for Lat "+latDeg);
         return "";
     }
}


text:
Q: Concatenation Values in IOS How to concatenate the value from UITextField and value from button and display
them together in Objective-C? I'm trying but not getting it.

A: NSString* aString = [NSMutableString stringWithFormat:@"String with two ints %d - %d", myInt, myInt];
NSLog(@"%@",aString);

NSString* aString = [NSMutableString stringWithFormat:@"String with two ints %d - ... now has another int: %d", myInt, myInt];
NSLog(@"%@",aString);

//suppose - int one = 1; int two = 2; int three = 3
NSString *oneTwoThree = [NSString stringWithFormat:@"%d/%d/%d", one, two, three];
NSLog(@"%@",oneTwoThree);

// suppose
//UITextField *tf = [[UITextField alloc] init];
//tf.text = "text field text"

//UIButton *btn = [[UIButton alloc] init];
//btn.titleLabel.text = "button text"

NSString* concatedString = [NSMutableString stringWithFormat:@"%@ - %@", tf.text, btn.titleLabel.text];
NSLog(@"%@",concatedString); //result:  "text field text = button text"

A: you can try this
NSString *strConcate = [NSString stringWithFormat:@"%@ %@",textFeild.text,button.titleLabel.text];