text:
Q: rocketmq throw exception "[TIMEOUT_CLEAN_QUEUE]broker busy, start flow control for a while" version:rocketmq-all-4.1.0-incubating
We send msg 1000 QPS,sync send, but throw exception:-

[TIMEOUT_CLEAN_QUEUE] broker busy, start flow control for a while

There is the related code:
while (true) {
        try {
            if (!this.brokerController.getSendThreadPoolQueue().isEmpty()) {
                final Runnable runnable = this.brokerController.getSendThreadPoolQueue().peek();
                if (null == runnable) {
                    break;
                }
                final RequestTask rt = castRunnable(runnable);
                if (rt == null || rt.isStopRun()) {
                    break;
                }

                final long behind = System.currentTimeMillis() - rt.getCreateTimestamp();
                if (behind >= this.brokerController.getBrokerConfig().getWaitTimeMillsInSendQueue()) {
                    if (this.brokerController.getSendThreadPoolQueue().remove(runnable)) {
                        rt.setStopRun(true);
                        rt.returnResponse(RemotingSysResponseCode.SYSTEM_BUSY, String.format("[TIMEOUT_CLEAN_QUEUE]broker busy, start flow control for a while, period in queue: %sms, size of queue: %d", behind, this.brokerController.getSendThreadPoolQueue().size()));
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        } catch (Throwable ignored) {
        }
    }
}

I find broker the default value of sendMessageThreadPoolNums is 1,
/**
 * thread numbers for send message thread pool, since spin lock will be used by default since 4.0.x, the default value is 1.
 */
private int sendMessageThreadPoolNums = 1; //16 + Runtime.getRuntime().availableProcessors() * 4;
private int pullMessageThreadPoolNums = 16 + Runtime.getRuntime().availableProcessors() * 2;

but the previous version isn't 1, and if I configure sendMessageThreadPoolNums = 100, can resolve this question ? It will lead to what is different with default value.
thanks

A: SHORT ANSWER:
you have two choices:
set sendMessageThreadPoolNums to a small number, say 1, which is the default value after version 4.1.x. And, remain the default value of useReentrantLockWhenPutMessage=false, which is introduced after 4.1.x
 sendMessageThreadPoolNums=1
 useReentrantLockWhenPutMessage=false

If you need to use a large numbers of threads to process sending message, you'd better use useReentrantLockWhenPutMessage=true
 sendMessageThreadPoolNums=128//large thread numbers
 useReentrantLockWhenPutMessage=true  // indicating that do NOT use spin lock but use ReentrantLock when putting message


text:
Q: Using Spinner To Filter Custom ArrayList in RecyclerView is clearing entire list I am attempting to filter a list of items base on their diameters.  The diameter is found within the string of the product name which is an element of the custom object.  So far when I select a diameter from the spinner it is clearing every item from the list.
Spinner Logic
 //Spinner
        diameterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Object diameterFilter = spinnerAdapter.getItem(position);
                dAdapter.getFilter().filter(diameterFilter.toString());
                dAdapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

Filter code on Adapter

    //FILTER
    @Override
    public Filter getFilter() {
        return displayFilter;
    }

    private Filter displayFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Inventory> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0){
                filteredList.addAll(displayedListFull);
            }else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (Inventory item : displayedListFull){
                    if (item.getProductName().toLowerCase().contains(filterPattern)){
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            displayedList.clear();
            displayedList.addAll((List)results.values);
            notifyDataSetChanged();
        }
    };

A: Change getItem into getItemAtPosition in the spinner callback
diameterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Object diameterFilter = spinnerAdapter.getItemAtPosition(position); // here is the change
        dAdapter.getFilter().filter(diameterFilter.toString());
        dAdapter.notifyDataSetChanged();
    }

// rest of your code

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python module grouping Is there a way in python to declare all the modules I want in one place? For example:
Modules.py
import math
import os
import re
...

main.py
import modules

os.path(path)
re.search(test)

Will help with organization and redundant code.

A: Create a new file called modules.py.
In modules.py:
import a
import b
import c
...

As long as modules.py and the script you are running are in the same dir, you can use from modules import * and it will be imported!

A: Option 1: For a quick fix, you can list the modules on the same line.
import math, os, re

os.path(path)

Option 2: Check this question for using a namespace to group modules.


text:
Q: MySQL 5.6: Slave_IO thread stops working while replicating Standard replication breaks for no apparent reason.
MariaDB [(none)]> SELECT @@version, @@version_comment;
+----------------+-------------------+
| @@version      | @@version_comment |
+----------------+-------------------+
| 5.5.52-MariaDB | MariaDB Server    |
+----------------+-------------------+
1 row in set (0.00 sec)

slave is running fine.
# mysql -e "SHOW SLAVE STATUS\G" | grep "Slave"
               Slave_IO_State: Waiting for master to send event
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it

Id  | User        | Host                        | db       | Command | Time | State                                                                       | Info             | Progress |
+-----+-------------+-----------------------------+----------+---------+------+-----------------------------------------------------------------------------+------------------+----------+
|   1 | system user |                             | NULL     | Connect |  438 | Waiting for master to send event                                            | NULL             |    0.000 |
|   2 | system user |                             | NULL     | Connect |  120 | Slave has read all relay log; waiting for the slave I/O thread to update it | NULL             |    0.000 |
|   3 | u271869     | S0280I2.ba.ad.ssa.gov:59117 | mysql    | Sleep   |    2 |                                                                             | NULL             |    0.000 |
|   4 | nagiosxi    | localhost                   | nagiosxi | Sleep   |  176 |                                                                             | NULL             |    0.000 |

mysql> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: $IP
                  Master_User: repluser
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000007
          Read_Master_Log_Pos: 433
               Relay_Log_File: mysql-relay.000265
                Relay_Log_Pos: 283
        Relay_Master_Log_File: mysql-bin.000007
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 433
              Relay_Log_Space: 710
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: Yes
           Master_SSL_CA_File: /etc/mysql/ca-cert.pem
           Master_SSL_CA_Path:
              Master_SSL_Cert: /etc/mysql/client-cert.pem
            Master_SSL_Cipher:
               Master_SSL_Key: /etc/mysql/client-key.pem
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1124732721
                  Master_UUID: 4412a455-e1d0-11e3-835a-5254007fe78d
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl: /etc/mysql/ca-cert.pem
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
1 row in set (0.00 sec)
mysql replication
shareedit
edited Jul 18 '14 at 13:16

A: Everything looks fine, what is making you think replication breaks? Is there any active writes being made to the master? If you did show master status\G on the master, as well as show processlist; are you seeing any active queries or any queries that are locked?
If you posted some of the binlog or taken a look at it, it may help you see, if replication is being broken, what exact query is breaking it. You can access the binlog by doing
mysqlbinlog binlog.file
For more reference on binlog


text:
Q: Auto close end tag by typing '  ' in Sublime Text 2 Sublime Text 2 has a default key binding to close an elements end tag automatically by typing (Alt + .)
For example,

 + (Alt + .), produces

Default keybindings are accessible through Package Controller,
{ "keys": ["alt+."], "command": "close_tag" }

However, I'm not sure how to write it for </, as this would be two keys pressed  consecutively as appose to two keys pressed at the same time.
How can I rewrite the key binding to use </?
Any insight would be helpful. Thanks!

A: Check in your preferences file if the following line exists
"auto_close_tags": true,

It works for me in Sublime Text 3.


text:
Q: Transform Dataframe Using Dplyr I have a dataframe that looks like this.
      Gene        SNP  Score
1     AKT3  rs2220276 6.5091
2 ARHGAP44  rs2220276 4.7194
3   BRINP2 rs16851037 3.2606
4 C12orf42 rs16851037 3.2563
5  CCDC122 rs11619756 4.3142
6   CCDC68 rs11619756 2.3614

I want to transform the dataframe so it looks like this - essentially creating an extra column for each element in the Gene column that matches the SNP column.
   Gene 1         SNP  Gene 1 Score       Gene 2   Gene 2 Score
1     AKT3  rs2220276        6.5091     ARHGAP44         4.7194
2   BRINP2 rs16851037        3.2606     C12orf42         3.2563
5  CCDC122 rs11619756        4.3142       CCDC68         2.3614

How can I achieve this?
df <- data.frame(Gene = c("AKT3", "ARHGAP44", "BRINP2", "C12orf42", "CCDC122","CCDC68")  ,
           "SNP" = c("rs2220276", "rs2220276", "rs16851037", "rs16851037","rs11619756", "rs11619756"),
           Score = c(6.5091, 4.7194, 3.2606, 3.2563, 4.3142, 2.3614))

A: You can transform this by using pivot_wider() from tidyr package, assisted by a helper column, id:

library(dplyr)
library(tidyr)

df %>%
  group_by(SNP) %>%
  mutate(id = row_number()) %>%
  ungroup() %>%
  pivot_wider(id_cols=SNP, names_from = id, values_from = c(Gene, Score))

Output:
  SNP        Gene_1  Gene_2   Score_1 Score_2
  <chr>      <chr>   <chr>      <dbl>   <dbl>
1 rs2220276  AKT3    ARHGAP44    6.51    4.72
2 rs16851037 BRINP2  C12orf42    3.26    3.26
3 rs11619756 CCDC122 CCDC68      4.31    2.36

A: The data is already in a favorable shape.
Anyways, the desired format can be generated using pivot_wider and unnest_wider
library(tidyr)

pivot_wider(df, SNP, values_from=c(Score, Gene), values_fn=list) |>
  unnest_wider(Score_, names_sep="") |>
  unnest_wider(Gene_, names_sep="")
# A tibble: 3 × 5
  SNP        Score_1 Score_2 Gene_1  Gene_2
  <chr>        <dbl>   <dbl> <chr>   <chr>
1 rs2220276     6.51    4.72 AKT3    ARHGAP44
2 rs16851037    3.26    3.26 BRINP2  C12orf42
3 rs11619756    4.31    2.36 CCDC122 CCDC68

A: Assuming you always want to keep the first occurrence of any duplicate you can do
library(tidyverse)

df %>%
  distinct(SNP, .keep_all = TRUE)

     Gene        SNP  Score
1    AKT3  rs2220276 6.5091
2  BRINP2 rs16851037 3.2606
3 CCDC122 rs11619756 4.3142

A: Using dcast
library(data.table)
dcast(setDT(df), SNP ~ rowid(SNP), value.var = c("Gene", "Score"))
Key: <SNP>
          SNP  Gene_1   Gene_2 Score_1 Score_2
       <char>  <char>   <char>   <num>   <num>
