text:
Q: pointer to pointer in linkedlist cannot preserve the pointer after every call from the main function. Why? #include<iostream>

#define print(x) std::cout<<x<<std::endl;

class Node
{
    public:
    int data;
    Node* next;
};

class LinkedList
{
private:
    Node** head_ref;
public:
    LinkedList() :head_ref(NULL) {};

    void insertFront(int new_data)
    {
        Node* new_node = new Node();
        new_node->data = new_data;

        if(this->head_ref == NULL)
            this->head_ref = &new_node;
        else
        {
            new_node->next = *(this->head_ref);
            this->head_ref = &new_node;
        }
    }

    void PrintLinkedList()
    {
        Node* temp = (*(this->head_ref));
        while (temp->next != NULL)
        {
            print(temp->data);
        }
        print("\n");
    }
};

int main()
{
    LinkedList a1;
    a1.insertFront(5);
    a1.insertFront(6);
    a1.insertFront(7);
    a1.PrintLinkedList();
    std::cin.get();
}

As you will see in the screenshots in the watch1 tab the this->head_ref preserves the location of the Node* but Node* i.e. (*(this->head_ref)) doesn't preserve the location of the Node. I want to know what is causing this. Is it because Node** head_ref has no regulation in how the inside pointer points to the Node or is it a scope problem? The problem occurs each time right after the next function call happens and the debugger enters the insertFront function, the Node* becomes a free pointer pointing to nothing.
First call screenshot
Second call screenshot before entering insertFront
Second call screenshot just after entering insertFront but a new Node object has not been made yet

A: The answer is provided by @IgorTandetnik in the comments.

The Node object is allocated on the heap. But the Node* object named new_node is allocated on the stack. You have head_ref point to new_node and new_node point to the Node object. Then the function returns, new_node is gone, and there is no longer any connection between head_ref and the heap-allocated Node. head_ref points to some garbage value where new_node used to be, and Node on the heap is leaked as nothing points to it anymore.

I have changed the code accordingly by using Node* head_ref which will refer to a heap allocated Node instead of the new_nodepointer which goes out of scope.
#include<iostream>
#define print(x) std::cout<<x<<std::endl;

class Node
{
public:
    int data;
    Node* next;
};

class LinkedList
{
private:
    Node* head_ref;
public:
    LinkedList() :head_ref(NULL) {};

    void insertFront(int new_data)
    {
        Node* new_node = new Node();
        new_node->data = new_data;

        if(this->head_ref == NULL)
            this->head_ref = new_node;
        else
        {
            new_node->next = this->head_ref;
            this->head_ref = new_node;
        }
    }

    void PrintLinkedList()
    {
        Node* temp = this->head_ref;
        while (temp->next != NULL)
        {
            print(temp->data);
            temp = temp->next;
        }
        print(temp->data);
        print("\n");
    }
};

int main()
{
    LinkedList a1;
    a1.insertFront(5);
    a1.insertFront(6);
    a1.insertFront(7);
    a1.PrintLinkedList();

    std::cin.get();
}


text:
Q: Как разрешить конфликт обновление Symfony 3.3 на Symfony 4? Пытаюсь обновить Symfony 3 на Symfony 4:
composer update symfony/symfony

Получаю ошибку:
      Problem 1
        - Conclusion: remove symfony/symfony v3.3.14
        - Conclusion: remove sensio/distribution-bundle v5.0.21
        - Conclusion: don't install sensio/distribution-bundle v5.0.21
        - Installation request for sensio/distribution-bundle == 5.0.21.0 -> satisfiable by sensio/distribution-bundle[v5.0.21].
        - Conclusion: don't install symfony/symfony v4.0.1
        - sensio/distribution-bundle v5.0.21 requires symfony/process
          ~2.3|~3.0 ->
           satisfiable by symfony/symfony[v3.3.14],
           symfony/process[v2.3.0, v2.3.1, v2.3.10,
           v2.3.11, v2.3.12, v2.3.13, v2.3.14,
           v2.3.15, v2.3.16, v2.3.17, v2.3.18,
           v2.3.19, v2.3.2, v2.3.20, v2.3.21,
           v2.3.22, v2.3.23, v2.3.24, v2.

Так как 4 версия стала стабильной недавно, подскажите пожалуйста, как разрешить конфликт?

A: Никак. В комментарии было правильно описано, что нужно переходить на symfony-flex.
В репозитории SensioDistributionBundle написано:

WARNING: This bundle does not support Symfony 4. Symfony Flex is a total replacement for this bundle.

Прочитайте подробнее про symfony-flex

*

*Документация на оф.сайте

*Репозиторий на github

A: На Symfony 4 можно перейти без использования Symfony Flex. Для этого из composer.json надо удалить sensio/distribution-bundle, после чего выполнить
composer update

либо
composer update "symfony/*" --with-all-dependencies

если не нужно обновлять все остальные зависимости.
Если будет ругаться на залоченную версию какой-то зависимости - можно временно удалить файл composer.lock
После перехода на Symfony 4 можно по желанию установить Symfony Flex. При этом это возможно сделать и в обратной последовательности, как душе угодно, т.к. Symfony Flex совместим с Symfony 3.4
И вот еще с сайта Symfony:
"Using Symfony Flex is optional, even in Symfony 4, where Flex is used by default"
https://symfony.com/doc/current/setup/flex.html#upgrading-existing-applications-to-flex
Т.е. Symfony Flex рекомендуется, но не является обязательным для Symfony 4.

redpajama_set_name: RedPajamaStackExchange


text:
Q: External-dns access private with EKS and Route53 don't work I'm using EKS, Route53 and External-dns for my DNS records.
Here is the nginx-ingress I'm currently using
nginx-ingress:
  controller:
    config:
      use-forwarded-headers: "true"
    service:
      annotations:
        external-dns.alpha.kubernetes.io/access: private
        external-dns.alpha.kubernetes.io/hostname: gitlab.${var.gitlab-domain}, registry.${var.gitlab-domain}
        service.beta.kubernetes.io/aws-load-balancer-ssl-cert: ${data.aws_acm_certificate.cert.arn}
        service.beta.kubernetes.io/aws-load-balancer-backend-protocol: https
        service.beta.kubernetes.io/aws-load-balancer-ssl-ports: https
        service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout: "3600"
        alb.ingress.kubernetes.io/scheme: internet-facing
        ${var.gitlab-domain}/dns-type: private

My problem is even though I'm using this line:
external-dns.alpha.kubernetes.io/access: private, external-dns will add records in both public and private route53 hosted zone. How to do to only have the records in my private zone?
For now, the only workaround I found is to not give the right on the public zone to route53, but it's not a long term solution.

A: I'm now using annotations filter
I have two external-dns one for the private zone one for the public
I add this to my external-dns helm chart:
set {
    name  = "annotationFilter"
    value = "company.com/dns-type in (private)"
}

And after in my nginx-ingress controller, in the annotations I can use this annotation:
company.com/dns-type: private


text:
Q: Java 8 datetime aging support? How to support hard aging of java.time date-time based system in Java 8?
I didn't find a way to inject fixed clock at one place for entire code base. Otherwise i need to change my code to either inject Clock in every place i get instant.
Testers wanted to validate year end,month end scenarios while running their scripts. I need to provide this feature through configuration which should to apply to entire application.


text:
Q: Elasticsearch configuration failed to load bundle I'm using Gradle (Spring Boot 1.4.2, Thymeleaf, Elasticsearch 2.3.4) and I'm working locally.
I'm trying to implement Thymeleaf security using thymeleaf-extras-springsecurity4 module but I faced a problem.
I got this error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDashboardDaoImpl': Unsatisfied dependency expressed through field 'userDashboardRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDashboardRepository': Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.IllegalStateException: java.lang.IllegalStateException: failed to load bundle [file:/D:/elasticsearch-2.3.4/modules/lang-expression/antlr4-runtime-4.5.1-1.jar, file:/D:/elasticsearch-2.3.4/modules/lang-expression/asm-5.0.4.jar, file:/D:/elasticsearch-2.3.4/modules/lang-expression/asm-commons-5.0.4.jar, file:/D:/elasticsearch-2.3.4/modules/lang-expression/lang-expression-2.3.4.jar, file:/D:/elasticsearch-2.3.4/modules/lang-expression/lucene-expressions-5.5.0.jar] due to jar hell

My build.gradle is:
buildscript {
    repositories {
       jcenter()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin: 1.4.2.RELEASE")
   }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
jar {
     baseName = 'Selva'
     version =  '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
dependencyManagement {
     imports {
         mavenBom 'org.springframework.boot:spring-boot-starter-parent:1.4.2.RELEASE'
     }
}
if (!hasProperty('mainClass')) {
     ext.mainClass = '*.*.config.Application'
 }
 configurations {
      provided
 }
 repositories {
       mavenCentral()
       maven {
         url "http://jasperreports.sourceforge.net/maven2"
       }
      maven {
       url "http://jaspersoft.artifactoryonline.com/jaspersoft/third-party-ce-artifacts/"
      }
     }
  dependencies {
     compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '1.4.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.2.RELEASE'
compile group: 'com.h2database', name: 'h2', version: '1.4.193'
compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.1.1'
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4', version: '3.0.1.RELEASE'
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
 }

A: This is because of JAR hell.
You have a dependency on org.springframework.boot:spring-boot-starter-data-elasticsearch:1.4.0.RELEASE' which will import org.springframework.data:spring-data-elasticsearch  which in turn imports org.elasticsearch:elasticsearch.
Aside from this, you're importing org.elasticsearch:elasticsearch:2.3.4 directly, which means that you'll end up with two elasticsearch JARs, hence the JAR hell.
If you're using the spring-boot-starter-data-elasticsearch, you shoulnd't need to have your own import for org.elasticsearch:elasticsearch.
Remove it and you'll be fine.


text:
Q: Retornar mensagem de erro para consultas no banco com PHP Existe alguma forma de receber mensagens de erro vindas do banco dados ao tentar-se executar uma Query com o PDO do PHP?
Já tentei botar um try catch no método ->execute() mas a classe PDOException não captura nada.
Alguém tem ideia de como ser faz?

A: Para manipular o error retornando por uma consulta pode-se utilizar exceptions ou retornos de funções(erros).

*

*Exceptions

O quarto argumento é um array onde algumas configurações podem ser passadas entra elas o PDO::ATTR_ERRMODE e o valor PDO::ERRMODE_EXCEPTION define que os erros serão tratados como exceptions.
Para capturar os erros do banco como exceptions primeiro definia isso no construção do PDO
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$db = new PDO('pgsql:host=localhost;dbname=test', 'root', '', $opcoes);

$sql = "select ... invalido";
$stmt = $db->prepare($sql);

try{
    $stmt->execute();
}catch(PDOException $e){
    echo $e->getMessage();
}

*

*Retorno de função

A abordagem padrão é essa, verificar o retorno de execute() caso seja false use o método errorInfo() para obter detalhes sobre o erro, com a mensagem e o SQLState.
$db = new PDO('pgsql:host=localhost;dbname=test', 'root', '');
$sql = "select ... invalido";
$stmt = $db->prepare($sql);

if($stmt->execute() === false){
    echo "<pre>";
    print_r($stmt->errorInfo());
}


text:
Q: How can I change the named keys in an associative array The following code returns an associative array as follows
Array ( [1] => Array (
   [url] => example.com
   [title] => Title.example
   [snippet] => snippet.example
) )

$blekkoArray = array();

    foreach ($js->RESULT as $item)
    {
        $blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'Url'}) );
        $blekkoArray[$i]['title'] = ($item->{'url_title'});
        $blekkoArray[$i]['snippet'] = ($item->{'snippet'});
        $i++;
    }

    print_r ($blekkoArray);

