text:
Q: How to convert from string array to int array and then sort it using c I have string array initialized like that:
char ** strArray;

if ( (strArray = malloc(sizeof(*strArray) + 3)) == NULL ) {
    fprintf(stderr, "ls1: couldn't allocate memory");
    //exit(EXIT_FAILURE);
}
strArray[0] = NULL;

strArray[0] = "111";
strArray[1] = "222";
strArray[2] = "1";
strArray[3] = "2";

I want to convert this string array to int array, like that:
int * toIntArray(char ** strArray) {

int size = getCharArraySize(strArray);
int intArray[size];
int i;

for ( i = 0; i < size  ; ++i)
{
   intArray[i] = atoi(strArray[i]);
   printf( "r[%d] = %d\n", i, intArray[i]);

}
intArray[size] = '\0';
return intArray;

}
int getCharArraySize(char ** strArray) {
  int s = 0;
  while ( strArray[s]) {
        printf("Char array: %s.\n", strArray[s]);
    s++;
 }
 return s;
}

And then I want to sort this int array.
I must have string array initilized like above (char ** strArray) and then convert this to int array and then sort it. Can anybody help my with that? I would ask about printed sorted integer in main function.

A: A few minor things to take note of in the question code:
char ** strArray;

if ( (strArray = malloc(sizeof(*strArray) + 3)) == NULL ) {
    fprintf(stderr, "ls1: couldn't allocate memory");
    //exit(EXIT_FAILURE);
}

If successful, the intention of the above code allocates memory to strArray sufficient for three char *'s.  Specifically, strArray[0], strArray1 and strArray[2].
NOTE: As pointed out in Matt McNabb's comment below, it actually incorrectly allocates memory sufficient for one char *, and three extra bytes.
strArray[0] = NULL;

The above line sets sets the first pointer in the **strArray to point at NULL.
strArray[0] = "111";

The above code is odd.  After just setting strArray[0] to point at NULL, the above line changes it to point to "111".  Kind of makes setting it to NULL (in the first place) seem unnecessary.
strArray[1] = "222";
strArray[2] = "1";

The above two lines initialize the other two pointers in the strArray correctly.
strArray[3] = "2";

The above line attempts to initialize strArray[3], when that element of the array really doesn't exist.  So, it is changing something to point to "2", but probably not with the expected result.
Perhaps the intent would be better served by changing the above code to:
   char **strArray;
   size_t strArrayElements=4;

   if(NULL == (strArray = malloc((strArrayElements+1) * sizeof(*strArray))))
      {
      fprintf(stderr, "ls1: couldn't allocate memory");
      exit(EXIT_FAILURE);
      }

   strArray[strArrayElements] = NULL;

   strArray[0] = "111";
   strArray[1] = "222";
   strArray[2] = "1";
   strArray[3] = "2";

As can be observed, the above code allocates 5 elements (strArrayElements+1) to the **strArray.  The last element strArray[4] is initialized to NULL; a marker to indicate End-Of-List.  Then the other 4 elements [0..3] are initialized.

Now shifting focus to:
int * toIntArray(char ** strArray) {
   int size = getCharArraySize(strArray);
   int intArray[size];
   int i;

   for ( i = 0; i < size  ; ++i)
      {
         intArray[i] = atoi(strArray[i]);
         printf( "r[%d] = %d\n", i, intArray[i]);
      }
   intArray[size] = '\0';
   return intArray;
}

The above code is successful at converting the strings to their integer forms, and storing them in intArray.  However, the code is flawed when it attempts to return intArray to the caller.  The intArray variable was declared as a local stack object.  The return statement causes all such stack variables to become invalid; and allows the stack memory such variables were using to be used for other things.
Perhaps the the following code better represents what was intended.  It allocates memory from the heap for intArray.  This allocated memory can outlive the return statement:
int *toIntArray(char **strArray)
   {
   int size = getCharArraySize(strArray);
   int *intArray = malloc(size * sizeof(*intArray));
   int i;

   for ( i = 0; i < size  ; ++i)
      {
      intArray[i] = atoi(strArray[i]);
      printf( "r[%d] = %d\n", i, intArray[i]);
      }

   intArray[size] = '\0';
   return(intArray);
   }

Spoiler code may be found here.


text:
Q: Two versions of the Breusch-Pagan test? I have learned (and it is the case for instance in Woolridge's Introductory Econometrics) that for testing heteroskedasticity with the BP test, the sample statistic is $nR^2_{\hat{u}^2}$, that follows a $\chi^2(k)$ distribution.
But I have come across another textbook that says that one must consider $\frac{SSE}{2}$, that is also supposed to follow a $\chi^2(k)$ distribution.
So I understand the intuition behind theses tests (if there is homoskedasticity, the second equation should be "poor"), but I am a bit confused by these two versions, especially as they are supposed to follow the same distribution. For a specific example, there is no reason that $nR^2_{\hat{u}^2}$ and $\frac{SSE}{2}$ would be equal, so that it is possible to imagine cases where in one version, one would accept the hypothesis of homoskedasticity, and that one would reject it with the other version.
Can someone enlighten me ? Either by bringing back the two together, or by the maths begin it, or by any other way that would be nice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a client IP address from a specific network? I have a condition to filtering IP address from client, and I just have their IP network like this 1.1.0.0/17. If some client from this network will be filtered as special user on my website. And I also use php as web service language.
In case client who have IP 1.1.4.24 will be automatically logged to databases.
Can someone tell me some way?

A: So I assume you are looking for a php solution?
In that case you will need something like this:
function get_ip_address() {
    // check for shared internet/ISP IP
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }

    // check for IPs passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // check if multiple ips exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    return $ip;
            }
        } else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];

    // return unreliable ip since all else failed
    return $_SERVER['REMOTE_ADDR'];
}

function validate_ip($ip) {
if (strtolower($ip) === 'unknown')
    return false;

// generate ipv4 network address
$ip = ip2long($ip);

// if the ip is set and not equivalent to 255.255.255.255
if ($ip !== false && $ip !== -1) {
    // make sure to get unsigned long representation of ip
    // due to discrepancies between 32 and 64 bit OSes and
    // signed numbers (ints default to signed in PHP)
    $ip = sprintf('%u', $ip);
    // do private network range checking
    if ($ip >= 0 && $ip <= 50331647) return false;
    if ($ip >= 167772160 && $ip <= 184549375) return false;
    if ($ip >= 2130706432 && $ip <= 2147483647) return false;
    if ($ip >= 2851995648 && $ip <= 2852061183) return false;
    if ($ip >= 2886729728 && $ip <= 2887778303) return false;
    if ($ip >= 3221225984 && $ip <= 3221226239) return false;
    if ($ip >= 3232235520 && $ip <= 3232301055) return false;
    if ($ip >= 4294967040) return false;
}
return true;
 }

Now you only need to call $ip = get_ip_address();
I need to tell you that THIS IS EXTREMELY DANGOROUS to give people access based on ip's!

A: I'm not sure what resources you have available to you, but there are devices that accomplish this based on the identity of the user logging in. For example, Cisco ASA Firewalls have an identity feature that picks up log-in events on a Microsoft Active Directory server and alerts the firewall of that user's IP address. Then you write ACL's based on username, as opposed to IP. It's not perfect but it works.
Cisco Identity Based Firewall: http://www.cisco.com/c/dam/en/us/products/collateral/security/asa-5500-series-next-generation-firewalls/at_a_glance_c45-675579.pdf
As it has been said, filtering on IP address alone is only a first step of security. It's easy to set a static IP, or even spoof an IP. You're going to want some authentication mechanism in there as well.


text:
Q: How to get the BSSID of the WiFi networks configured in the supplicant - android? When i use getConfiguredNetworks() to get the BSSID value, it doesnt give me anything. I get all other values except BSSID. Can anyone tell me why this is happening? And yes the networks which i receive have their respective BSSIDs. I found that out by getScanResults(). I'm not getting the BSSID when i use getConfiguredNetworks().