1: rs11619756 CCDC122   CCDC68  4.3142  2.3614
2: rs16851037  BRINP2 C12orf42  3.2606  3.2563
3:  rs2220276    AKT3 ARHGAP44  6.5091  4.7194

Or similar option with pivot_wider
library(tidyr)
library(dplyr)
df %>%
   mutate(rn = rowid(SNP)) %>%
   pivot_wider(names_from = rn, values_from = c(Gene, Score))
# A tibble: 3 × 5
  SNP        Gene_1  Gene_2   Score_1 Score_2
  <chr>      <chr>   <chr>      <dbl>   <dbl>
1 rs2220276  AKT3    ARHGAP44    6.51    4.72
2 rs16851037 BRINP2  C12orf42    3.26    3.26
3 rs11619756 CCDC122 CCDC68      4.31    2.36


text:
Q: Updating a node module without updating its dependencies We have our own node module that we use to keep shared code for several of our internal projects.  The entry in package.json looks like this:
"dependencies": {
  "foo": "git+https://github.secureserver.net/MyProject/foo.git#master",
}

As a matter of practice, we keep our dependent node modules checked into git along with the project code.  For example, our tree in git looks something like this:
application\
config\
package.json
node_modules\
test\

Whenever we do an "npm update foo" in any of the projects that depends on foo we get the updated foo but then npm also updates the node modules that foo depends on even though they are checked into git along with foo.  This is not what we want.  On "npm update" we want foo and all of its node modules to exactly mirror what's in master because that's what foo was tested with.  We could require exact versions of modules in the package.json in foo but that makes updating foo's dependencies more problematic when we want to check in new versions.  How can we get "npm update foo" to pull foo from Github without having it update foo's node_modules?

A: This looks like a job for npm shrinkwrap!
In the foo project directory, run npm shrinkwrap.  This will generate a npm-shrinkwrap.json with the installed versions of your dependencies, their dependencies, all the way down.
When npm install is run against foo, the versions specified in npm-shrinkwrap.json will take precedence over package.json.
One caveat: npm won't look in package.json at all, so if you use npm install --save or edit package.json directly to install new packages, you'll need to also rerun npm shrinkwrap.


text:
Q: Excel: text-to-columns anomaly I have a large-ish pipe delimited CSV file which is causing me some serious trouble. It has data until column FM, so more than 150 columns, and 6496 rows.

*

*Opening the file in a text editor, shows 6496 lines.

*Renaming the file to a .txt file, the open with text importer, shows 6496 lines.

*Opening the CSV file in Excel, then use text-to-columns functionality, shows 6490 lines.

Somehow, 6 lines go missing.
I am using Excel 2007 on Windows 7, on this particular computer, but the client is using Excel 2013 on Windows 8.1, so it is not a "version" thing, as far as I can tell, unless both versions are affected.
Any ideas?

A: Perhaps some lines are combined when you open the .csv? I would import into Excel, in both ways, and then do a line by line comparison; then examine closely the "missing" lines.
I would suspect some subtle difference in the lines -- perhaps something that is causing the EOL to be misinterpreted when you OPEN the CSV file.


text:
Q: How to get the expiration time of the ssl certification of a kubernetes cluster with kubernetes-python-client? I have four kubernetes clusters, and I want to check the expiration time of them with kubernetes-python-client.
I am following this page: https://github.com/kubernetes-client/python
Is there anyone know how to get it?

