counting number of surjections when order matters with in each subset

Question: Question: On a ship, signals are transmitted by putting flags on flagpoles (the order of the flags on each pole is important). There are 10 different flags and 3 different flagpoles. All of the flags are used. Each flagpole must have at least one flag. How many orderings are there?
Comment: Are the flag-poles ordered as well? That means if I exchange the flags between leftmost and rightmost pole, will it be a different signal?
Comment: No, the order of the poles do not matter
Answer: Let's first calculate the number of ways to do this problem when the order of the poles matters.
In this case, we order the 3 poles in some way, and thus each signal corresponds to one permutation of the 10 flags: First the first flag from the first pole, then the second flag from the first pole, until the last flag from the first pole, then the first flag from the second pole a.s.o.
However, each permutation of the 10 flags corresponds to multiple signals, because to get back the signal from the permutation one needs to decide after which flag  the first and second pole end. Since each pole cannot be empty, the last flag of each pole is well defined, and the second pole cannot end after the 10th flag. So we have $9 \choose 2$ ways to choose the unorderd pair of ending flags for the first and second pole from the 1st to 9th flag.
That means, if pole order matters, there are exactly ${9 \choose 2}10!$ possible signals.
But since all flags (and thus the flags on each pole) are different, finding the number of signals when pole order doesn't matter means just deviding the above number by $3!=6$.
That means the answer to the stated problem is that ${{9 \choose 2}10! \over 3!} = 19353600$ different signals exist.
Answer: First, answer the question without the "all flagpoles must be used" restriction. Edit: I will also first assume that the order of the poles does matter.
Imagine placing the flags one at a time.

There are $3$ places you can put the first flag, on any pole.
There are then $4$ places you can put the second flag: either you can put it on top of any of the three poles, or just below the first flag.
There are then $5$ places you can put the third flag.
$\vdots$

In general, there are  $3+i-1$ places you can put the $i^{th}$ flag; either on top of any of the three poles, or just below any of the $i-1$ previous flags. Therefore, the number of ways to place the flags is
$$
3\cdot 4\cdot 5\cdots \cdot 12.
$$
What if all flagpoles must be used (and the order of the poles still matters)? There are two ways to reduce this to the previous case:

Choose the flags on the bottom of the poles first, then place the remaining $7$ flags without restriction.
Use principle of inclusion exclusion, taking all arrangements, and subtracting the bad ones where some flagpole is empty, then adding back in the doubly subtracted arrangements, etc.

Edit: I leave the details of carrying out either of the last two bullets to you. Finally, since we want the order of the poles to not matter, we must divide by $6!$.


Does caching has to be manually disabled for ajaxified forms?

Question: I switched on caching on my dev environment and it looks like ajaxified forms won't work* unless I specifically set max-age to them to 0. Is this normal? Or is this the case only when a form is displayed via lazy builder?
*they will work but submitting them will result in normal behavior where the form is submitted and the page is reloaded.
Comment: If this is normal why can't Drupal do this automatically by detecting presence of #ajax configuration in the form array and setting max-age=0 on its own?
Comment: IIRC, there is an issue about this.  Wim and/or Tim would know if you can catch them in IRC.
Answer: Not sure what you mean by "ajaxified". That sounds like a regular form is automatically "ajaxified".
Potentially this form is violating the principle that GET forms should not manipulate state. i.e. GET forms must be stateless. HTTP dictates this, but in Drupal 7 it was not respected. In Drupal 8 it is.
See https://www.drupal.org/node/2502785.
Answer: My issue was caused by the page_cache module. It caches everything and I had wrong impression of how page_cache and dynamic_page_cache are working. I have disabled the page_cache module because I have some dynamic code that varies by the visitor so I cannot cache everything for anonymous users.
Comment: You really want to avoid disabling page cache. If you have specific pages that can't be cache, that's fine, there's an API to disable it there: "\Drupal::service('page_cache_kill_switch')->trigger();"
Comment: @Berdir I have a block(visible on all pages) and a form(rendered as computed fields on an entity and that entity can be displayed in various pages, not just on its own page) that varies by visitor(not user! and the identification is done via cookie). And so since lazy builders will get cached via page_cache as well there is no other way for me that I see at this point.
Comment: @Berdir I have enabled page_cache and I have altered the DefaultRequestPolicy so it won't get involved if additional conditions are met. Unfortunately the forms wont use ajax submit, they will get submitted as normal forms. Also this happens with dynamic_page_cache as well. My forms are displayed as entity field and use lazy builder/post cache render method.
Comment: It looks like this issue occurres only on entity page, not when i am listing multiple entities on a single page(also via lazy builder)


Divide timespan in JavaScript

Question: I have to recreate some logic from Kusto query language in JS and I'm struggling with duration division. How can I get quotient from two durations, like this :
One can divide two timespan values to get their quotient. For example, 1d / 5h gives 4.8. This gives one the ability to express any timespan value as a multiple of another timespan value. For example, to express an hour in seconds, simply divide 1h by 1s: 1h / 1s (with the obvious result, 3600).
(taken from https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/datetime-timespan-arithmetic)
I'm using date-fns, but I'm flexible  with libraries.
Answer: You can simply define constants. For example, if the smallest unit you are going to use is 1 seconds, then you can put:
const
  S = 1,
  M = 60,
  H = M * 60,
  D = H * 24,
  W = D * 7;

Now terms like 1s cannot magically become a valid syntax in JavaScript, but expressions like (2 * D) / (10 * H) can work just fine.
(edited the answer to use uppercase for constants as it's a common convention)

Divide timespan in JavaScript


c++ templates to build list of unknown class instances

Question: I have a situation that I am attempting to write some c++ code to implement and I think I need to use templates but I am unsure.  I don't think I understand templates well enough and just want to know if I am on the right track.  I have never implemented a class that requires templates before.
I have a base class that needs to instantiate a new class and store it on a list for future access.  The class that needs to be instantiated is derived from a base class that has one virtual method.  After the class is instantiated, this method is called and the new instance is stored on a list.  Another method is provided to get the instantiated object.
Say the virtual class is named foo:
class foo
{
    public:
    virtual void process() = 0;
}

the user would create a class bar:
class bar : public foo
{
    public:
    void process() {};
}

The class that I think needs to be a template class:
class Filter<Foo* T>
{
public:
    // use value junk to derive foo
    // and put the new instance on a std::list
    add(Junk* junk);
    T get();

private:
    std::list<T> mFooList;
}

void Filter::add(Junk* junk)
{
    T* foo = new T();
    foo.p(junk);
    mFooList.push_back(foo);
}

T* Filter::get()
{
    if(!mFoolist.empty())
    {
        T* res = mFooList.back();
        mFooList.pop_back();
        return res;
    }
    return nullptr;
}

Comment: You have several problems here. `class Filter` isn't the way to declare a template. And `void Filter::add(Junk* junk)` doesn't use `junk` in any way, so how is it supposed to affect the stored value? And also, `mFooList.pop_back();` is a `void` function so doesn't actually return anything.
Comment: I just left out the detail for how junk is used as the coefficients for fir filter.  I just thought it would add unneeded complexity to the question.
Comment: So let me understand your syntax clearer - you want `T` to be the type derived from `Foo` passed to the `Filter` class as a template parameter or am I over-interpreting your code?
Comment: Like I said, I don't know I understand this.  The user will define a class derived from foo, call it bar and tell it to the filter class.  Then as new data is coming in, the filter will process the incoming data and create instances of the class bar.  The user can get the filtered result via the get method.
Answer: You don't need to use a templatevin this situation. In c++ a derived class can be assigned to a pointer of the base class. You can just use foo pointers.
class foo
{
    public:
    virtual void process();
};

class bar1: public foo
{
     public:
     void process();
};

class bar2 : public foo
{
    public:
     void process();
};

class filter
{
     private:
     std::list<foo*> _foos;

     public:
     foo* get();
     void add(foo* f);
};

void filter::add(foo* f)
{
    _foos.push_back(f);
}

foo* filter::get()
{
    if(!_foos.empty())
    {
         return _foos.pop_back();
     }
    return nullptr;
}

You can then just add and get foos and bars
filter fil;
fil.add(new foo());
fill.add(new bar1());
fill.add(new bar2());

foo f = fill.get();
while(f != nullptr)
{
    f->process();
    delete f;
    f = fil.get();
}

Comment: When the user calls add, the argument is a different class that is know when the class filter is defined.  It is the input class.  I want to be able to allow the user to change the implementation of the filter by specifying a class that will process the input the way they want.
Comment: [`list::pop_back` is used incorrectly](http://en.cppreference.com/w/cpp/container/list/pop_back). Note the `void` return type. And careful with underscore prefixes. [Sometimes they mean more than you might think.](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)


Conflitos com jquery no template AdminLTE

Question: Colegas.
Estou usando o template  AdminLTE para um projeto, porém em uma das páginas quero colocar uma API de autocomplete para as buscas. O problema é que quando coloco essa API que tem uma referência do jquery dentro de sua pasta, o menu para de funcionar e quando tiro a API ou sua referência ao Jquery, o menu volta a funcionar, porém a API não funciona mais. Já troquei as posições e o conflito permanece. Enfim, alguém saberia como faço para resolver esse impasse entre esses códigos. Veja abaixo:
AdminLTE

Answer: Acredito que este problema esteja sendo causado na verdade por um conflito relacionado ao método autocomplete, veja bem:

Você está adicionando o jquery-autocomplete/jquery.autocomplete.js, que possui o método autocomplete() que você pretende utilizar.
Antes, você adiciona o https://code.jquery.com/ui/1.11.4/jquery-ui.min.js, que adivinhe só, possui o método autocomplete().

Minha sugestão é que utilize a própria ferramenta de autocomplete do jQuery UI, pois provavelmente você o adicionou por que utiliza outros recursos do mesmo. Neste caso você poderia seguir o seguinte exemplo que a própria documentação oferece:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

  Birds:
  <input id="birds">

  Result:

Comment: Obrigado Kenny Rafael.
Answer: Aproveitando a solução do Kenny Rafael, na linha:
dataType: "jsonp",

Troquei para:
dataType: "json",

e o search.php pode ficar dessa forma:
<?php
include("sua-conexao.php"); // $con = conexao

$valor = $_GET["term"];
$trazer = array();

$sql = mysqli_query($con,"SELECT * FROM suatabela WHERE campotabela like '%" . $valor . "%'");

while($mostrar = mysqli_fetch_array($sql)){
        $trazer[] = $mostrar["campotabela"];
}
echo json_encode($trazer);
 ?>


Does large Rhat for one parameter mean that marginal posterior for another cannot be trusted?

Question: I'm using Stan to fit a model on some simulated data. The model has several parameters and one of them, say $\alpha$, has a large Gelman-Rubin statistic value, $\hat{R} > 1.1$. This is however  a parameter I'm no interested in. Moreover, marginal posteriors for all parameters are accurate.
So my question is does a large $\hat{R}$ for one parameter mean that the entire inference cannot be trusted?
Answer: Yes, I would not trust the inferences (unless the higher R-hat were for the log-kernel, lp__, or perhaps for a generated quantity that does not go into the log-kernel). This question was considered in a paper by Jeff Gill whose abstract is

Increasingly, political science researchers are turning to Markov chain Monte Carlo methods to solve inferential problems with complex models and problematic data. This is an enormously powerful set of tools based on replacing difficult or impossible analytical work with simulated empirical draws from the distributions of interest. Although practitioners are generally aware of the importance of convergence of the Markov chain, many are not fully aware of the difficulties in fully assessing convergence across multiple dimensions. In most applied circumstances, every parameter dimension must be converged for the others to converge. The usual culprit is slow mixing of the Markov chain and therefore slow convergence towards the target distribution. This work demonstrates the partial convergence problem for the two dominant algorithms and illustrates these issues with empirical examples.

In the case of the dynamic Hamiltonian MCMC algorithm used by Stan --- which makes joint proposals for the next iteration of the parameters --- I do not generally see how the Markov Chain could be performing well if it is misbehaving on any margin. Moreover, a R-hat of 1.1 is extremely large in the Stan era, and we should be worried if any R-hat were greater than 1.01.


jdbc connection socketexception error

Question: am successfully finished login form in android using mysql connection via jdbc in java...its successfully worked in my localhost...but development site its not worked...the following error is displyed.
java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: Connection timed out: connect

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection timed out: connect

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection timed out: connect
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
    at com.mysql.jdbc.Connection.<init>(Connection.java:452)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.retrieve.retrieve.main(retrieve.java:15)

** END NESTED EXCEPTION **

    at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
    at com.mysql.jdbc.Connection.<init>(Connection.java:452)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.retrieve.retrieve.main(retrieve.java:15)

why dis error  is occurred.give me some solutions.
if am running localhost means my sql query is
             package com.example.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayoutActivity extends Activity {

    EditText username,password;
    TextView error;
    Button ok;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        username=(EditText)findViewById(R.id.et_un);
        password=(EditText)findViewById(R.id.et_pw);
        error=(TextView)findViewById(R.id.tv_error);
        ok=(Button)findViewById(R.id.btn_login);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Editable user = username.getText();
                Editable pass = password.getText();

                try {

                    **Class.forName("com.mysql.jdbc.Driver");

                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/people", "root", "");
                        Statement st = con.createStatement();

                        ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**

                        if(rs.next())
                        {
                            String dbpass = rs.getString(1);
                            if(dbpass.equals(pass)){
                                 error.setText("Correct Username or Password");

                        }
                        else
                        {
                            error.setText("Sorry!! Incorrect Username or Password");
                        }
                        }
                }

                     catch (SQLException e) {
                        username.setText(e.toString());
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

        });
    }
}