A: I'm guessing that it's expected to work like that (even if the documentation doesn't mention it): getConfiguredNetworks() only retrieves my "saved" wifi hotspots, which probably don't save the BSSID (since you don't care which access point to connect to, just that it has the expected ssid).  If you need the BSSID you probably just have to cross-reference getScanResults() with getConfiguredNetworks().


text: Q: Страничка с шаблонами код-генераторов .net? Не могу пользоваться aspnet-codegenerator и visual studio, и потому не могу генерировать вообще никакой код. Есть где то все шаблоны, которые могут быть сгенерированны aspnet-codegenerator, чтоб я мог просто почитать их и понять что делать?


text:
Q: Postgres CITEXT working when querying in DBeaver but not working when calling through an API in postman or swagger I have a database where I have a column that is of CITEXT datatype to allow for case insensitive search.  When I test the query select * from DB where description = 'tEsT'; it returns what I want in a case insensitive way.
But when I have an API call which uses that column and has a case insensitive search it doesn't work at all.  It is strange since it is working when querying the DB directly, but not when being called through an API and the service is making the call.
I can provide more information if I need to.

A: The answer in this case is that CITEXT when you add the extension with
create extension if not exist citext;

It defaults to the public schema.  So when the API was calling the service with our schema it wasn't working.
alter extension citext schema actualCorrectSchema

You can also alter the extension to turn on the ability for it to jump between any schema as well by changing the relocatable feature to true instead of false.
Thank you all for your answers and help!


text:
Q: Loop and morph an SVG between two paths I am using Popmotion, Pose and flubber to morph and transition two paths of an SVG between React Route changes.
This works perfectly as
import posed from 'react-pose';
import { tween, easing } from 'popmotion';
import { interpolate } from 'flubber';

const pathIds = Object.keys(paths);

const morphTransition = ({ from, to }) =>
  tween({
    from: 0,
    to: 1,
    duration: 1000,
    ease: easing.easeInOut
  }).pipe(interpolate(from, to));

const Background = posed.path(
  pathIds.reduce((config, id) => {
    const path = paths[id].path;
    config[id] = {
      d: path,
      transition: morphTransition
    };
    return config;
  }, {})
);

Where the paths are defined as
const paths = {
  first: {
    path:
      'M 262.9,252.2 C 210.1,338.2 212.6,487.6 288.8,553.9 372.2,626.5 511.2,517.8 620.3,536.3 750.6,558.4 860.3,723 987.3,686.5 1089,657.3 1168,534.7 1173,429.2 1178,313.7 1096,189.1 995.1,130.7 852.1,47.07 658.8,78.95 498.1,119.2 410.7,141.1 322.6,154.8 262.9,252.2 Z',
    pathAlt:
      'M 262.9,252.2 C 210.1,338.2 273.3,400.5 298.5,520 323.7,639.6 511.2,537.2 620.3,555.7 750.6,577.8 872.2,707.4 987.3,686.5 1102,665.6 1218,547.8 1173,429.2 1128,310.6 1096,189.1 995.1,130.7 852.1,47.07 658.8,78.95 498.1,119.2 410.7,141.1 322.6,154.8 262.9,252.2 Z'
  },
  second: {
    path:
      'M 415.6,206.3 C 407.4,286.6 438.1,373.6 496.2,454.8 554.3,536.1 497,597.2 579.7,685.7 662.4,774.1 834.3,731.7 898.5,653.4 962.3,575 967.1,486 937.7,370 909.3,253.9 937.7,201.5 833.4,105.4 729.3,9.338 602.2,13.73 530.6,41.91 459,70.08 423.9,126.1 415.6,206.3 Z',
    pathAlt:
      'M 415.6,206.3 C 407.4,286.6 415.5,381.7 473.6,462.9 531.7,544.2 482.5,637.6 579.7,685.7 676.9,733.8 826.2,710.7 890.4,632.4 954.2,554 926.8,487.6 937.7,370 948.6,252.4 937.7,201.5 833.4,105.4 729.3,9.338 602.2,13.73 530.6,41.91 459,70.08 423.9,126.1 415.6,206.3 Z'
  },
  third: {
    path:
      'M 383.8,163.4 C 335.8,352.3 591.6,317.1 608.7,420.8 625.8,524.5 580.5,626 647.3,688 714,750 837.1,760.5 940.9,661.5 1044,562.3 1041,455.8 975.8,393.6 909.8,331.5 854.2,365.4 784.4,328.1 714.6,290.8 771.9,245.2 733.1,132.4 694.2,19.52 431.9,-25.48 383.8,163.4 Z',
    pathAlt:
      'M 383.8,163.4 C 345.5,324.9 591.6,317.1 608.7,420.8 625.8,524.5 595.1,597 647.3,688 699.5,779 837.1,760.5 940.9,661.5 1044,562.3 1068,444.4 975.8,393.6 884,342.8 854.2,365.4 784.4,328.1 714.6,290.8 820.3,237.2 733.1,132.4 645.9,27.62 422.1,1.919 383.8,163.4 Z'
  }
};

On a route change the effect is

However, how could I loop and morph between paths[id].path and paths[id].pathAlt at all other times. For example, I am trying to achieving this result shown here by codrops where the svg is constantly moving.

A: Find out which function is morphing the shape when you change the url.
Then use that function within setInterval() to alternate between the path and path-alt, as opposed to the different paths.


text:
Q: Sprite appearing large when zoomed in and appearing small when zoomed out In a three.js scene, I have an image sprite whose image is constructed out of a html canvas. When I zoom in to the scene ( using mouse scroll ) the sprite appears larger and when I zoom out it appears smaller. But its not the case with other material like PointsMaterial. They appear smaller when I zoom in they appear smaller and when I zoom out they appear larger - which I think is the desired behavior.
Here is the code for my sprite that uses canvas:
var image = new Image();
image.src = canvas.toDataURL("image/png");
var imgLoader = new THREE.TextureLoader();
imgLoader.setCrossOrigin("");
var imgTexture = imgLoader.load(image.src);
imgTexture.minFilter = THREE.LinearFilter;

var spriteMaterial = new THREE.SpriteMaterial({
    map: imgTexture,
    depthWrite: false,
    depthTest: false,
    transparent: true,

});
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(0.3*canvas.width, 0.25*canvas.height, 1);
sprite.position.x = x0; //fixed
sprite.position.y = y0; //fixed
sprite.position.z = z0; //fixed

var cx = (0.17/187)*w; // w is width of text present on canvas.
var cy = 0.35;
sprite.center.set(cx, cy);

Is there any setting that I forgot to get the behavior that I described?

A:
They appear smaller when I zoom in and when I zoom out they appear larger - which I think is the desired behavior.

It sounds to me like you're trying to get rid of the sprite's size attenuation, so it maintains the same size regardless of distance to the camera. To achieve this, you can set the material's .sizeAttenuation property to false:
var spriteMaterial = new THREE.SpriteMaterial({
    map: imgTexture,
    depthWrite: false,
    depthTest: false,
    transparent: true,
    sizeAttenuation: false
});


text:
Q: How to insert a PHP variable in to HTML stored in a JS variable? Is it possible to insert the ButtonSend var inside my <input> part? This way will not work:
var ButtonSend = <?php _e('Go!', $this->plugin_slug) ?>;
LangKeys['en']['button'] = '<input v-on:click.prevent="submit" type="button" value="ButtonSend" />';

A: Assuming it's a string value (from the context of the property name) you need to wrap the PHP output in quotes. Then you can concatenate the value as you would any other:
var ButtonSend = '<?php _e('Go!', $this->plugin_slug) ?>';
LangKeys.en.button = '<input v-on:click.prevent="submit" type="button" value="' + ButtonSend + '" />';

Alternatively you could use a template literal to do the concatenation, assuming you don't need IE support:
LangKeys.en.button = '<input v-on:click.prevent="submit" type="button" value="${ButtonSend}" />';


text:
Q: Spring JPA/HIbernate create/update views when the application starts Our application is based on spring, JPA, Hibernate (3.5.1), postgresql 8.4
We will deliver a new .war file to our clients, but we have quite a few new views in the DB needed to be created before they can run some reports.
I tried to put an import.sql file under src folder, and configured my persistence.xml like this
:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="myApp">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>....</class>

       <properties>
           <property name="hibernate.hbm2ddl.auto" value="update" />
             <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
        </properties>
    </persistence-unit>
</persistence>

and my data-access-context.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
          class="org.springframework.jndi.JndiObjectFactoryBean">
          <property name="jndiName"
                      value="java:comp/env/jdbc/mydb"/>
          <property name="resourceRef"
                      value="true" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="persistenceUnitName" value="myApp" />
            <property name="jpaVendorAdapter">
                    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                            <property name="generateDdl" value="true" />
                            <property name="showSql" value="true" />
                            <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
                    </bean>
            </property>
    </bean>

    <tx:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <context:component-scan base-package="com.pb.redline.dao" />

</beans>

But I cannot get the new views created?
any idea? Thanks in advance.

A: This is not really an answer to your question, but maybe a valuable solution. What about using a database migration framework? I suggest flyway which gives you full access to your database.
During application start (see post) the migration can be triggered using the flyway java api.
Properties properties = new Properties();
properties.setProperty("flyway.user", "postgres");
properties.setProperty("flyway.password", "secret");
properties.setProperty("flyway.url", "jdbc:postgresql://localhost/database-name");
properties.setProperty("flyway.driver", "org.postgresql.Driver");

flyway = new Flyway();
flyway.configure(properties);
flyway.clean();
flyway.migrate();


text:
Q: Free abelian group - exercise Can someone please help me understand how to do this exercise?
Show that multiplicative group of positive rationals is a free abelian group of countably infinite rank.
So, I know i can begin with:
Let Q be multiplicative group of positive rationals. Let r $\in$ Q that $r = \frac{a}{b} \in Q$.
I have no idea what next? :/

A: Hint: Fundamental theorem of arithmetic.
Full solution:
Every positive rational can be written as a unique product $$n=p_1^{a_{n1}}p_2^{a_{n2}}p_3^{a_{n3}}\ldots$$ where $p_i$ is the $i$th prime, and $a_{nj}\in\mathbb Z$ is eventually constant and $0$. Thus we can write a group homomorphism $$\phi:(\mathbb Q,\times)\to(\mathbb Z^\omega,+)$$ sending $n\to(a_{nj})_{j\in\mathbb{N}}$. But because each product also uniquely determines a rational, this map is actually a bijection and thus $$(\mathbb Q,\times)\sim(\mathbb Z^\omega,+)$$ which gives the result.

A: For any $\frac{m}{n}$ with $m,n\in\Bbb N$ write $m=p_1^{r_1}....p_k^{r_k}$ and $n=p_1^{s_1}...p_k^{s_k}$ for $s_i,r_i\in\{0,1,2,...\}$ and $p_i$ primes. Then, $$\frac{m}{n}=p_1^{r_1-s_1}...p_k^{r_k-s_k}.$$ So, $\{p^t|t\in\Bbb N\text{ and }p \text{ prime }\}$ is a basis. Note that if $p$ is in basis then, $1/p$ cannot be  in basis. Also, $p^0=1$.


text:
Q: How to restore postgres dump our developers have sent us a dump file from postgresql(file.sql) and we do not know how to restore it, we have already tried
psql -U <username> -d <dbname> -1 -f <filename>.sql

and received an error a 'superuser' failed to authenticate (by password)
what does it mean? should I enter the superuser of my laptop? Or is it a db user?

A: You can try with follow lines:
PGPASSWORD=password;

pg_restore --host "hostname" --port "port" --username "postgres" --no-password --verbose --dbname "dbname"  --schema "schema" "dump_filename";

where "hostname" is the hostname of the postgresql server (localhost), "port" is the port of listen postgresql server (5432), "postgres" is the username, "dbname" database name

A: pg_dump does not dump users but it does their permissions. If the 'superuser' is being used to be set as the owner of some object, then you will want to create that user on your instance first. Since you are using -1 it may fail when adding permissions to a user that does not exist. You could try psql -h <dbhost> -U <username> -W -d <dbname> < filename.sql that will run each statement in the dump and will continue even if it errors while setting permission.
Note: all objects will now be owned by the user you connected with.


text:
Q: PayPal Android Sdk Vault My requirement is to store credit card details in Paypal vault using Android.
I followed these link
https://github.com/paypal/PayPal-Java-SDK
https://github.com/paypal/PayPal-Android-SDK
https://developer.paypal.com/docs/integration/direct/rest-vault-overview/
there is no mention on how to vault a credit using Android sdk. I think it can be done using their Rest API. How do I achieve this in Android?

A: You can store credit card in paypal using vault api Follow this steps
Step 1: Generate Access Token By OAuth Token Request
Try in postman
      Url :- https://api.sandbox.paypal.com/v1/oauth2/token

      Headers :- (Key,Value)

      1.(Accept , application/json)
      2.(Accept-Language , en_US)
      3.(Content-Type , application/x-www-form-urlencoded)
      4.(Authorization , Basic<Space>(here your code generated by postman))

Note :- Generate a Basic Auth in post man by select authorization tab ==> Basic Auth and enter paypal Client secret and Client id.
      Body :- (Key,Value)
      1.(grant_type,client_credentials)

Note :- Select x-www-form-urlencoded in body tab in postman
Step 2: Store credit card using valut api
Try in postman
      Url :- https://api.sandbox.paypal.com/v1/vault/credit-cards

      Headers :- (Key,Value)

      1.(Accept , application/json)
      2.(Accept-Language , en_US)
      3.(Content-Type , application/x-www-form-urlencoded)
      4.(Authorization , Bearer(your Access Token))

      Body : (Json)

{
  "payer_id": "user12345",
  "type": "visa",
  "number": "4111111111111111",
  "expire_month": "11",
  "expire_year": "2018",
  "first_name": "Joe",
  "last_name": "Shopper",
  "billing_address": {
    "line1": "52 N Main ST",
    "city": "Johnstown",
    "state": "OH",
    "postal_code": "43210",
    "country_code": "US"
  }
}

Note :- Select raw tab in body in postman.

A: Thanks to vishal for his help. I was able to solve this using retrofit (adding headers statically).
1. First get the value of your authorization header:
    String clientId = "your client id";
    String clientSecret = "your client secret";
    String credentials = clientId + ":" + clientSecret;
    String basic =
            "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    Log.e("Authorization",basic);

Copy this value from log, it will be used later in our solution.
2. Make the response model according to this json:
 {
  "scope":"https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
  "access_token":"Access-Token",
  "token_type":"Bearer",
  "app_id":"APP-6XR95014SS315863X",
   "expires_in":28800
 }

3. Make retorfit call method as this:
    @Headers({
        "Accept: application/json",
        "Accept-Language : en_US",
        "Content-Type : application/x-www-form-urlencoded",
        "Authorization:your basic string value here"
        })
    @POST("https://api.sandbox.paypal.com/v1/oauth2/token/")
    Call<AuthenticationTokenModel> getAuthentionToken(@Query("grant_type") String grant_type);

4. Finally make the call as:
     ApiInterface apiInterface= ApiClient.getClient().create(ApiInterface.class);
    apiInterface.getAuthentionToken("client_credentials").enqueue(new Callback<AuthenticationTokenModel>() {
        @Override
        public void onResponse(Call<AuthenticationTokenModel> call, Response<AuthenticationTokenModel> response) {
            Log.e("response",response.body().getAccess_token());
        }

        @Override
        public void onFailure(Call<AuthenticationTokenModel> call, Throwable t) {
            Log.e("response",t.getMessage());
        }
    });

Thanks.
Edited:
You can also add dynamic headers to requests in Retrofit 2.
Follow this:
https://futurestud.io/tutorials/retrofit-add-custom-request-header


text:
Q: Why is .NET unable to decode this string when Java can "Hi%E1"? My problem is with .Net Http/Uri libraries not being able to decode or unescape this character sequence: "Hi%E1".
Neither Uri.UnescapeDataString nor HttpUtility.UrlDecode can do it.
Although I have a solution to get around this problem ( URL decoding confusion ) I would like to understand why it is failing.
The 1st test here throws an exception! The second just fails.
Assert.That(Uri.UnescapeDataString("Hi%E1"), Is.EqualTo("Hiá"));
HttpUtility.UrlDecode("Hi%E1").ShouldBe("Hiá");

There is nothing in the docs to indicate that UnescapeDataString or UrlDecode are restricted to character sets or any reason why these tests would fail. However, from testing, it would appear that HttpUtility assumes UTF-8 (or some other) encoding.
The Java equivalent works! Probably because it allows an encoding to be set.
URLDecoder.decode("Hi%E1","windows-1252");    // this works btw, ie passes tests

Which looks like a very sensible move considering the .Net work-around (see URL above)
Are the .Net implementations of these methods just crap and .Net devs just have to write their own - or am I missing something?
BTW Everything I know of in IIS set to UTF-8, and Chinese/Japanese characters show fine, so I don't yet know how it could it be that this URI consists of windows-1252 encoded characters. If I could fix the URI to contain UTF-8 encoding, that would be a better way of fixing this.

A: According to this you can also set the encoding using the HttpUtility.UrlDecode.
Although, that seems to simple if you're running into problems... just making sure you saw the overload.

A: Addendum
I discovered the underlying issue to this problem.
I was using 'escape' in javascript - it's deprecated, don't use it.
escape('á') returns '%E1' - which is a windows-1252 encoding (ie it will fail or return the wrong character when using the methods above eg HttpUtility.UrlDecode unless you are able to specify 'windows-1252' in the overload)
encodeURI('á') returns '%C3%A1' - which is a UTF-8 encoding. Which will work and all your troubles will go away. The methods above will work without throwing exceptions or producing the wrong character.
Dreaming: Wouldn't it be nice if the Uri.UnescapeDataString specified which escape character was the problem? My URI at the time of diagnosis was 23,000 characters long. "Invalid URI" is not such a helpful message in that scenario.

A: Seems to work as specified...
HttpUtility.UrlDecode("Hi%E1", System.Text.Encoding.GetEncoding("windows-1252"));

Edit: Answer to comment.
If you use Reflector on HttpUtility.UrlDecode(string) you see that it uses UTF8 as the default Encoding. (As it should.)
//From Reflector (System.Web)
public static string UrlDecode(string str)
{
    if (str == null)
    {
        return null;
    }
    return UrlDecode(str, Encoding.UTF8);
}


text:
Q: Forecasting Cashflow based on previous Billing Detailed historical data for a utilities company:
customer details, bill posted date, amount billed, amount paid, payment date
Question:
Based on how much has been billed before today, how much do we forecast to be paid in the next 15 days , broken down by days (e.g. day 1 = 1.5 mill, day 2 = 4 mill,...., day 15 = 12 mill)
From my perspective we need to take into consideration both how much has been billed and also the speed at which the payments were made historically, i.e. gap between billed and payment date.
Would like to hear your thoughts about how to tackle this question, and potentially what type of statistical/predictive modelling technique to use for this forecasting.

A: You really only more or less have the bill amount and how long payment took then. Your best bet is probably to attempt regression analysis.


text:
Q: why does python submodule not show up in list from dir(module)? This is probably a more general question, because I have seen similar behavior with other modules.  But I will show the issue as I am seeing it with module matplotlib.  I thought that dir(module) lists all attributes of the specified module.  So I can do the following:
import matplotlib
dir(matplotlib)

Among the results listed is 'dateutil', but 'dates' is NOT listed by dir(matplotlib).  But then I do this:
import matplotlib.dates   ## why does this work? `dir(matplotlib)` did not list it
dir(matplotlib)           ## this now lists both 'dates' and 'dateutil'

Why does dir(matplotlib) now list 'dates' as one of its attributes?
What's going on here?
I just noticed now, it appears to me that dateutil is not actually part of matplotlib, but is imported by matplotlib:
In [11]: matplotlib.dateutil.__file__
Out[11]: '/anaconda3/lib/python3.6/site-packages/dateutil/__init__.py'

In [12]: matplotlib.__file__
Out[12]: '/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py'

In [13]: matplotlib.dates.__file__
Out[13]: '/anaconda3/lib/python3.6/site-packages/matplotlib/dates.py'

Notice in the output above, matplotlib.dateutil.__file__ shows a file that is not even in the matplotlib directory.  Furthermore I can see in file '/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py' that dateutil is imported by matplotlib/__init__.py.
So when I run dir(module) is there an easy way to tell which attributes are part of the module itself, and which were imported by the module?  And how could I have know (other than reading documentation, or "ls"ing the matplotlib directory) that 'dates' is also a valid "attribute" and "module" within matplotlib?

A: Simply matplotlib does not itself import .dates. What dir() shows you is a list of attributes of an object. If matplotlib does not import .dates, then there's no local name dates on the matplotlib module object.
Now, if you do import matplotlib.dates, Python's import system resolves that to the file/folder matplotlib/dates.py or matplotlib/dates/__init__.py, whichever exists. It's important to emphasise that matplotlib itself has nothing to do with that file resolution and hence does not need to "know" in any way about the existence of that submodule.
If you load a module, it does not automatically load all possible submodules as well. That only happens if something explicitly imports that name.


text:
Q: Haskell: Convert String to [(String,Double)] I parse an XML and get an String like this:

"resourceA,3-resourceB,1-,...,resourceN,x"

I want to map that String into a list of tuples (String,Double), like this:

[(resourceA,3),(resourceB,1),...,(resourceN,x)]

How is it possible to do this? I ve looked into the map function and also the split one. I am able to split the string by "-" but anything else...
This is the code i have so far:
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s

it is just a function to split my string into a list of Stirng, but then i dont know how to continue.
What I want to do know is to loop over that new list that i have created with the split method and for each element create a tuple. I hace tried with the map function but i dont get it to compile even

A: So in Haskell you dont really mutate any value, instead you'll create a new list of pairs from the string you've described, so the solution would look something similar to the following:
import Data.List.Split

xmlList = splitOn "-" "resourceA,3-resourceB,4-resourceC,6"

commaSplit :: String -> [String]
commaSplit = splitOn ","

xmlPair :: [String] -> [(String, Double)] -- might be more efficient to use Text instead of String
xmlPair [x]    = [(\x' -> ((head x') :: String, (read (last x')) :: Double )) (commaSplit x)]
xmlPair (x:xs) = xmlPair [x] ++ xmlPair xs

main :: IO ()
main = mapM_ (\(a,b) -> putStrLn (show a++" = "++ show b)) (xmlPair $ xmlList)

This is my quick and dirty way of showing things but I'm sure someone can always add a more detailed answer.


text:
Q: How to handle external not stable code? I have asp.net Web Api 2 Application that is working with External COM Object (pvxcom). In Some reasons COM Object is hanging, there is no chance for me to report bug for pvxcom.
I need to figure out something to bypass this issue. I want to clarify some points.

*

*How can I set maximimum execution time for external source ?

*How can I force browser to resent request ? ( is it possible ? )

*How can I figure out in which procedure of COM Object is hanging ?

*Is it good practice to dispose com object and recreate?

Have you any other ideas, how to figure it out ?

A: You can run it in a thread and you can kill this thread if it hangs or takes longer then expected.
Here is my sketch for MVC, but for WebApi code will be the same. This is based on this answer:
public ActionResult Index()
{
    var sw = new Stopwatch();
    Exception threadException = null;
    var workerThread = new Thread(() =>
    {
        try
        {
            sw.Start();

            // Access your COM here instead of sleep
            Thread.Sleep(6000);

            sw.Stop();
        }
        catch (Exception ex)
        {
            threadException = ex;
            sw.Stop();
        }
    });

    var timeoutTimer = new System.Threading.Timer((s) =>
    {
        workerThread.Abort();
    }, null, 5000, Timeout.Infinite);

    workerThread.Start();
    workerThread.Join();

    ViewBag.Message = String.Format("Time: {0}; Exception: {1}", sw.Elapsed, threadException);

    return View();
}


text:
Q: background image repeat effect in cocos creater How can background image be set in repeat effect in cocos creater ?
If character runs, back image should be flow backwards, but I want to background repeatedly continuously repeated by using one device size image file.

A: I think you can do this by using two background images, placed one after the other, with anchors 0,0, size assumed to be same as canvas size (Images not placed inside the canvas). This script applied to both images can achieve that effect, in simplest form.

cc.Class({
    extends: cc.Component,

    properties: {
        // speed of scrolling
        speed: 0,
        // reset to position
        bgwidth: 0
    },

    // use this for initialization
    onLoad: function () {
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        var x = this.node.x;
        x -= this.speed * dt;
        if (x <= -this.bgwidth) {
            x += this.bgwidth*2;
        }
        this.node.x = x;
    },
});


text:
Q: How to map list of strings containing key value to dict in Python? My list contains the following elements:
>>> s = "foo a=b c=d e=f"
>>> s.split()
['set', 'a=b', 'c=d', 'e=f']
>>> splitted = s.split()
>>> splitted[1:]
['a=b', 'c=d', 'e=f']

Now I want to use map to get the following result:
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I tried the following, but this gives me an IndexError:
>>> map(lambda x : dict((a[0], a[1]) for a in x.split('=')) , splitted[1:])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <genexpr>
IndexError: string index out of range

A: You don't want to iterate over what you've split, just wrap that in an iterable, like a tuple:
>>> splitted
['a=b', 'c=d', 'e=f']
>>> [dict((x.split('='),)) for x in splitted]
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I.E.
(x.split('='),)

Is a tuple with one element, the result of .spliting on the '=' sign.
Or using map and lambda:
>>> list(map(lambda x: dict((x.split('='),)), splitted))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I will say, this seems like a rather un-useful data-structure.
To be clear, your construction fails because you are iterating too deeply. The generator expression:
(a[0], a[1]) for a in x.split('=')

Is iterating over x.split('='), which in this case is always a list with two elements, length-1 strings, e.g. ['a','b'].

A: You may create a simple list comprehension to achieve this. Here you need to split each string based on = and type-cast it to dict. For example:
>>> my_list = ['a=b', 'c=d', 'e=f']

>>> [dict([my_str.split('=')])  for my_str in my_list]
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

Here's the working working version of your solution using lambda:
#     actually you don't need to iterate here v
>>> list(map(lambda x : dict([[a for a in x.split('=')]]) , my_list))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

This could be simplified as:
>>> list(map(lambda x : dict([x.split('=')]) , my_list))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

A: You can use zip function:
result= list(map(lambda x: dict(zip(*x.split('='))) ,splitted[1:]))

OR
needed = list(dict(zip(*x.split('='))) for x in splitted[1:])


text:
Q: How to show that all level curves of $f(x,y)=\sqrt{x^2+y^2}-x^2-y^2+2$ are circumferences? Consider the function $f(x,y)=\sqrt{x^2+y^2}-x^2-y^2+2$. Then it's easy to show that $x^2+y^2=h$ is a level curve for $f$, for all $h\in[0,\infty)$. Here I'm saying that all circumferences $\{(x,y,x^2+y^2):x^2+y^2=r^2, r\ge 0\}$ are level curves of $f$. Given the last fact, how can I prove the title? If not, how do I prove that all the level curves of $f$ are circumferences?
I'd have to show that $f(x,y)=k$, $k\in\text{Ran}(f)$ denotes a circumference. I don't know how to write $f$ like $(x-a)^2+(y-b)^2$.
I appreciate your thoughts.

A: the level curves of $f$ are given by $\sqrt{x^2 + y^2} -(x^2+y^2) = C = \text{ constant}$ this is equivalent to $r - r^2 = C$ for $C > -\frac{1}{4}$ this give $r = \dfrac{1+\sqrt{1+4C}}{2}$ where $r = \sqrt{x^2 + y^2}.$  these are parts of circles of radius greater or equal to ${1}/{2}.$

A: Your function $f$ is defined on all of ${\Bbb R}^2$. Given an arbitrary $C\in{\Bbb R}$ the set
$$L_C:=f^{-1}(C):=\{(x,y)\in{\Bbb R}^2\>|\>f(x,y)=C\}$$
is called the level set of $f$ belonging to the value $C$. In the case at hand we have
$$f(x,y):=r-r^2+2\ ,$$
where $r:=\sqrt{x^2+y^2}$. Finding the level set $L_C$ means solving the equation
$$r-r^2+2=C\ .$$
Formally this leads to
$$r={1\over2}\left(1\pm\sqrt{9-4C}\right)\ .\tag{1}$$
But now the work is not over yet. Instead we have to discuss what $(1)$ is telling us for various values of $C$.
When $C>{9\over4}$ then $L_C=\emptyset$.
When $C={9\over4}$ then $L_C$ is a circle of radius ${1\over2}$.
When $2<C<{9\over4}$ then $L_C$ consists of two circles with positive radii.
When $C=2$ then $L_C$ consists of the origin and a circle of positive radius.
When $C<2$ then $L_C$ consists of a single circle.


text:
Q: Why some types from my library don't autocomplete when using in a project I have my own library where I have my basic components as inputs, containers, etc.
The library bundles in my project same as any 3rd party library.
The problem is that when using it in my project, the types which are imported from another file in the library don't autocomplete but if I define all the types within the same file which I export the component they autocomplete correctly.
Seems like it is not resolving the types when they are not in the same file. They resolve well within the library but not in the exported bundle.
For example,
The following works well:
interface IInputProps{ ......}

const input=({inputProps:IInputProps})=>.....

The following works well in the library but does not autocomplete the types:
 import {IInputProps} from './Types'

 const input=({inputProps:IInputProps})=>....

Any idea?
This is my tsconfig.json in my library:
 {
  "compilerOptions": {
    "baseUrl": "src",
    "lib": ["dom", "dom.iterable", "esnext", "es5"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "jsx": "react-jsx",
    "outDir": "dist/library",
    "sourceMap": true,
    "declaration": true,
    "strictNullChecks": true,
    "noImplicitAny": false,
    "downlevelIteration": true,
    "types": ["node", "lodash", "jest", "sortablejs"],
    "typeRoots": [
      "src/typings/*.d.ts",
      "node_modules/@types",
      "node_modules/ui-lib/src/typings/*.d.ts",
      "node_modules/jest-canvas-mock/types/index.ts"
    ]
  },
  "include": [
    "src/**/*",
    "src/mylib-ui/typings/*.d.ts",
    "node_modules/ui-library/**/*.d.ts"
  ],
  "exclude": ["src/**/*.spec.*", "src/**/*.md", "dist"]
}

My webpack configuration in my library is:
 {
    test: /\.(ts|js)x?$/i,
   include: [srcPath, uiLibraryPath],
    use: [
             'babel-loader', //javascript files loader
                    {
                    loader: 'ts-loader', //typescript loader
                    options: {
                            allowTsInNodeModules: true,
                            transpileOnly: true,
                        },
                    },
                ],
            },


text:
Q: How to access files at a path NSURL Hello everyone i have the following code :
  NSString* issuePath =[[self contentURL] URLByAppendingPathComponent:@"magazine"].path;

I have a file called a.plist in the above directory. I have to read the a.plist file contents. How to do that. Before the file was local and I was accessing it as follows
 NSString *path = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"plist"];

A:   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"a.plist"];
NSMutableDictionary *plistContents = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

A: Refer this file handler utility which provides API's to interact with most of your file related operations.
It exposed API for below features,

*

*Check if the file, or directory, exists in the given path

*Create a folder in a given path

*Verify if a folder exists at a given path

*Get the size of a file

*Check if a file with that name exists in the folder

*Check if this folder has more subfolder or if it's the last folder

File Handler Utility Class link

A: You can simply use the following method.
NSString *path = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];


text:
Q: I face android media player error (-38, 0) in Samsung and Google latest version mobile ref: log
We use the Google sample project with the following changes. Same things we use in our project, we got an error (-38,0) on media player error listener in Samsung flagship devices and Google devices. (tested in note 8-8.1 and pixel 2xl-9.0)
Here, onError listener calls first then onPrepared listener.
Expected solution: Play audio without any error.
package com.example.android.mediaplayersample;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Exposes the functionality of the {@link MediaPlayer} and implements the {@link PlayerAdapter}
 * so that {@link MainActivity} can control music playback.
 */
public final class MediaPlayerHolder implements PlayerAdapter {

    public static final int PLAYBACK_POSITION_REFRESH_INTERVAL_MS = 1000;

    private final Context mContext;
    private MediaPlayer mMediaPlayer;
    private int mResourceId;
    private PlaybackInfoListener mPlaybackInfoListener;
    private ScheduledExecutorService mExecutor;
    private Runnable mSeekbarPositionUpdateTask;

    public MediaPlayerHolder(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * Once the {@link MediaPlayer} is released, it can't be used again, and another one has to be
     * created. In the onStop() method of the {@link MainActivity} the {@link MediaPlayer} is
     * released. Then in the onStart() of the {@link MainActivity} a new {@link MediaPlayer}
     * object has to be created. That's why this method is private, and called by load(int) and
     * not the constructor.
     */
    private void initializeMediaPlayer() {
        if (mMediaPlayer != null) {

            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    logToUI("OnPrepared()");
                    mediaPlayer.start();
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    stopUpdatingCallbackWithPosition(true);
                    logToUI("MediaPlayer playback completed");
                    if (mPlaybackInfoListener != null) {
                        mPlaybackInfoListener.onStateChanged(PlaybackInfoListener.State.COMPLETED);
                        mPlaybackInfoListener.onPlaybackCompleted();
                    }
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    logToUI("OnError()" + i + " " + i1);
                    return true;
                }
            });
            logToUI("mMediaPlayer = new MediaPlayer()");
        }
    }

    public void setPlaybackInfoListener(PlaybackInfoListener listener) {
        mPlaybackInfoListener = listener;
    }

    // Implements PlaybackControl.
    @Override
    public void loadMedia(int resourceId) {
        mResourceId = resourceId;
        mMediaPlayer = new MediaPlayer();

        try {
            logToUI("load() {1. setDataSource}");
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource("http://radio-electron.ru:8000/96");
        } catch (Exception e) {
            logToUI(e.toString());
        }

        initializeMediaPlayer();

        try {
            logToUI("load() {2. prepare}");
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            logToUI(e.toString());
        }

        initializeProgressCallback();
        logToUI("initializeProgressCallback()");
    }

    @Override
    public void release() {
        if (mMediaPlayer != null) {
            logToUI("release() and mMediaPlayer = null");
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    @Override
    public void play() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            logToUI(String.format("playbackStart() %s",
                    mContext.getResources().getResourceEntryName(mResourceId)));
            mMediaPlayer.start();
            if (mPlaybackInfoListener != null) {
                mPlaybackInfoListener.onStateChanged(PlaybackInfoListener.State.PLAYING);
            }
            startUpdatingCallbackWithPosition();
        }
    }

    @Override
    public void reset() {
        if (mMediaPlayer != null) {
            logToUI("playbackReset()");
            mMediaPlayer.reset();
            loadMedia(mResourceId);
            if (mPlaybackInfoListener != null) {
                mPlaybackInfoListener.onStateChanged(PlaybackInfoListener.State.RESET);
            }
            stopUpdatingCallbackWithPosition(true);
        }
    }

    @Override
    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            if (mPlaybackInfoListener != null) {
                mPlaybackInfoListener.onStateChanged(PlaybackInfoListener.State.PAUSED);
            }
            logToUI("playbackPause()");
        }
    }

    @Override
    public void seekTo(int position) {
        if (mMediaPlayer != null) {
            logToUI(String.format("seekTo() %d ms", position));
            mMediaPlayer.seekTo(position);
        }
    }

    /**
     * Syncs the mMediaPlayer position with mPlaybackProgressCallback via recurring task.
     */
    private void startUpdatingCallbackWithPosition() {
        if (mExecutor == null) {
            mExecutor = Executors.newSingleThreadScheduledExecutor();
        }
        if (mSeekbarPositionUpdateTask == null) {
            mSeekbarPositionUpdateTask = new Runnable() {
                @Override
                public void run() {
                    updateProgressCallbackTask();
                }
            };
        }
        mExecutor.scheduleAtFixedRate(
                mSeekbarPositionUpdateTask,
                0,
                PLAYBACK_POSITION_REFRESH_INTERVAL_MS,
                TimeUnit.MILLISECONDS
        );
    }

    // Reports media playback position to mPlaybackProgressCallback.
    private void stopUpdatingCallbackWithPosition(boolean resetUIPlaybackPosition) {
        if (mExecutor != null) {
            mExecutor.shutdownNow();
            mExecutor = null;
            mSeekbarPositionUpdateTask = null;
            if (resetUIPlaybackPosition && mPlaybackInfoListener != null) {
                mPlaybackInfoListener.onPositionChanged(0);
            }
        }
    }

    private void updateProgressCallbackTask() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            int currentPosition = mMediaPlayer.getCurrentPosition();
            if (mPlaybackInfoListener != null) {
                mPlaybackInfoListener.onPositionChanged(currentPosition);
            }
        }
    }

    @Override
    public void initializeProgressCallback() {
        final int duration = mMediaPlayer.getDuration();
        if (mPlaybackInfoListener != null) {
            mPlaybackInfoListener.onDurationChanged(duration);
            mPlaybackInfoListener.onPositionChanged(0);
            logToUI(String.format("firing setPlaybackDuration(%d sec)",
                    TimeUnit.MILLISECONDS.toSeconds(duration)));
            logToUI("firing setPlaybackPosition(0)");
        }
    }

    private void logToUI(String message) {
        if (mPlaybackInfoListener != null) {
            mPlaybackInfoListener.onLogUpdated(message);
        }
    }

}