How can I modify the array so that instead of the array element been identified by 1,2,3 etc it would be identified by the url eg.
Array ( [example.com] => Array (
   [title] => Title.example
   [snippet] => snippet.example
) )

A: You may try this too (one line solution)
$newArray = array( $old[0]['url'] => array_splice($old[0], 1) );

DEMO.

A: Very simple, just use the url instead of $i
foreach ($js->RESULT as $item)
{
    $url = str_replace ($find, '', ($item->{'Url'}) )
    $blekkoArray[$url]['title'] = ($item->{'url_title'});
    $blekkoArray[$url]['snippet'] = ($item->{'snippet'});
    $i++;
}

A: foreach ($js->RESULT as $item)
    {
        $url = str_replace ($find, '', ($item->{'Url'}) );
        $blekkoArray[$url] = array("title"=>($item->{'url_title'}), "snippet"=>($item->{'snipped'}));
    }

A: Considering your example as follows. Where $js is the array you would want to modify.
$js = array(
    1 => array ( 'url' => 'example.com', 'title' => 'Title.example','snippet' => 'snippet.example'),
    2 => array ( 'url' => 'example2.com', 'title' => 'Title.example2','snippet' => 'snippet.example2'),
    3 => array ( 'url' => 'example3.com', 'title' => 'Title.example3','snippet' => 'snippet.example3'));

$blekkoArray = array();

// The lines below should do the trick
foreach($js as $rows) { // main loop begins here
    foreach($rows as $key => $values) { // access what's inside in every $row by looping it again
        if ($key != 'url') {
             $blekkoArray[$rows['url']][$key] = $values; // Assign them
        }
    }
}

print_r ($blekkoArray);

It doesn't matter how many elements there are in your $js array as it will only repeat the process each time.

A: foreach ($arr as $key => $value){
    $out[$value['url']] = array_slice($value, 1);
}

A: The other solutions seem to focus on changing the array after
foreach ($js->RESULT as $item)
    {
        $blekkoArray[str_replace ($find, '', ($item->{'Url'}))] = array(
        'title'=> $item->{'url_title'},
        'snip pet' => $item->{'snippet'}
         );

    }

That should make the array how you need it


text:
Q: Different types of MongoDB nodes I am building a monitoring plugin designed to detect--among other things--when any given Mongo node is down. These are the types of nodes I am looking for: mongo-s, mongo-d configsvr, replica set, and the individual shards that make up the replica set--a primary, secondaries, and arbiters. I am gathering the list of nodes from the getShardMap command, and querying each node individually to find out which type it is. Are there any other types of nodes I might need to be aware of? And, if so, where can I find them listed within Mongo commands?

A: I think you've got the different "types" of nodes covered, but you might also want to monitor the current "state" of each node in each replica set (in addition to being PRIMARY or SECONDARY, a node can also be in a RECOVERY state, or in a ROLLBACK state, etc.).  You can query for the state using the replSetGetStatus command.  The different states are listed here:
http://www.mongodb.org/display/DOCS/Replica+Set+Commands#ReplicaSetCommands-state


text:
Q: Adding custom header with volley request and response is "data": "This field is required" i am just started with volley request with custom request here is peace of code what i am using for sending a custom header. headers must be
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json");
When i am hitting this url with postman it is working fine.
row data in postman

and
Headers

StringRequest stringRequest = new StringRequest(Request.Method.POST,
            WebConstants.BASE_URL + method,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    if (dialog != null)
                        dialog.dismiss();

                    if (response != null) {
                        dialog.dismiss();
                        Log.e("res", response);
                        //    eventHandler.onResponse("" + method, response);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (dialog != null)
                        dialog.dismiss();
                    eventHandler.onResponse("" + method, "");
                }
            }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap headers = new HashMap();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");

            return headers != null ? headers : super.getHeaders();
        }

        @Override
        public byte[] getBody() {
            String str = "{\"firstname\":\"Test\", \"lastname\":\"User\", \"gender\":\"male\", \"country\":\"US\", \"zipcode\":\"H1A NFG\", \"email\":\"testuseef434532r@mail.com\", \"password\":\"123456\", \"referral_code\":\"\", \"requested_plan\":\"\"}";
            return str.getBytes();

        }

/* Tried with this
@Override
            public byte[] getBody() {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("firstname","Sandeep");
                    jsonObject.put("lastname","Parish");
                    jsonObject.put("gender","M");
                    jsonObject.put("country","US");
                    jsonObject.put("zipcode","H1A NFG");
                    jsonObject.put("email","usermail@localmail.com");
                    jsonObject.put("password","123456");
                    jsonObject.put("referral_code","123456");
                    jsonObject.put("requested_plan","123456");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return jsonObject.toString().getBytes();

            }

//Tried with map
  @Override
            protected Map<String, String> getParams() {
  Map<String, String> map = new HashMap<>();
        map.put("firstname", "sandeep");
        map.put("lastname", "sada");
        map.put("gender", "d");
        map.put("country", "sdfasiio");
        map.put("zipcode", "test");
        map.put("email", "testmail@mail.com");
        map.put("password", "0");
        map.put("referral_code", "0");
        map.put("requested_plan", "0");

        Log.e("Map", map.toString());
                return map;
            }
*/

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

    };

    stringRequest.setShouldCache(false);
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);

please help me to find out what's the issue with this code i am getting  response with this code is.
E/res: {
        "success": false,
        "data": "This field is required"
    }

if any issue at my side please let me know.

A:   StringRequest stringRequest = new StringRequest(Request.Method.POST,
        WebConstants.BASE_URL + method,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json; charset=utf-8");
        return headers;
    }
    @Override
    protected Map<String, String> getParams() {
      Map<String, String> map = new HashMap<>();
      map.put("firstname", "sandeep");
      map.put("lastname", "sada");
     map.put("gender", "d");
    map.put("country", "sdfasiio");
    map.put("zipcode", "test");
    map.put("email", "testmail@mail.com");
    map.put("password", "0");
    map.put("referral_code", "0");
    map.put("requested_plan", "0");

    Log.e("Map", map.toString());
            return map;
        }
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
        DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);


text:
Q: Is summary feature supported on ExtJS 4.2.5 for TreePanel's? Context: I'm upgrading an application from 4.1.1 to 4.2.5 I've gone successfully to 4.1.3 but when upgrading to 4.2.5 ...
I noticed an issue with the summary feature on treepanel's and based on what I see on this thread https://www.sencha.com/forum/showthread.php?264726-Summary-feature-doesn-t-work-with-TreePanel Evan Trimboli is saying this feature is not intended for treepanels but then again it worked on previous versions.
Ultimately there is an error accessing childNodes of null:
  collectNodes: function(targetEl) {
        this.all.fill(this.getNodeContainer().childNodes, this.all.startIndex);
    },

So: Is summary feature supported on ExtJS 4.2.5 for TreePanel's ?
I'll try the overrides provided on the Sencha forum and post how it went for me, I just wanted to have this issue also in SO and see if someone else faced this issue too.


text:
Q: Как удалить имена из списка? li = ['Седьмая печать',
'Ингмар Бергман', '5', '1957',
'Остров проклятых',
'Мартин Скорсезе', '4', '2010',
'Земляничная поляна',
'Ингмар Бергман', '5', '1957',
'Час волка',
'Ингмар Бергман', '3', '1968']

Как удалить каждый 4 элемент списка?

A: from itertools import cycle, compress

li = [
    'Седьмая печать', 'Ингмар Бергман', '5', '1957',
    'Остров проклятых', 'Мартин Скорсезе', '4', '2010',
    'Земляничная поляна', 'Ингмар Бергман', '5', '1957',
    'Час волка', 'Ингмар Бергман', '3', '1968'
]

new_li = [*compress(li, cycle([True, True, True, False]))]

print(new_li)
# ['Седьмая печать', 'Ингмар Бергман', '5', 'Остров проклятых', 'Мартин Скорсезе', '4', 'Земляничная поляна', 'Ингмар Бергман', '5', 'Час волка', 'Ингмар Бергман', '3']