A: The apiserver certificate is generally handled out of band, either by your Kubernetes installer tool (kubeadm, rancher, talos, etc) or off-cluster in a load balancer layer. As such the K8s API won't help you with this.
That said, you can get the certificate of any HTTPS server in Python using ssl.get_server_certificate() (https://docs.python.org/3/library/ssl.html#ssl.get_server_certificate) along with other functions in the ssl module to parse the cert data and then look at the Not After timestamp.


text:
Q: Obtaining nearest neighbor distances from a distance matrix in R I have a large dataset that is a list of 1500 pairwise distance matrices created with the dist command in R.  I need to get the nearest neighbor for each 'individual' in each of the 1500 matrices (which differ in the number of individuals they contain), but am having problems.  I've found other links Computing sparse pairwise distance matrix in R that will supposedly do this for a distance matrix but the first issue is that it seems to leave one individual out of every matrix.  If there are 6 individuals, it only returns nearest neighbors for the first 5.  The other issue is that it doesn't return the same values that are in the original distance matrix (as it shows in the link) but rather is changing the values.  Are there any newer packages or commands that can do this?  Or does anyone know of a trick to be able to do this?  Thanks!
Here is an example matrix and desired output
      a  b  c   d   e
b   1.5
c   1.3 2.3
d   2.2 2.1 3.1
e   2.4 1.4 1.6 2.2
f   3.2 1.6 2.7 3.1 1.5

desired output
a   1.3
b   1.4
c   1.3
d   2.1
e   1.4
f   1.5

EDITED to show the loop I'm trying to use with digEmAll's suggestion, which works on a single matrix.  dists is a list of distance matrices already computed that I need the nearest neighbors from.
nearest<-list()
tempd<-list()
runndist<- for (i in 1:1561) {
tempd[[paste(i)]]<-as.matrix(dists[[i]])
nearest[[paste(i)]]<-diag(tempd[[i]]) <-NA;apply(tempd[[i]],1,min,na.rm=TRUE)}

EDIT  Got the loop to work and this now gives the nearest neighbor distance for all matrices in the list.  I'm sure this can be done much more elegantly, but it worked for what I need.
 nearest<-list()
tempd<-list()
tempd2<-list()
runndist<- for (i in 1:1561) {
tempd[[paste(i)]]<-as.matrix(dists[[i]])
tempd2[[paste(i)]]<-diag(tempd[[i]])<-NA

tryCatch({
    nearest[[paste(i)]]<-apply(tempd[[i]],1,min,na.rm=TRUE)
    if (i==7) stop("could not calculate")
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}


text:
Q: Gmarker custom icon not showing full size We have manage to create markers with custom icon where we define first the icon for e.g.
var pIcon = new google.maps.MarkerImage('alertIcon/P.png',
                                         new google.maps.Size(15, 15));

Then we define the marker in this manner.
var marker = new google.maps.Marker({
                            position: point,
                            map: map,
                            icon: yIcon
                        });

The issue now the custom icon appear but just partial of it not the complete one as we had in V2 what could be issue here?

A: An icon for a Google maps marker just needs to be a string for the URL of the icon image. Creating a MarkerImage is probably causing the Google maps api to scale down the size of your custom icon.
    var pIcon = "alertIcon/P.png"

This is all you should need when defining your icon.

A: var pIcon = new google.maps.MarkerImage('alertIcon/P.png',
    // This might be where you're running into trouble, set
    // Size(w,h) to the dimensions of the image
    new google.maps.Size(72, 95),
    // This is the origin, probably want to keep it at 0,0
    new google.maps.Point(0,0),
    // This is the anchor. For Point(x,y) x should be
    // half the image width and y should be the height
    new google.maps.Point(36, 95)
);


text:
Q: How to return to previous value in dictionary given a specific value? I have different tax rates for different income levels.
I am trying to return the previous tax rate from the tax rate acquired from a function. How can I get it to return to the previous tax rate?
tax_levels = [
{
    "min": 0,
    "max": 999,
    "rate": 1,
},
{
    "min": 1000,
    "max": 1999,
    "rate": 5
},
]

current_rate = 5
previous_rate = ??

I am trying to get it to return to 1 for previous_rate using the variable current_rate.

A: You can define a function
def previous_tax_rate(current_rate, tax_levels):
    for index, tax_level in enumerate(tax_levels):
        if tax_level['rate'] == current_rate:
            return tax_levels[index - 1]['rate']

A: tax_level[0]['rate']

tax_level is a list containing dictionaries.
tax_level[0] will give you the first dictionary in the list.
['rate'] will give you the value of the key 'rate' in the first dictionary in the tax_level list of dictionaries.


text:
Q: How to handle ISO date strings in TypeScript? I'm brand new to typescript, so I'm trying to get the hang of it.
A network request is going to return a JSON object with a field in ISO Date string format.
data : Data = {when: "2016-07-13T18:46:01.933Z"}

When I create the type signature for this interface, is there any way of specifying that this is actually an ISO timestamp or do I just have to use string?
interface Data {
  when: string
}

I found out I could use a type alias which mentally helps, but doesn't really validate the ISO string.
type iso = string
interface Data {
  when: iso
}

On a similar vein, I'm curious if there's anyway to generate js validation from these typescript annotations so I can validate the information received by the endpoint, otherwise the rest of my typed application is worthless.
If this is possible then it would be really cool if this iso string could be coerced into an actual Date object.
As I said, I'm new to typescript, so I'm not sure if this is beyond the scope of what typescript is supposed to do.

A: You can use a Type Guard.
import moment from 'moment'

export const isISO = (input: any): input is tISO =>
  moment(input, moment.ISO_8601, true).isValid()

Then you can use whatever custom logic in your you want to handle any bad dates, e.g.:
const maybeISO = fetch('Maybe ISO')

if (isISO(maybeISO)) {
  // proceed
} else {
  // check other format?
  // log error?
}

Cheers.

A:
it would be really cool if this iso string could be coerced into an actual Date object

No this is not possible. For javascript there's nothing to do with typescript's interfaces. (JS is not generated at all for interfaces). Also all the type checks are done at "compile" or "transpile" time, not at run time.
What you can do, is to use reviver function when parsing json. For example:
const datePattern = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
const json = '{"when": "2016-07-13T18:46:01.933Z"}';

const result = JSON.parse(json, (key: any, value: any) => {
    const isDate = typeof value === 'string' && datePattern.exec(value);
    return isDate? new Date(value) : value;
});

Also you can identify Date property by key and in case it doesn't match the date pattern you could throw an error or do whatever you want.

A: Try this:
// In TS, interfaces are "open" and can be extended
interface Date {
  /**
   * Give a more precise return type to the method `toISOString()`:
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
   */
  toISOString(): TDateISO;
}

type TYear         = `${number}${number}${number}${number}`;
type TMonth        = `${number}${number}`;
type TDay          = `${number}${number}`;
type THours        = `${number}${number}`;
type TMinutes      = `${number}${number}`;
type TSeconds      = `${number}${number}`;
type TMilliseconds = `${number}${number}${number}`;

/**
 * Represent a string like `2021-01-08`
 */
type TDateISODate = `${TYear}-${TMonth}-${TDay}`;

/**
 * Represent a string like `14:42:34.678`
 */
type TDateISOTime = `${THours}:${TMinutes}:${TSeconds}.${TMilliseconds}`;

/**
 * Represent a string like `2021-01-08T14:42:34.678Z` (format: ISO 8601).
 *
 * It is not possible to type more precisely (list every possible values for months, hours etc) as
 * it would result in a warning from TypeScript:
 *   "Expression produces a union type that is too complex to represent. ts(2590)
 */
type TDateISO = `${TDateISODate}T${TDateISOTime}Z`;

The source

A: You can use DateFromISOString from io-ts-types
See its documentation.


text:
Q: Can YouTube API retrieve captions of an unlisted video? Is it possible to retrieve the captions track for an unlisted video using the YouTube Data API v3?  The video is in a playlist and has a known URL, but I am not the content owner.
What I have tried:

*

*captions/list does not find video with matching ID.

*playlistItmes/list returns the correct video ID, but no new information that lets it work with captions/list.

*Youtube API get unlisted videos

*Maybe there is a URL approach similar to this?


text:
Q: What response times can be expected from GAE/NDB? We are currently building a small and simple central HTTP service that maps "external identities" (like a facebook id) to an "internal (uu)id", unique across all our services to help with analytics.
The first prototype in "our stack" (flask+postgresql) was done within a day. But since we want the service to (almost) never fail and scale automagically, we decided to use Google App Engine.
After a week of reading&trying&benchmarking this question emerges:
What response times are considered "normal" on App Engine (with NDB)?
We are getting response times that are consistently above 500ms on average and well above 1s in the 90percentile.
I've attached a stripped down version of our code below, hoping somebody can point out the obvious flaw. We really like the autoscaling and the distributed storage, but we can not imagine 500ms really is the expected performance in our case. The sql based prototype responded much faster (consistently), hosted on one single Heroku dyno using the free, cache-less postgresql (even with an ORM).
We tried both synchronous and asynchronous variants of the code below and looked at the appstats profile. It's always RPC calls (both memcache and datastore) that take very long (50ms-100ms), made worse by the fact that there are always multiple calls (eg. mc.get() + ds.get() + ds.set() on a write). We also tried deferring as much as possible to the task queue, without noticeable gains.
import json
import uuid

from google.appengine.ext import ndb

import webapp2
from webapp2_extras.routes import RedirectRoute

def _parse_request(request):
    if request.content_type == 'application/json':
        try:
            body_json = json.loads(request.body)
            provider_name = body_json.get('provider_name', None)
            provider_user_id = body_json.get('provider_user_id', None)
        except ValueError:
            return webapp2.abort(400, detail='invalid json')
    else:
        provider_name = request.params.get('provider_name', None)
        provider_user_id = request.params.get('provider_user_id', None)

    return provider_name, provider_user_id

class Provider(ndb.Model):
    name = ndb.StringProperty(required=True)

class Identity(ndb.Model):
    user = ndb.KeyProperty(kind='GlobalUser')

class GlobalUser(ndb.Model):
    uuid = ndb.StringProperty(required=True)

    @property
    def identities(self):
        return Identity.query(Identity.user==self.key).fetch()

class ResolveHandler(webapp2.RequestHandler):
    @ndb.toplevel
    def post(self):
        provider_name, provider_user_id = _parse_request(self.request)

        if not provider_name or not provider_user_id:
            return self.abort(400, detail='missing provider_name and/or provider_user_id')

        identity = ndb.Key(Provider, provider_name, Identity, provider_user_id).get()

        if identity:
            user_uuid = identity.user.id()
        else:
            user_uuid = uuid.uuid4().hex

            GlobalUser(
                id=user_uuid,
                uuid=user_uuid
            ).put_async()

            Identity(
                parent=ndb.Key(Provider, provider_name),
                id=provider_user_id,
                user=ndb.Key(GlobalUser, user_uuid)
            ).put_async()

        return webapp2.Response(
            status='200 OK',
            content_type='application/json',
            body = json.dumps({
                'provider_name' : provider_name,
                'provider_user_id' : provider_user_id,
                'uuid' : user_uuid
            })
        )

app = webapp2.WSGIApplication([
      RedirectRoute('/v1/resolve', ResolveHandler, 'resolve', strict_slash=True)
], debug=False)

For completeness sake the (almost default) app.yaml
application: GAE_APP_IDENTIFIER
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: .*
  script: main.app

libraries:
- name: webapp2
  version: 2.5.2
- name: webob
  version: 1.2.3

inbound_services:
- warmup

A: In my experience, RPC performance fluctuates by orders of magnitude, between 5ms-100ms for a datastore get.  I suspect it's related to the GAE datacenter load.  Sometimes it gets better, sometimes it gets worse.
Your operation looks very simple.  I expect that with 3 requests, it should take about 20ms, but it could be up to 300ms.  A sustained average of 500ms sounds very high though.
ndb does local caching when fetching objects by ID.  That should kick in if you're accessing the same users, and those requests should be much faster.
I assume you're doing perf testing on the production and not dev_appserver.  dev_appserver performance is not representative.
Not sure how many iterations you've tested, but you might want to try a larger number to see if 500ms is really your average.
When you're blocked on simple RPC calls, there's not too optimizing you can do.

A: The 1st obvious moment I see: do you really need a transaction on every request?
I believe that unless most of your requests create new entities it's better to do .get_by_id() outside of transaction. And if entity not found then start transaction or even better defer creation of the entity.
def request_handler(key, data):
  entity = key.get()
  if entity:
    return 'ok'
  else:
    defer(_deferred_create, key, data)
    return 'ok'

def _deferred_create(key, data):
  @ndb.transactional
  def _tx():
    entity = key.get()
    if not entity:
       entity = CreateEntity(data)
       entity.put()
  _tx()

That should give much better response time for user facing requests.
The 2nd and only optimization I see is to use ndb.put_multi() to minimize RPC calls.
P.S. Not 100% sure but you can try to disable multithreading (threadsave: no) to get more stable response time.


text:
Q: Reorder a graph in ggplot2 I have a df that seems like this:
    CIUDAD    MPond_Ciud IDPROV MPond_Prov   PCPROV     DIFMP
1     ABANCAY   513.2121    301   490.4090 72.28465  22.80311
2 ANDAHUAYLAS   382.7516    302   318.6479 57.21274  64.10372
3    AREQUIPA   703.0134    401   683.6721 93.61579  19.34131
4    AYACUCHO   461.3796    501   387.6766 79.26356  73.70302
5     AYAVIRI   404.8749   2108   253.2098 36.42051 151.66505
6    AZANGARO   289.3249   2102   183.8901 27.23929 105.43477

##DIFMP is the result of MPond_Ciud - MPond_Prov

What I am looking for is to obtain a graph that allows visualizing the distance between MPond_Ciud and MPond_Prov. For that I use this code
ggplot(df) +
  geom_segment( aes(x=CIUDAD, xend=CIUDAD, y=MPond_Prov, yend=MPond_Ciud), color="grey") +
  geom_point( aes(x=CIUDAD, y=MPond_Prov), color=rgb(0.2,0.7,0.1,0.5), size=3 ) +
  geom_point( aes(x=CIUDAD, y=MPond_Ciud), color=rgb(0.7,0.2,0.1,0.5), size=3 ) +
  coord_flip()+
  theme(
    legend.position = "none",
  ) +
  xlab("") +
  ylab("")

which returns this graph:

In principle it is not bad, but if you notice the Y axis is ordered alphabetically. What I want is to reorder it from highest to lowest values of column DIFMP.
Is there a way to do so?

A: Original image:

df$CIUDAD <- factor(df$CIUDAD, levels=unique(df$CIUDAD[order(df$DIFMP)]))
df[order(df$DIFMP),]
#        CIUDAD MPond_Ciud IDPROV MPond_Prov PCPROV  DIFMP
# 3    AREQUIPA      703.0    401      683.7  93.62  19.34
# 1     ABANCAY      513.2    301      490.4  72.28  22.80
# 2 ANDAHUAYLAS      382.8    302      318.6  57.21  64.10
# 4    AYACUCHO      461.4    501      387.7  79.26  73.70
# 6    AZANGARO      289.3   2102      183.9  27.24 105.43
# 5     AYAVIRI      404.9   2108      253.2  36.42 151.67

Newly ordered image:


text:
Q: Why does 'const' behave differently in these two cases? I have a question about just why a certain thing can be compiled when done "in one step" but can't when done "in two steps". I have three classes;
class Time {
  int mTime;

  int Time::getTimeAsUnix() const {return mTime;}
}

class Travel {
  Time mTimestamp;

  const Time& Travel::getTime() const { return mTimestamp; }
  Time& Travel::getTime() { return mTimestamp; }
}

class Analysis : public Travel {

  int Analysis::getUnixTime() const {
    // Time& t = Travel::getTime();
    // return t.getTimeAsUnix();     // This does NOT compile

    return Travel::getTime().getTimeAsUnix();  // This compiles
  }
}

Anyone knows why, in the Analysis class, the non-commented approach compiles while the commented approach gives me an instant "c++ error: binding 'const Time' to reference of type 'Time&' discards qualifiers" when I try?
Aren't the two the exact same thing when executed??

A: The line
Time& t = Travel::getTime();

needs to be
const Time& t = Travel::getTime();

for it to work.  The reason this is needed is because you are inside a const-qualified function.  When you are in  a const-qualified function all members of the class are considered to be const.  That means when you call getTime you call the
const Time& Travel::getTime() const { return mTimestamp; }

version of the function.  Trying to assign a const Time& to a Time& wont work because you would be stripping away the constness of the return type.

A: In this function definition where you shall remove Analysis::
  int Analysis::getUnixTime() const {
     Time& t = Travel::getTime();
     return t.getTimeAsUnix();
  }

there is called the function
const Time& Travel::getTime() const { return mTimestamp; }

that returns a constant reference. It is this overloaded function is used because the function getUnixTime declared as a const member function.
However the constant reference is assigned to a non-constant reference
     Time& t = Travel::getTime();

so the compiler issues an error.

A: Okay, let's break down the working version:
int Analysis::getUnixTime() const { // (1)
    // (2) --------v        v----- (3)
    return Travel::getTime().getTimeAsUnix();
}

At (1), the function getUnixTime is defined to work on a constant instance. That means you can only call other constant functions and can't change any member variables.
At (2), Travel::getTime() is called. This call a non-static member function, depite its syntax. But that's okay, it's clear and calls the const version of the function, which return const Time&. A reference to a constant Time object.
At (3), the member function getTimeAsUnix gets called on a const Time&.  This is perfect because Time has a member function named that way that is marked to work on constant objects.
So as you see, every objects are constant and you only call constant function.

What went wrong when you broke down the code in two lines?
Let's take a look at the first line in the body of you function:
Time& t = Travel::getTime();

As we stated, Travel::getTime() calls a non-static member function. Since this is a constant object (you're in a const function) then the const version of getTime gets called, just as before.
The return type of the const getTime is const Time&.
Then you do Time& t =. This is where you error is. const Time& cannot be modified. A Time& can be modified. If you refer to a constant object using a mutable reference, then you'd be able to mutate constant object. The language prohibit that!
To fix this, simply use constant references:
const Time& t = Travel::getTime();


text:
Q: Google + access token insufficient permission Using OAuth code i am able to generate access token for google+ API .
using this access token in oauthpalyground iam getting JSON response .
When I paste this this URL into a browser am get an error message.
 https://www.googleapis.com/plus/v1/activities?query=%22great%22&access_token=xxxxxxxxxxx

Error Message
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

Can anyone explain to me why?

A: You can not query directly from browser sending the access_token as a querystring. You must send access_ token in headers this way:
Authorization: Bearer <access_token>

Try it with Fiddler or some similar software.


text:
Q: DotNetNuke module position and panes I have been using DotNetNuke for a couple of weeks but there is one thing I can't figure out.  How can I find out which pane a module currently resides in.  I have used mostly version 7 but I have tried version 6 too.  I can't find this information anywhere.
When a page is in Edit Mode in 7.x there is an option to move a module to a different pane by hovering over the Move Icon.  DNN displays a list of panes where the module can be moved when the mouse is over the Move Icon.  DNN knows what pane the module is currently in because the current pane is excluded from the list.  However, under the Settings for a module there is no property to tell you in which pane the module resides.
This is really important because most skins have LOTS (20+) of different panes.  Usually panes are collapsible it is quite hard to tell which pane a module is in based solely on the position of the module on the page.  Knowing the current pane of one module is required to get the correct layout when you add new modules.
The only thing that works is to use process of elimination.  I can figure out a module's current pane if I can find which pane is NOT in the list of panes where I can move that module.  This method is tedious and un-usable if you are trying to work with modules via the Page Management admin screen.  Am I missing where to find this property or is not available.  If it is not available then is there are better way to position items that I am missing?

A: Layout Mode should show you the PANE names. If you don't have Pane Names then it is possible that the Skin you are using has hidden the the name of the pane, but why they would do that I don't know.
Here's an Example of one of the Panes in my MultiFunction skin (available on codeplex) when in Layout Mode
TopPane


text:
Q: mongo - unique name field base on parent_id field I have a collection parents with sample documents
===FIRST DOCUMENT===
_id: 1111,
name: Parent 1
===SECOND DOCUMENT===
_id: 2222,
name: Parent 2

I have a collection children with sample documents
===FIRST DOCUMENT===
_id: 123123131321,
parent_id: 1111,
name: Child 1

===SECOND DOCUMENT===
_id: 29139114142,
parent_id: 2222,
name: Child 2

I want to make field name unique when We have the same parent_id
For example:
_id: 10239120321da,
parent_id: 2222,
name: Child 2

Attempt to insert above document into children collection should throws exception DuplicateKeyError.
I read something about Partial Index but I don't know that this is the proper path.
I'm using python with flask.

A: For a mongoDB collection that is named "collectionName",
db.collectionName.createIndex( { parent_id: 1, name: 1}, { unique: true } )


text:
Q: Python - Compare first item in sublist, if repeated, compare third item and pick lesser value So I have a list that has sublists within it.
For example
biglist = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Hello', 'Friend', '1.5'],
['Blue', 'Yo', 'Dude', '1.2'], ['Green', 'Bon', 'Jour', '0.1'],
['Purple', 'Hey', 'Sup', '0.4'], ['Purple', 'Greetings', 'Pal', '2.8']]

This is what I am trying to do...I want to iterate though this to do the following:

*

*For each sublist, read position 0.

*If there is another sublist with the same string at position 0, then read position 3

*Whichever number is lower in position three, delete the other sublist entirely and keep the sublist with the smaller value. Some times there are more than 2 sublists with the same position[0]

So, for my example list. I want to keep the 'Red' sublist, compare the two 'Blue' sublists and keep the one with the smaller numerical value at specific position 3, then also keep the 'Green' sublist. I have been messing around with set() but am a little stumped. At first I tried hashing it to where that 0 position (red, blue etc) was the key, and the rest of the positions were the values (as a list) but I got stuck and went a different route.
Desired result:
biglist = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Yo', 'Dude', '1.2'],
['Green', 'Bon', 'Jour', '0.1'], ['Purple', 'Hey', 'Sup', '0.4']]

To note: the list I am using is being passed on by a previous function.
I found this on another question, however set() confuses me a bit and I don't know how to further look into that third position or how to properly pass the list I've already created via another function before this one in the same script. When I run this while trying to pass the list on, I get nothing out.
def unique_items(L):
found = set()
for item in L:
    if item[0] not in found:
        yield item
        found.add(item[0])

Thank you so much.

A: First, I would create a dictionary of lists with first item in sublist (color) as key and value would be the tuple (index of sublist in list, last item in sublist):
from collections import defaultdict
x = defaultdict(list)

# This for loop extracts the index of each sublist (i) and then
# assigns the contents of the sublist to variables, in this case
# we want the first item in the sublist to be the 'key', ignore
# everything in between and grab the last item as the 'val'.
# If the sublists have arbitrary number of items then you could
# use for i, item in enumerate(biglist) and replace key with
# item[0] and val with item[3]
for i, (key, *_, val) in enumerate(biglist):
    x[key].append((i, float(val))

x now looks like:
defaultdict(<class 'list'>, {'Blue': [(1, '1.5'), (2, '1.2')], 'Purple': [(4, '0.4'), (5, '2.8')], 'Green': [(3, '0.1')], 'Red': [(0, '0.534')]})

Then I would create a new list by

*

*sorting the entries for each color in the dictionary, x, in ascending order so that the first item in the list is the item with the smallest "weight" value (what you called position 3

*taking the first item of that sorted list which is a tuple containing the sublist index as its first item

*finally retrieve the sublist using the index

So something like:
res = [biglist[sorted(val, key=lambda x: x[1])[0][0]] for val in x.values()]

res now contains
[['Blue', 'Yo', 'Dude', '1.2'],
 ['Purple', 'Hey', 'Sup', '0.4'],
 ['Green', 'Bon', 'Jour', '0.1'],
 ['Red', 'HiThere', '0.534']]

A: Here's another approach - I think slightly more readable
# result_list for verification
result_list = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Yo', 'Dude', '1.2'], ['Green', 'Bon', 'Jour', '0.1'], ['Purple', 'Hey', 'Sup', '0.4']]

# original list
biglist = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Hello', 'Friend', '1.5'], ['Blue', 'Yo', 'Dude', '1.2'], ['Green', 'Bon', 'Jour', '0.1'],
['Purple', 'Hey', 'Sup', '0.4'], ['Purple', 'Greetings', 'Pal', '2.8']]

another_list = []

import itertools

# Sort the big list by tuple of x[0], x[3] First sort by x[0] and then resolve tie by x[3]
biglist = sorted(biglist, key=lambda x:(x[0],x[3]))

# now group the list by the first element of each list, y gives an iterator, we simply make a list of that and take first element.

for x, y in itertools.groupby(biglist, lambda x:x[0]):
    another_list.append(list(y)[0])

# following line is just for verification
print another_list == sorted(result_list)

Note: here the order in the original list is not preserved. If you want that to be preserved, following should work
 result_list = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Yo', 'Dude', '1.2'],
['Green', 'Bon', 'Jour', '0.1'], ['Purple', 'Hey', 'Sup', '0.4']]
biglist = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Hello', 'Friend', '1.5'],
['Blue', 'Yo', 'Dude', '1.2'], ['Green', 'Bon', 'Jour', '0.1'],
['Purple', 'Hey', 'Sup', '0.4'], ['Purple', 'Greetings', 'Pal', '2.8']]

#print sorted(sorted(biglist), key=lambda x:(x[0],x[3]))
cleanup_list = []
import itertools
s_biglist = sorted(biglist, key=lambda x:(x[0],x[3]))

for x, y in itertools.groupby(s_biglist, lambda x:x[0]):
    cleanup_list.extend(list(y)[1:])

for x in cleanup_list:
    biglist.remove(x)

print biglist

A: Thank you so much everyone! This is how I solved it my own way. Maybe it is not the best way and I know my variables aren't named the best (I actually named them simplistic purposefully in this example, but for my real script they are specific and unique). The actual input list is from a file that is 50,000+ lines long.
#!/usr/bin/python

from collections import defaultdict

biglist = [['Red', 'Hi', 'There', '0.534'], ['Blue', 'Hello', 'Friend', '1.5'],
['Blue', 'Yo', 'Dude', '1.2'], ['Green', 'Bon', 'Jour', '0.1'],
['Purple', 'Hey', 'Sup', '0.4'], ['Purple', 'Greetings', 'Pal', '2.8']]

x = defaultdict(list)
for item in biglist:
    x[item[0]].append(item[1:])

y = dict(x)

for key, value in y.items():
    FINAL = []
    if len(value) <= 1:
        FINAL.append(value)
    else:
        valuelist = []
        for version in value:
            valuelist.append(version[3])
            best = min(valuelist)
        for version in value:
            if version[3] == best:
                FINAL.append(version)
        y[key] = FINAL
print y


text:
Q: sort two array list simuntaneously in one activity I am working on application in which i want one output as shown in below image.

for that i tried following code:
private ListView notification_listview;
    private String BeauticianId="98";
    private String serviceType="all";
    private ArrayList<NameValuePair> params11;
    ArrayList<MainArray_method> MainList;
    MainArray_adapter main_adapter;
    ArrayList<SubArray_method> SubList;
    SubArray_adapter sub_adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        notification_listview = (ListView) findViewById(R.id.listView_notification);

    }

    @Override
    public void onResume() {
        super.onResume();
        params11 = new ArrayList<NameValuePair>();
        params11.add(new BasicNameValuePair("iBeauticianId", BeauticianId));
        params11.add(new BasicNameValuePair("serviceType", serviceType));

        new background().execute();

    }

    private class background extends AsyncTask<Void, Void, String> {

        ProgressDialog pDialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.setMessage("Please Wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        protected String doInBackground(Void... params) {
            String obj;//new JSONArray();
            try {
                obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/services", params11);
                return obj;
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String result) {
            super.onPostExecute(result);

            Log.e("Result", "" + result);

            try {
                JSONObject json = new JSONObject(result);
                String status = json.getString("status");
                Log.d("Status:", status);

                String data = json.getString("data");
                Log.d("Data:", data);

                MainList = new ArrayList<MainArray_method>();
                JSONArray MainArray = json.getJSONArray("data");

                for (int i = 0; i < MainArray.length(); i++) {

                    JSONObject jsonObject = MainArray.getJSONObject(i);

                    String MainServiceId = jsonObject.getString("iMainServiceId");
                    Log.d("MainServiceId:", MainServiceId);

                    String MainService = jsonObject.getString("main");
                    Log.d("MainService:", MainService);

                    String sub = jsonObject.getString("sub");
                    Log.d("sub:", sub);

                    SubList = new ArrayList<SubArray_method>();
                    JSONArray SubArray = jsonObject.getJSONArray("sub");
                    for (int j = 0; j < SubArray.length(); j++) {

                        /*JSONObject subjsonObject = SubArray.getJSONObject(j);*/

                        /*String SubServiceId = subjsonObject.getString("iSubServiceId");
                        Log.d("subserviceid:", SubServiceId);

                        String SubServiceName = subjsonObject.getString("vName");
                        Log.d("SubServiceName:", SubServiceName);

                        String SubServicePrice = subjsonObject.getString("fPrice");
                        Log.d("SubServicePrice:", SubServicePrice);

                        String SubServiceTime = subjsonObject.getString("vDuration");
                        Log.d("SubServiceTime:", SubServiceTime);*/
                        MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
                                MainArray.getJSONObject(i).getString("main")));

                        SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
                                SubArray.getJSONObject(j).getString("vName"),
                                SubArray.getJSONObject(j).getString("fPrice"),
                                SubArray.getJSONObject(j).getString("vDuration")));
                    }
                }

                if (main_adapter== null && sub_adapter == null)
                {
                    main_adapter=new MainArray_adapter(getApplicationContext(),MainList);
                    notification_listview.setAdapter(main_adapter);

                    sub_adapter=new SubArray_adapter(getApplicationContext(),SubList);
                    notification_listview.setAdapter(sub_adapter);

                } else {
                    sub_adapter.notifyDataSetChanged();
                    main_adapter.notifyDataSetChanged();
                }

            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            pDialog.dismiss();
        }

        public String getJSONFromUrl(String url, List<NameValuePair> params) {
            InputStream is = null;
            String json = "";

            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    //sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
                Log.e("JSON", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            return json;

        }
    }