A: We are use getDuration() in onBufferingUpdate() & that creates the issue so now we are initializing the onBufferingUpdate() listener in onPrepared() & remove the listener when try to play the next audio.


text:
Q: How to employ jquery autocomplete with ID/value pairs using a hidden field There are several questions regarding my problem, but somehow none could actually help me solve it.
I'm not that familiar with javascript let alone jquery so please bear with me.
As stated I have a text field with jquery autocomplete in place, which works just great.
But I need to have a hidden field populated with the corresponding ID to the selected value.
Here's the form:
<input name="clubname" id="clubname" type="text" />
<input name="clubid" id="clubid" type="hidden" value="" />

For the autocomplete I use an array like this: {id: 1, value: 'something' }.
The whole page is in php getting the data from the DB and writing the array.
Into the autocomplete I added the accented text feature.
Here's the code:
var accentMap = {
    'á': 'a',
    'ä': 'a',
    'à': 'a',
    'â': 'a',
    'ö': 'o',
    'ô': 'o',
    'ó': 'o',
    'ò': 'o',
    'ü': 'u'
};

var normalize = function (term) {
    var ret = '';
    for (var i = 0; i < term.length; i++) {
        ret += accentMap[term.charAt(i)] || term.charAt(i);
    }
    return ret;
};