if am running development site means my query is:
              package com.example.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayoutActivity extends Activity {

    EditText username,password;
    TextView error;
    Button ok;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        username=(EditText)findViewById(R.id.et_un);
        password=(EditText)findViewById(R.id.et_pw);
        error=(TextView)findViewById(R.id.tv_error);
        ok=(Button)findViewById(R.id.btn_login);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Editable user = username.getText();
                Editable pass = password.getText();

                try {

                    **Class.forName("com.mysql.jdbc.Driver");

                        Connection con = DriverManager.getConnection("jdbc:mysql://dev.xxxxx.com/xxx", "xxxx", "xxxx");
                        Statement st = con.createStatement();

                        ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**

                        if(rs.next())
                        {
                            String dbpass = rs.getString(1);
                            if(dbpass.equals(pass)){
                                 error.setText("Correct Username or Password");

                        }
                        else
                        {
                            error.setText("Sorry!! Incorrect Username or Password");
                        }
                        }
                }

                     catch (SQLException e) {
                        username.setText(e.toString());
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

        });
    }
}

dis development site username,password,database name and url all r correct only...then why dis error is occured....give me solutions...
Comment: Can you ping to that host? Can you connect to MySQL via other tools ?
Comment: ya i ping the host...then only putting...no..here  jdbc only used...
Comment: Try to connect using other tools, and try to narrow down the issue search space
Comment: am developed android native apps...here mysql connection via jdbc only possible...so only am asked...any other solutions
Answer: If you are trying to connect your mysql in the localhost from an android application, it may not get communication, refer this.
This exception seems like the mysql doesn't have public access.
Make your mysql available in a remote system and give the remote system's ip. Let 192.168.1.102 be its ip, then change this statement as jdbc:mysql://192.168.1.102:3306/people.
You have to modify the mysql configuration file. It may be /etc/mysql/my.cnf (in linux) or  \xampp\mysql\bin\my.ini (depends on mysql refer more).
By default it contains bind-address            = 127.0.0.1, change it as bind-address            = 0.0.0.0. When this change is made, then the mysql is available publicaly i.e. it can be accessed remotely. Now your application can access this mysql.
Answer: Sounds like a network problem. Verify if you can access the Database host and port from the device you're making the connection, and if the DBMS is up and running.
Comment: what is meant by dbms...bez database host and port all r correct only in my connection...
Comment: "Data Base Management System". If you can ping it, maybe is a DNS problem. Have you tried using IP in your JDBC URL?
Answer: The key question is whether or not the mobile device is on the network when you try to connect to the database.  If you're on the network, you'll need to talk to the MySQL database administrator to see if you have permission to access that database.  I'm guessing that you do not, because you're trying to log in as root without a password.  No administrator in their right mind would allow you to do that.
If you're the administrator, please call your therapist of pharmacist.
If the mobile device is not on the network,  I'm guessing that the database is behind a firewall of some kind.  At best you'll have to talk to some administrator to get firewall rules set up to allow access from the mobile device.  Those usually require some information about the device.  Firewall rules won't be practical if you intend to release an app for several users.
A better solution would be to set up a proxy that would authenticate incoming mobile devices and communicate with the database on their behalf.
I would not have a mobile device connecting directly to a database, especially the way you're trying to do it.
Who else knows about what you're trying to do?  It looks to me like you're trying to connect to a database, but that fact isn't widely known.  Who else knows about your project?
Answer: If you use en emulator use a special IP to your localhost.
10.0.2.2
jdbc:mysql://10.0.2.2:3306/people

jdbc connection socketexception error


Cant solve error: # received unexpected message :[]= with (:rule_code, 1)

Question: Im a struggling to solve the above error i get when testing the following:
def add_rule_code new_rule
  count = list[:multiple_item_rules].count + list[:total_price_rules].count + 1
  new_rule[:rule_code] = count
end

with the following test:
  it "adds a unique rule code" do
    item_rule = double( {rule_type: "item", item_code: 001, number_of_items: 2, new_item_price: 8.50} )
    rules.add_rule_code item_rule
    expect(rules.list[:multiple_item_rules][:rule_code]).to eq 1
  end

I get the following error message:
1) Promotional_Rules New rules adds a unique rule code
   Failure/Error: new_rule[:rule_code] = count
     #<Double (anonymous)> received unexpected message :[]= with (:rule_code, 1)
   # ./lib/Promotional_Rules.rb:21:in `add_rule_code'
   # ./spec/promotional_rules_spec.rb:27:in `block (3 levels) in <top (required)>'

I sure its a simple fix but i cant figure it out despite googling etc. Any help would be great.
Thanks
Comment: Does the error point to any line in particular?
Comment: Make sure that `new_rule` is what you think it is.  My guess is that it's not
Comment: The final line in the method, "new_rule[:rule_code] = count"  from the line in the test "rules.add_rule_code item_rule"
Comment: when i "p" new rule at the top of the method it gives me "#"
Comment: In add_rule, does it have all the expected values? `rule_type`? `item_code`? etc?
Comment: if i do the following at the top of the method:
 " p new_rule.rule_type
  p new_rule.item_code
  p new_rule.number_of_items
  p new_rule.new_item_price"

  i get:
"
  "item"
1
2
8.5 "
Comment: Try `new_rule.rule_code = count`
Comment: it gives the same error
Answer: You are calling new_rule[:rule_code] but the double does not respond to :[].
One way you can make it work is:
allow(new_rule).to receive(:[])
See RSpec Mocks Method Stubs.
I don't know why you are using a double. I think you might want to use a factory.
Comment: Hi, thanks for replying, i just tried that and a few other combinations but had no luck. I am fairly new to this and am not familiar with factories and factory girl. Can you lend any more advice? Thanks
Comment: Here is the Factory Girl docs: https://github.com/rspec/rspec-mocks#method-stubs. But you don't really need a Factory. You can do `item_rule = ItemRule.new( ... )`.
Comment: It seems that you may want to learn more about RSpec. Here's a tutorial: https://semaphoreci.com/community/tutorials/getting-started-with-rspec . I suggest you go through a few tutorials and then come back to your project. Also, writing model specs is a great way to learn.


Dataloader for attributes that are not at top level does not work

Question: I am using Netflix's DGS framework to build a java graphqQL service. I tried to use the data loader (https://netflix.github.io/dgs/data-loaders/) and it works fine as long as the parent type is a top level attribute (i.e. immediate child of Query).
For example, consider the following schema:
<code>type Person{
  location: Location
  preferences: Preferences
}

type Location {
   x: Int
}