but in this i just get two  record of subarray.
What should i do to get output as shown in image.
Thanks in advance.
JSON response:
  {
   "status":1,
   "data":[
      {
         "iMainServiceId":1,
         "main":"NAILS",
         "sub":[
            {
               "iSubServiceId":1,
               "vName":"Manicure",
               "fPrice":15,
               "vDuration":"20 Minutes"
            },
            {
               "iSubServiceId":2,
               "vName":"Gel Manicure",
               "fPrice":25,
               "vDuration":"30 Minutes"
            },
            {
               "iSubServiceId":5,
               "vName":"Nail art ",
               "fPrice":10,
               "vDuration":"20 Minutes"
            },
            {
               "iSubServiceId":6,
               "vName":"Nail Pain ",
               "fPrice":10,
               "vDuration":"20 Minutes"
            }
         ]
      },
      {
         "iMainServiceId":2,
         "main":"HAIR",
         "sub":[
            {
               "iSubServiceId":3,
               "vName":"Haircuts",
               "fPrice":20,
               "vDuration":"30 Minutes"
            },
            {
               "iSubServiceId":4,
               "vName":"Hair color",
               "fPrice":50,
               "vDuration":"60 Minutes"
            },
            {
               "iSubServiceId":7,
               "vName":"Textures",
               "fPrice":20,
               "vDuration":"30 Minutes"
            },
            {
               "iSubServiceId":8,
               "vName":"Treatments",
               "fPrice":30,
               "vDuration":"60 Minutes"
            }
         ]
      },
      {
         "iMainServiceId":3,
         "main":"Face",
         "sub":[
            {
               "iSubServiceId":9,
               "vName":"Facials",
               "fPrice":20,
               "vDuration":"49 Minutes"
            },
            {
               "iSubServiceId":10,
               "vName":"Brow Bar",
               "fPrice":40,
               "vDuration":"49 Minutes"
            },
            {
               "iSubServiceId":11,
               "vName":"Makeup ",
               "fPrice":40,
               "vDuration":"49 Minutes"
            }
         ]
      },
      {
         "iMainServiceId":4,
         "main":"Body",
         "sub":[
            {
               "iSubServiceId":12,
               "vName":"Hair Removal",
               "fPrice":40,
               "vDuration":"49 Minutes"
            },
            {
               "iSubServiceId":13,
               "vName":"Body Treatments",
               "fPrice":30,
               "vDuration":"30 Minutes"
            }
         ]
      }
   ]
}