$().ready(function () {
    $('#clubname').autocomplete({
        source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), 'i');
            response($.grep(clubs, function (value) {
                value = value.label || value.value || value;
                return matcher.test(value) || matcher.test(normalize(value));
            }));
        }
    });
});
});

It seems I have to use the result handler to get the ID into the hidden field. But how to exactly access the ID of the selected value escapes me.
Any help would be greatly appreciated!

A: Hope this solution helps you
$JsonArray =array();
foreach($EmployeeDetailList as $value){
    $Array[label]=$value['user_name'];
    $Array[value]=$value['user_name'];
    $Array[eid]=$value['id']; //Here goes the ID of the employee
    array_push($JsonArray,$Array);
}
$JsonSerialize=json_encode($JsonArray);

This was the  server side coding to populate the Json encoded array
Now the next portion implements the JQuery Part
$(function() {
var availableTags = <?php echo $JsonSerialize;?>;
$( "#imas" ).autocomplete({
source: availableTags,
select: function(event,ui){
    var userid = ui.item.eid;
    alert(userid); //This will alert the Employee ID . You can use it any where you want
},
});
});


text:
Q: Smooth scroll automatically starts on page load I am new to programming. I wanted to create a smooth scrolling effect when I click on an href on my page, to do so I have used the scroll behavior:smooth in css. I've applied the rule like this
html {
  scroll-behavior: smooth;
}