A: Думаю, это будет наиболее простым и удобным способом в вашем случае.
new_list = []
for i in range(0, len(li)):
    if i % 4 != 3:
        new_list.append(li[i])
print(new_list)

Пример вывода на Ваших данных:
['Седьмая печать', 'Ингмар Бергман', '5', 'Остров проклятых', 'Мартин Скорсезе', '4', 'Земляничная поляна', 'Ингмар Бергман', '5', 'Час волка', 'Ингмар Бергман', '3']

A: new_list = [i for i in li if (li.index(i) + 1) % 4 != 0 or li.index(i) == 0 or li.index(i) == 4]

как вариант


text:
Q: Approximation by Taylor polynomial Let $f(x) = (1 − x)^{-1}$ and $x_{0} = 0.$
(a) Find the nth Taylor polynomial $P_{n}(x)$ for $f(x)$ about $x_{0}$.
(b) Find the smallest value of $n$ necessary for $P_{n}(x)$ to approximate $f(x)$ to
within $10^{-6}$ on $[0; 0.5]$.
For part (a) I get $P_{n}(x)=1+x^{2}+x^{3}+...+x^{n}.$ I don't know how to get started with part (b), is it finding $n$ such that $|f(x)-P_{n}(x)| \leq 10^{-6}$? Thanks!

A: We could try to use various general expressions for the remainder. You may have learned already about the Lagrange form of the remainder.
These however often do not give good upper bounds for the error. We want a good upper bound because we were asked to find the smallest $n$.
Instead of attempting to use a general estimate, we work with our particular function.  Note that the error we make by truncating just after the $x^n$ term is exactly equal to the missing tail, which is
$$x^{n+1}+x^{n+2}+x^{n+3}+\cdots.$$
The sum of this geometric series is equal to
$$\frac{x^{n+1}}{1-x}.$$
In our interval, this is biggest at $x=0.5$, when it is equal to $(0.5)^n$.
So we are trying to find the smallest integer $n$ such that $(0.5)^n\lt 10^{-6}$.
You can solve $(0.5)^t=10^{-6}$ using logarithms. But in this case we can do the problem in our heads, since $1000$ is very close to $2^{10}$.

A: a is correct.  For part b, you are right you want $|f(x)-P_n(x)|\le 10^{-6}$ over the given interval.  To do that, you need the error term in the Taylor series.  It has the $n+1^{\text{st}}$ derivative in it, you find the maximum of that derivative and plug it in.


text:
Q: Ionic app not working on device/simulator It was working fine in the simulator yesterday but now it's acting goofy. I happened to stumble on a way to get it working in the simulator though:
Normally to simulate the app on ios I run
$ ionic run ios

Which now shows the app but the "broken" version of it.
However, if I run
$ ionic run ios --livereload

Then my app works as expected! Unfortunately the ionic view app displays the broken version. Chrome (via ionic serve) shows the working version so I'm using that to develop now but I need to get this fixed. What's the troubleshooting process at this point?

A: Even though this worked on the web along with --livereload the issue all along was with a script href url.
The problem: The google maps js link was using "//url.to.site" so I had to manually prepend "http:" and voila.
How to properly debug ionic + angularjs apps on iOS devices
Debugging this was terrible until I came with up a good solution. Beware: this requires OS X or some serious hacking skills.
Here are the steps in order:

*

*$ ionic build ios

*Open TheApp/platforms/ios/TheApp.xcworkspace in Xcode

*Build/Run the app in xcode to device OR simulator

*Open Safari w/ Developer Mode enabled (Preferences > Advanced > Show Develop menu in menu bar)

*In the Safari menu select Debug > [Name of iOS device] > index.html

*While the Inspector window is active, hit CMD+R (refresh) and you'll be able to watch your console.logs from the beginning of the page load.

EDIT Shortcut: You can skip steps 1-3 if you use $ ionic run ios --device
This is awesome because now you can step through your code on an actual iOS device! I hope this will save some of you heaps of time. Best of luck!
For Android Devices
Thanks to @sajclarke I found this article: https://developer.chrome.com/devtools/docs/remote-debugging


text:
Q: AWS Elemental MediaPackage Time-shifted is not working 404 error In AWS Elemental MediaPackage, I am trying enable time-shifted viewing as below reference link:
https://docs.aws.amazon.com/mediapackage/latest/ug/time-shifted.html
But an HTTP error 404 occured. How can I fix it? Please help!

A: You can use Time-Shifted viewing on Elemental MediaPackage if start-over window is configured on your end-point. Looking at your description it looks like MediaPackage could not find a segment to satisfy your request. It may be due to one of the following :

*

*Start Over window was configured after the end-point was created.

*No ingest into the MediaPackage channel for the timestamps you requested.

Inorder to find out the reason behind this issue, I'll need the channel arn or the playback URL along with the timestamps when you made this request. Can you please provide these details to take a look ?


text:
Q: How to configure log rotate for Gunicorn running as a systemd service within a venv behind an Nginx reverse proxy? I can't figure out how to cleanly configure log rotation for my python app (served by Gunicorn 20.0.4 behind an Nginx reverse proxy). Official Gunicorn documentation states:

Send the USR1 signal to rotate logs if you are using the logrotate
utility: kill -USR1 $(cat /var/run/gunicorn.pid)

I'm not sure what pid file I should target and where above logrotate directive should reside (postrotate or other).
SystemD service
# /etc/systemd/system/my_app.service
[Unit]
Description=My App
After=network.target
Wants=celery-my_app.service
Wants=celerybeat-my_app.service

[Service]
User=my_app_user
Group=nginx
Environment=FOO=bar
RuntimeDirectory=my_app
WorkingDirectory=/opt/my_app/my_project
ExecStart=/opt/my_app/my_project/venv/bin/gunicorn --workers 3 --log-level debug --error-logfile /var/log/my_app/my_app_error.log --access-logfile /var/log/my_app/my_app_access.log --capture-output --bind unix:/var/run/my_app/my_app.sock my_project.wsgi:application

[Install]
WantedBy=multi-user.target

Logrotate configuration
/var/log/my_app/my_app_error.log /var/log/my_app/my_app_access.log {
    weekly
    missingok
    rotate 4
    delaycompress
    notifempty
    copytruncate
    postrotate
        # Gunicorn alleged pid file
        kill -USR1 $(cat /var/run/my_app.pid)
    endscript
}

*

*Do I have to assume that Gunicorn pid file used for kill signal
mentionned in documentation is /var/run/my_app.pid?

*Are there additionnal directives to add to the logrotate configuration file
below especially regarding my use case (venv, Gunicorn, Nginx,
systemd) or caveats I shiuld be aware of to properly configure log rotation?


text:
Q: When trying to get Xml data from URL, it returns null I'm trying to get xml data and parse it with an async task. Here is what I did :
In OnCreate method I get url as string. I tested my url and it doesn't return null. Also has permission to connect to Internet.
            startDownload start = new startDownload();
            start.execute(url.toString());