and wt i get as enter image description hereoutput is:

A: for (int i = 0; i < MainArray.length(); i++) {

    JSONObject jsonObject = MainArray.getJSONObject(i);

    String MainServiceId = jsonObject.getString("iMainServiceId");
    Log.d("MainServiceId:", MainServiceId);

    String MainService = jsonObject.getString("main");
    Log.d("MainService:", MainService);

    String sub = jsonObject.getString("sub");
    Log.d("sub:", sub);

    SubList = new ArrayList<SubArray_method>();
    JSONArray SubArray = jsonObject.getJSONArray("sub");
    for (int j = 0; j < SubArray.length(); j++) {

        /*JSONObject subjsonObject = SubArray.getJSONObject(j);*/

        /*String SubServiceId = subjsonObject.getString("iSubServiceId");
        Log.d("subserviceid:", SubServiceId);

        String SubServiceName = subjsonObject.getString("vName");
        Log.d("SubServiceName:", SubServiceName);

        String SubServicePrice = subjsonObject.getString("fPrice");
        Log.d("SubServicePrice:", SubServicePrice);

        String SubServiceTime = subjsonObject.getString("vDuration");
        Log.d("SubServiceTime:", SubServiceTime);*/

        SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
                SubArray.getJSONObject(j).getString("vName"),
                SubArray.getJSONObject(j).getString("fPrice"),
                SubArray.getJSONObject(j).getString("vDuration")));
    }
    // This should be in outer for loop<<---------------------<<<<<
    MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
                MainArray.getJSONObject(i).getString("main")));
}


text:
Q: Loading transactional email for different store issue I created this file:
app/locale/fr_FR/template/email/html/footer.html

I want to load it for france. So I went to system->t.emails -> selected the Email-Footer template -> select this option value:
<option value="fr_FR">French (France)</option>

from locale and then I pressed the Load Template button , but i got the content from:
app/locale/en_US/template/email/html/footer.html

Any idea why ? I am using enterprise version:1.14.3.0.  Thx

A: you need to add an entry to your config.xml file like shown below.
<global>
    <template>
        <email>
            <custom_email_template1 module="SampleModule1">
                <label>ActiveCodeline custom email module</label>
                <file>activecodeline_custom_email1.html</file>
                <type>html</type>
            </custom_email_template1>
        </email>
    </template>
</global>

Change it as per you module naming. above code is just for sample.


text:
Q: How do I specify that an operation is returning a template with a template parameter bound to something with * multiplicity? In UML, I want an operation of the form:
+operation(param: String): Binding

where I want Binding to be a bound type as:
Template<TParam -> ISingle[*]>

and Template is defined as:
Template<TParam:Interface>


text:
Q: PowerShell returns multiple values I'm writing a PowerShell function, and I want it to return a single Boolean. The problem is that PowerShell will return anything in the pipeline and not just what was explicitly included in the return statement.
Consider the following code.
function getTrue(){
  $testVariable = "test"
  $test
  return $true
}

$answer = getTrue

Write-host $answer

The output of this code is
test True

This returns a System.Object[]. I want to force the return value to be a System.Boolean.
This code works fine if I add a Write-Host:
function getTrue(){
  $testVariable = "test"
  Write-Host $test
  return $true
}

The only problem is that I'm depending on a function that someone else is writing (I can't modify it), and I can't gaurantee that they used a Write-Host instead of just leaving the variable on the line by itself.
Is there a way to force the function to only return the value that I want?

A: Just use Out-Null to suppress unexpected returning:
function getTrue(){
    $test = "test";
    $test | Out-Null;
    return $true;
}

$answer = getTrue
Write-Host $answer

and
function getTrue(){
    $test = "test";
    Write-Host $test | Out-Null;
    return $true;
}

$answer = getTrue
Write-Host $answer


text:
Q: Проблема с ботом на Heroku Написал бота и загрузил на HEROKU, но после запуска, через 60 секунд вылетают такие логи:
2022-07-19T16:55:23.130953+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-07-19T16:55:23.227546+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-07-19T16:55:23.407912+00:00 heroku[web.1]: Process exited with status 137
2022-07-19T16:55:23.695291+00:00 heroku[web.1]: State changed from starting to crashed

В чем проблема?


text:
Q: How can I have Hashable element type for an Array that is wrapped value for optional I am looking the correct syntax of this code:
extension Optional where Wrapped == Array<Element> where Element == Hashable {

}

The elements of Array are Hashable.

A: You can either constrain every member, or use a typealias. But you can't use properties unless you use the typealias solution.
typealias OptionalHashableArray<Hashable: Swift.Hashable> = [Hashable]?

extension OptionalHashableArray {
  var : String { "" }
}

([] as Optional).

extension Optional {
  func <Hashable: Swift.Hashable>() -> String
  where Wrapped == [Hashable] {
    ""
  }
}

[AnyHashable]?.none.()


text:
Q: Javascript coding working in Google Chrome but not on other browsers like FF I did a quiz page for our computer project and I've recently finished it.I was happy to know that it was working well. The problem now is that it only works on Google Chrome but not on Firefox. When I open it in Google Chrome, everything works: prompts for a name, function for score, etc. But nothing works in Firefox. Need help please.

    <title>Javascript Quiz</title>

How well do you know me? Take this quiz to find out!

            Observe correct capitalization of letters in typing.