Otherwise it works great, but there's a consequence that I do not wish is there, on page load it automatically smooth scrolls to the identifier that's applied onto the href. I want to avoid this, how can I do that?
Thank you.

A: try this:
<script>
window.onload = function() {
    var node = document.createElement('style');
    node.innerHTML = "html {scroll-behavior: smooth;}";
    document.body.appendChild(node);
};
</script>


text:
Q: C++ returning locally allocated dynamic memory without leak? I am learning about C++ in school and creating a string class for an assignment.  I have a couple of questions:
First, will the following create a memory leak?
MyString operator() (int sliceStart, int sliceEnd) {
    sliceStart = sliceStart%_len;
    if(sliceStart < 0)
        sliceStart = _len + sliceStart;
    sliceEnd = sliceEnd%_len;
    if(sliceEnd < 0)
        sliceEnd = _len + sliceEnd;
    char* temp = new char[_len + 1];

    if(sliceStart == sliceEnd)
        return *this;
    int i;
    if(sliceStart < sliceEnd)
        for(i = 0; sliceStart < sliceEnd; ++sliceStart && ++i)
            temp[i] = _str[sliceStart];
    else if(sliceStart > sliceEnd) {
        for(i = 0; sliceStart < _len; ++sliceStart && ++i)
            temp[i] = _str[sliceStart];
        for(int k = 0; k < sliceEnd; ++i && ++k)
            temp[i] = _str[k];
    }
    temp[i] = '\0';
    //delete [] temp
    return MyString(temp);
}

And if so, will adding the commented delete line return a valid value since it is freed right before the return.  Or is it possible that the memory could possibly be snatched up between the two lines?
(I know that in this particular case I could simply create a MyString object before the return, but I am curious as if I HAD to return the temp char)
What is the common/proper way to manage dynamic local memory that you also wish to return by value?

A: Yes - there's a memory leak in your code, you allocate memory and then potentially return a different value on the next line.
Use encapsulation to help the user understand the lifetime of any allocations; either use something like std::shared_ptr or create a class that wraps ownership of the allocation.


text:
Q: To what degree can effective indexing overcome performance issues with VERY large tables? So, it seems to me like a query on a table with 10k records and a query on a table with 10mil records are almost equally fast if they are both fetching roughly the same number of records and making good use of simple indexes(auto increment, record id type indexed field).
My question is, will this extend to a table with close to 4 billion records if it is indexed properly and the database is set up in such a way that queries always use those indexes effectively?
Also, I know that inserting new records in to a very large indexed table can be very slow because all the indexes have to be recalculated, if I add new records only to the end of the table can I avoid that slow down, or will that not work because the index is a binary tree and a large chunk of the tree will still have to be recalculated?
Finally, I looked around a bit for a FAQs/caveats about working with very large tables, but couldn't really find one, so if anyone knows of something like that, that link would be appreciated.

A: Here is some good reading about large tables and the effects of indexing on them, including cost/benefit, as you requested:
http://www.dba-oracle.com/t_indexing_power.htm

A: Indexing very large tables (as with anything database related) depends on many factors, incuding your access patterns, ratio of Reads to Writes and size of available RAM.
If you can fit your 'hot' (i.e. frequently accessed index pages) into memory then accesses will generally be fast.
The strategy used to index very large tables, is using partitioned tables and partitioned indexes. BUT if your query does not join or filter on the partition key then there will no improvement in performance over an unpartitioned table i.e. no partition elimination.
SQL Server Database Partitioning Myths and Truths
Oracle Partitioned Tables and Indexes
It's very important to keep your indexes as narrow as possible.
Kimberly Tripp's The Clustered Index Debate Continues...(SQL Server)

A: Accessing the data via a unique index lookup will slow down as the table gets very large, but not by much. The index is stored as a B-tree structure in Postgres (not binary tree which only has two children per node), so a 10k row table might have 2 levels whereas a 10B row table might have 4 levels (depending on the width of the rows). So as the table gets ridiculously large it might go to 5 levels or higher, but this only means one extra page read so is probably not noticeable.
When you insert new rows, you cant control where they are inserted in the physical layout of the table so I assume you mean "end of the table" in terms of using the maximum value being indexed. I know Oracle has some optimisations around leaf block splitting in this case, but I dont know about Postgres.

A: If it is indexed properly, insert performance may be impacted more than select performance.  Indexes in PostgreSQL have vast numbers of options which can allow you to index part of a table or the output of an immutable function on tuples in the table.  Also size of the index, assuming it is usable, will affect speed much more slowly than will the actual scan of the table.  The biggest difference is between searching a tree and scanning a list.  Of course you still have disk I/O and memory overhead that goes into index usage, and so large indexes don't perform as well as they theoretically could.


text:
Q: Starting a Program with Powershell Remoting Using Windows Powershell, this opens notepad.
notepad.exe

But this, which is meant to remote into a virtual machine and open notepad there, does not. Instead, the process starts but the GUI is hidden.
$s = New-PSSession -ComputerName MyVirtualMachine
Invoke-Command -Session $s -ScriptBlock {notepad.exe}

I need to know a few things.

*

*How do I start a process with Powershell remoting such that its GUI is visible?

*Why is the GUI invisible?

*If I follow your advice regarding item 1., what are the implications regarding how the process starts? I want the process to start as the user I am logged in as (same as credentials I am connecting Powershell with).

*I want to choose whether the process has administrator privileges (the credentials will) as I need to run tests on processes both with and without admin rights.

*Other factors you can think of which may affect how the process runs. I am testing software, so the behavior ought to be identical to a user double clicking on an icon.


text:
Q: Rename columns with regex and Pandas to extract contents between specific punctuations Given a test dataset as follows:
  city district  ... Q3:*your age[open question]  Q4:*skill[open question]
0   bj       cy  ...                          45                              R
1   bj       cy  ...                          34                         Python