And my Async class :
protected class startDownload extends AsyncTask<String, Void, String>{
    @Override
    protected void onPreExecute() {

        eczaDialog = ProgressDialog.show(ListViewXML.this,"", "Loading...");
    }
    @Override
    protected String doInBackground(String... aurl) {
        try {
            URL url = new URL(aurl[0]);

            DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize(); ....

When i debug my code i saw that this doc variable returned null. I don't understand where was the problem. I hope you can help me to find out Thanks.

A: You have to get the content of the xml. You can use this, the code returns the content in the string, after you can create an XML object :
public static String getStringPage(String url){
    StringBuffer stringBuffer = new StringBuffer();
    BufferedReader bufferedReader = null;
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    URI uri = null;
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    String HTMLCode = null;

    //Create client and a query to get the page
        httpClient = new DefaultHttpClient();
        httpGet = new HttpGet();

        //Set the query with the url in parameter
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        httpGet.setURI(uri);

        //Execute the query
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Create a buffer to get the page
        try {
            inputStream = httpResponse.getEntity().getContent();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        //Get the buffer caracters
    try {
        HTMLCode = bufferedReader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    while (HTMLCode!= null){
        stringBuffer.append(HTMLCode);
        stringBuffer.append("\n");
        try {
            HTMLCode = bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Return the string of the page code
    return stringBuffer.toString();
}


text:
Q: Permissions difficulty accessing remote '/' with CIFS I'm having trouble accessing the root directory of another Linux machine.
In my fstab I have two entries for the machine in question
//ltotto/root   /mnt/ltroot     cifs    auto,users,credentials=/home/otto/.smbcredentials,uid=otto,gid=otto,file_mode=0770,dir_mode=0770,iocharset=utf8 0 0
//ltotto/otto   /mnt/ltotto     cifs    auto,users,credentials=/home/otto/.smbcredentials,uid=otto,gid=otto,file_mode=0770,dir_mode=0770,iocharset=utf8 0 0

i.e. both to the same machine with the same credentials. On the other machine there are two Samba shares 'root' and 'otto' for '/' and '/home/otto' respectively, both with write permission for the user otto.
Both are mounted with no errors and the 'otto' mount works perfectly.
The 'root' mount however is the problem
ls -la /mnt/ltroot/
ls: /mnt/ltroot/var: Permission denied
ls: /mnt/ltroot/lib64: Permission denied
ls: /mnt/ltroot/cdrom: Permission denied
[etc]

I can't understand why the home mount is fine and the root mount not. Can anyone explain and suggest a solution?
Note: I'm sure this configuration worked perfectly until recently.
EDIT: The Samba configuration of the remote machine:
[root]
    comment = file system root
    path = /
    writeable = yes
;   browseable = yes
    valid users = otto

[otto]
    path = /home/otto
    writeable = yes
;   browseable = yes
    valid users = otto
    comment = otto's Home


text:
Q: How to dynamically create and pass an object I am trying to add and invoke function dynamically. For that, below is the code

filed = [];

function fileIt(thing) {
    // Dynamically call the file method of whatever
    thing.addIt();

    // Mark as filed
    filed.push(thing);
}

function repType1(name) {
    this.name = name;
}

repType1.prototype.addIt = function () {
    //Business Logic will go here
    console.log("Heloo From repType1");
}

function repType2(name) {
    this.name = name;
}

repType2.prototype.addIt = function () {
    //Business Logic will go here
    console.log("Heloo From repType2");
}

let rep1 = new repType1("repType1");
fileIt(rep1);

I am able to call function using let rep1 = new repType1("repType1"); for repType1but i need to do it dynamically so that same line of code can call my other function 'repType2' as well. I have the function parameter value as string for example: "repType1", "repType2", etc. How to do it?

A: Look like you are trying to mutate objects to perform something like the following If I understood you correctly :

const filed = [];

function fileIt(thing) {
  // Dynamically call the file method of whatever
  thing.addIt();

  // Mark as filed
  filed.push(thing);
}

class RepType {
   addItrepType1() {
     //Business Logic will go here
     console.log('Heloo From repType1');
   }

   addItrepType2() {
    //Business Logic will go here
    console.log('Heloo From repType2');
   }

   constructor(type) {
      // Set the function depending on the type
      this.addIt = this[`addIt${type}`];

      this.name = name;
   }
}

const rep1 = new RepType('repType1');
const rep2 = new RepType('repType2');

fileIt(rep1);
fileIt(rep2);

Though I would recommand you to use the inheritance system like :

const filed = [];

function fileIt(thing) {
  // Dynamically call the file method of whatever
  thing.addIt();

  // Mark as filed
  filed.push(thing);
}

// Abstract class
class ARepType {
  addIt() {
    throw new Error('Unimplemented abstract method');
  }

  constructor() {
    this.name = 'Abstract';
  }
}

class RepType1 extends ARepType {
  // override the function
  addIt() {
    //Business Logic will go here
    console.log('Heloo From repType1');
  }

  constructor() {
    super();

    this.name = 'repType1';
  }
}

class RepType2 extends ARepType {
  // override the function
  addIt() {
    //Business Logic will go here
    console.log('Heloo From repType2');
  }

  constructor() {
    super();

    this.name = 'repType2';
  }
}

const rep1 = new RepType1();
const rep2 = new RepType2();

fileIt(rep1);
fileIt(rep2);

A: Another possible way!

filed = [];

function fileIt(thing) {
    // Dynamically call the file method of whatever
    thing.addIt();

    // Mark as filed
    filed.push(thing);
}

function RepType() {
    RepType.types = {repType1, repType2};
    this.addIt = function () {
    };

    RepType.of = function (type) {
        return new (this.types[type])();
    };
}

function repType1(name) {
    this.name = name;
}

repType1.prototype = new RepType();
repType1.prototype.addIt = function () {
    //Business Logic will go here
    console.log("Heloo From repType1");
};

function repType2(name) {
    this.name = name;
}

repType2.prototype = new RepType();
repType2.prototype.addIt = function () {
    //Business Logic will go here
    console.log("Heloo From repType2");
};

let rep1 = RepType.of("repType1");

fileIt(rep1);


text:
Q: remove responsiveness from slideshow I have a simple slideshow, only images with controllers but it is responsive, and i want to remove the responsiveness.
So far i removed all the media queries from the style-sheet (css) and removed the meta viewport also; but the slider is still responsive, i know or at least i think i know this feature is set on the jQuery file linked to my slider but i am not sure which action i should remove or how to edit it.
This is the file:
(function (e) {
    e.skdslider = function (t, n) {
        var r = {
            delay: 2e3,
            animationSpeed: 500,
            showNav: true,
            autoSlide: true,
            showNextPrev: false,
            pauseOnHover: false,
            numericNav: false,
            showPlayButton: false,
            animationType: "fading"
        };
        if (n) {
            e.extend(r, n)
        }
        var i = "ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch;
        e(t).wrap('

');
        var s = e(t).closest("div.skdslider");
        s.find("ul").addClass("slides");
        var o = s.find("ul.slides li");
        var u = 0;
        r.currentSlide = 0;
        r.currentState = "pause";
        r.running = false;
        if (r.animationType == "fading") {
            o.each(function () {
                e(this).css({
                    position: "absolute",
                    left: "0",
                    top: "0",
                    bottom: "0",
                    right: "0"
                })
            })
        }
        if (r.animationType == "sliding") {
            o.each(function () {
                e(this).css({
                    "float": "left",
                    display: "block",
                    position: "relative"
                })
            });
            var a = s.outerWidth() * o.size();
            s.find("ul.slides").css({
                position: "absolute",
                left: "0",
                width: a
            });
            o.css({
                width: s.outerWidth(),
                height: s.outerHeight()
            });
            e(window).resize(function () {
                var e = s.outerWidth() * o.size();
                s.find("ul.slides").css({
                    position: "absolute",
                    left: "0",
                    width: e
                });
                o.css({
                    width: s.outerWidth(),
                    height: s.outerHeight()
                })
            })
        }
        e.skdslider.enableTouch(s, o, r);
        e.skdslider.createNav(s, o, r);
        o.eq(u).show();
        if (r.autoSlide == true) {
            r.currentState = "play";
            r.interval = setTimeout(function () {
                e.skdslider.playSlide(s, o, r)
            }, r.delay)
        }
        if (r.pauseOnHover == true) {
            o.hover(function () {
                if (r.autoSlide == true) {
                    r.currentState = "pause";
                    clearTimeout(r.interval)
                }
            }, function () {
                if (r.autoSlide == true) {
                    r.currentState = "play";
                    if (r.autoSlide == true) e.skdslider.playSlide(s, o, r)
                }
            })
        }
    };
    e.skdslider.createNav = function (t, n, r) {
        var s = '
';
        for (i = 0; i < n.length; i++) {
            var o = "";
            if (r.numericNav == true) o = i + 1;
            if (i == 0) s += '
' + o + "
";
            else s += '
' + o + "
"
        }
        s += "
";
        if (r.showNav == true) {
            t.append(s);
            var u = t.find(".slide-navs")[0].offsetWidth;
            u = parseInt(u / 2);
            u = -1 * u;
            t.find(".slide-navs").css("margin-left", u);
            t.find(".slide-navs li").click(function () {
                index = t.find(".slide-navs li").index(this);
                targetSlide = index;
                clearTimeout(r.interval);
                r.currentState = "play";
                r.running = false;
                e.skdslider.playSlide(t, n, r, targetSlide);
                return false
            })
        }
        if (r.showNextPrev == true) {
            var a = '';
            a += '';
            t.append(a);
            t.find("a.prev").click(function () {
                e.skdslider.prev(t, n, r)
            });
            t.find("a.next").click(function () {
                e.skdslider.next(t, n, r)
            })
        }
        if (r.showPlayButton == true) {
            var f = r.currentState == "play" || r.autoSlide == true ? '' : '';
            t.append(f);
            t.hover(function () {
                t.find("a.play-control").css("display", "block")
            }, function () {
                t.find("a.play-control").css("display", "none")
            });
            t.find("a.play-control").click(function () {
                if (r.autoSlide == true) {
                    clearTimeout(r.interval);
                    r.autoSlide = false;
                    r.currentState = "pause";
                    e(this).addClass("play");
                    e(this).removeClass("pause")
                } else {
                    r.currentState = "play";
                    r.autoSlide = true;
                    e(this).addClass("pause");
                    e(this).removeClass("play");
                    if (r.currentSlide + 1 == n.length) targetSlide = 0;
                    else targetSlide = r.currentSlide + 1;
                    clearTimeout(r.interval);
                    e.skdslider.playSlide(t, n, r, targetSlide)
                }
                return false
            })
        }
    };
    e.skdslider.next = function (t, n, r) {
        if (r.currentSlide + 1 == n.length) targetSlide = 0;
        else targetSlide = r.currentSlide + 1;
        clearTimeout(r.interval);
        r.currentState = "play";
        e.skdslider.playSlide(t, n, r, targetSlide);
        return false
    };
    e.skdslider.prev = function (t, n, r) {
        if (r.currentSlide == 0) targetSlide = n.length - 1;
        else targetSlide = r.currentSlide - 1;
        clearTimeout(r.interval);
        r.currentState = "play";
        r.running = false;
        e.skdslider.playSlide(t, n, r, targetSlide);
        return true
    };
    e.skdslider.prev = function (t, n, r) {
        if (r.currentSlide == 0) targetSlide = n.length - 1;
        else targetSlide = r.currentSlide - 1;
        clearTimeout(r.interval);
        r.currentState = "play";
        r.running = false;
        e.skdslider.playSlide(t, n, r, targetSlide);
        return true
    };
    e.skdslider.playSlide = function (t, n, r, i) {
        if (r.currentState == "play" && r.running == false) {
            t.find(".slide-navs li").removeClass("current-slide");
            if (typeof i == "undefined") {
                i = r.currentSlide + 1 == n.length ? 0 : r.currentSlide + 1
            }
            if (r.animationType == "fading") {
                r.running = true;
                n.eq(r.currentSlide).fadeOut(r.animationSpeed);
                n.eq(i).fadeIn(r.animationSpeed, function () {
                    e.skdslider.removeIEFilter(e(this)[0]);
                    r.running = false
                })
            }
            if (r.animationType == "sliding") {
                var s = i * t.outerWidth() * -1;
                r.running = true;
                t.find("ul.slides").animate({
                    left: s
                }, r.animationSpeed, function () {
                    r.running = false
                })
            }
            t.find(".slide-navs li").eq(i).addClass("current-slide");
            r.currentSlide = i
        }
        if (r.autoSlide == true && r.currentState == "play") {
            r.interval = setTimeout(function () {
                e.skdslider.playSlide(t, n, r)
            }, r.delay)
        }
    };
    e.skdslider.enableTouch = function (t, n, r) {
        function a(e) {
            i = e.touches[0].pageX;
            s = e.touches[0].pageY;
            t[0].addEventListener("touchmove", f, false);
            t[0].addEventListener("touchend", l, false)
        }
        function f(e) {
            e.preventDefault();
            var t = e.touches[0].pageX;
            var n = e.touches[0].pageY;
            o = i - t;
            u = s - n
        }
        function l(i) {
            t[0].removeEventListener("touchmove", f, false);
            if (o > 0) {
                e.skdslider.next(t, n, r)
            } else {
                e.skdslider.prev(t, n, r)
            }
            t[0].removeEventListener("touchend", l, false)
        }
        t[0].addEventListener("touchstart", a, false);
        var i;
        var s;
        var o;
        var u
    };
    e.skdslider.removeIEFilter = function (e) {
        if (e.style.removeAttribute) {
            e.style.removeAttribute("filter")
        }
    };
    e.fn.skdslider = function (t) {
        return this.each(function () {
            new e.skdslider(this, t)
        })
    }
})(jQuery)

A: You could try adding a return statement to the top of the resize handler within the plug-in code which will prevent it executing the code below:
    e(window).resize(function () {

        // don't do anything on window resize
        return;

        var e = s.outerWidth() * o.size();
        s.find("ul.slides").css({
            position: "absolute",
            left: "0",
            width: e
        });
        o.css({
            width: s.outerWidth(),
            height: s.outerHeight()
        })
    })


text:
Q: Need to change the list items so they dont go directly down the page? HTML is below

Home

Franchises

elroyz Xpress

skye stickbeetles

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Juddamania

Fixtures

Round 1

Round 2

Round 3

Round 4

Round 5

Round 6

Round 7

Round 8

Round 9

Round 10

Round 14

Round 15

Round 16

Round 17

Round 18

Round 19

Round 20

Round 21

Round 22

Round 23

Free Agents

Adelaide

Brisbane

Carlton

Collingwood

Essendon

Fremantle

Geelong

Gold Coast

GWS

Hawthorn

Melbourne

North Melbourne

Port Adelaide

Richmond

St Kilda

Sydney

West Coast

Western Bulldogs

CSS is below
#wrap {
    width:100%;
    height: 28px;
    margin: 0;
    z-index:99;
    background-color:#F00;
    text-align:left;}

.navbar {

    padding:0;
    height: 25px;
    margin: 0 auto;
    width: 400px;
    border-right: 1px solid #1c1c1c;
    border-left: 1px solid #1c1c1c;
}

    .navbar li  {
            width: 100px;
            float: left;
            text-align: center;
            list-style: none;
            font: normal bold 11px Arial, Verdana, Helvetica;
            padding: 0;
            margin: 0;
            background-color: #F00
                        }

.navbar a   {
        padding: 7px 0;
        border-left: 1px solid #1c1c1c;
        border-right: 1px solid #1c1c1c;
        text-decoration: none;
        color: white;
        display: block;

        }

 .navbar li:hover, a:hover {
     background-color: #900;
 }

.navbar li ul   {
        display: none;
        height: auto;
        margin: 0;
        padding: 0;
        }

.navbar li:hover ul     {
                        display: block;
                        }

.navbar li ul li {background-color: #a4a4a4;
}

.navbar li ul li a  {
        border-left: 1px solid #1c1c1c;
        border-right: 1px solid #1c1c1c;
        border-top: 1px solid #1c1c1c;
        border-bottom: 1px solid #1c1c1c;
        }

.navbar li ul li a:hover    {background-color: #1c1c1c;
}

The problem i am having is that the list items go too far down the page when hovered over the item. is there a way i can divide them into 2 or 3 rows so they go side by side ? only new to html and css and cant work it out myself. Thanks in advance

A: Please put your code in jsFiddle or something so it's clear what you're trying to do. Based on your code it looks like you've made a CSS dropdown menu but you have too much stuff in it.
Technically CSS3 supports multi-column layouts. Practically speaking it's not widely supported yet so you should probably avoid it. There are a couple of things you can do:

*

*Make the inner
s display inline: Not pretty but very easy. If you then put a width on the inner
 they will pop up in a box and look a little disorganized but usable.

*Switch to a smart <select>: Select2 is great for this. Add  "GO" button and the whole thing will take up less space without being hard to use. This will require javascript, but just one line on your part.
You could also manually split the list into several separate sublists and array them using floated divs, but that's finicky and more trouble than it's worth. You could also read this ("How to Build a Kick-Butt CSS3 Mega Drop-Down Menu"), but again, I think that's more than you need or want.

A: Adding a width to the submenu will give the list items more horizontal space to use.
.navbar li ul {
    display: none;
    height: auto;
    margin: 0;
    padding: 0;
    width:200px; /* for example */
}

The browser will naturally lay out the list items across the container, so knowing how wide the container is you could re-order the list items to correctly display the columns you want.
Edit: It's a bit very hacky, but if the widths and number of list items in the submenus are known and are fixed (or at least don't change much) you could use CSS positioning to create pseudo columns, for example in this demo

A: a good starting point is to adjust the width of the ul tags
add to the bottom of your css
ul{width:200px;}

check out this working example http://jsfiddle.net/Sj6Am/1
you can experiment from there..


text:
Q: PHP How can i include a var in my mail message? Good Day,
I have a form that saves Name, Email, Subject, Tel Number, Message, and a checkbox.
I m sadly not so good in php at all. Im just started to learn the basics. Thats why i need a little help from you :)
The Form
<form class="contact-form" id="contact" role="form">

                 Your Message has been send.

                 Error

                    <input class="form-control input-box" id="cf-name" type="text" name="cf-name" placeholder="Name*" required>

                    <input class="form-control input-box" id="cf-email" type="email" name="cf-email" placeholder="E-Mail*" required>

                    <input class="form-control input-box" id="cf-subject" type="text" name="cf-subject" placeholder="Subject*" required>

                    <input class="form-control input-box" id="cf-number" type="tel" name="cf-number" placeholder="Number">

                    <textarea class="form-control textarea-box" id="cf-message" rows="7" name="cf-message" placeholder="Message*" required></textarea>

                    <input type="checkbox" class="form-check-input" id="Checkdata" required>
                     yes to this*

*required

                <button class="btn standard-button" type="submit" id="cf-submit" name="submit" data-style="expand-left">Send</button>
            </form>

Now i need this information: Name, Subject, Email, Number and if the checkbox was checked. I would like to include the Number and the checkbox info in the message, that will send as a email to me, because the Name, Subject and Email info will go in the email header.
I figured out how i could save all to the header, but im not really sure about how to include something in the message. Do i have to sent a HTML email for that? or can i do it without html?
There goes my php code
        <?php

if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['subject']) && isset($_POST['number']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {

  $test = "/(content-type|bcc:|cc:|to:)/i";
  foreach ( $_POST as $key => $val ) {
    if ( preg_match( $test, $val ) ) {
      exit;
    }
  }

$headers = 'From: ' . $_POST["name"] . '<' . $_POST["email"] . '>' . "\r\n" .
    'Reply-To: ' . $_POST["email"] . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

  mail( "hey@example.net", $_POST['subject'], $_POST['message'], $headers );

}
?>

Thank you all for your help.

A: Your question is not clear but assuming you want to append more text to the message?
You can do something like this:
$more_message = $_POST['name']. "hello, this is more \n";

  mail( "hey@example.net", $_POST['subject'], $more_message.$_POST['message'], $headers );

Update based on comment below on additional requirements:
$header_1 = $_POST['subject'] ."\n" .$_POST['name'] ."\n";
$more_message = $_POST['message']. "\n". $_POST['number'] ."\n". $_POST['Checkdata'];

something like this...


text:
Q: Unable to access all ItemResponses in a FormResponse I have a strange error occurring in an Apps Script function attached to a Google Form.
I call the responses, then list them in an array. The log shows that there are 6 items in the array, which matches the six form questions:
[18-05-08 00:13:31:900 AEST] [ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse]

When I call the first two, it works just fine. Any more and it bugs out and says undefined.
// Open a form by ID and log the responses to each question.
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
  var formResponse = formResponses[i];
  var editUrl = String(formResponse.getEditResponseUrl());
  var theResponseId = formResponses.indexOf(form);
  var itemResponses = formResponse.getItemResponses();
  var timestamp = formResponse.getTimestamp();
  var firstName = itemResponses[0].getResponse();
  var lastName = itemResponses[1].getResponse();
  Logger.log(itemResponses); // Log shows there are 6 objects in the array. Matching the amount of Form Questions.

  // If I try to use these variables below, it doesn't work and the script 'breaks' at this point.

  //var number = itemResponses[2].getResponse();
  //var email = itemResponses[3].getResponse();
  //var firstName2 = itemResponses[4].getResponse();
  //var comments = itemResponses[5].getResponse();
}

Note: I have tried FormApp.openById('id'); to see if maybe getting the active form was a problem. This didn't help.

A: This is because some answers were submitted to a 2 question form. If you submitted some responses prior to updating the form, the answers to these new questions will be "undefined".


text:
Q: clustering over sphere surface I have two algorithms, both of which create points on the surface of a higher dimensional sphere (say in $\mathbb{R}^n$). Now, I want to check, which algorithm gives a more uniform spread of points over the surface of the sphere. In lower dimensional cases like $\mathbb{R}^2$ and $\mathbb{R}^3$ both perform well but I want to check in higher dimension, say $n \geq 50$. I believe, some kind of clustering algorithm may help but I don't know which one to use in this situation (since the points are on surface and not inside). Is there a way to solve this problem ?
I can generate as many points as required for both the algorithms, if that helps.

A: Your question doesn't have many specifics, so my assumption is that you need a way to check how uniform a distribution of points over a sphere is, so as to compare your two algos.
Here are two simple suggestions:

*

*Empirically estimate the entropy or uniformity. Essentially, divide the sphere into segments (e.g. in spherical coordinates, but be careful) and count the number of points that fall into each segment. You could then measure the entropy of the histogram (i.e. if $n_i$ points fall into area $i$, and $N$ points were sampled in total, then $p_i = n_i/N$ and the entropy is $\mathbb{H}=-\sum_ip_i\log p_i$. Higher entropy means more uniformity. You could also compute the variance in the set of observed probability values to estimate uniformity, i.e. $\mu_p = \frac{1}{N}\sum_ip_i$, then $V = \frac{1}{N-1}\sum_j (p_j - \mu_p)^2$.

*Fit a von Mises distribution to the data, and simply check the concentration parameter $\kappa$. As $\kappa\rightarrow 0$, the distribution approaches the uniform one. (See the link for how to do parameter estimation).


text:
Q: Run multiple threads in sequence using locks I am trying to run 4 threads in sequence like 4 -> 3 -> 2 -> 1.
And I am using int threadId and AtomicInteger to validate if the current thread is eligible to run or not.
But the 4th thread starts and the execution gets stuck, I am not getting why the thread 3, 2 and 1 are not getting a chance to run.
Here is what I did:
public class SequenceDemo implements Runnable{

    int threadId;
    static AtomicInteger currentThread = new AtomicInteger(4);
    ReentrantLock lock;
    Condition condition;

    public SequenceDemo( ReentrantLock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        try {
            lock.lock();
            threadId = Integer.parseInt(Thread.currentThread().getName());
            while(currentThread.get()!=threadId) {
                condition.await();
            }

            System.out.println("Thread "+Thread.currentThread().getName()+" started executing");
            Thread.sleep(1000);
            System.out.println("Thread "+Thread.currentThread().getName()+" finished executing");

            currentThread.decrementAndGet();
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        SequenceDemo demo1 = new SequenceDemo(lock, condition);

        Thread t1 = new Thread(demo1, "1");
        Thread t2 = new Thread(demo1, "2");
        Thread t3 = new Thread(demo1, "3");
        Thread t4 = new Thread(demo1, "4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}

output: Execution gets stuck after execution of thread 4:
Thread 4 started executing
Thread 4 finished executing

A: Your code is fine, you should just pass a new SequenceDemo instance to each thread, otherwise they share the threadId and it's just stuck on the value 4 for all threads. (Took me a few minutes to see haha)


text:
Q: Sending emails not working after updating to Codeigniter 3 I bought a php script a while back when php5 and codeigniter 1.0 were the thing. Now I come back to the script and had to upgrade to Codeigniter 3, now sending emails to my clients does not work. I looked at the code and can't figure out how the Send_mail.php gets the data from the Ajax.php controller. I would appreciate it if you guys could take a look at it. I know it looks like a bulky code, I will try to strip all the unnecessary junk.
The layout is as follows:
  View           Controller      Controller

v_sendmail.php  __ Controller1 _____ Controller2
Controller1
Opens the socket connection and sends header info to controller2 to initiate the emailing process.
This is the content to be to be sent to controller2:
POST ssl://mywebsite.com/index.php/controller2/sendMailnow
HTTP/1.0 Host:www.mywebsite.com Content-Type: multipart/form-data;
boundary=AaB03x Content-length: 653 --AaB03x Content-Disposition: form-data;
name="user_id" 2 --AaB03x*

Controller 2
    Starts the emailing process to send emails

The issue I see is that Controller2 never gets initialized. If I type the whole URL (https://www.mywebsite.com/index.php/controller2/sendMailnow) I see some action in the server logs but nothing from controller to controller

A: Well it turns out my CI3 setup does not want to get the array data like:
 $data['user_id'] = $this->input->post('user_id');
 $data['user_name'] = $this->input->post('user_name');

Instead I had to get the data this way:
 $userid = $this->input->post('user_id');
 $username = $this->input->post('user_name');

Now, Controller2 is able to set all the necessary stuff and send emails to all my customers without having to open the controller through the browser.


text:
Q: Is there a tutorial for Facebooker (Rails API for Facebook) There once was a Facebooker tutorial which was a facebook app but for the last few weeks I'm greeted with just a blank page when I go to it. Does anyone know of any good resources for getting started with the Facebooker plugin for Rails?
I was kind of surprised at how difficult it is to find this... any help would be greatly appreciated thanks!

A: There are several resources for FBML canvas apps including http://www.pragprog.com/titles/mmfacer and the related screencasts. These are out of date, but give you at least a good overview. You can also ask questions on the Facebooker google group.
(Note: I'm a little biased as I'm the author of the link book and the maintainer of Facebooker)


text:
Q: Android uber ping request animation or component Can any one suggest me how to do circle animation and progress button like Uber driver pickup request in Android. If you can provide some code that will be good.

A: You can refer to this.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import com.circularseekbar.R;

public class CircularProgressBar extends View {

private Context mContext;
private Paint circleColor, innerColor, circleRing;
private int angle = 0, startAngle = 270, barWidth = 50, maxProgress = 100;

private int width, height, progress=1, tmpProgress=1, progressPercent;
private float innerRadius, outerRadius, adjustmentFactor=100;//The radius of the inner circle

private float cx, cy; //The circle's center X, Y coordinate

private float left, right, top, bottom, startPointX, startPointY, markPointX, markPointY;
private float dx, dy;//The X and Y coordinate for the top left corner of the marking drawable
private Bitmap progressMark, progressMarkPressed;

private RectF rect = new RectF();
{

    circleColor = new Paint();
    innerColor = new Paint();
    circleRing = new Paint();

    circleColor.setColor(Color.parseColor("#ff33b5e5")); // Set default
    // progress
    // color to holo
    // blue.
    innerColor.setColor(Color.BLACK); // Set default background color to
    // black
    circleRing.setColor(Color.GRAY);// Set default background color to Gray

    circleColor.setAntiAlias(true);
    innerColor.setAntiAlias(true);
    circleRing.setAntiAlias(true);

    circleColor.setStrokeWidth(25);
    innerColor.setStrokeWidth(15);
    circleRing.setStrokeWidth(10);

    circleColor.setStyle(Paint.Style.FILL);
}

public CircularProgressBar(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mContext = context;
}

public CircularProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
}

public CircularProgressBar(Context context) {
    super(context);
    mContext = context;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    width = getWidth(); // Get View Width
    height = getHeight();// Get View Height

    int size = (width > height) ? height : width; // Choose the smaller
    // between width and
    // height to make a
    // square

    cx = width / 2; // Center X for circle
    cy = height / 2; // Center Y for circle
    outerRadius = size / 2; // Radius of the outer circle

    innerRadius = outerRadius - barWidth; // Radius of the inner circle

    left = cx - outerRadius; // Calculate left bound of our rect
    right = cx + outerRadius;// Calculate right bound of our rect
    top = cy - outerRadius;// Calculate top bound of our rect
    bottom = cy + outerRadius;// Calculate bottom bound of our rect

    startPointX = cx; // 12 O'clock X coordinate
    startPointY = cy - outerRadius;// 12 O'clock Y coordinate
    markPointX = startPointX;// Initial locatino of the marker X coordinate
    markPointY = startPointY;// Initial locatino of the marker Y coordinate

    rect.set(left, top, right, bottom); // assign size to rect
}

@Override
public void onDraw(Canvas canvas) {
    canvas.drawCircle(cx, cy, outerRadius, circleRing);
    canvas.drawArc(rect, startAngle, angle, true, circleColor);
    canvas.drawCircle(cx, cy, innerRadius, innerColor);
    super.onDraw(canvas);
}

public int getAngle() {
    return angle;
}

public void setAngle(int angle) {
    //System.out.println("Angel "+angle);
    this.angle = angle;
    float donePercent = (((float) this.angle) / 360) * 100;
    float progress = (donePercent / 100) * getMaxProgress();
    setProgressPercent(Math.round(donePercent));
    setProgress(Math.round(progress));
}

public int getBarWidth() {
    return barWidth;
}

public void setBarWidth(int barWidth) {
    this.barWidth = barWidth;
}

public int getMaxProgress() {
    return maxProgress;
}

public void setMaxProgress(int maxProgress) {
    this.maxProgress = maxProgress;
}

public int getProgress() {
    return progress;
}

public void setProgress(int progress) {
    if (this.progress != progress) {
        this.progress = progress;
        int newPercent = (this.progress * 100) / this.maxProgress;
        int newAngle = (newPercent * 360) / 100;
        this.setAngle(newAngle);
        this.setProgressPercent(newPercent);
    }
}

long mAnimStartTime;

Handler mHandler = new Handler();
Runnable mTick = new Runnable() {
    public void run() {
        invalidate();
        update();
        mHandler.postDelayed(this, 100); // 20ms == 60fps
    }
};

public void update(){
    if(IS_ACTIVE){
        setProgress(tmpProgress);
        if(tmpProgress>maxProgress){
            stopAnimation();
        }
        tmpProgress++;
    }
}

boolean IS_ACTIVE=false;
public void startAnimation() {
    IS_ACTIVE=true;
    tmpProgress=1;
    mHandler.removeCallbacks(mTick);
    mHandler.post(mTick);
}

public void stopAnimation() {
    IS_ACTIVE=false;
    progress=1;
    mHandler.removeCallbacks(mTick);
}

public int getProgressPercent() {
    return progressPercent;
}

public void setProgressPercent(int progressPercent) {
    this.progressPercent = progressPercent;
}

public void setRingBackgroundColor(int color) {
    circleRing.setColor(color);
}

public void setBackGroundColor(int color) {
    innerColor.setColor(color);
}

public void setProgressColor(int color) {
    circleColor.setColor(color);
}

public float getAdjustmentFactor() {
    return adjustmentFactor;
}

public void setAdjustmentFactor(float adjustmentFactor) {
    this.adjustmentFactor = adjustmentFactor;
}
}


text:
Q: Why is my report not showing the fields I place down? I am currently using iReport to edit and customize another report that has been previously built by someone else. The only thing I am trying to do is add a Static Text Label and a Text Field.
The text label should say "Email"
The text field should hold the variable "SHIPTOEMAIL"
The goal is to have the report include the email variable and display it when compiled.
Now, the report currently already has a Static Text Label named "Notes" and a Text Field that holds the variable "MEMO". These currently work just fine. My problem is that when ever I add a text label and text field (the email one) when ever I compile and run my report (without errors) the fields do not show up- though they're placed on the report.

My only guess, because I am very new to SQL, is that this persons SQL is what is making his fields work. Here is the code of the current SQL for the report. I have not altered a thing but maybe i need to in order for my fields to work?
SELECT so.id AS soid, ship.id AS shipid, so.locationgroupid AS locationgroupid, ship.statusid AS shipstatus,
ship.note AS memo, so.customerpo AS socustomerpo, ship.dateshipped AS shipdate,
COALESCE(so.shiptoname,'') AS shiptoname, so.shiptoaddress AS shiptoaddress, so.shiptocity AS shiptocity,
shipState.code AS shiptostate, so.shiptozip AS shiptozip, so.customercontact AS shiptocontact,
COALESCE(so.billtoname,'') AS billtoname, so.billtoaddress AS billtoaddress, so.billtocity AS billtocity,
billState.code AS billtostate, so.billtozip AS billtozip, COALESCE(ship.cartoncount,0) AS cartoncount,
so.datefirstship AS regshipdate, fobpoint.name AS fobpoint, shipterms.name AS ShippingTerms, ship.num AS shipnum,
carrier.name AS carriername, so.num AS sonum, shipcountry.name AS shipcountry, billcountry.name AS billcountry,
(SELECT s1.sysvalue
    FROM sysproperties s1
    WHERE s1.syskey = 'Barcodes have DI'
) AS barcodeshavedi,
company.name AS company,
contact.datus as customerphone,
paymentterms.name as paymentterms,
memo.memo as memo1,shiptophone.datus as shiptophone, shiptoemail.datus as      shiptoemail, customer.number as accountNum, billtoemail.datus as billtoemail,     upsservices.description AS shipservice

FROM ship
    INNER JOIN carrier ON ship.carrierid = carrier.id
    INNER JOIN so ON ship.soid = so.id
inner join customer on so.customerid = customer.id
INNER JOIN fobpoint ON so.fobpointid = fobpoint.id
INNER JOIN shipterms ON so.shiptermsid = shipterms.id
LEFT OUTER JOIN stateconst shipState ON so.shiptostateid = shipState.id
LEFT OUTER JOIN stateconst billState ON so.billtostateid = billState.id
LEFT OUTER JOIN countryconst shipCountry ON so.shiptocountryid = shipCountry.id
LEFT OUTER JOIN countryconst billCountry ON so.billtocountryid = billCountry.id
JOIN company ON company.id = 1
left join address on address.accountid = customer.accountid and address.typeid = 50 and address.defaultflag = 1
left join contact on contact.addressid = address.id and contact.typeid = 50 and contact.defaultflag = 1
left join paymentterms on paymentterms.id = so.paymenttermsid
left join memo on company.id = memo.recordid and memo.tableid = -776196226
left join address shippingaddress on shippingaddress.accountid = customer.accountid and shippingaddress.typeid = 10 and shippingaddress.defaultflag = 1
left join contact shiptoemail on shippingaddress.id = shiptoemail.addressid  and customer.accountid = shiptoemail.accountid and shiptoemail.typeid = 60 and shiptoemail.defaultflag = 1
left join contact shiptoPhone on shippingaddress.id = shiptoPhone.addressid  and customer.accountid = shiptoPhone.accountid and shiptoPhone.typeid = 50 and shiptoPhone.defaultflag = 1
left join contact billtoemail on billtoemail.addressid = address.id and billtoemail.accountid = customer.accountid and billtoemail.typeid = 60 and billtoemail.defaultflag = 1
LEFT OUTER JOIN upsservices ON so.upsserviceid = upsservices.id
WHERE ship.id = '7'AND ship.ordertypeid = 20

A: First execute this query in any other console and see if it return all the values you want in the report.
If not, correct the query
If yes, use a blank normal report with all the fields that the query returns and see if it is your report design problem.


text:
Q: Entering data directly via table view swift 4 I'm having a play about with table views and saving data. I've managed to created an add button where you can add some data to a table view (like a to do list app) and it saves in user defaults. However, I can't seem to figure out how to add and save data directly just by pressing an empty row in the table view. Basically, I would like to know how to add data and display data on a table view just like the stock To Do and Reminders app from Apple.
I'm working with Swift 4.
Any help or code examples would be much appreciated!


text:
Q: My crontab run sequently less than 1 minute I use crontab to run Laravel schedule, this is my cron entry:
* * * * * php /var/www/mailserver/artisan schedule:run >> /dev/null 2>&1

In App/Console/Kernel.php I just write log file:
Log::info('Schedule excuted');

But in my log file, it seems run sequently in 3 seconds instead of 1 minute

Please help me, how to run cronjob slow down?

A: The cron statement you provide is telling it to run constantly. Chances are there is just a delay of 3 seconds between the log being called. If you read the scheduling docs you would see that to run every minute you need to do the following:
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        Log::info('Schedule excuted');
    })->everyMinute();
}

Source: Scheduling Docs


text:
Q: "ValueError: No Shapely geometry can be created from null value" from Shapely's ops.shared_paths I get this error:
ValueError: No Shapely geometry can be created from null value

on some occassions where I am trying to find the common or shared paths between two linestrings. I am using the ops.shared_paths method.
Suppose I have the following linestrings with their geometries:
geom1 = LINESTRING (-79.38545 43.65393, -79.38578 43.65472, -79.38578 43.65472, -79.38596 43.65515, -79.38596 43.65515, -79.38601 43.65525, -79.38601 43.65525, -79.38551 43.65535, -79.38551 43.65535, -79.38417 43.65564, -79.38417 43.65564, -79.38283 43.65593, -79.38283 43.65593, -79.38163 43.65618, -79.38163 43.65618, -79.38105 43.65631, -79.38105 43.65631, -79.38056 43.65641, -79.38056 43.65641, -79.38024 43.65645, -79.38024 43.65645, -79.37979 43.65635, -79.37979 43.65635, -79.3803 43.65645, -79.3803 43.65645, -79.38073 43.65638)
geom2 = LINESTRING (-79.38621 43.65786, -79.38634 43.65812, -79.38634 43.65812, -79.38634 43.65812, -79.38634 43.65812, -79.38586 43.65705, -79.38586 43.65705, -79.38562 43.65648, -79.38562 43.65648, -79.3852 43.65542, -79.3852 43.65542, -79.38452 43.65557, -79.38452 43.65557, -79.38387 43.6557, -79.38387 43.6557, -79.38373 43.65573, -79.38373 43.65573, -79.38344 43.65502, -79.38344 43.65502, -79.38292 43.65372, -79.38292 43.65372, -79.38245 43.65251, -79.38245 43.65251, -79.38231 43.65215, -79.38231 43.65215, -79.38221 43.65205)

So when I try:
ops.shared_paths(geom1, geom2)

I get this weird output first:
4169999999997 43.655639999999998

And then the ValueError message.
It is expected that it outputs a GeometryCollection object consisting of a "forward" and a "backward" MultiLineStrings. In fact, visualizing these two linestrings, they have a shared path:

where the red linestring is geom1 and the blue linestring is geom2. I'm just not sure why I get the weird error and why it complains. There clearly is a shared path but it doesn't report it and just reports an error instead. For other pairs of linestrings, the behavior is quite unpredictable. Sometimes, it reports it correctly (whether there is a shared path or none). But there are times when it reports an error instead (regardless of whether there was a shared path or none).


text:
Q: ubuntu 14.04 wired connection connects and disconnects I installed Ubuntu 14.04 LTS on a HP Proliant dl380 gen 9 two weeks ago. Ever since I installed, it has been misbehaving by automatically disconnecting during the day and connecting again at night and during week ends (Disconnecting during peak hours). If I unplug and plug the network cable during the day, it tends to connect for some minutes and then disconnects (while showing the connected icon on the network area). The output of the command lspci -knn | grep Eth -A2 returns
02:00.0 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM5719 Gigabit Ethernet PCIe [14e4:1657] (rev 01)
Subsystem: Hewlett-Packard Company Device [103c:22be]
Kernel driver in use: tg3
02:00.1 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM5719 Gigabit Ethernet PCIe [14e4:1657] (rev 01)
Subsystem: Hewlett-Packard Company Device [103c:22be]
Kernel driver in use: tg3
02:00.2 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM5719 Gigabit Ethernet PCIe [14e4:1657] (rev 01)
Subsystem: Hewlett-Packard Company Device [103c:22be]
Kernel driver in use: tg3
02:00.3 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM5719 Gigabit Ethernet PCIe [14e4:1657] (rev 01)
Subsystem: Hewlett-Packard Company Device [103c:22be]
Kernel driver in use: tg3

A: At last was able to find the answer through 14e4:1687 broadcom tg3 network driver disconnects under high load. Disabling highdma with ethtool seems to work around the issue, to make the solution permanent add udev rule in /etc/udev/rules.d/70-persistent-net.rules:
ACTION=="add", SUBSYSTEM=="net", ATTRS{vendor}=="0x14e4", ATTRS{device}=="0x1687", RUN+="/sbin/ethtool -K %k highdma off"


text:
Q: Junit output using the-missing-android-xml-junit-test-runner I am having trouble setting up http://code.google.com/p/the-missing-android-xml-junit-test-runner/ within Jenkins.
I can get the tests to run and pass in eclipse.  When I pull them into jenkins and build via ant I get the following problem:
 [echo] Running tests ...
 [exec] INSTRUMENTATION_RESULT: shortMsg=java.lang.ClassNotFoundException
 [exec] INSTRUMENTATION_RESULT: longMsg=java.lang.ClassNotFoundException: pl.polidea.instrumentation.PolideaInstrumentationTestRunner in loader dalvik.system.PathClassLoader[/system/framework/android.test.runner.jar:/data/app/mj.geo.golf.application.test-1.apk:/data/app/mj.geo.golf.application-1.apk]
 [exec] INSTRUMENTATION_CODE: 0

The manifest looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mj.geo.golf.application.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<instrumentation
    android:name="pl.polidea.instrumentation.PolideaInstrumentationTestRunner"
    android:targetPackage="mj.geo.golf.application"
    android:label="Tests for pl.polidea.somepackage" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <uses-library android:name="android.test.runner" />
</application></manifest>

I have looked around at other related posts and made sure that eclipse exports the the-missing-android-xml-junit-test-runner-release-1.3_2.jar and it appears in the workspace.
I am pretty new to android and java so any thoughts would be useful

A: You should read the Wiki more carefully.

The test runner should be added to the test project. Either as a .jar file (added in libs directory) or as external library (standard android external library approach). You can download the .jar file from here.

So the easiest way is to create a folder named libs just under the root of the project (the same level as src folder) and put the *the-missing-android-xml-junit-test-runner-release-1.3_2.jar* in it and then 'Add it to Build Path'.


text:
Q: Delphi TIdHttp freezes thread I have an application that has multiple forms, each form has a thread that does a GET() on a given url every 3 seconds ... the problem is that every call of GET() the user interface freezes until the GET() be completed, and how are various forms doing the same thing every 3 seconds, the application is very slow, has put a "IdAntiFreeze" on the main form, most did not work, so read the "IdAntiFreeze" does not work in Threads, follows the example below:
  private
    { Private declarations }
    GlobalHtml : String;
    TimerGlobal : Integer;

//Thread
TMyThread= class(TThread)
private
  FForm : TForm1;
  strTemp: String;
protected
  procedure Execute; override;
public
  constructor Create(Form : TForm1; gpLinkTemp : String);
  destructor Destroy; override;
end;

//get string http
procedure TMyThread.GetStringHttp;
var
  meuIdHTTP : TIdHttp;
  strResponse:  String;
begin
  meuIdHTTP := TIdHTTP.Create(nil);
  strResponse := meuIdHTTP.Get('url...'); //<-- freezes up complete
  FForm.GlobalHtml := strResponse; //<-- private form variable
end;

//execute
procedure TMyThread.Execute;
begin
  while not (terminated) do
   begin
      Synchronize(GetStringHttp);
      FForm.LabelStatus.Visible := False;
      FForm.ButtonStatus.Enabled := False;
      FForm.TimerStatus.Enabled := True;
      if FForm.TimerGlobal >= 10 then
       begin
         Synchronize(UpdateGrid);
         FForm.TimerGlobal := 0;
       end;
   end;
end;

//update TStringGrid on form
procedure TForm1.UpdateGrid;
begin
 //I update the TStringGrid here with the data of variable
 TSGridDados.Cells[0,1] := GlobalHtml;
 //...
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
 Inc(TimerGlobal);
end;

Call Thread:
procedure TForm1.Button1Click(Sender: TObject);
begin
  TMyThread.Create(Self, 'string-url');
end;

If the internet is slow or the server takes to respond is even worse,
is there any special configuration in TIdHttp component to avoid this?
Why does it happen? Thanks in advance!

A: Here is an example of using TIDHttp in thread.
You can use multiple thread with TList or TThreadList instead of one thread as provided below.
The main idea is using "thread safe" list for waitinglist and resultlist.
waitinglist used to list every url request while resultlist used to list responses from idhttp.get().
Timer on Form used to pop each item from resultlist for GUI updating purpose.
here is the code:
.dfm:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 396
  ClientWidth = 660
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCloseQuery = FormCloseQuery
  OnCreate = FormCreate
  OnDestroy = FormDestroy
  PixelsPerInch = 96
  TextHeight = 13
  object Splitter1: TSplitter
    Left = 193
    Top = 33
    Height = 363
    ExplicitLeft = 256
    ExplicitTop = 248
    ExplicitHeight = 100
  end
  object TreeView1: TTreeView
    Left = 0
    Top = 33
    Width = 193
    Height = 363
    Align = alLeft
    Indent = 19
    ReadOnly = True
    TabOrder = 0
    OnChange = TreeView1Change
    OnDeletion = TreeView1Deletion
  end
  object Memo1: TMemo
    Left = 196
    Top = 33
    Width = 464
    Height = 363
    Align = alClient
    Lines.Strings = (
      'Memo1')
    ScrollBars = ssBoth
    TabOrder = 1
    WordWrap = False
  end
  object Panel1: TPanel
    Left = 0
    Top = 0
    Width = 660
    Height = 33
    Align = alTop
    BevelOuter = bvNone
    TabOrder = 2
    object Button1: TButton
      Left = 5
      Top = 5
      Width = 75
      Height = 25
      Caption = 'get URL'
      TabOrder = 0
      OnClick = Button1Click
    end
  end
  object IdAntiFreeze1: TIdAntiFreeze
    Left = 56
    Top = 64
  end
  object Timer1: TTimer
    Interval = 33
    OnTimer = Timer1Timer
    Left = 56
    Top = 120
  end
end

.pas:
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdAntiFreezeBase,
  Vcl.IdAntiFreeze, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
  Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls, IdThreadSafe;

type

  TMyUrl = class(TStringlist)
  private
    fUrl:String;
  end;

  TMyThread= class(TThread)
  private
    fWaitingList : TIdThreadSafeObjectList;
    fResultList  : TIdThreadSafeObjectList;
  protected
    procedure Execute; override;
  public
    constructor Create(aWaitingList, aResultList:TIdThreadSafeObjectList);
  end;

  TForm1 = class(TForm)
    IdAntiFreeze1: TIdAntiFreeze;
    TreeView1: TTreeView;
    Memo1: TMemo;
    Splitter1: TSplitter;
    Timer1: TTimer;
    Panel1: TPanel;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure TreeView1Deletion(Sender: TObject; Node: TTreeNode);
    procedure Timer1Timer(Sender: TObject);
    procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    fWaitingList : TIdThreadSafeObjectList;
    fResultList  : TIdThreadSafeObjectList;
    fThread      : TmyThread;  //... You can change this to Multiple Threads instead
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{TMyThread}
constructor TMyThread.Create(aWaitingList, aResultList:TIdThreadSafeObjectList);
begin
  inherited Create;
  fWaitingList:=aWaitingList;
  fResultList:=aResultList;
end;

procedure TMyThread.Execute;
var
  Url:TMyUrl;
  http:TIdHttp;
begin
  while not Terminated do begin
    url:=fWaitingList.Pop;
    if assigned(url) then begin
      http:=TIdHTTP.Create(nil);
      try
        try
          url.Text:=http.Get(Url.fUrl);
        except
          on E:exception do
            Url.Text:=E.Message;
        end;
      finally
        http.Free;
        fResultList.Add(Url);
      end;
    end else
      sleep(100);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyUrl:TMyUrl;
  url:String;
begin
  url:='http://';
  if InputQuery('Add Url','Set Url',url) then begin
    url:=trim(url);
    if (sametext(copy(url,1,7),'http://')) and (length(url)>7) then begin
       MyUrl:=TMyUrl.Create;
       MyUrl.fUrl:=url;
       fWaitingList.Add(MyUrl);
    end;
  end;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  fThread.Terminate;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  fWaitingList:=TIdThreadSafeObjectList.Create;
  fResultList:=TIdThreadSafeObjectList.Create;
  fWaitingList.OwnsObjects:=true;
  fResultList.OwnsObjects:=true;
  fThread:=TMyThread.Create(fWaitingList, fResultList);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FreeAndNil(fWaitingList);
  FreeAndNil(fResultList);
  FreeAndNil(fThread);
end;

//.... For updating GUI every 33 miliseconds
procedure TForm1.Timer1Timer(Sender: TObject);
var
  url:TMyUrl;
begin
  url:=fResultList.Pop;
  if assigned(url) then begin
    with TreeView1.Items.AddChild(nil,url.fUrl) do
      data:=url;
  end;
end;

procedure TForm1.TreeView1Change(Sender: TObject; Node: TTreeNode);
begin
  if TreeView1.Selected<>nil then
    Memo1.Text:=TMyUrl(TreeView1.Selected.Data).Text;
end;

procedure TForm1.TreeView1Deletion(Sender: TObject; Node: TTreeNode);
begin
  TObject(Node.Data).Free;
  Node.Data:=nil;
end;

end.

Hope this small example could give some inspirations for your works.


text:
Q: How to create one FusionAuth application with many oauth clients with scopes I want to have a main application where all users are registered and create many oauth clients with limited scopes to access user data.
I tried to solve this with applications, but it seems that them don't know about each other.
Is this possible with fusion auth? If so, how can I implement that.

A: This feature is not available yet.
Github Issue

A: You can create as many applications as you want. User grants of custom OAuth scopes are not fully implemented, as mentioned in that GitHub issue.
You could work around that by creating an application for each type of access, or by using roles within an application. If you had a blog, for example, you could create an admin role, an editor role, a contributor role, and a subscriber role. You could use a lambda to assign the roles to the JWT ( see example here: https://fusionauth.io/community/forum/topic/281/implementing-a-role-based-access-system-for-authorization/2 ).
Then your application could examine roles in the JWT and provide appropriate access.
Hope that helps. Feel free to respond here or in the forum if you'd like to discuss further.