<form name="q">

What is my COMPLETE name? (with correct middle initial)

        Answer: <input type="text" name="answer1" value=""/>

        From who among the following was my name gotten from?

        <select name="answer2">
            <option value=""></option>
            <option value="grandfathers">Grandfathers</option>
            <option value="uncle">Uncle</option>
            <option value="stranger">Stranger</option>
            <option value="famous">Famous person</option>
        </select>

Which of the following is the correct spelling of my family name?

        <input type="radio" name="choicesSet1" onclick="q.answer3.value='a' ">Billiones

        <input type="radio" name="choicesSet1" onclick="q.answer3.value='b'">Billones

        <input type="radio" name="choicesSet1" onclick="q.answer3.value='c' ">Biliones

        <input type="radio" name="choicesSet1" onclick="q.answer3.value='d' ">None of the above.

        <input type="hidden" name="answer3" value=""/>

When is my birthday?

        <input type="radio" name="choicesSet2" onclick="q.answer4.value='a' ">February 14

        <input type="radio" name="choicesSet2" onclick="q.answer4.value='b'">October 17

        <input type="radio" name="choicesSet2" onclick="q.answer4.value='c' ">December 17

        <input type="radio" name="choicesSet2" onclick="q.answer4.value='d' ">March 28

        <input type="hidden" name="answer4" value=""/>

How many siblings do I have?

        <input type="radio" name="choicesSet3" onclick="q.answer5.value='a' ">3

        <input type="radio" name="choicesSet3" onclick="q.answer5.value='b' ">2

        <input type="radio" name="choicesSet3" onclick="q.answer5.value='c' ">1

        <input type="radio" name="choicesSet3" onclick="q.answer5.value='d' ">100

        <input type="hidden" name="answer5" value=""/>

Name one of my siblings. (nickname/first name only)

        Answer: <input type="text" name="answer6" value="">

Which of the following are my hobbies? (only three of them are correct)

        <input type="checkbox" name="choicesSet2a">Playing soccer

        <input type="checkbox" name="choicesSet2b">Studying

        <input type="checkbox" name="choicesSet2c">Surfing the net

        <input type="checkbox" name="choicesSet2d">Drinking

        <input type="checkbox" name="choicesSet2e">Reading

What is my favorite number?

        <select name="answer8">
            <option value=""></option>

        </select>

How did I have my front tooth broken?

        <input type="radio" name="choicesSet4" onclick="q.answer9.value='a' ">I fainted.

        <input type="radio" name="choicesSet4" onclick="q.answer9.value='b'">I got punched in the face.

        <input type="radio" name="choicesSet4" onclick="q.answer9.value='c' ">I tripped and fell down.

        <input type="radio" name="choicesSet4" onclick="q.answer9.value='d' ">None of the above.

        <input type="hidden" name="answer9" value=""/>

How many times have I been in a relationship?

        <select name="answer10">
            <option value=""></option>
            <option value="1">1</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="never">Never</option>
        </select>

    <input type="button" value="Well...how did I do?" onclick="score()">
    <input type="reset" value="Reset"/>

    Thank you for taking the quiz, <input type="text" name="name" size="5">.You scored <input type="text" name="final" id="final" size="1"> out of 10.

    <input type="text" name="remark" size="50">

</form>

A: My Firefox Web Developer Toolbar tells me the following when running this code:

*

*Error: unlabeled break must be inside loop or switch

*Error: name is not a function

The first is to be fixed by replacing break with return. The second has disappeared after fixing the first.
Firebug also tells about the same problems in the JS console.


text:
Q: calling `log stream --predicate` command via `subprocess` does not append logs to stdout I'm writing a python script which calls the below commmand via subprocess and stores the logs to output.txt for further parsing

log stream --level debug  --predicate 'subsystem contains "com.apple.UVCExtension" and composedMessage contains "Post PowerLog"'

when I execute this command in the terminal, the logs stream produces output like below
Filtering the log data using "subsystem CONTAINS "com.apple.UVCExtension" AND composedMessage CONTAINS "Post PowerLog""

Timestamp                       Thread     Type        Activity             PID    TTL
2022-02-17 17:07:51.336951+0530 0xbb0f0    Default     0x0                  369    0    UVCAssistant: (UVCExtension) [com.apple.UVCExtension:device] UVCExtensionAppleDevice:0x1000005fe [0x7f8sffea0he80] Post PowerLog {
    "VDCAssistant_Device_GUID" = "XXXXX";
    "VDCAssistant_Power_State" = On;
}
2022-02-17 17:07:52.241387+0530 0xbb0f0    Default     0x0                  369    0    UVCAssistant: (UVCExtension) [com.apple.UVCExtension:device] UVCExtensionAppleDevice:0x1000004ty [sdg4566679e80] Post PowerLog {
    "VDCAssistant_Device_GUID" = "XXXX";
    "VDCAssistant_Power_State" = Off;
}

However while calling the same command via subprocess, I'm unable to see any of the log values. I just see the first line of output. I want to parse the "ON" "Off" status of VDCassistant.
This is my python code
import subprocess
from threading import Thread
from time import sleep

def func1():
    f = open("output.txt", "w")
    subprocess.call(['log', 'stream','--style', 'json' , '--predicate', '(subsystem contains "com.ale.UVCExtension") and (composedMessage contains "Post PowerLog")'], stdout=f, stderr=f)
    return f

def func2():
    while True:
        sleep(5)
        with open("output.txt", "r") as file:
            result = (list(file))
            print(result)
            if "On;" in result:
                print (On status)
            else:
                print ("Off status")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

What is going wrong here?


text:
Q: When use malloc for a static pointer inside a function? I don't understand why, in the following code snippet, the programmer used a static variable (and as a consequence I started to doubt all my little knowledge):
int func (...) {
    static unsigned int *temp = NULL;

    if( temp == NULL ) {
        temp = malloc(dim*sizeof(*temp));
    }

    // do stuff with temp

}

In main(), func is called several time in a loop:
int main() {

    for (i = 0; i < N; ++i)
        x = func(...);

}

The first call to func initialise the variable temp to NULL and thus temp is allocated (maybe the initialisation is also redundant (according to this post).
The function func doesn't do anything special with temp, just copy some values to it from another (global) array if a condition is met and return the number of elements written.
If I understand correctly, malloc allocates the memory in the heap, thus the memory will be persistent until it is explicitly freed and as the pointer is static it can be accessed in subsequent calls.
Then the questions:

*

*Do I understand it correctly?

*Which is the advantage of this approach instead of malloc temp
outside func and then explicitly pass it to func? I guess it
depends on circumstances, ok, but maybe there is a well known
example. I also saw this answer but I cannot understand the
usefulness of the first example.

*I must free temp inside func (at the last step, which, by the way, is not done in this code)?

I need to modify the code above (which is a lot more complex) and I prefer to allocate temp outside func and then pass it to the function and I want to be sure that I am not missing something important. By the way I thought I could learn something :).
Thanks.

A:

*

*Do I understand it correctly?

You understand the initialization of temp correctly, for all practical intents and purposes, including that the explicit initializer is redundant.  You also seem to understand the allocation correctly, and the implication of temp being declared static.  In practice, temp is probably initialized to NULL before func() is ever called, and even if it is never called, but there is no way for the program itself to tell the difference from it being initialized on the first call.

*Which is the advantage of this approach instead of malloc temp outside func and then explicitly pass it to func? I guess it depends on circumstances, ok, but maybe there is a well known example. I also saw this answer but I cannot understand the usefulness of the first example.

Presumably the amount of storage needed -- as governed by variable dim -- is not known until run time.  This is the reason for dynamic allocation.
Putting the variable in the function's local scope ensures that it has no linkage -- it is not visible and cannot be referenced (directly) from anywhere outside the function.  It is, on the other hand, managed by the function itself.  Other functions do not need to worry about preparing an array for this function or passing one to it, and this function does not need to rely on anyone else to set up the array correctly.
As a stylistic matter, I would be inclined to consider a static file-scope pointer instead (in which context, confusingly, the static keyword signifies something different: internal linkage rather than static duration).  The only difference would be the visibility of the variable.
Ultimately, however, the choice of visibility and provisioning of the variable are design issues that to some extent have multiple solutions.  You have not provided enough information for us to reason about the specific choices made in the code you are examining.

*I must free temp inside func (at the last step, which, by the way, is not done in this code)?

If temp is freed then it should be done inside func().  It would be possible to expose a copy of the temp pointer to code outside the function, in which case the allocated space could be freed via that pointer, but then temp would be left as an invalid pointer, with no way for func() to tell.
However, the point of making temp static is surely for the value to be preserved across multiple function calls, so that the allocated space need not be freed and is not leaked.  Note in particular that because temp has static duration, the initialization to NULL is performed as if at program initialization, not each time the function is called.
In fact, it is probably not necessary to free temp in this case.  Not doing so does not create a memory leak, because the memory allocated for temp continues to be available indefinitely (albeit only within the scope of func()).  When the program exits, that memory will be returned to the operating system, just like any other memory allocations still outstanding at that time.

A: "The first call to func initialise the variable temp to NULL".
No you are not (completely) correct. A static variable is initialised by the environment before any function (including) main is called. This is the reason initialisers for static variables have to be constant-expressions. As you understood correctly, without an explicit initialiser, it would also be set to a null pointer during startup. It is questionable if explicit is better here. Problem with explicit initialisers is for actual implementations they consume additional space in the program storage. For bare-metal embedded systems this costs precious Flash/ROM storage. Some compilers (e.g. gcc) provide options to circumvent this penalty.
So, the first call of func will effectively allocate the object which can then be used during subsequent calls. Note that the function (and its caller) must handle allocation failure properly.
Reason not to use a global variable is information hiding. In general, you should define variables at the smallest scope possible (and reasonable). That way you can be sure the variable will not be modified elsewhere. And the likelyhood of name-clashes is reduced to a minimum. As C does not have user-defined namespaces, all such names go into a global pool, which makes this issue quite relevant.
freeing such allocated data can be handled various ways. One is to add a parameter to explicitly request freeing. Alternatively, there could be a global registry (basically a simple linked list) of such blocks. On program termination, a framework-function would just traverse this list and free all blocks.
Alternatively, the program could just rely on the runtime-environment which releases allocated storage automatically on exit. While legal, this is IMO not the cleanest way.

A:
Do I understand it correctly?

Yes.

Which is the advantage of this approach instead of malloc temp outside func and then explicitly pass it to func?