I need to rename columns by using regex to extract the contents between * and [, also removing your if they exist. Please note in real case, I have many Questions columns as below.
df.columns
Out[112]:
Index(['city', 'district', 'name', 'Q1:*your tel[open question]',
       'Q2:*your profession[close question]', 'Q3:*your age[open question]',
       'Q4:*skill[open question]'],
      dtype='object')

The expected columns will like this:
['city', 'district', 'name', 'tel', 'profession', 'age', 'skill']

How could I do that in Pandas and regex? Many thanks at advance.

A: df13 = df.filter(regex = '^[^Q]', axis = 1) #Isolate columns without Q
df12 = df.filter(regex = '^Q', axis = 1) #isolate columns with Q
x = df.filter(regex = '^Q', axis = 1).reindex(df.filter(regex = '^Q', axis = 1).\
columns.str.findall('([a-z]+(?=\[))').str.join(','),\
axis = "columns").columns # transform column names with q
df12.columns=list(x) # reset df12 column names
pd.concat([df13, df12], axis = 1)

Example Data
df=pd.DataFrame({'city':[1], 'district':[1], 'name':[1], 'Q1:*your tel[open question]':[1],
       'Q2:*your profession[close question]':[1], 'Q3:*your age[open question]':[1],
       'Q4:*skill[open question]':[1]})

print(df)
 city  district  name  Q1:*your tel[open question]  \
0     1         1     1                            1

   Q2:*your profession[close question]  Q3:*your age[open question]  \
0                                    1                            1

   Q4:*skill[open question]
0                         1

Outcome
    city  district  name  tel  profession  age  skill
0     1         1     1    1           1    1      1

A: Try:
cols = []
for i in df.columns:
    if re.search(r'Q\d:',i) != None:
        cols.append(re.match(r'^Q\d:\*(your\s)?([\w]*)',i).group(2))
    else:
        cols.append(i)

Oneliner substitute for above:
[(re.match(r'^Q\d:\*(your\s)?([\w]*)',i).group(2)) if re.search(r'Q\d:',i) is not None else i for i in df.columns]

Both prints:
['city', 'district', 'name', 'tel', 'profession', 'age', 'skill']

A: Whenever facing problems like this, you may wanna give yourself some time to think what pattern does match what you want. For this I'd recommend this site, where you can paste your target text and try some patterns out. It takes some time, but that is how we actually learn (regex are always a good exercise for the brain).
For your case, the pattern you desire is r'\*(your)?(.*)\[', where the second matching group is the word to be new name of the column. So you can try something like :
import re

pattern = r'\*(your)?(.*)\['

print('# Before\n', df.columns)
df = df.rename({
     col: re.search(pattern, col).group(2).strip()
     if re.search(pattern, col)
     else col
     for col in df.columns
     }, axis=1)
print('# After\n', df.columns)

And the output will be:
# Before
 Index(['city', 'district', 'name', 'Q1:*your tel[open question]',
       'Q2:*your profession[close question]', 'Q3:*your age[open question]',
       'Q4:*skill[open question]'],
      dtype='object')
# After
 Index(['city', 'district', 'name', 'tel', 'profession', 'age', 'skill'], dtype='object')


text:
Q: How to decrease the width of the tableview cell? I want to decrease the tableviewcell width and place imageview on that cell.
And that imageview should contain the ADD Photo text inside it.
Whenever we click on that one then imagepicker is shown and selected picture is place on that cell's imageview.
Please give me any suggestions.
Help me.

A: please read the table view programming guide.


text:
Q: Fastest way of checking for word in huge list of keywords - Python performance Thanks for amazingly quick response. Stackoverflow is awesome!
I need to check if a word (or rather thousands of them) is matching a dict containing keywords.
For example, say I have a string: "The fluffy fox jumped the friggin fence."  I need to check each word of the string against a dict of keywords, and if there's a match, return all values.
I've created a dict filters: (uniqueid means ie. "lk2m3lk4m2", rest is 'static'.)
filters:
        { "fox" : [
                    { 'subscription' : 'uniqueid', 'link' : 'uniqueid' },
                    { 'subscription' : 'uniqueid', 'link' : 'uniqueid' }
                  ]},

        { "fence" : [
                      { 'subscription' : 'uniqueid', 'link' : 'uniqueid' }
                    ]}

...and plan to iterate over filters for each word in string (and I have to do this with perhaps 5000 words / second.  In other words, performance is the issue ABOVE ALL.
The number of filter-keywords may grow to thousands, while the strings will never be more than a normal sentence long (ie. 5-20 words). I'll therefore iterate over each word in the string and check if it's contained in the filter-list.  However, at 500 sentences / second, I'm still looking at a lot of computation.
Is it possible to sort the list (ie. the key of dict's in list) and thus drastically improve performance, for example?  And are there C-implementations I should use (like I'm using cjson with great performance gain)?
Sorry for the somewhat fluid question -- but how should I go about this task?
Edit:
Expected input: "The fluffy fox jumped the friggin fence."
Expected output: { 'subscription' : 'flskdmfslk32232', 'link' : 'sfdksmfls22323' },
                    { 'subscription' : '3023940fsdf', 'link' : 'sdflsfm223' } (ie. the subscriptions listed under each matching keyword.)

A: You can determine if a word is a key in filters by simply by doing filters.has_key(word) or by doing:
subscriptions = filters.get(word)
if subscriptions is not None:
    pass # TODO do something with subscriptions

or:
try:
    subscriptions = filters[word]
    # TODO do something with subscriptions
except:
    pass # probably don't need to do anything if not present

It isn't necessary to iterate over each entry in filters.  Rather you will want to split your input string, add each word to a Set (to eliminate duplicates), and then iterate over your set to look up each word in your filters dictionary.

A: The fastest way to do it in Python would be to use a dictionary look each word of the sentence up in it, and accumulate and associated values. The main data structure would probably look something like this:
filters = {
    "fox" : (
              ('uniqueid1', 'uniqueid2'),
              ('uniqueid3', 'uniqueid4'),
            ),
    "fence" : (
                ('uniqueid5', 'uniqueid6'),
              ),
          }

Using this way (on 8-bit chars):
from string import punctuation

sentence = 'The fluffy fox jumped the friggin fence.'
sentence = sentence.translate(None, punctuation)  # remove punctuation chars

print [filters.get(word) for word in sentence.split() if word in filters]

Or it might be faster (time it to find out) like this which avoids a double dictionary look-up:
from string import punctuation

def map_words(sentence):
    for word in sentence.translate(None, punctuation).split():
        try:
            yield filters[word]
        except KeyError:
            pass

sentence = 'The fluffy fox jumped the friggin fence.'
print [v for v in map_words(sentence)]

Either way this is the output:
[(('uniqueid1', 'uniqueid2'), ('uniqueid3', 'uniqueid4')), (('uniqueid5', 'uniqueid6'),)]


text:
Q: What proxy package to install under Ubuntu/OpenSUSE I am looking for a software to isntall under Ubuntu or OpenSUSE so that my server can provide proxy to internal users. The proxy needs to support HTTP and HTTPS. Then, All I need to do is to point to its IP address from my browser proxy configuration.

A: Squid is the gold standard in open source caching proxies.  I don't know how sane the default config in the Ubuntu/OpenSUSE package is, but it's not too difficult to configure.


text:
Q: Write down Bokeh plot selected data not working I am trying to write the selected datapoints from a Bokeh plot.
The idea is to access ColumnDataSource selected property to get the selected data points whenever the Button is clicked.
Below goes a model of the functionality I'm trying to achieve.
Expectation: after clicking the 'Selected points' button, a file /tmp/datapoints.json would be created containing the list of points selected (if any).
Reality: no /tmp/datapoints.json.
from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import ColumnDataSource, Button
from bokeh.layouts import column

# setup plot
fig = figure(title='Select points',
            plot_width=300, plot_height=200)

import numpy as np
x = np.linspace(0,10,100)
y = np.random.random(100) + x

import pandas as pd
data = pd.DataFrame(dict(x=x, y=y))

# define data source
src = ColumnDataSource(data)

# define plot
fig.circle(x='x', y='y', source=src)

# define interaction
def print_datapoints(attr, old, new):
    with open('/tmp/datapoints.json', 'w') as f:
        import json
        json.dump(src.selected, f)

btn = Button(label='Selected points', button_type='success')
btn.on_click(print_datapoints)

curdoc().add_root(column(btn,fig))

What am I missing?
Thanks.

A: with the lasso_select tool you can work it like this:
from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, Button
from bokeh.layouts import column

# setup plot
tools = "pan,wheel_zoom,lasso_select,reset"
fig = figure(title='Select points',
            plot_width=300, plot_height=200,tools=tools)

import numpy as np
x = np.linspace(0,10,100)
y = np.random.random(100) + x

import pandas as pd
data = pd.DataFrame(dict(x=x, y=y))

# define data source
src = ColumnDataSource(data)

# define plot
fig.circle(x='x', y='y', source=src)

# define interaction
def print_datapoints():
    indices=src.selected['1d']['indices']
    results=data.iloc[indices]
    resultsDict=results.to_dict()['x']
    resultString=str(resultsDict)
    with open('tmp/datapoints.json', 'w') as f:
        import json
        json.dump(resultString, f)

btn = Button(label='Selected points', button_type='success')
btn.on_click(print_datapoints)

curdoc().add_root(column(btn,fig))

To make the json.dump work i had to remove the first '/' from '/tmp/datapoints.json' .


text:
Q: pq o loop while True acessa o if e o else em sequência a cada loop completo nesse código? #! /usr/bin/python3

valor = int(input("Digite o valor a pagar: "))

cedulas = 0
atual = 50
apagar = valor

while True:
    if atual <= apagar:
        apagar = apagar - atual
        cedulas += 1
    else:
        print("%d cedula(s) de R$%d" %(cedulas, atual))
        if apagar == 0:
            break
        elif atual == 50:
            atual = 20
        elif atual == 20:
            atual = 10
        elif atual == 10:
            atual = 5
        elif atual == 5:
            atual = 1
        cedulas = 0

não entendo como o loop acessa o primeiro if e o else na sequência dentro do while True. O else não deveria ser acessado somente quando o primeiro if do código for falso? como esse código funciona linha a linha?, alguém poderia me explicar?, lembrando que sou iniciante em programação.

A: Não entra nos dois (if e else) na mesma volta do ciclo.
O "problema" é que visto ser while True... ele vai fazer várias voltas, entrando no if (caso a condição se verifique) e decrementando 50 (valor inicial de atual) ao valor de apagar, até que ao momento que apagar for menor que atual, aí já vai entrar no else. Podes testar isto fazendo um print(valor, apagar) dentro do ciclo, e colocando o valor apagar a 200 por exemplo.
Se quiseres fazer um break na primeira vez que entra no if, deves explicitar.
Explicação visual:
valor = int(input("Digite o valor a pagar: "))

cedulas = 0
atual = 50
apagar = valor

while True:
    print(valor, atual, apagar) # acrescentei isto para perceberes o que se passa
    if atual <= apagar:
        apagar = apagar - atual
        cedulas += 1
    else:
        print("%d cedula(s) de R$%d" %(cedulas, atual))
        if apagar == 0:
            break
        elif atual == 50:
            atual = 20
        elif atual == 20:
            atual = 10
        elif atual == 10:
            atual = 5
        elif atual == 5:
            atual = 1
        cedulas = 0

A saída do programa com apagar sendo 200:

200 50 200
      200 50 150
      200 50 100
      200 50 50
      200 50 0 <-- só aqui depois deste print, na mesma volta, é que vai entrar no else
      4 cedula(s) de R$50

Aqui podes ver que nas primeiras 4 voltas entramos no if, porque apagar nestas 4 voltas ainda era maior ou igual que atual.
Lembrando que atual também vai alterando a partir do momento que antramos no else, assim sendo, neste caso, mais tarde ou mais cedo vamos parar dentro o if apagar == 0: que é o que 'faz' break ao ciclo
Se quiseres sair do ciclo ao entrar no if:
...
if atual <= apagar:
    apagar = apagar - atual
    cedulas += 1
    break
...


text:
Q: Implementing ACPI function in UEFI I'm trying to implement ACPI function that will run in UEFI that will respond to code similar to this:
'executes a WQL query
Set colItems = objWMIService.ExecQuery("Select * from Password where InstanceName='ACPI\\PNP0C14\\0_0'")
'modify the supervisor password
For Each objItem in colItems
     'execute the method and obtain the return status
     objItem.SetPassword strInParamValue, strReturn Next

Which UEFI protocol/functions are needed to be implemented? please refer me to sample code.
Thanks.

A: what would you like to development, it is built from BIOS. unless you got source code from project vendor. otherwise, you cannot change it. however, if you are application development. you can get mof to create self-application to do something.


text:
Q: File ReadAllLines turns foreign language into gibberish (�) I am creating a tool that replaces some text in a text file. My problem is that File ReadAllLines turns the Hebrew characters into Gibberish (weird question marks �)
Does anyone know why this is happening? Note that I do have a problem with Hebrew in games and such.. And in Notepad, I can't save Hebrew documents. I can write Hebrew letters but when I save it tells me there's a problem with that.
EDIT - Tried this, but it only turned the Hebrew into regular question marks and not "special" ones-
string[] lines = File.ReadAllLines(fullFilenameDir);
byte[] htmlBytes = Encoding.Convert(Encoding.ASCII, Encoding.Unicode, Encoding.ASCII.GetBytes(String.Join("\r\n", lines)));
char[] htmlChars = new char[Encoding.Unicode.GetCharCount(htmlBytes)];
Encoding.Unicode.GetChars(htmlBytes, 0, htmlBytes.Length, htmlChars, 0);

A: Try using the Windows-1255 code page to get the encoder.
var myLines = File.ReadAllLines(@"C:\MyFile.txt",  Encoding.GetEncoding("Windows-1255"));


text:
Q: gcc warning flag at the end of warning output. what does it mean? I want to know what does the warning flag at the end of warning statement (in compilation output) shows ?
e.g in this code
#include <stdio.h>

int g_var = 'ghij';

int
main(void)
{
fprintf(stderr," g_var = %d " , g_var);
return 0;
}

when compiled with
gcc temp.c

compilation shows this output

temp.c:3:13: warning: multi-character character constant [-Wmultichar]

what does the -Wmultichar at the end has to say ?
EDIT: I understant why this warning is there but I want to know the meaning of this flag e.g how can this flag be used to remove this warning ?

A: This is indicating the specific warning flag which was enabled and found an issue in your code.
The actual issue is that you have more than one character in a character constant: 'ghij'
If you wanted to turn off that warning for some reason, you would use -Wno-multichar.
If you wanted to treat warnings like this as errors, pass -Werror.

A: multichar is one of the options supplied with gcc to "Request or Suppress Warnings"

*

*-Wmultichar is used to turn ON the warning.

*-Wno-multichar is used to turn OFF the warning.

From the gcc online manual

-Wno-multichar
Do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code.

A:
what does the -Wmultichar at the end has to say ?

It indicates that that's the specific flag which enables this warning. Often, you'll enable multiple warnings with -Wall or -Wextra, and it can be useful to know where each warning came from, for example if you want to disable just one warning.

how can this flag be used to remove this warning ?

Add -Wno-multichar to the compiler options, after any options that enable warnings, to disable this warning.


text:
Q: Error: Could not find module 'C:\Users\phong\Desktop\Python\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax I have a code like this
import vlc
player = vlc.MediaPlayer("a.mp4")
player.play()

and it give me this error
Traceback (most recent call last):
  File "c:\Users\phong\Desktop\Python\Media player\media_player.py", line 1, in <module>
    import vlc
  File "C:\Users\phong\AppData\Local\Programs\Python\Python310\lib\site-packages\vlc.py", line 210, in <module>
    dll, plugin_path  = find_lib()
  File "C:\Users\phong\AppData\Local\Programs\Python\Python310\lib\site-packages\vlc.py", line 170, in find_lib
    dll = ctypes.CDLL('.\\' + libname)
  File "C:\Users\phong\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'C:\Users\phong\Desktop\Python\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax.

A: download VLC 3.0.8
and unpack libvlc.dll、libvlccore.dll and plugins to the path "c:\windows\system32",
but make sure vlc is 64 bits in case your python is 64 bits
you can download from this address:
http://download.videolan.org/pub/videolan/vlc/


text:
Q: Why is my class undefined at runtime. Javascript module pattern When i run my application i get: "Uncaught TypeError: Cannot read property 'init' of undefined"
The alert in the document reasdy function runs, so i know jQuery is loaded at that point. But i don't know why Task is undefined.
This is in a MVC5 application, and running jQuery 1.10.2
Please help, jsFiddle works fine, and JsHint shows no errors.
    var Task = (function () {

    var initialize = function () {
        console.log($);
        bindEvents();
    };
    var postFilter = function () {
        console.log("clicked");
        var postData = {
            UserID: $('#user_select').val,
            TaskTypeID: $('#taskTypeSelect').val,
            TaskStatusID: $('#status_select').val,
            PriorityID: $('#priority_select').val
        };

        $.ajax({
            url: "/Tasks/_AllTaskView",
            data: postData,
            success: function (response) {
                $('#results').html(response);
            }

        });
    };

    var bindEvents = function () {
        $('#submit_filter').on('click', postFilter);
    };

    return
    {
        init : initialize

    };

})();

$(document).ready(function () {
    alert()
    Task.init();
});

A: Put the curly brace of your return on the same line as return.
Instead of:
return
{
    init : initialize

};

Do this:
return {
    init : initialize
};

JavaScript has automatic semi-colon insertion which will automatically end the return statement before it hits the curly brace.

A: Here try this:
return{ init : function(){
                 initialize();
               }
      }


text:
Q: Compact storage coefficients of a multivariate polynomial The setup
I am writing a code for dealing with polynomials of degree n over d-dimensional variable x and ran into a problem that others have likely faced in the past. Such polynomial can be characterized by coefficients c(alpha) corresponding to x^alpha, where alpha is a length d multi-index specifying the powers the d variables must be raised to.
The dimension and order are completely general, but known at compile time, and could be easily as high as n = 30 and d = 10, though probably not at the same time. The coefficients are dense, in the sense that most coefficients are non-zero.
The number of coefficients required to specify such a polynomial is n + d choose n, which in high dimensions is much less than n^d coefficients that could fill a cube of side length n. As a result, in my situation I have to store the coefficients rather compactly. This is at a price, because retrieving a coefficient for a given multi-index alpha requires knowing its location.
The question
Is there a (straightforward) function mapping a d-dimensional multi-index alpha to a position in an array of length (n + d) choose n?

A: Ordering combinations
A well-known way to order combinations can be found on this wikipedia page. Very briefly you order the combinations lexically so you can easily count the number of lower combinations. An explanation can be found in the sections Ordering combinations and Place of a combination in the ordering.
Precomputing the binomial coefficients will speed up the index calculation.
Associating monomials with combinations
If we can now associate each monomial with a combination we can effectively order them with the method above. Since each coefficient corresponds with such a monomial this would provide the answer you're looking for. Luckily if
alpha = (a[1], a[2], ..., a[d])

then the combination you're looking for is
combination = (a[1] + 0, a[1] + a[2] + 1, ..., a[1] + a[2] + ... + a[d] + d - 1)

The index can then readily be calculated with the formula from the wikipedia page.

A: A better, more object oriented solution, would be to create Monomial and Polynomial classes.  The Polynomial class would encapsulate a collection of Monomials.  That way you can easily model a pathological case like
y(x) = 1.0 + x^50

using just two terms rather than 51.
Another solution would be a map/dictionary where the key was the exponent and the value is the coefficient.  That would only require two entries for my pathological case.  You're in business if you have a C/C++ hash map.
Personally, I don't think doing it the naive way with arrays is so terrible, even with a polynomial containing 1000 terms.  RAM is cheap; that array won't make or break you.


text:
Q: Difference usage of document level, sentence level and aspect level in sentiment analysis I'm studying about Sentiment analysis. And I wonder for what purpose we should use document level, for what we use sentence level and for what we should use aspect level.
Thanks.


text:
Q: Youtube API how to get video info When you right click on the video and say "show video info", there is popup that shows fps, frames dropped etc in real time with a timestamp.
I tried to look in the API documentation but couldn't find how this data could be retrieved.
I would like to store this realtime video info data in a file and do post analysis based on time to understand video streaming quality.
Thanks in advance.

A: You're going to have to use the new v3 API. You can sign up for a YouTube key here: https://console.developers.google.com/apis/api/youtube.googleapis.com
Documentation: https://developers.google.com/youtube/v3/docs/videos/list
To get the actual video info you can then use this URL:
https://www.googleapis.com/youtube/v3/videos?id={VIDEO_ID}&part=snippet%2CcontentDetails%2Cstatistics &key={YOUR_API_KEY}

A: Note that this answer no longer works. See Dex's answer below.
All the data an app can see about a video is parsed in XML (or JSON if you prefer) using this URL:

XML: http://gdata.youtube.com/feeds/api/videos/###########?v=2
JSON: http://gdata.youtube.com/feeds/api/videos/###########?v=2&alt=json-in-script

Just replace ########## with the ?v= numbers of your video. For instance: http://gdata.youtube.com/feeds/api/videos/rznYifPHxDg?v=2


text:
Q: Integrate $\int_{0}^{2}{\int_{y^2}^{4}{y\cos(x^2)dxdy}}$ I'm asked to evaluate $\int_{0}^{2}{\int_{y^2}^{4}{y\cos (x^2)dxdy}}$. Letting $f(x)=\cos (x^2)$ We have have that $\int_{y^2}^{4}{\cos (x^2)dx} = F(4)-F(y^2)$ by the FTC. This gives us
\begin{align*}
\int_{0}^{2}{\int_{y^2}^{4}{y\cos(x^2)dxdy}} &= \int_{0}^{2}{(yF(4)-yF(y^2))dy}\\
&=2F(4)-\int_{0}^{2}yF(y^2)dy\\
&=2F(4)-(\frac{y^2}{2}F(4) \big|_0^2 - \int_{0}^{2}{\frac{y^2}{2} \cdot 2y \cdot f(y^2)dy})\\
&= \int_{0}^{2}{y^3\cos(y^4)dy} = \frac{\sin(16)}{4}
\end{align*}
Is this a valid way to evaluate this integral? The solution given to me changed the order of integration instead and did it a bit differently. Thanks.

A: hint: Switch the order is better: $I = \int_{0}^ 4\int_{0}^{\sqrt{x}} y\cos(x^2)dydx$


text:
Q: How to draw the graph of a function of $x$.
$$y=\begin{cases} x^3 & x\le 1 \\ x & x \ge 1\end{cases}$$
Both are continuous at $x=1$. But not differentiate at the point.
Is the graph right?

A: Yes.
To  the degree of detail.  For $x\le1$ the graph will resemble the graph of $y = x^3$, and for $x > 1$ the graph will resemble the graph $y = x$.  As at $x = 1$, both $x^3$ and $x$ equal $1$, the graph with "connect".

A: Here is a graph generated with MATHEMATICA

Well, I have had installed the program in a PC. There are some sites where you can graph functions, but I'm not sure if you can get graphs with the same quality:
Wolfram Alpha
Desmos
Geogebra
I hope they will be useful to you.

A: The graph is correct, although the currently-attached statement $f'(x) = 3$ at $x \le 1$ is incorrect. It would be true to say that $f'(x) = 3x^2$ at $x < 1$, for which the limit of $f'(x)$ approaches 3 as $x$ approaches 1 from the left.


text:
Q: Show that for each $p \in P(n)$, the set $A(p) = \{x \mid p(x) = 0\}$ is countable Show that for each $p \in P_n\;$, the set $\;A(p) = \{x \mid p(x) = 0\}\;$ is countable.
  Where $P_n$ is the set of all polynomials of degree $n$ with integer coefficients.
I just proved that $P_n$ is countable.   My issue here is I just do not understand fully what the question is trying to ask me to prove is countable.   It almost seems like it's asking me to prove that all algebraic numbers are countable but that's the next question...
Some clarification would be helpful. I am simply rewriting what my professor has assigned.
This is what I've come up with so far (not very good)
Using the fact that any polynomial with integer coefficients and degree $n$ has at most $n$ roots, we can directly conclude that the set of all roots is finite, and thus countable. Now, If we consider all the roots of every polynomial, we have infinite union of countable sets, and thus the set of all roots to all polynomials with integer coefficients and degree $n$ are countable by the fact that the infinite union of countable sets is countable.

A: The key idea you can use to prove this is that a polynomial $P$ of degree $n$ cannot have more than $n$ roots (in the complex numbers). This is a simpler statement to prove than the fundamental theorem of algebra, which says that such a polynomial has exactly $n$ roots, counting multiplicity. In particular, you can prove this statement inductively; clearly, a polynomial of degree $0$ (i.e. a non-zero constant polynomial) cannot have more than $0$ roots. For the inductive step, notice that if $k$ is a root of $P$, then $Q(x)=\frac{P(x)}{x-k}$ is a polynomial of degree $n-1$. So if $Q(x)$ has no more than $n-1$ roots, $P(x)=Q(x)\cdot (x-k)$ must have no more than $n$. This implies that each set $A(P)$ has finitely many elements, bounded by the degree of the polynomial.
This looks to be essentially the idea that you already have - and I think it's a complete answer to the question as it is. For any $P$, it holds that $A(P)$ is finite, hence countable. This is what you're being asked to prove. I assume the next step you're meant to take is "Well, the union of all $A(P)$, which is the algebraic numbers, is a countable union of countable sets, and is therefore countable" - which is essentially what you've already written (which is getting a little ahead of the current problem). It is worthy of note that you have "an infinite union of countable sets", where we actually need the stronger hypothesis that it is a countable union of countable sets. Other than that, you clearly have the right idea.
(It is not immediately obvious that $\frac{P(x)}{x-k}$ is actually a polynomial if $k$ is a root, but you can easily prove that by using polynomial long division to see that there is no remainder when dividing $x-k$ if and only if $k$ is a root - and when there is no remainder, the quotient is clearly a polynomial)

A: Given that $P_n$ is the set of polynomials with $n$ integer coefficients and $\;p\in P_n\;$ then $\;A(p) = \{x \mid p(x) = 0\}\;$ is the set of roots to a specified polynomial with $n$ integer coefficients.
Hence it appears that you are required to prove: That a polynomial with $n$ integer coefficients has a countable number of roots (that is, solutions for $x$ to the equation $p(x)=0$).


text:
Q: How do you pronounce "exegesis"? I'm getting confusing results from dictionaries.
Would you mind uploading or linking to a recording of the correct pronunciation -- perhaps you would record yourself saying it, both isolated and in a sentence?
Edit
Does it rhyme with nemesis?

A: Exegesis is pronounced /ˌɛksɪˈdʒiːsɪs/ or  /ˌɛksəˈdʒiːsɪs/ (or possibly /ˌɛksəˈdʒiːsəs/), with primary stress on the second-to-last syllable. More or less: ek-sih-JEE-sis.
It rhymes with thesis, for most people (not for the ones who say "thessis", which apparently some people do). I think the pronunciation on Forvo sounds correct.
There is an explanation (of sorts) for why it is stressed on the second-to-last syllable, unlike nemesis.
"Exegesis" comes from the (ancient) Greek word ἐξήγησις. The English language has had very little direct contact with Greek. Most Greek-derived words in English were either taken from Latin, or were taken from Greek by scholars but treated "as if" they were passed through Latin. For example, Greek kappa (κ) corresponds most directly in form and sound to English "k", but Greek-derived words usually have "c" instead because that was the letter that was regularly used in Latin to transliterate Greek "κ".
This Latinization of Greek loans extends to stress patterns. Greek has its own stress system, but in general this is irrelevant to the pronunciation of an English word that is taken from Classical Greek. Instead, most loanwords like this conform to Latin stress patterns.
In Latin, the position of the stress in a polysyllabic word was, in general, entirely determined by the sounds and syllable structure of the second-to-last syllable.
The relevant rule in this case is that if the second-to-last syllable contained a long vowel, it was stressed.
The word ἐξήγησις can be transliterated as exēgēsis. The symbol ē represents the Greek "long e" vowel (thought to have been pronounced as something like an extended version of the vowel in English "bed"). Because the second-to-last syllable of exēgēsis contains a long vowel, it would have been stressed on this syllable in Latin. And this is the source of the stress pattern of this word in English.
The word "nemesis", on the other hand, comes from Greek νέμεσις nemesis, with a short vowel in the second-to-last syllable. In words with a "short" second-to-last syllable like this, the Latin stress rule regularly places the stress on the third-to-last syllable.
Hopefully this explanation is clear enough. As with many explanations relating to English pronunciation, it has exceptions. Some words, like plethora from Greek πληθώρα/πληθώρη and metamorphosis from μεταμόρϕωσις, are pronounced differently from how we'd expect from the Latin stress rules. (In general, at least—the OED does record an alternate pronunciation of metamorphosis with stress on the second-to-last syllable, although it doesn't seem to be common.)
Examples where the Latin stress rule holds:

*

*Stressed on second-to-last syllable because it had a long vowel: oecesis, kinesis, mimesis, noesis, cyesis, ketosis, osmosis, xerosis, zygosis, meiosis, ptosis.

*Stressed on third-to-last syllable because the second-to-last syllable was "short": genesis, emesis, ectasis, entasis, epitasis, protasis, di(a)eresis, syn(a)eresis, paresis, telesis, paralysis, hypothesis, aphesis.


text:
Q: Bijection between sets (p-groups and conjugacy classes) Let $G$ be a finite group. We let $T_{G}$ denote the set of conjugacy classes of subgroups of $G$ and let $T$ denote a set of representatives of $T_{G}$.
How to establish a bijection between the following sets:
$\{H \in T: O^{p}(H)=H\}$ and $\{S \in T: [N_{G}(S): S] \textrm{is not divisible by p} \}$.
Here $N_{G}(S)$ means the normalizer of $S$ in $G$ and $O^{p}(H)$ the smallest normal subgroup of $H$ such that $H/O^{p}(H)$ is a $p$-group.

A: Let $A=\{H\in T\ |\ O^p(H)=H\}$ and $B=\{S\in T\ |\ p\nmid [N_G(S):S]\ \}$. We need to define two maps $\phi:A\rightarrow B$ and $\psi:B\rightarrow A$, which are both well-defined up to conjugacy, and are inverses of one another.
The map from $B$ to $A$ is easier to describe: $\psi(S)=O^p(S)$.  Note that $O^p(O^p(S))=O^p(S)$, so $\psi(S)\in A$. Since $O^p(S)^g=O^p(S^g)$, this map is well-defined.
To define $\phi(H)$, choose a subgroup $K$, with $H\le K\le N_G(H)$, such that $K/H$ is a Sylow p-subgroup of $N_G(H)/H$. Let $\phi(H)=K$. Since $N_G(H)^g=N_G(H^g)$, and Sylows are conjugate, this map is well-defined. Moreover, since $K/H$ is a p-group, $O^p(K)\subset H$, and thus $O^p(K)=H$ since $H\in A$. Thus $N_G(K)\subset N_G(H)$, and since $p\nmid [N_G(H):K]$, certainly $p\nmid [N_G(K):K]$. Thus $\phi(H)\in B$.
From what was said above, we see that $O^p(\phi(H))=H$, so that $\psi\phi(H)=H$.
In the other direction, since $O^p(S)$ is characteristic in $S$, we have $N_G(S)\subset N_G(O^p(S))$.  Now $S/O^p(S)$ is a p-subgroup of $N_G(O^p(S))/O^p(S)$, and since "normalizers grow" in p-groups, yet $S\in B$, $S/O^p(S)$ must be a Sylow p-subgroup of $N_G(O^p(S))/O^p(S)$. Thus $\phi(\psi(S))=\phi(O^p(S))=S$.


text:
Q: chartkick JSON data source I'm trying to get Chartkick in Rails to use a JSON data source.
When specifying a chart as pie_chart User.group(:language).count I get the expected pie chart.
But when specifying the chart as: pie_chart /path_to_report_data from data controller method I get nothing.
That is, an empty, blank chart (no data in it)
My data controller:
  def report
    @language= User.group(:language).count
    if request.xhr?
      render :json => { :language => @language }
    end
  end

My view:
<%= line_chart "/data/report" %>

I can see the data is delivered through an Ajax call to the specified controller.

A: This one works for me:
def report1
  begin
    @data= [["Cat",6],["Dog",4],["Horse",1],["Parrot",2]]
  rescue Exception => ex
    logger.info('Report 1 error : ' + ex.message)
    @data = nil
  end
  if request.xhr?
    render json: @data
  end
end

and in the view:
<%= datasource = "/path_to_data_controller/report1"
    line_chart datasource, discrete: true
%>

HTH