type Preferences {
  typeA: TypeAPreferences
  typeB: TypeBPreferences
}
</code>
If I try using a dataloader for a child of a level 1 type it works fine, example:
<code>@DgsData(parentType = "Person" field="location")
public Location loadLocation(DgsDatafetchingEnvironment dfe){
  ... //use data loader here
</code>
However if the parent type is not level 1 , the data loader is never invoked (no errors are thrown). Example:
<code>@DgsData(parentType = "Preferences" field="typeA")
public TypeAPreferences loadTypeAPreferences(DgsDatafetchingEnvironment dfe){
... //use data loader here
</code>
Wondering if others have been able to make this work successfully and if there is something I am missing here that is causing it not to work?
Answer: This was just me doing something silly - i had the parent type and field attributes incorrectly filled out.


How to query JSON data from REST API in React Native

Question: I want to query through some data from NewsAPI in React Native and have no idea how to do so and none of the tutorials I've seen have helped. Thanks!
Comment: take a look at: http://stackoverflow.com/help/how-to-ask you'll have more luck getting answers to your question
Answer: Check out the Docs on Networking from React Native... I'm using Fetch in our production apps.

React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

MDN Fetch API Guide
<code>fetch('http://google.com')
 .then(res => {
    if (res.ok) return res.json())
    else throw new Error(res)
 .then(json => {
   for (var key in json) {
     // now you can parse it by calling json[key]
   }
 .catch(error => console.log(error)
 }
</code>
Comment: Their docs are kinda throwing me off... all I wanna do is get the JSON, parse through data and print it, I can't seem to find that only a network request. thanks for the help though!
Comment: I added an example... I agree the docs are confusing. You can probably get better examples on the web or in other people's code.
Comment: Ok thank you Brad! Is there a way I could print this now or call it in a ?
Comment: You probably going to want to throw the json object into your component's state and then display that inside a `` component.


Angular Não consigo criar um componente com o ng g c

Question: Ola estou tentando usar o comando para criar componente chamado sidebar no angular o ng g c sidebar
porem quando aperto enter o terminal fica como na foto.
Comment: Você está no diretório certo?
Comment: estava sim, não sei era algum bug formatei a maquina voltou ao normal, obrigado.
Answer: Antes de tudo certifique se o diretório está correto.
1 - Utilizar o terminal cmd com atalho (ctrl + shift + c), ai tu digita esse comando.
2 - atualizando o angular-cli: ng update
Caso continue, crie um projeto novo para desencargo.
Abs.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-ask).


How to create xy grid that covers entire sample area with specific number of nodes in python?

Question: I am looking at 2D spatial data (x,y,(z)), where z is a property of x,y not another spatial dimension. What I want to do in my application is to have the user toggle an "Number of x nodes" slider bar. The program looks at their sample data that they loaded, and, using the aspect ratio of their data, chooses the number of y nodes to have 1:1 aspect grid created over their sample.

This part works fine. But know I need to create that actual grid data. I do this using itertools, and getting all the combinations of two arrays. One for x and one for y.
xnodes=#number of x from user choice
dx=(max(x)-min(x))/xnodes
grid_xy = np.array(list(itertools.product(
            np.arange(min(x),max(x),step=dx),
            np.arange(min(y),max(y),step=dx))))

Note that I use dx in both arrays because I want the grid aspect to be 1:1. The number of total nodes just goes to the user so that they know if it's going to take a long time to compute or not. What I get is a situation like this.

The grid nodes do not cover the whole area (as the number of x nodes gets larger, it eventually gets very close). Also, the rounding inherent in np.arange means that sometime it overshoots the sample data, which is what I want, bt sometimes undershoots. How can I make sure to capture all the sample data with my grid, while only using the number of nodes specified to the user? One solutio n I can see would be to add another row of nodes to the end of each grid columns.
Comment: have you looked at np.linspace?  np.linspace(0, 9, 5) with nodes=5
array([0.  , 2.25, 4.5 , 6.75, 9.  ]) or adding dx to np.arange …. np.arange(x.min(), x.max()+dx)
Comment: Sorry. Just had time to test this. The np.linspace worked. I didn't know that linspace worked by always including endpoints and doing the intermittent division for me. Thanks!
Answer: The answer was
self.grid_xy = np.array(list(itertools.product(
     np.linspace(self.min_gx,self.max_gx,num=self.s1.get()),
     np.linspace(self.min_gy,self.max_gy,num=self.s2.get()))))

or, without the class structure
self.grid_xy = np.array(list(itertools.product(
     np.linspace(min(x),(max(x),num=x_nodes),
     np.linspace(min(y),(max(y),num=y_nodes))))


how to make this div draggable on chrome like on firefox

Question: this is the code:

dddw

this code can be draggable on firefox , but cant on chrome ,
so how to make it draggable on chrome
thanks
Answer: The resizing "handles" are managed differently so it will cause a noticeably different look between the browsers, however, you can get resize in Chrome using CSS3 resize attribute in combination with overflow:auto. (Firefox doesn't pick up on these, but its already being done by the ContentEditable as it adds a -moz-resizing="true" attribute to the element when it gets clicked.)

dddw


How to programmatically get the NID of the current node

Question: I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.
And solutions like
global $node;
$nid = $node->nid;

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value.
It feels like there must be something really obvious that I'm missing.
So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?
Answer: Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():
if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

or
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.
Comment: @sheldonkreger The node's already loaded by that point, `menu_get_object()` (or even `node_load()`) is just getting it from static cache. Even if you call it early on, it's still going to be loaded by a core module later on in the page build (as this is a node page), in that case you'd just be warming the static cache for the next process
Comment: @Letharion Yeah I feel just a little bit guilty every time I do it ;)
Comment: @beth What function are you calling it from? And is it definitely a node page you're calling it on?
Comment: @beth They 100% will work with path aliasing enabled. Path aliasing has nothing to do with the _router path_ of the menu item, which is `node/1`, `node/2` etc. If you're still having trouble it might be worth posting another question with the exact code you're using, and provide a bit of context. Then we might be able to pinpoint where the problem's happening
Comment: A single line solution `$nid = ($node = menu_get_object()) ? $node->nid : NULL;`
Comment: You don't _need_ to combine assignment with a condition to use menu_get_object though. :) Otherwise I agree, unless you're using [Page manager](http://drupal.org/project/ctools), menu_get_object() is the way to go.
Comment: Neither of those appears to work. When I do `dsm(menu_get_object());` (with `dsm()` being [devel](http://drupal.org/project/devel)'s way of displaying the contents of objects and arrays), I just get an empty line.
Comment: @Clive Ah, I was calling it on a Webform page. Though I thought Webforms get NIDs as well?
Comment: Yeah they should be nodes as well...is it possible you're on a webform results page/sub page of some sort? Then it wouldn't be a node page as such
Comment: @Letharion I'm using ctools... will it interfere with something?
Comment: No, it definitely won't interfere, but Page manager is how I always solve this problem. That's a whole different way of thinking though, and not suitable for these comments.
Comment: Neither of these methods work with path aliasing enabled.
Comment: Loading the node is rather heavy, I prefer to use the method I outline below, working with the path.
Answer: Easiest way to do this in Drupal 8 since arg() no longer works:
$path_args = explode('/', current_path());
print $path_args[1];

Change record
Comment: This also works in Drupal 7. However, if you are on a page which isn't a node, such as admin/structure/blocks , then you will receive an invalid value (in this case, 'structure'). Simply check to see if path_args[1] is an integer and you're probably fine.
Comment: You will likely want to use arg(1) instead of explode, since it has already done that for you:
https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7
Comment: @RobLoach but arg() doesn't exist in D8
Answer: arg(0) returns 'node' and arg(1) returns node nid.
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}

Answer: In D8:
$node = \Drupal::routeMatch()->getParameter('node');

Comment: Better wrap the output like shown in https://drupal.stackexchange.com/a/145826/15055. And also worth to note that this won't work on node preview pages and node revision pages.
Comment: This is the cleanest answer for d8 if looking for a node.
Answer: The second method in the currently accepted answer is the cleanest in D7. The first answer:
if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

is only visually cleaner. In fact, menu_get_object() is calling quite a lot of code and may lead to unforeseen errors. I was using it inside a hook_node_grants() function and ran into a PHP Fatal error:

Maximum function nesting level of '256' reached, aborting!

The explanation, found at https://drupal.stackexchange.com/a/69232/9158

The infinite loop you are noticing is caused from the fact that
  menu_get_object() causes Drupal to verify the currently logged-in user
  has access to the node, which causes your implementation of
  hook_node_grants() to be invoked again, which calls menu_get_object(),
  which causes your implementation of hook_node_grants() to be invoked
  again, which...

This was solved by using the second method:
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

Answer: Another option, in D7:
function _my_module_get_nid() {
  $path_args = explode('/', current_path());
  //$nid = $path_args[1];
  if(is_int($path_args)) {
    return($path_args[1]);
  }
  // Log that we failed to load a NID.
  else {
    watchdog('my_module', 'Unable to gather NID at: ' . current_path(),  WATCHDOG_WARNING, NULL);
  return FALSE;
  }
}

If you plan to use the function outside your module, do not use the leading _ at the begining of the name of the function.
Comment: This is the same thing but with an expensive watchdog call on all paths that aren't nodes.
Comment: I like to know if my code is failing unexpectedly. I wouldn't want this code being executed on non-nodes, watchdog will show me where that is happening so I can fix it. Otherwise I'll have no trace that this code is running for no reason (on non-nodes). Otherwise it's the same as the D8 method mentioned above.
Answer: <?php
if (isset($node->nid) && count($node->nid) > 0){
  $mynodeid = $node->nid;
}
?>

Comment: Could you please add some "whys" and "hows" to your answer?Code-only answer might work, but it hardly helps to understand one's mistakes.
Comment: It first checks if the node is defined before executing.
Comment: `count($node->nid) > 0` where `$node->nid` is an integer doesn't make any sense, since `count()` counts the number of items in an array. It's would causes a _PHP Warning:  count(): Parameter must be an array or an object that implements Countable_.


Determine which set is from a different distribution

Question: I am given 5 sets of data and I know one of them is different from the rest. How would I go about identifying which one. The sample sizes and variances are different. The datasets are greater than 10,000 elements.
I calculated the mean and standard deviation for each of the sets, and one of the sets is very different. I want to statistically prove that the difference is significant.
I tried to do a welch t test using python with the following function:
scipy.stats.ttest_ind(a, b, equal_var=False)

but the p-values are very low for everything (ex. low like 1e-21).
I'm not sure why the welch t-test is not working and if another method is more suitable.
Comment: The P-value (very nearly 0 and certainly <0.05=5%) shows strong evidence that the null hypothesis (equal means) as rejected at any reasonable level of significance. What result did you anticipate the Welch test would give? // It would help to know what kind of data you have (integers? continuous scale?)  Also, what size and kind of differences btw datasets are you looking for? With samples as large as 10,000 you have good power to detect even tiny differences that may not be of importance to you. Please give more context and information.
Comment: Hi, thank you for your comment. My data is continuous floating point numbers. From the 5 sample sets (each over 10,000 elements), 4 of them has a range between -300 and +300. Mean is approx 3-5 and std approx 40-50 for 4/5 samples. One of the samples has mean of 25 and std of 130 with a range of -500 and +1000. So I can visually see the problem here. I am looking for a method to show that this difference is statistically significant with some confidence.
Comment: In the situation you describe, you may need to do tests for equal variances instead of Welch test which compares means. But I fear you may be missing the point. You keep on saying "statistical significance," possibly without understanding what that terminology really means. // With large enough $n$ you can tell the difference btw a coin with P(Heads) = 0.5000 and a coin with P(Heads) = 0.5001 and that difference would be real. But for purposes of deciding which team defends which goal there is no practical importance btw the two coins.
Answer: Two datasets that may be essentially the same for practical purposes, but are
found to be different by Welch two-sample t test:
    set.seed(904)
    x1 = rnorm(10000, 1001, 15)
    x2 = rnorm(10000, 1002, 15)
    t.test(x1, x2)

    Welch Two Sample t-test

data:  x1 and x2
t = -4.6203, df = 19998, p-value = 3.856e-06
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
  -1.3913997 -0.5624911
sample estimates:
mean of x mean of y
 1001.138  1002.115

boxplot(x1, x2, col="skyblue2", pch=20)

If you're mainly interested in differences large enough to be obvious
from looking at summary statistics or boxplots, then maybe just do
a visual inspection.
x3 = rnorm(10000, 1000, 15)
x4 = rnorm(10000, 1020, 15)
x5 = rnorm(10000, 999, 15)

boxplot(x1, x2, x3, x4, x5, col="skyblue2", pch=20, names=T)

Addendum: Now that you have given approximate means and SDs, I'll try another example.
set.seed(2020)
y1 = rnorm(10000, 2, 40)
y2 = rnorm(10000, 3.5, 40)
y3 = rnorm(10000, 4.5, 40)
y4 = rnorm(10000, 25, 130)
y5 = rnorm(10000, 5.5, 40)
boxplot(y1, y2, y3, y4, y5, col="skyblue2", pch=20, names=T)

Boxplots show clearly that Group 4 differs from the others.

Some of the Welch t tests will detect the relatively small (perhaps unimportant) differences between means of Groups 1, 2, 3, and 5; with P-values below 5%.
 t.test(y1,y2)$p.val
 [1] 0.00703525
 t.test(y2,y5)$p.val
 [1] 0.003545032

However, group variances are all the same---except for Group 4. So you
will mostly not find differences in variances among Groups 1, 2, 3, and 5.
And you should find different variances between Group 4 and one of the other groups.
var.test(y1, y2)

        F test to compare two variances

data:  y1 and y2
F = 0.96727, num df = 9999, denom df = 9999, p-value = 0.09614
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.9300803 1.0059402
sample estimates:
ratio of variances
         0.9672668

var.test(y1,y4)

         F test to compare two variances

data:  y1 and y4
F = 0.094033, num df = 9999, denom df = 9999, p-value < 2.2e-16
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
  0.09041748 0.09779217
sample estimates:
ratio of variances
        0.09403255

Comment: Thanks for your answer. Would there be a way to determine if the difference is statistically significant to come to a conclusion?
Comment: Each group is sampled from a different population. Means $\mu = 1001, 1002, 1000, 1020, 999,$ respectively. For samples of sizes $n=10\,000,$ a Welch test will find a _**statistically significant difference**_ between any two samples. However, in some real-world application you may feel that Sample 4 from population with $\mu=1020$ is the only difference of _**practical importance.**_ The point of my Comment and Answer is that you have to understand the distinction between statistical significance and practical importance.// Tests with only $n = 100$ would give different results. Try it.
Comment: Please see my Addendum.


3D is not rendering in WPF Application

Question: I am trying to render 3D object using the below code.
But when I run the application, nothing is displayed. It seems to be blank. Am I missing anything?
<Page x:Class="SampleWpfApplication.DemoPage3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DemoPage3" xmlns:my="clr-namespace:SampleWpfApplication">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="126*" />
        <RowDefinition Height="126*" />
        <RowDefinition Height="66" />
    </Grid.RowDefinitions>
    <Viewport3D x:Name="theView3D">
        <Viewport3D.Camera>
            <PerspectiveCamera Position="6,6,6" LookDirection="-4,-4,-4"
UpDirection="0,1,0" />
        </Viewport3D.Camera>
        <ModelVisual3D x:Name="theModel">
            <ModelVisual3D.Content>
                <Model3DGroup>
                    <GeometryModel3D x:Name="theGeometry">
                        <GeometryModel3D.Geometry>
                            <MeshGeometry3D Positions="0,1,0 1,-1,1 -1,-1,1 1,-1,-1 -1,-1,-1"
        Normals="0,1,0 -1,0,1 1,0,1 -1,0,-1 1,0,-1"
        TriangleIndices="0,2,1 0,3,1 0,3,4 0,2,4" />
                        </GeometryModel3D.Geometry>
                        <GeometryModel3D.Material>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="Red" Opacity="0.9"/>
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.Material>
                        <GeometryModel3D.BackMaterial>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="Green" Opacity="0.9"/>
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.BackMaterial>
                    </GeometryModel3D>
                </Model3DGroup>
            </ModelVisual3D.Content>
        </ModelVisual3D>
        <ModelVisual3D>
            <ModelVisual3D.Content>
                <Model3DGroup>
                    <DirectionalLight Direction="0,-5,-2" />
                    <DirectionalLight Direction="3,2,2" />
                    <GeometryModel3D x:Name="theGeometry2">
                        <GeometryModel3D.Transform>
                            <ScaleTransform3D ScaleX="2" ScaleY="2" ScaleZ="2"></ScaleTransform3D>
                        </GeometryModel3D.Transform>
                        <GeometryModel3D.Geometry>
                            <MeshGeometry3D Positions="0,1,0 1,-1,1 -1,-1,1 1,-1,-1 -1,-1,-1"
        Normals="0,1,0 -1,0,1 1,0,1 -1,0,-1 1,0,-1"
        TriangleIndices="0,2,1 0,3,1 0,3,4 0,2,4" />
                        </GeometryModel3D.Geometry>
                        <GeometryModel3D.Material>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="#7FB0C4DE" Opacity="0.9"/>
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.Material>
                        <GeometryModel3D.BackMaterial>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="#7FB0C4DE" Opacity="0.9"/>
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.BackMaterial>
                    </GeometryModel3D>
                </Model3DGroup>
            </ModelVisual3D.Content>
        </ModelVisual3D>
    </Viewport3D>
</Grid>
</Page>

Answer: It appears to render fine for me in Kaxaml.
Perhaps you should try a different machine or use Kaxaml to see if you get any result at all. At this point, it could be any number of things.
EDIT: I noticed that I didn't copy the Grid.RowDefinitions. When I add them, it clips the viewport. If you remove those, does it work?
Answer: I try to render your Viewport3D in WPF application and it's successfully rendered. It shows me a pyramid mesh.
From your code above, you get a blank screen because you are not defining your page height and width.
Here is my solution for your page (Please add your page height and width properties as follow) :
<Page x:Class="SampleWpfApplication.DemoPage3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="300"
    Title="DemoPage3" xmlns:my="clr-namespace:SampleWpfApplication">

Comment: DesignWidth & DesignHeight are meaningful for the designer only. They are not even compiled in run time. How does that help?

3D is not rendering in WPF Application


Add classes to org.eclipse.swt

Question: I'm working on a Eclipse plugin which need to modify classes from the core packages of Eclipse. I want to write my own org.eclipse.swt.StyledText (not extend byt copy past the source code and modify some behaviors) and to instantiate it in org.eclipse.jface.text.TextViewer instead of the default StyledText.
It seems that the best way to modify TextViewer is to make my own version of the org.eclipse.jface plugin and to release it wrapped into a feature project.
But adding a class to swt package seems harder, first because there is different jars depending on the operating system used (org.eclipse.swt.cocoa, org.eclipse.swt.gtk ....) and also because copy pasting the code of StyledText is not that easy since there is call to external methods waiting for a strict StyledText.
Any ideas ?
Comment: Why do you need to modify these classes? This is going to be a maintenance nightmare and as you have found changing StyledText would be very difficult.
Comment: I know i'm about to do something really dirty, my goal is to make a plugin modifying caret behavior and display. I think I have no other choice.
Comment: @SegFault If you can explain in detail what you're trying to achieve, there might be an easier way...
Comment: I would like to add multiple-cursor to the text editor. The cursor is managed in StyledText.
Answer: I did something similar with the org.eclipse.jface.preference.ColorSelector. I really needed a color widget that could accept a null value. This would be impossible to achieve without refactoring the widget.
Since overriding the respective class wasn't enough, because a lot of the functionality is encapsulated, I too wanted to modify the whole class directly.
Then again, as greg and Baz mentioned, it is a maintenance hell. Say you want to include this widget of yours in an RCP plugin. Then what do you do? The RCP platform provides its own SWT packages.
My solution was simple and straightforward. You copy-paste the entire class into a new one of your own, and simply use that one in your app.
But in your case, it seems that you are hitting more than one class (TextViewer and StyledText). Still, I would go with the copy-paste method ONLY if the desired behaviour exceeds the platform capabilities.

Add classes to org.eclipse.swt


systemd container: how can I automatically run a bash script?

Question: After successfully following these RHEL systemd container instructions, I'd  now like the container, every time it starts, to run a bash script. However, I'd like it to run only once. That doesn't seem like a "service" to me. I don't want to start the container, then manually run the bash script (e.g., docker exec -it ...). Should I make a systemd unit file to start the script and then disable the service in my bash script? That seems a bit like a hack, no?
Update: To answer commenters, the bash script requires systemd. So first systemd must start, then the script runs, installs software, and then issues systemctl start commands. Yes, I know what you're thinking: install the software using RUN and then let systemd start it, but unfortunately, I can't do that for this project. The script, which I didn't write, expects systemd to be running. Also, the script does run inside the container, in a named volume.
Comment: only once per container start?
Comment: Is there any reason why you don't simply modify the container to execute that script as part of its startup?
Comment: and from your reference to `docker exec` this script is inside the container?
Answer: You can create a systemd unit file of service type oneshot for your bash script. The oneshot type represents short-lived process, usually run as one-off task. systemd waits for the process to exit before continuing on with other units.
For example,
[Unit]
Description=my only-once script

[Service]
Type=oneshot
ExecStart=/bin/bash /path/to/only_once_script.sh
RemainAfterExit=true
StandardOutput=journal

[Install]
WantedBy=multi-user.target

Note that RemainAfterExit must be set to true if you want systemd to consider the service as active after the start action completed successfully.
Take a look at Example 2 and Example 3 in the systemd docs.
Comment: in my case, the script will take 20 minutes and I don't want to block/prevent the loading of other services. Can I set ExecStart=/bin/bash /some/script.sh & to run it in the background?
Comment: No, `&` isn't supported by any of the `ExecStart=`, `ExecStartPre=`, `ExecStartPost=`, `ExecReload=`, `ExecStop=`, and `ExecStopPost=` options, as said in the [docs](https://www.freedesktop.org/software/systemd/man/systemd.service.html) under _Command lines_.
Answer: If you just need "systemd" because the installer program runs "systemctl start" commands then may be you can avoid the fuzz by using the systemctl-docker-replacement wrapper.
I am regurlarly using it to overwrite /usr/bin/systemctl in which case "systemctl start" is executed correctly without any systemd daemon running. Tested with quite a number of installer programs to mimic the behaviour that they expect from "systemctl start".
Answer: You can do that in your same service itself. Consider the below flow on my machine
$ docker run -d ubuntu:16.04 sleep 200
2e76d13cee285143dc91af0e6ddbd51bd31e92d7baa3ec34638726cdd0abb572

$ docker exec -d 2e76d13cee285143dc91af0e6ddbd51bd31e92d7baa3ec34638726cdd0abb572 sleep 300

$ docker exec  2e76d13cee285143dc91af0e6ddbd51bd31e92d7baa3ec34638726cdd0abb572 ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.2  0.0   4384   756 ?        Ss   12:25   0:00 sleep 200
root         5  0.1  0.0   4384   792 ?        Ss   12:25   0:00 sleep 300
root         9  0.0  0.2  34428  2740 ?        Rs   12:25   0:00 ps aux

As you can see i executed a command in background (-d/--detach of exec command)
So in your Service file. Just define the ExecStartPost= in your main unit which launches the docker container and use exec with -d flag


Google apps script Basecamp create attachment from anothr project

Question: I want to copy attachments from project to anther project already has attachments on basecamp here is the code I'm using
my problem in creating attachments I can upload attachemets but I can't create attachment with right file content  the created file is with wrong content file which return invalid file while i try to ope it
I used this documentation
Thanks
<code> function copyAttachements()
    {
     sourceProjectID=4683117;
     destinationProjectID=4683125;
     var url=getProjectURL(sourceProjectID);

     var unamepass=username+":"+password ;
     var digest = Utilities.base64Encode(unamepass);
     var digestfull = "Basic "+digest;

     var header={Authorization: digestfull};
     var option={ method : "get",muteHttpExceptions:true,headers : header,contentType :      "application/json"};
     var response=UrlFetchApp.fetch(url,option);

     if(String(response.getResponseCode())=="200")
     {
     var name,content;
     url=url.replace(".json","/attachments.json");
     var header={Authorization: digestfull};
     var option={ method : "get",muteHttpExceptions:true,headers : header,contentType : "application/json"};
     var response=UrlFetchApp.fetch(url,option);

     var jsonData=Utilities.jsonParse(response.getContentText());
     for(var j in jsonData)
     {
       var option={ method : "get",muteHttpExceptions:true,headers : header,contentType : "application/json"};
       var response=UrlFetchApp.fetch(url,option);

       content=UrlFetchApp.fetch(url,option).getContent();

       var url = "https://basecamp.com/"+BasecampID+"/api/v1/attachments.json";//getProjectURL(destinationProjectID);

       var data={"content": content,"Content-Length":jsonData[j].byte_size,"Content-Type":jsonData[j].content_type};
       var header={Authorization: digestfull};
       var payload = JSON.stringify(data);

       var option={ method : "post",muteHttpExceptions:true,headers : header,payload:payload,contentType : "application/json"};
       var response=UrlFetchApp.fetch(url,option);

       var url =getProjectURL(destinationProjectID);
       url=url.replace(".json","/uploads.json");
       var header={Authorization: digestfull};

       var data={"content": jsonData[j].content,
            "attachments": [{"token": Utilities.jsonParse(response.getContentText()).token, "name": jsonData[j].name}]};
       var payload = JSON.stringify(data);
       var option={ method : "post",muteHttpExceptions:true,headers : header,payload:payload,contentType : "application/json"};
       var response=UrlFetchApp.fetch(url,option);
         }
       }
       else
         Browser.msgBox("Error",response);
      }
</code>
Answer: <code>function copyAttachements()
{
  sourceProjectID=4683117;
  destinationProjectID=4683125;
  var url=getProjectURL(sourceProjectID);

  var unamepass=username+":"+password ;
  var digest = Utilities.base64Encode(unamepass);
  var digestfull = "Basic "+digest;

  var header={Authorization: digestfull};

  var option={ method : "get",muteHttpExceptions:true,headers : header,contentType : "application/json"};
  var response=UrlFetchApp.fetch(url,option);

  if(String(response.getResponseCode())=="200")
  {
    var name,content;

    url=url.replace(".json","/attachments.json");

    var header={Authorization: digestfull};
    var option={ method : "get",muteHttpExceptions:true,headers : header,contentType : "application/json"};
    var response=UrlFetchApp.fetch(url,option);

    var jsonData=Utilities.jsonParse(response.getContentText()).reverse();
    for(var j in jsonData)
    {
      url=jsonData[j].url;
      var option={ method : "get",muteHttpExceptions:true,headers : header,contentType : "application/json"};

 /**********************Changes Done here*********************************/
      content=UrlFetchApp.fetch(url,option).getContent();
      var url ="https://basecamp.com/"+BasecampID+"/api/v1/attachments.json";
      var header={Authorization: digestfull};
      var option={ method : "post",muteHttpExceptions:true,headers : header,payload:content,contentType : jsonData[j].content_type};
/***********************************************************************/
      var response=UrlFetchApp.fetch(url,option);
      var url =getProjectURL(destinationProjectID);
      url=url.replace(".json","/uploads.json");
      var header={Authorization: digestfull};
      var token=Utilities.jsonParse(response.getContentText()).token
      var data={"attachments": [{"token":token, "name": jsonData[j].name}]};
      var payload = JSON.stringify(data);
      var option={ method : "post",muteHttpExceptions:true,headers : header,payload:payload,contentType : "application/json"};
      var response=UrlFetchApp.fetch(url,option);
    }
  }
  else
    Browser.msgBox("Error",response);
}
</code>


Whats wrong with this original mail message?

Question: Recently I have bring up a mail server with postfix. After lots of configurations and settings such as DKIM and rDNS, unfortunately its outgoing mail messages to Gmail are still blocked from the inbox. ( get spam )
Now I don't have any idea about what to do next to make more confidence.
Here is the latest "Original message" which Gmail received from my mail server.
Delivered-To: firstname.lastname@example.com
Received: by 10.28.175.19 with SMTP id y19csp228206wme;
        Thu, 24 Nov 2016 06:00:59 -0800 (PST)
X-Received: by 10.194.96.164 with SMTP id dt4mr2470853wjb.28.1479996059102;
        Thu, 24 Nov 2016 06:00:59 -0800 (PST)
Return-Path: <firstname.lastname@example.com>
Received: from mail.mydomain.tld (mail.mydomain.tld. [188.8.131.52])
        by mx.google.com with SMTP id w65si8419044wma.20.2016.11.24.06.00.57
        for <firstname.lastname@example.com>;
        Thu, 24 Nov 2016 06:00:57 -0800 (PST)
Received-SPF: pass (google.com: domain of firstname.lastname@example.com designates 188.8.131.52 as permitted sender) client-ip=126.96.36.199;
Authentication-Results: mx.google.com;
       dkim=pass firstname.lastname@example.com;
       dkim=pass firstname.lastname@example.com;
       spf=pass (google.com: domain of email@example.com designates 220.127.116.11 as permitted sender) firstname.lastname@example.com;
       dmarc=pass (p=NONE dis=NONE) header.from=mydomain.tld
Received: from mail.mydomain.tld (localhost [127.0.0.1])
    by mail.mydomain.tld (Postfix) with ESMTP id 630ED9FAD9
    for <email@example.com>; Thu, 24 Nov 2016 17:30:55 +0330 (IRST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain.tld;
    s=mail; t=1479996055;
    bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;
    h=Date:From:To:Subject:From;
    b=SbPcmZtuc54ZqmGYCU/O5kzKUPdN3x3qNS+EneBYPtD4HKIXCNJ4NMCT+pWEOkn5b
     9tiWWBaIuj+n4LoCLrZlNgQHWOKanUG9G5l2+wPw97ELBDaOEAtRb5PnLt+TxIP8A/
     SzK+bUwQ14DjY91bTDC3UBpgQ1QEtl+3L4VQa7N8tL1DByF4kOlB5N5oHpaRTOUHGc
     pitcJQ9rm2YdcMUD5vD6/EbMmCfiMkISkAfAuU8kakD3aQvFfXQ8XhrnRsK3gvv9pP
     1VTQnuHUTEoqjJb/nO9rpOdt7v0HSpxluTXt1qrTbBTXiIYhyvehnOoh4+a4VXm6sd
     VnTs1M29NeTDg==
Received: from inbox.mydomain.tld (localhost [127.0.0.1])
    (using TLSv1 with cipher ECDHE-RSA-AES256-SHA (256/256 bits))
    (No client certificate requested)
    by mail.mydomain.tld (Postfix) with ESMTPSA id 3C4609FA9D
    for <email@example.com>; Thu, 24 Nov 2016 17:30:55 +0330 (IRST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain.tld;
    s=mail; t=1479996055;
    bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;
    h=Date:From:To:Subject:From;
    b=SbPcmZtuc54ZqmGYCU/O5kzKUPdN3x3qNS+EneBYPtD4HKIXCNJ4NMCT+pWEOkn5b
     9tiWWBaIuj+n4LoCLrZlNgQHWOKanUG9G5l2+wPw97ELBDaOEAtRb5PnLt+TxIP8A/
     SzK+bUwQ14DjY91bTDC3UBpgQ1QEtl+3L4VQa7N8tL1DByF4kOlB5N5oHpaRTOUHGc
     pitcJQ9rm2YdcMUD5vD6/EbMmCfiMkISkAfAuU8kakD3aQvFfXQ8XhrnRsK3gvv9pP
     1VTQnuHUTEoqjJb/nO9rpOdt7v0HSpxluTXt1qrTbBTXiIYhyvehnOoh4+a4VXm6sd
     VnTs1M29NeTDg==
MIME-Version: 1.0
Content-Type: text/plain; charset=US-ASCII;
 format=flowed
Content-Transfer-Encoding: 7bit
Date: Thu, 24 Nov 2016 17:30:55 +0330
From: firstname.lastname@example.com
To: =?UTF-8?Q?=D8=B4=D8=A8=DA=A9=D9=87_=D9=87=D9=85=D8=B1=D8=A7=D9=87_?=
 =?UTF-8?Q?=D8=AF=D8=A7=D9=86=D8=B4?= <email@example.com>
Subject: DKIM algorithm with 2048 key
Message-ID: <firstname.lastname@example.com>
X-Sender: email@example.com
User-Agent: Roundcube Webmail/1.1.6
X-AV-Checked: ClamAV using ClamSMTP

TEST

and sending to email@example.com responded with this report:
This message is an automatic response from Port25's authentication verifier
service at verifier.port25.com.  The service allows email senders to perform
a simple check of various sender authentication mechanisms.  It is provided
free of charge, in the hope that it is useful to the email community.  While
it is not officially supported, we welcome any feedback you may have at
<firstname.lastname@example.com>.

Thank you for using the verifier,

The Port25 Solutions, Inc. team

==========================================================
Summary of Results
==========================================================
SPF check:          pass
DomainKeys check:   neutral
DKIM check:         pass
DKIM check:         pass
SpamAssassin check: ham

==========================================================
Details:
==========================================================

HELO hostname:  mail.mydomain.tld
Source IP:      18.104.22.168
mail-from:      firstname.lastname@example.com

----------------------------------------------------------
SPF check details:
----------------------------------------------------------
Result:         pass
ID(s) verified: email@example.com
DNS record(s):
    mydomain.tld. SPF (no records)
    mydomain.tld. 14400 IN TXT "v=spf1 a mx ip4:184.108.40.206 ~all"
    mydomain.tld. 14400 IN A 188.8.131.52
    mydomain.tld. 14400 IN MX 10 mail.mydomain.tld.
    mail.mydomain.tld. 14400 IN A 220.127.116.11

----------------------------------------------------------
DomainKeys check details:
----------------------------------------------------------
Result:         neutral (message not signed)
ID(s) verified: firstname.lastname@example.com
DNS record(s):

----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         pass (matches From: firstname.lastname@example.com)
ID(s) verified: header.d=mydomain.tld
Canonicalized Headers:
    date:Thu,'20'24'20'Nov'20'2016'20'13:33:53'20'+0330'0D''0A'
    from:email@example.com'0D''0A'
    to:firstname.lastname@example.com'0D''0A'
    subject:DKIM'20'algorithm'20'with'20'2048'20'key'0D''0A'
    in-reply-to:<firstname.lastname@example.com>'0D''0A'
    references:<firstname.lastname@example.com>'0D''0A'
    dkim-signature:v=1;'20'a=rsa-sha256;'20'c=relaxed/simple;'20'd=mydomain.tld;'20's=mail;'20't=1479981833;'20'bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;'20'h=Date:From:To:Subject:In-Reply-To:References:From;'20'b=

Canonicalized Body:
    TEST'0D''0A'

DNS record(s):
    mail._domainkey.mydomain.tld. 14400 IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArPpOXRz6vYf19XExCZ528I7s3EOR4YJYdsq0w8QQhbd8coDXOTpoK8rdMhcgvX+X/fvP2R9uEBP7y2U53Y312CsP4vfrAFUIRvqP28PGeN55dpCtfN603xURrTp4ee0qPkdC3N3aVrbnHLgDOiFZcrncHAXkOc7H1dsMs6ARj+qLrRjyrj7+MyCw6R49exhC0bhoHTuglhd7zivVKytt/ySaUZANDKBKFhLWATBLAHS98PtYWVieTeSA2oDCn+IKgDD5RZYECNe0VXhbMh+hrbpcKfsmZWsCtx0PH+Aoe22idd241vkkp4MZqqwY8nsb0uYmCKZgcTB8teMgzz1bfwIDAQAB"

Public key used for verification: mail._domainkey.mydomain.tld (2048 bits)

NOTE: DKIM checking has been performed based on the latest DKIM specs
(RFC 4871 or draft-ietf-dkim-base-10) and verification may fail for
older versions.  If you are using Port25's PowerMTA, you need to use
version 3.2r11 or later to get a compatible version of DKIM.

----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         pass (matches From: email@example.com)
ID(s) verified: header.d=mydomain.tld
Canonicalized Headers:
    date:Thu,'20'24'20'Nov'20'2016'20'13:33:53'20'+0330'0D''0A'
    from:firstname.lastname@example.com'0D''0A'
    to:email@example.com'0D''0A'
    subject:DKIM'20'algorithm'20'with'20'2048'20'key'0D''0A'
    in-reply-to:<firstname.lastname@example.com>'0D''0A'
    references:<firstname.lastname@example.com>'0D''0A'
    dkim-signature:v=1;'20'a=rsa-sha256;'20'c=relaxed/simple;'20'd=mydomain.tld;'20's=mail;'20't=1479981833;'20'bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;'20'h=Date:From:To:Subject:In-Reply-To:References:From;'20'b=

Canonicalized Body:
    TEST'0D''0A'

DNS record(s):
    mail._domainkey.mydomain.tld. 14400 IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArPpOXRz6vYf19XExCZ528I7s3EOR4YJYdsq0w8QQhbd8coDXOTpoK8rdMhcgvX+X/fvP2R9uEBP7y2U53Y312CsP4vfrAFUIRvqP28PGeN55dpCtfN603xURrTp4ee0qPkdC3N3aVrbnHLgDOiFZcrncHAXkOc7H1dsMs6ARj+qLrRjyrj7+MyCw6R49exhC0bhoHTuglhd7zivVKytt/ySaUZANDKBKFhLWATBLAHS98PtYWVieTeSA2oDCn+IKgDD5RZYECNe0VXhbMh+hrbpcKfsmZWsCtx0PH+Aoe22idd241vkkp4MZqqwY8nsb0uYmCKZgcTB8teMgzz1bfwIDAQAB"

Public key used for verification: mail._domainkey.mydomain.tld (2048 bits)

NOTE: DKIM checking has been performed based on the latest DKIM specs
(RFC 4871 or draft-ietf-dkim-base-10) and verification may fail for
older versions.  If you are using Port25's PowerMTA, you need to use
version 3.2r11 or later to get a compatible version of DKIM.

----------------------------------------------------------
SpamAssassin check details:
----------------------------------------------------------
SpamAssassin v3.4.0 (2014-02-07)

Result:         ham  (-3.8 points, 5.0 required)

 pts rule name              description
---- ---------------------- --------------------------------------------------
-0.0 SPF_PASS               SPF: sender matches SPF record
-2.9 RP_MATCHES_RCVD        Envelope sender domain matches handover relay domain
-1.9 BAYES_00               BODY: Bayes spam probability is 0 to 1%
                            [score: 0.0000]
-0.1 DKIM_VALID_AU          Message has a valid DKIM or DK signature from author's
                            domain
 0.1 DKIM_SIGNED            Message has a DKIM or DK signature, not necessarily valid
-0.1 DKIM_VALID             Message has at least one valid DKIM or DK signature
 1.1 BODY_SINGLE_WORD       Message body is only one word (no spaces)

==========================================================
Explanation of the possible results (from RFC 5451)
==========================================================

SPF and Sender-ID Results
=========================

"none"
      No policy records were published at the sender's DNS domain.

"neutral"
      The sender's ADMD has asserted that it cannot or does not
      want to assert whether or not the sending IP address is authorized
      to send mail using the sender's DNS domain.

"pass"
      The client is authorized by the sender's ADMD to inject or
      relay mail on behalf of the sender's DNS domain.

"policy"
     The client is authorized to inject or relay mail on behalf
      of the sender's DNS domain according to the authentication
      method's algorithm, but local policy dictates that the result is
      unacceptable.

"fail"
      This client is explicitly not authorized to inject or
      relay mail using the sender's DNS domain.

"softfail"
      The sender's ADMD believes the client was not authorized
      to inject or relay mail using the sender's DNS domain, but is
      unwilling to make a strong assertion to that effect.

"temperror"
      The message could not be verified due to some error that
      is likely transient in nature, such as a temporary inability to
      retrieve a policy record from DNS.  A later attempt may produce a
      final result.

"permerror"
      The message could not be verified due to some error that
      is unrecoverable, such as a required header field being absent or
      a syntax error in a retrieved DNS TXT record.  A later attempt is
      unlikely to produce a final result.

DKIM and DomainKeys Results
===========================

"none"
      The message was not signed.

"pass"
      The message was signed, the signature or signatures were
      acceptable to the verifier, and the signature(s) passed
      verification tests.

"fail"
      The message was signed and the signature or signatures were
      acceptable to the verifier, but they failed the verification
      test(s).

"policy"
      The message was signed but the signature or signatures were
      not acceptable to the verifier.

"neutral"
      The message was signed but the signature or signatures
      contained syntax errors or were not otherwise able to be
      processed.  This result SHOULD also be used for other
      failures not covered elsewhere in this list.

"temperror"
      The message could not be verified due to some error that
      is likely transient in nature, such as a temporary inability
      to retrieve a public key.  A later attempt may produce a
      final result.

"permerror"
      The message could not be verified due to some error that
      is unrecoverable, such as a required header field being
      absent. A later attempt is unlikely to produce a final result.

==========================================================
Original Email
==========================================================

Return-Path: <firstname.lastname@example.com>
Received: from mail.mydomain.tld (184.108.40.206) by verifier.port25.com id h6qtgq20i3gp for <email@example.com>; Thu, 24 Nov 2016 05:03:56 -0500 (envelope-from <firstname.lastname@example.com>)
Authentication-Results: verifier.port25.com; spf=pass email@example.com
Authentication-Results: verifier.port25.com; domainkeys=neutral (message not signed) firstname.lastname@example.com
Authentication-Results: verifier.port25.com; dkim=pass (matches From: email@example.com) header.d=mydomain.tld
Authentication-Results: verifier.port25.com; dkim=pass (matches From: firstname.lastname@example.com) header.d=mydomain.tld
Received: from mail.mydomain.tld (localhost [127.0.0.1])
    by mail.mydomain.tld (Postfix) with ESMTP id C4A449FA85
    for <firstname.lastname@example.com>; Thu, 24 Nov 2016 13:33:53 +0330 (IRST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain.tld;
    s=mail; t=1479981833;
    bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;
    h=Date:From:To:Subject:In-Reply-To:References:From;
    b=kbHJbY6k1nmQ0KmNL1ZsqQ9YP31Xdv3sfqzqJTriHrtiIO06Z4hHCsFYbrHTHL579
     tsVcPhAxLA4vxnZgASlQpYOhuJvUDe3C4EtPAjUA+9Tof1wbSeqWYFnHDHvRz4bbkP
     YKfg582YsITfw6ENEua0xKgw+ogFknWKLyeXfJXCxidO7MuNBgIWJdhYajTUmr/+WY
     yVg6D6StgiJl6tNS0U2C1qghvI/HF9wxan6+Uy8B4iTmuErzBCGly+hCbbdcl/MQOA
     sLAzh/HbsnxuOJj37QLPIpj5+dblKpAhmmR+jIQD8sAU2dCi6PvSAsYq8eOd4sgnB4
     +s9FmHfDamEJg==
Received: from inbox.mydomain.tld (localhost [127.0.0.1])
    (using TLSv1 with cipher ECDHE-RSA-AES256-SHA (256/256 bits))
    (No client certificate requested)
    by mail.mydomain.tld (Postfix) with ESMTPSA id 9D4589F9B8
    for <email@example.com>; Thu, 24 Nov 2016 13:33:53 +0330 (IRST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain.tld;
    s=mail; t=1479981833;
    bh=q5cyARPl5zX/knmvCnEy11G7/r6gcljJ44qrvv5DErY=;
    h=Date:From:To:Subject:In-Reply-To:References:From;
    b=kbHJbY6k1nmQ0KmNL1ZsqQ9YP31Xdv3sfqzqJTriHrtiIO06Z4hHCsFYbrHTHL579
     tsVcPhAxLA4vxnZgASlQpYOhuJvUDe3C4EtPAjUA+9Tof1wbSeqWYFnHDHvRz4bbkP
     YKfg582YsITfw6ENEua0xKgw+ogFknWKLyeXfJXCxidO7MuNBgIWJdhYajTUmr/+WY
     yVg6D6StgiJl6tNS0U2C1qghvI/HF9wxan6+Uy8B4iTmuErzBCGly+hCbbdcl/MQOA
     sLAzh/HbsnxuOJj37QLPIpj5+dblKpAhmmR+jIQD8sAU2dCi6PvSAsYq8eOd4sgnB4
     +s9FmHfDamEJg==
MIME-Version: 1.0
Content-Type: text/plain; charset=US-ASCII;
 format=flowed
Content-Transfer-Encoding: 7bit
Date: Thu, 24 Nov 2016 13:33:53 +0330
From: email@example.com
To: firstname.lastname@example.com
Subject: DKIM algorithm with 2048 key
In-Reply-To: <email@example.com>
References: <firstname.lastname@example.com>
Message-ID: <firstname.lastname@example.com>
X-Sender: firstname.lastname@example.com
User-Agent: Roundcube Webmail/1.1.6
X-AV-Checked: ClamAV using ClamSMTP

TEST

Would you help me please?
Thanks
Comment: @DonnLee I added the result to the question, thank you
Comment: Try sending a blank email to firstname.lastname@example.com
It will reply with a report.  There's a section for SpamAssassin scores, which gives you some feedback on your spaminess.
Answer: For anyone who is excited about this,
My problem was solved without any action from me after about 2 months. So I can guess that it was about my domain reputation. If you have the same problem I suggest you to wait for a while. In addition you can send some messages from your newly configured server to some recipient you know and you trust. Ask them to add this email address to their contacts. It will make some authority for your sever and may make the process faster.
Good luck


dynamic link to view page

Question: So i have set up a page view which has the path about/% with % representing the argument used in that view. I now want to link to this page on the main navigation bar.
I created a menu item  about/%dest but that didnt work as i guess the route is already registered by the view? so i altered it to look like this:
<code>$items['%dest/about']= array(
  'page callback' => '_bps_path_redirect',
  'page_arguments' => 'about',
  'title' => 'about',
  'title callback' => 'get_title',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu',
);

function dest_to_arg() {
  $arg = arg(1);
  return $arg;
}

function _bps_path_redirect($arg) {
  drupal_goto($arg.'/'.arg(1));
}
</code>
But to no success, the redirect doesn't work. So am i missing something? Is there a simple way to link a view which has a wildcard in its path?
Answer: Solved. I modified the page views to use a static path and then set up a contextual argument to grab the parameter of the url to use as an argument.

dynamic link to view page


Set the value of a date field

Question: I am trying to set the value of a user field which is a date. If i check the database, the date is in this format:
2016-06-30T07:52:51
I have the user ID and a new Unix timestamp value that I want to overwrite the existing value with.
The following shows no error messages but does not change the date
$account = \Drupal\user\Entity\User::load($email_result); // pass your uid
$account->set('field_expiry_date',strval(date('c',($new_expiry))));

//$field = $account->field_expiry_date;
//$field->set(date('c',($new_expiry)));
//$field = $account->get('field_expiry_date');
//$field->setValue(date('c',($new_expiry)));

What is wrong with this code?
Comment: Are you sure the code is called?  What function is this code within?
Comment: Positive. It's directly underneath a database insert (to a different table) and a `drupal_set_msg`, both of which work. The function is within a public function `submitForm` on a Config Form
Answer: The problem is more than likely that the 'c' format includes the timezone, which is not (currently) included in storage.
The storage format for fields that have both date and time is defined by the datetime module as DateTimeItemInterface::DATETIME_STORAGE_FORMAT, which is 'Y-m-d\TH:i:s'.
Something like this will work:
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\Entity\User;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

$date = DrupalDateTime::createFromTimestamp($new_expiry, 'UTC');
$account = User::load($email_result);
$account->field_expiry_date->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
  'timezone' => 'UTC',
]);
$account->save();

Just remember that date+time values in storage are implicitly UTC, so if you are setting the value manually, you need to ensure that what you are saving represents what you want, but converted to UTC.

Set the value of a date field


what is the data received from OBD device and what is its form?

Question: me and group of colleges are working on app that connects to OBD device and displays that data after working on it, but we are facing a problem on understanding what is the data received by the phone if it connects with the device via Bluetooth and its form.
after some research all we could find was that data can be of hexa form but that did not help us to fully understand the process.
if someone can kindly help us with some resources or description that would be appreciated.
Comment: There are different OBD protocols: https://www.csselectronics.com/pages/obd2-explained-simple-intro Does your OBD device provide documentation?
Answer: OBD2 itself is documented in various ISO standards, which you probably want to obtain and read. The guts of it is a protocol where you send a PID to an ECU and receive the result. Different PIDs have different meanings and are encoded in a certain fashion, which you can learn from the ISO standard (or Wikipedia, which contains an excerpt).
Since you have mentioned Bluetooth, you probably have a generic serial adapter based on an ELM327. In that case you need to learn about the ELM327-compatible AT commands which are necessary to setup the communication and adjust the addressing.


Determining domain and range with inverse function

Question: $$f\left(\frac{1-x}{1+x}\right)=x+2$$
In this function,i have to calculate the domain and range as well as its inverse function.
I have tried to do in this way:
Let $p=(\frac{1-x}{1+x})$.
After some calculations, I found that $f(p)=\frac{3+p}{p+1}$.
This shows the domain must be all real numbers except $(-1)$
Is it correct or not?
Comment: Use mathjax formatting
Answer: Yes mate,you are right About the domain it's$\mathbb{R}-\{-1\}$
And range is $\mathbb{R}-\{1\}$
The inverse function$f^{-1}:$$\mathbb{R}-\{1\}\rightarrow \mathbb{R}-\{1\} $such that $f^{-1}(x)=\frac{3-x}{x-1}$
Comment: well i calculated that the domain would be all real number except(-1) but you wrote all real number except 1.
Comment: Sorry , forget to input the $(-)$ sign.see the answer if it's okay..
Comment: Yeah,now it is ok


Locally installed TYPO3 doesn't load TypoScript record edit

Question: I'm new to development and just started with a local TYPO3 installation on my Mac. I've installed PHP 8.2 with home-brew on this computer and after that installed TYPO3 for my localhost. Everything works fine except the part of 'edit the whole TypoScript record'.
When clicking on that the page is loading infinity, without endings, nothing happens here.
Any advice what I could do? Already asked google for that problem but have found nothing at least. Hopefully someone could help me out here.

Ive tried to google my problem - no results. Already edited the php.ini as TYPO3 installation was recommended.
Comment: Your browser console should give you an idea what's going wrong as it's certainly a JavaScript or CSP (content security policy) problem.
Comment: Btw. It's a TypoScript record, that's different than Typescript, they exist both and need to be distinguished. There aren't any Typescript records at all though, Typescript is used in files only.
Comment: As recommended by David please check the browser console. Further more, check the logs in the TYPO3 backend and in var/logs/ of your installation. For local development you should use something like [DDEV](https://ddev.com/). That's much more convenient.
Answer: Try using another browser! I had the exact same issue only on my server online. Did you use Safari by any chance? When i switched to Firefox everything was loading as it should!


How do I add extra/custom plugins in CKEditor?

Question:
I am copying the templates plugin http://ckeditor.com/addon/templates
I put    it in my D8 folder /core/asstes/vendor/ckeditor/plugins
I do a 'drush    cr'

I do not see the templates plugin under available buttons in my text format
How do I get the templates plugin to show up?
Comment: While this worked in D7, for D8 I think you have to create a custom module.
Comment: take a look at the 2nd last comment here https://www.drupal.org/node/2618278
Answer: You have to build a plugin in Drupal using the CKEditor classes in the CKEditor module in core, it is not an automatic integration.
Check some of the existing modules that integrate plugins for examples on how to do this.
Checkout:

CodeSnippet
Color Button
Panel Button
Comment: Slow progress.  Noticing that the ckeditor_font module together with the font add-on from ckeditor.com works so well,  I created a ckeditor_templates based on the ckeditor_font module, module and put the Content Templates add-on from ckeditor into d8site/library/  This works! I can see the templates when creating content.  But when I remove or add new templates to the D8site/library/templates/templates/default.js,  I do NOT see my changes.
Comment: the templates add-on was placed in the d8site/libraries folder
Comment: I have noticed that there is a particular quirk with caching of CKEditor plugins where clearing Drupal cache or cache-rebuild does not get new changes to plugin js. I verified by comparing my source in my browser to the JS file, even with aggregation off. Try seeing if your updated plugin code is in the JS file the browser sees.
Comment: FYI - Got it working!!!!  In the file d8site/lbraries/templates/plugin.js on line 81, I changed the path to point to '/libraries/templates/templates/default.js'  and that made use my templates file.
Comment: Hm, not familiar with why the CKEditor plugin would need modification, but welcome to the quick world of plugin integration. Contribute back on d.o. If it is useful.
Comment: The content of d8sites/libraries/ckeditor should be managed with drush/drupal commands that CKEditor exposes to you (each library is mapped with a module that command with it's own commands). CKEditor has its versioning, Drupal CKEditor module has its versioning, and each CKEditor plugin has its versioning. Thats why you can not work with raw CKEditor and should follow integration Drupal guidance for each plugin.


How to Process PayPal Subscription Refund With API?

Question: After proceeding with the subscription to Sandbox, the data below will be answered.
<code>orderID:3MA30854KN5622241
subscriptionID:I-E1DY12BAWXD1
</code>
With the above information, it is possible to suspend the subscription, but it does not appear to be refundable for the subscription.
API
https://api-m.paypal.com/v1/billing/subscriptions/{id}
I checked if there was any information if I searched for subscription information, but I couldn't find a way to process a subscription refund in the response value, so I'm asking for your help.
If a refund is originally impossible, I would appreciate it if you could let me know that it is impossible.
Thank you.
How to handle PayPal subscription cancellation and refund processing with API
Comment: Where exactly is `3MA30854KN5622241` from? Show the precise location and time you obtained this.
Comment: "npmi @paypal/react-paypal-js" response..
Answer: Here is what should work...
Query transactions on the profile with the List transactions for subscription API. Note that start_time and end_time are required query string parameters , e.g. as per the sample

https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G/transactions?start_time=2018-01-21T07:50:20.940Z&end_time=2018-08-21T07:50:20.940Z

The response will have transaction IDs (which are not order IDs)
Transaction IDs are the same as captures or sales, and should be usable with one of the refund API operations...

v2: https://developer.paypal.com/docs/api/payments/v2/#captures_refund
older v1: https://developer.paypal.com/docs/api/payments/v1/#sale_refund


Can ADMM be applied to optimisation with matrix variables and inequality constraint?

Question: Can ADMM be applied to optimisation with matrix variables and inequality constraint? If so, how may I do it? My optimisation problem looks something like this:
\begin{align}
\min_{X \in \mathbb{R}^{n \times n}} \quad & \|Xv \|_2 + \|X\|_F^2 \\
\quad &\text{Tr}(AX) \geq \text{Tr}(B)
\end{align}
where $v \in \mathbb{R}^n$, $A,B \in \mathbb{R}^{n \times n}$ are known constant vector and matrices.
Thanks a lot!
Answer: Honestly, I do not see big issues here. Assume $n=2$ to clarify the ideas, and set $$ v = \begin{pmatrix} v_1 \\ v_2 \end{pmatrix}, \ A= \begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{pmatrix}, \ B= \begin{pmatrix} b_{11} & b_{12} \\ b_{21} & b_{22} \end{pmatrix}, \ X= \begin{pmatrix} x_{11} & x_{12} \\ x_{21} & x_{22} \end{pmatrix}.  $$Then $$ \|Xv\|_2 + \|X\|_F ^2  = \sqrt{ (v_1 x_{11} + v_2 x_{12} )^2 + (v_1 x_{21} + v_2 x_{22})^2 }+ x_{11} ^2 + x_{12} ^2 + x_{21} ^2 + x_{22} ^2, $$ $$\text{Tr}(AX) = a_{11} x_{11} + a_{12} x_{21} + x_{22} a_{22} + a_{21} x_{12} $$ and $$\text{Tr}(B)=b_{11} + b_{22}. $$
Then you want to minimize a nonlinear objective function (differentiable almost everywhere, but maybe you wanted $\|Xv\|_2 ^2$ instead?) under linear inequality constraints. This paper briefly explains how ADMM can deal with linear inequality constraints.


Most appropriate analysis method - Clustering?

Question: I have 2 large data frames with similar variables representing 2 separate surveys. Some rows (participants) in each data frame correspond to the other and I would like to link these two together.
There is an index in both dataframes though this index indicates locality of the survey (i.e region) and not individual IDs.
Merging is not possible as in most cases there is an identical index values for different participants.
Given that merging on an index value from the 2 data frames is not possible, I wish to compare similar variables (binary) from both data frames that (in addition to the index values common to both data frame) in order to give me a highest likelihood of a match. I can then (with some margin of error) match rows with the most similar values for similar variables and merge them together.
What do you think would be the appropriate method for doing this? Clustering?
Best,
James
Answer: That obviously is not clustering. You don't want large groups of records.
What you want to do is an approximate JOIN.


Is $0$ a cluster point of the set $\{0\}$?

Question: I just read the theorem

A subset of R is closed if and only if it contains all of its cluster points.

And I found that the set {0} is closed (Is that correct?), then the set {0} should contains all its cluster points, right? But I just checked the definition of cluster point in the textbook (it appears at the beginning of the limit of function) and found that 0 is not the cluster point of the set {0}
I want to know where the false is ?
Comment: Post the definition of "cluster point" in your book.
Comment: Do you think that the set is not closed? If yes then can you give a cluster point which is not in the set?      The definition says that A set is closed iff it contains all its cluster point. If 0 is not the cluster point then why do you even worry about it?
Comment: I got it ! I just thought 0 "should" be a cluster point of the set .Then the set does not have a cluster point, right? Thank you. But wait a minute, the set {0} contains the element 0 !
Comment: I think it appears at the answer provided by Anthony Ter .
Comment: @YangGao The set {0}  contains the element 0! Yes, It contains. So what?
Comment: @YangGao Why 0 should be a cluster point and why do you feel like that?
Answer: If $0$ was a cluster point of $\{0\}$ then for every $\delta > 0$ there would exist an $x \neq 0, x \in N_\delta(0)$ such that $x \in \{0\}$. clearly no such $x$ exists, for any $\delta$. Thus $0$ is not a cluster point of $\{0\}$.
So is $\{0 \}$ closed? Does it contain all of its limit points? Well, $\emptyset \subseteq \{0\}$, so $\{0\}$ is closed.
Comment: No,the empty set isn't a point. The empty set represents the set of limit points, and I was trying to show that that set is contained in $\{0\}$. I should have used $\subseteq$, not $\in$. I'll edit it now.
Comment: So the set does not have a cluster point ? wow
Comment: Thanks. Now I really get it . The closed set contains all of its cluster point but not all of its elements! Thank you!
Comment: Now the empty set is the only cluster point of the set, right? Just a little "weird".
Comment: Yep, in fact, no finite subset of $\mathbb{R}$ has a cluster point.
Comment: The finite subsets of R are closed, but they don't have any cluster point. So should the theorem I mentioned in the question have a premise that the set have at least cluster point? Thank you very much!!
Comment: You can do that, but it would be redundant. The set is closed iff it contains all its limit points, so if there are no limit points to begin with, the set will be closed.
Comment: I got it.Thank you!


Alternatives to Marching with Bassoon

Question: Situation: I am currently a bassoon player, and I am in marching band. I have marched only once with the bassoon before, and I know that the bassoon is both unsafe and impractical for marching. After mentioning this to my director, he said that I can choose a different instrument to play during marching season, and play bassoon the rest of the year.
Question: I have been considering clarinet, tenor saxophone, or percussion. I played clarinet for half a year before switching to bassoon. I am looking for suggestions on which one I should play (considering that clarinet/tenor saxophone would mess up my embouchure). What are the pros/cons of each?
Thanks.
Comment: If I remember the fingerings correctly, clarinet is similar to bassoon in terms of construction, whereas playing tenor might actually mess you up (because it would almost be like you reversed hands.)  A common misconception is that similarities between instruments make them hard to learn, but in truth, it actually makes them easier as you are able to create more neurological connections between concepts.  Honestly, I would not recommend brass as it would be too different and the learning curve too steep for the time you have. That said, I would highly recommend you ask your music teacher to...
Comment: yes, I know, I was typing a second comment when my computer restarted suddenly, and I just never got around to typing the other comment.  Basically, I was just going to add that you should try each of the instruments your teacher recommended and see which one you respond best to.  In the end, what we say here will only apply so far - what really matters is how you respond to the instrument. Embouchure is fluid, so don't worry about messing it up.
Comment: I'm with jjmusicnotes here: play the clarinet or sax because they're closer to your main instrument. There are advantages to learning sax (octave fingerings) vs. clarinet (octave+fifth fingerings) in the sense that it'll help you in transposing music later on.   Hey it could be worse- remember Woody Allen marching w/ a cello?
Answer: Have you considered a brass instrument like trombone or euphonium? For me, the embouchures share some important characteristics, while still being distinct enough that one shouldn't mess up the other.
If you are an advanced player and plan on pursuing music as a career, I would highly recommend continuing to practice bassoon throughout marching season, while doubling on one of those brass instruments for marching -- see it as a challenge with great payoff for your musicianship.
If you are not such an advanced player, then I think percussion would be the best choice -- you should still practice bassoon throughout the year, but for marching, you won't get messed up by the similarity of a different woodwind instrument, and it'll be GREAT for your sense of rhythm.
If the choice is already narrowed down between clarinet and tenor sax for whatever reason, I think clarinet would probably have the more distinct embouchure due to the angle of the mouthpiece. But to reiterate for the 3rd time, KEEP PLAYING BASSOON throughout marching season! Equal practice time to both instruments would be ideal.
Answer: Choose whichever instrument you believe you will find most joyous to play! This is to ensure that you will enjoy spending time practicing. Spending time practicing something you don't enjoy I believe will be bad for your overall joy of practicing music. I think all other aspects are of minor importance to this.
In my opinion the only thing that would mess up your bassoon playing from playing another instrument (including the embouchure aspect) would be if you cut down on your bassoon practicing time. You need to reallize that to reach a certain technical level you need to spend just as much practice time each on each instrument as you would for the one instrument (except for instruments that are very closely related such as perhaps alto- and tenorsaxophone). Regarding other aspects such as ear training, music theory and understanding, and to some extent sight reading, there will however be synergy effects.
As an inspiration on the possibility of mastering several instruments here's a video with Australian multiinstrumentalist James Morrison playing a "few" of the instruments that he's proficient on:

As for mastering two instruments on a world class level in the classical genre check out for instance violinist and pianist Julia Fischer.
(Granted these examples aren't of persons combining bassoon with another single reed instrument, but my point is that the instrument doesn't matter - only the time and/or effort spent on each instrument matters.)
Answer: I went from clarinet to bassoon in high school. The fingerings are very similar, just less thumb keys on a clarinet. Keep practicing the bassoon though otherwise you'll lose your upper lip strength. I moved away from the clarinet because of all the squeaky high notes. When I marched, I usually played the bass clarinet. I would go with whatever you like the sound of
~D~

Alternatives to Marching with Bassoon