In one case, every caller must be aware of temp and its correct initialisation for func, making callers strongly coupled to func. If at any time in the future the type or the size of the temp array need to be changed, every caller is affected. In the other case, all of this is abstracted away.

I must free temp inside func?

temp is used throughout the program lifetime. If you free it at the end of the function, you defeat its purpose, which is to reduce the number of calls to malloc and/or retain data between invocations. You can free  it at the end of the program if you find a way to. If you do free it at the end of the function, then you don't need it to be static, and you don't need the if (temp == NULL) test. IOW you lose the reason to ask this question.

A:

*

*Do I understand it correctly?

Yes, you do.

*Which is the advantage of this approach instead of malloc temp outside func and then explicitly pass it to func? I guess it depends on circumstances, ok, but maybe there is a well known example. I also saw this answer but I cannot understand the usefulness of the first example.

The advantage is that the callers of the function don't need to know that func needs a buffer to implement the functionality.

*must free temp inside func (at the last step, which, by the way, is not done in this code)?

Yes, you should. Unfortunately, the way it's implemented, you cannot do it. There is no way to access temp outside func. func does not free it due to the way it's been implemented.
In order to free the memory allocated in func, you can use something along the lines of:
static unsigned int *temp = NULL;

void free_temp()
{
   free(temp);
}

int func () {
    if( temp == NULL ) {
        temp = malloc(dim*sizeof(*temp));
        // Register free_temp to be called at exit time.
        atexit(free_temp);
    }

    // do stuff with temp
}

A: *

*Yes.

*Since we're in C, not C++, I guess this is a way to try and limit the ownership and management of the allocated memory such that the callee doesn't have to care. Is there a benefit to spreading that pointer outside of the one function that manages it?

*Yes. Unless you intend to cache that data or hold onto it until the termination of the program.


text:
Q: Change height of single char inside a text in html/css I'm using an Unicode symbol (U+25C0) to make a "left arrow" on a button, but the symbol itself is shifted down a bit. I couldn't find a way to center it, I tried margins, padding and line-height with no success.
Here's what it looks like:

And the simple code:

h2 {
  font-family: Oswald;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Oswald">

  &#9664
   Return

I just need to vertically center the symbol, if anyone could help me :)

A: You can add this to your CSS to center it vertically:
h2 {
  display: flex;
  align-items: center;
}

if you want to align it horizontally as well use justify-content: center;

A: It looks like it because of style="font-size: 70%". When I remove it, it looks fine. try to remove it or move it to another place outside the span element


text:
Q: Dynamically change the title of a android.support.v4.view.PagerTitleStrip I am currentky using a PagerTitleStrip in my application
(Doc: http://developer.android.com/reference/android/support/v4/view/PagerTitleStrip.html)
Everything works fine, and I have set the title like this:
public class PageAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public PageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }

    String[] titles = { "1", "2", "3", "4","5" };

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}

My concern now, is that once the first Fragment has finished loading, I have to change the title of the strip.
I have already tried to get the FragmentPagerAdapter and tried to manipulate it, but never succeed to change a title (text)
There is indeed a getPageTitle method: mPagerAdapter.getPageTitle(position) but no setPageTitle ...
Any idea or suggestion?

A: If I understand problem correctly - you get data later and then want to update titles array and trigger refresh of titles.
If that's the case just trigger PagerAdapter.notifyDataSetChanged(); after that method is invoked Fragments will call getPageTitle method and update themselves.

A: Kind of ugly solution but working : iterate to the visual tree and set the text yourself.
Also, you have to be aware that there is a first transparent/empty item on the left.
Here is the code (Xamarin here) to update the first title.
var firstHidedOneFound = false;
for (int i = 0; i < _tabstrip.ChildCount; ++i)
{
    var child = _tabstrip.GetChildAt(i) as TextView;

    if (child == null) { continue; }
    if (!firstHidedOneFound)
    {
        firstHidedOneFound = true;

        continue;
    }
    child.Text = ViewModel.MyShowPanelTitle;
    break;
}


text:
Q: supervisord as watchdog for various services I tried to configure supervisord as watchdog for tomcat, redis and some other services. The goal is to automatic restart if the services are crashed or stopped.
Here is my configuration for redis and tomat
[program:redis]
command=sudo /etc/init.d/redis-server start
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisour_redis.err.log
stdout_logfile=/var/log/supervisour_redis.out.log
logfile_maxbytes=10MB

[program:tomcat]
command=sudo /root/apache-tomcat-7.0.75/bin/startup.sh
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisour_tomcat.err.log
stdout_logfile=/var/log/supervisour_tomcat.out.log
logfile_maxbytes=10MB

But I'm not able to control the services completely. After restart of supervisor, I see
root@test:~/apache-tomcat-7.0.75/bin# supervisorctl
redis                            BACKOFF    Exited too quickly (process log may have details)
tomcat                           BACKOFF    Exited too quickly (process log may have details)

If I start tomcat with supervisor, it is showing error
supervisor> start tomcat
tomcat: ERROR (abnormal termination)

but the tomcat is starting(I have chacked with ps aux | grep tomcat). But I'm not able to STOP the tomcat. In redis case, supervisor says the service is stopped, but it not!


text:
Q: opencv conflict when trying to update all python packages using conda I have not used python for a while but I am going to heavily use it again very soon, so I decided to update all packages and typed
conda update -all

(I did all the installations using anaconda) I then get:
Fetching package metadata: ..
Warning: No packages found in current osx-64 channels matching: pymc >=2.3.3, skipping
Solving package specifications: ..
Error: Unsatisfiable package specifications.
Generating hint:

WARNING: This could take a while. Type Ctrl-C to exit.
|################################################################| 100%

Hint: opencv >=2.4.8 has a conflict with the remaining packages

From what I read in internet, this hint for opencv comes from the fact that python 3.x does not support opencv (?). However, I am on Python 2.7.8. I am on a mac 10.9.5 and my conda version
conda info
Current conda install:

         platform : osx-64
    conda version : 3.7.3
  conda-build version : 1.3.5
   python version : 2.7.8.final.0
 requests version : 2.4.3
 root environment : //anaconda  (writable)
  default environment : //anaconda
 envs directories : //anaconda/envs
    package cache : //anaconda/pkgs
     channel URLs : http://repo.continuum.io/pkgs/free/osx-64/
                    http://repo.continuum.io/pkgs/pro/osx-64/
      config file : None
is foreign system : False

So far all packages I have tried work and opencv seems to work. However, I would like to know what should I do to successfully update my installed packages with conda.
Thanks

A: That error message doesn't always mean that. It only means that if python 3* is mentioned in the error output.
In your case, some package you have installed depends on some earlier version of opencv. If you don't care what version of opencv you have installed, run
conda remove opencv
conda update --all


text:
Q: The function $g(x)=3x+\ln2x$ for $x>0$. Find $g'(x)$ and prove that $g(x)$ has an inverse function.
The function $g(x)=3x+\ln2x$ for $x>0$. Find $g'(x)$ and prove that $g(x)$ has an inverse function.

So $g'(x)=3+\frac{1}{x} $ for $x>0$ But I have no idea how I'm supposed to prove that this means $g(x)$ has an inverse function. Any help will be appreciated

A: What is required for a function to be invertible? It must be one-to-one and onto. Your function is $g:\mathbb{R}^+\rightarrow\mathbb{R}$. Establishing one-to-one-ness should be doable via the derivative you calculated, and establishing onto-ness should follow from continuity, the intermediate value theorem, and the appropriate limits to $0^+$ and $\infty$.

A: Hint: It follows from what you did that $x>0\implies g'(x)>0$.

A: Since you have the condition $x>0$ and $g'(x) > 0$ for positive $x$, then you know $g$ is strictly increasing. This means that $g$ is injective on $(0,\infty)$ and has an inverse on that interval.

A: Generally speaking, there are two `standard' ways to show the existence of something. The first is to construct it, and the second is to show that if we suppose that such a thing does not exist, we get a contradiction. The intuitionist in me would always recommend the former before falling back on the latter. In this case you need to show that $g'(x)=3+\frac{1}{x}$. To find the inverse of a function $f$, I was taught to substitute to let $y=f(x)$, swap the roles of $x$ and $y$, then rearrange for $y$. In this case, this amounts to setting $x=g'(y)=3+\frac{1}{y}$ and rearranging for $y$. Good luck!
EDIT:
It's been pointed out that you've been asked to find the inverse of $g$ and not of $g'$. In that case, we recall the following lemma:

Let $f:I\to \mathbb{R}$ be a strictly monotonic, continuous function on an interval $I$. Then $f$ has an inverse.

In light of this lemma, it suffices to show that $g$ is monotonic (since $\mathbb{R}^+=(0,\infty)$ is an interval). To do so we require that $g'(x)>0$ (or $g'(x)<0$) $\forall x\in \mathbb{R}^+$. The result follows quickly from you calculation.


text:
Q: Flex SDK 3.5 - Check file magic number Related to:
Flex SDK 3.5 - Check file mimetype
Is there a way to get a file's magic number in Flex SDK 3.5 in order to get the file type?

A: In my understanding the magic number is the first couple of bytes in a file. Also, in my opinion, this is a very loose term.
So assuming that the magic number is the first bytes in a file, you could open a byte stream and check the bytes read. I think this is the only reliable way (but also very error prone and might open security problems, think about IEs' content sniffing issues). The UNIX tool file actually does that and still, it is called a file type guesser.
The actual number depend on the file format you are trying to use. If you are lucky it's documented. If not, it might get painful.


text:
Q: Mount a specified subset of filesystems with ONE command ("mount -a; but with pattern") To mount all available (and not yet mounted) disks and filesystems/partitions, one can use
mount -a

However, what I want to do is to mount a specific subset of all filesystems/partitions, but not ALL of them. Example:
mount -a /mnt/hotplugA  # mount command does not support this
mount -a /mnt/hotplugB  # mount command does not support this
umount -R /mnt/hotplugA # umount DOES support recursive unmounting

where hotplugA and hotplugB are mount points for two different drives (that I use for backup), and that also have multiple additional filesystems/partitions to be mounted underneath the top-level mount point.
The semantics should be that mount -a /mnt/hotplugA should mount all partitions that /etc/fstab specifies as to be mounted at /mnt/hotplugA and below, such that the result is the mounts
/mnt/hotplugA
/mnt/hotplugA/fs1
/mnt/hotplugA/fs2
...
/mnt/hotplugA/fsN

Basically whatever /etc/fstab specifies. Now, the standard mount command does not support the functionality I describe above (but umount does know how, it supports umount -R /path and will unmount anything including and below /path).
Are there any good solutions to the above requirement?

A: I found a solution that involves creating and using an alternate /etc/fstab file that contains only the filesystems that you want to operate on:
grep PATTERN       /etc/fstab >! /tmp/fstab.$$; mount -a --fstab /tmp/fstab.$$
grep /mnt/hotplugA /etc/fstab >! /tmp/fstab.$$; mount -a --fstab /tmp/fstab.$$

Tested and working.


text:
Q: Displaying tooltips on disabled menu items or alternative solutions in .NET I'm trying to display a tooltip on a disabled ToolStripMenuItem, to inform the user why it is disabled.
My initial thought was (as events don't get fired on disabled controls) to pick up the MouseMove event on the parent MenuStrip instead and display the tooltip if over a disabled control. But the event doesn't seem to propagate up the parent MenuStrip as expected. This is how it works usually right? Example, a disabled textbox events would move up to the parent panel?
PS. I'm starting to think this bad idea UI design anyway? What's a better way to do it?

A: Tricky. I'd either accept that it's not possible to tell users (most users these days are happy that sometimes options are disabled because of context/selected data etc). Alternatively, you have to enable these items, and display popups or other warning messages when users try to invoke them.

A: I won't get in to whether it's bad UI design or not to display tooltips detailing the reason something is disabled.
However I did figure out how to do it for disabled buttons a number of years ago. I know it isn't your exact issue, but it is similar enough that the blog post I wrote may be of some use to you.

A: You should set ShowItemToolTips = true on the containing MenuStrip. The tooltip will show even when the ToolStripMenuItem is disabled (but it will not show if the entire MenuStrip is disabled).
This is an old question, so the functionality might have changed, but OP probably did the same mistake I did - my tooltip was not showing so I wrongly assumed it was because the ToolStripMenuItem was disabled.
Just wanted to point this out for future reference.


text:
Q: C# Changing a part of a line of code to a variable I am using Unity3D.
I have a script to sort a list based on a certain value of a creature.
For example, the creatures have a variable saying how much food they've eaten, how many calories they currently have, and how large they are.
I want the user to be able to change the way the values are sorted by clicking a button. I don't want to pile if statements though, such as
if(sortType == "calories") {
    entrySortedText.text = creatureData.calories.ToString();
} else if(sortType == "food eaten") {
    entrySortedText.text = creatureData.foodEaten.ToString();
}

I want to be able to do something like
entrySortedText.text = creatureData.sortType.ToString();

to automatically find the variable with the name of what the sort type is in creatureData. But obviously this doesn't work, as there is no variable "sortType" in creature data, but I want it to replace what the sortType is automatically with the variable name, such as "calories" or "food eaten".
Does anyone know a way to change a part of a line of code to the value of a variable? Or do I have to just use a bunch of if statements?
Thanks. Your response is greatly valued.
P.S.
Here is the current sorting code:
public void LoadList() {
    foreach(Transform child in transform) {
        GameObject.Destroy(child.gameObject);
    }

    List<GameObject> creatures = new List<GameObject>(GameObject.FindGameObjectsWithTag("Creature").ToList());

    // Sort list based on calories
    creatures.Sort(
        delegate(GameObject i1, GameObject i2) {
            return i2.GetComponent<CreatureData>().calories.CompareTo(i1.GetComponent<CreatureData>().calories);
        }
    );

    foreach(GameObject creature in creatures) {
        GameObject entry = Instantiate(entryPrefab);
        entry.transform.SetParent(transform, false);
        entry.transform.GetChild(0).GetComponent<Text>().text = creature.GetComponent<CreatureData>().creatureName;
        entry.transform.GetChild(1).GetComponent<Text>().text = creature.GetComponent<CreatureData>().calories.ToString();
        entry.GetComponent<CreatureListEntryButton>().targetCreature = creature;
    }
}

A: So you want to sort on a property but that property will be decided at runtime.
Let's say you have a collection named items and the items have a property named Calories. Then you can do this:
var sortBy = "Calories";
var propertyInfo = typeof(YourObject).GetProperty(sortBy);

Then you can sort on that:
var orderByCalories = items.OrderBy(x => propertyInfo.GetValue(x, null));


text:
Q: Evaluate gradient for each input keras I want to be able to access the gradient function of a keras neural network. I want to be able to compute the gradient of the output with respect to the input at many input values. Essentially I want to be able to evaluate the gradient as a function.
model = Sequential()
model.add(Dense(500, activation='relu'))
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam',  metrics=['accuracy'])
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=2, verbose = 1)

Now instead of evaluating the output at every input, I want to evaluate the gradient at every input. How can I do this?
This is what I have tried.
grads = K.gradients(model.output, model.input)
gradient_func = K.function([model.input], [grads[0]])
print(gradient_func([x]))


text:
Q: Regarding Login Page before loading Tabbarcontroller with navigationcontroller for iPhone As i am newbie i want to add navigation controller with tabbar controller and login page and when i click on logout button on tabbar controller view it will let me to login page without navigationbar as well as without tabbar contrller.
Thanks in advance.

A: on click of that tab call a function and that function contains these line of code
self.hidesBottomBarWhenPushed=YES;//for hiding tabBar

befor push statements
and use this
self.navigationController.navigationBarHidden=YES;//for hiding navigation bar


text:
Q: Transitions and Transforms on the same Element, triggered by different Parents I'm having a UL, LI with Links in it.
There is also an Arrow-Circle on the right side of the LI. It will be a subnavigation later.

I want the Arrow to grow (which works), when hovering the LI and to rotate (which works only a bit) when hovering the Arrow itself.
Unfortunately, only the growing is triggered, when hovering the LI and moving on to the Arrow. When hovering the Arrow directly, the rotation is triggered. So I'm sure the CSS Attribute is right, but the combination somehow isn't.
This is the relevant code:
li:hover .arrow {
  transition : 0.3s linear;
  transform : scale( 1.5 );
}
.arrow-wrap:hover .arrow {
  transition : 0.6s linear;
  transform : rotate(360deg);
}

To see a mockup-html version, visit this jsFiddle:
https://jsfiddle.net/csf3wwjn/1/
Can anyone tell, whe the rotate isn't triggered when first moving over the LI? I'm not very into the whole CSS3 animation thing and I didn't even know what to search for.
Thx!

A: The second transformation rule is overriding the first, you should define the scale rule together with the rotate one
/* interesting css */
li:hover .arrow {
  transition : 0.3s linear;
  transform: scale( 1.5 ) rotate(0deg);
}
.arrow-wrap:hover .arrow {
  transition : 0.6s linear;
  transform: scale( 1.5 ) rotate(360deg);
}

Demo: https://jsfiddle.net/csf3wwjn/5/
Or, as @Harry pointed out, you can rotate the .arrow-wrap element
/* interesting css */
li:hover .arrow {
  transition : 0.3s linear;
  transform: scale( 1.5 );
}
.arrow-wrap:hover {
  transition : 0.6s linear;
  transform: rotate(360deg);
}

Demo: https://jsfiddle.net/csf3wwjn/6/


text:
Q: Getting started with wxWidgets and CLion? Can anyone suggest a tutorial or getting started guide to CLion and wxWdgets? I have searched around but am unable to find anything.

A: Well,

*

*you should download WxWidgets here http://www.wxwidgets.org/downloads/.

*Then, you should compile and install to your system.

*Download and install CLion.

*Create new Project.

*Then, follow to this edit your CMakeLists.txt Building wxWidgets 3.1.0 on CLion (Ubuntu)

*Then try Hello World sample http://docs.wxwidgets.org/trunk/overview_helloworld.html.

*If everything okay, start to develop great apps!


text:
Q: how to pass one pointer value to another pointer?like can I do int *a=*b;where b is defined already but the pointer a is not addressing to any integer Actually I was reading about pointers and wanted to try something ,so I wrote a small code
int main(){
    int x = 10;
   int *ptr;
    ptr = &x;
    printf("%d is stored at address %d\n",x,ptr );
    int *c=*ptr;
    c=&ptr;
   printf("location is %d\n",c);
 printf("value of c= %d",*c);
}

the result I expected was value  of c would be 10  but instead the value came as the location of x.
output: 10 is stored at address 997523644 location is 997523648 value of c= 997523644
does this problem arise because I didnt pass any location as first?or is it something else or my question is quite silly I know:D,Can anyone help me?

A: The first thing that is missing in the code that you have provided, is the declaration of ptr. You haven't declared the ptr variable yet, so first you need to do
int *ptr;

, which tells that you need a pointer variable to point to a int variable.
Since you declare another pointer int *c and ptr is already a pointer, you only need to assign int *c = ptr (or c=ptr in case you want to declare int *c seperately first), which will store the value of ptr (location of x) to c. So, doing int *c=*ptr is wrong. Now you can access the value of x by doing derefencing (*c or *ptr), which you already did.
Doing c=&ptr is also wrong, because c is of type int * and &ptr is of type int **. In case you are trying to store the address of ptr, you have to first declare a variable of type int **, for example int **d. Now d=&ptr is valid and d holds a value which is the address of ptr. Dereferencing d (*d) should give you the value that the address of ptr is holding, which is nothing but the address of x (same as the value of c). If you dereference d twice (**d), you should get the back the value of x (10).

A: int* c = ptr should be enough, you can read it as: c is pointer to integer, c = ptr since ptr is already a pointer this will make both c and ptr point to the same value.
What you are currently doing: c=&ptr; is making c point to the address of ptr, so if you want to access x value you will need to dereference twice, once to get the address of ptr, and once again to get the content of x.

A: Changed it to this:
#include <stdio.h>

int main(void) {
    int x = 10;
    int *ptr = &x;
    printf("%d is stored at address %p\n",x,ptr );
    int *c=ptr;
    int d = &ptr;
    printf("location is %p\n", c);
    printf("value of c= %d", *c);
    return 0;
}

As ptr is an address already, you can just do it:
int *c=ptr;

Output is:
10 is stored at address 0x7ffd6127dd54
location is 0x7ffd6127dd54
value of c= 10

To print variable address, you can check this answer:
Stackoverflow Answer

A: You just need to remove the line
c=&ptr;

The above line means that you're setting C as the location of ptr, which is some random value. So C points to the location of ptr, and ptr points to the location of x. C is a double-pointer
Alternatively, if you keep that line in there, you can make it work by instead printing
printf("value of c= %d",**c);

either solution would get the output you expect