text:
Q: ViewPager tabs handling I have some problems with rendering of pages of a ViewPager with Tabs into the ActionBar.
Example:

Android info: minimum API 19, compile API 21 (Using AppCompat)

Main layout (main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.MainFragment">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

MainFragment:
public class MainFragment extends Fragment {
private ViewPager viewPager;
private PagerTabsAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs;
private int startIn;

MainActivity main;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    main = (LessonsScheduler) getArguments().get("instance");
    tabs = new String[]{"1","2","3"};
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.main, container, false);
}

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if(!main.getSupportActionBar().isShowing())
        main.getSupportActionBar().show();

    viewPager = (ViewPager) main.findViewById(R.id.pager);
    actionBar = main.getSupportActionBar();

    // Getting item array
    mAdapter = new PagerTabsAdapter(getChildFragmentManager(), main.getGroups());
    viewPager.setAdapter(mAdapter);

    actionBar = main.getSupportActionBar();
    //Enable Tabs on Action Bar
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ActionBar.TabListener tabListener = new ActionBar.TabListener(){
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            viewPager.setCurrentItem(tab.getPosition());
        }
        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        }
        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        }
    };
    if (actionBar.getTabCount() == 0) {
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab()
                    .setText(tab_name)
                    .setTabListener(tabListener));

        }
    }
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}
}

When i click tab buttons my viewpager doesn't change. I already tested invalidate(), requestLayout(), forceLayout() but these doesn't works.

Line of code to test:
viewPager.setCurrentItem(tab.getPosition());

A: Currently I'm using TabLayout (thanks @Wizard). It seems to work with old APIs.
I'm still open for new ideas.


text:
Q: On constant global variables In c++ programming I want to create a global variable that can be used in  every function without explicitly passing this variable (E.g., main calls f1, which calls f2, which calls f3, which uses this variable. Passing all the way down just makes no sense!)
However this variable is input by the user in main. (So it can't simply be a const variable outside the main function.) Also, I don't want anyone to be able to change it after the input (but anyone can read it). Is there a way to implement this variable?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cache Layers in GitLab Runner Docker Executor - Long Time DinD Container I'm working on GitLab CI at my project, and I created an image to make my tests and builds. When I ran it in docker executor every job needs to download images from the beginning. I need to cache layers and pulled images to improve my build and deploy time (5 min, up to 1 min with the insecure option).
I searched multiples links, and multiples articles, with many people with the same problem. But, the GitLab team does not resolve the problem. And the community doesn't have a solid and secure solution. The links below follow with the same problem:

*

*The best answer don't work: Store layers in gitlab ci docker executor

*Multiple changes to bypass the problem, but nothing work: https://blog.scottlogic.com/2018/02/09/multi-dind-ci-boxes.html

*Discussion for don't use mounted docker.sock: https://gitlab.com/gitlab-org/gitlab-foss/issues/17769

*Discussion for use mounted docker.sock: https://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/

*Build a container of long time (don't work with me): https://medium.com/@tonywooster/docker-in-docker-in-gitlab-runners-220caeb708ca

*Documentation for don't mounted docker.sock: https://docs.gitlab.com/ce/ci/docker/using_docker_build.html#use-docker-in-docker-executor

*Volumes config examples: https://github.com/ayufan/gitlab-ci-multi-runner/blob/master/docs/configuration/advanced-configuration.md#the-runnersdocker-section
The most likely approach (with layer caching) is to use a separate container and make the runner connect to it, and trigger executions from it. That way, all the layers would be in an "infinite life" container and not lose all cache at the end of a stage.
The approach that considers exposing docker.sock as a mount is not only insecure but also has many problems with sharing files between containers, since they are all siblings, not parents and children who share volumes.
The approach to using an infinite life container would look something like this:
docker run --privileged --name gitlab-dind -d --restart=always  docker:19-dind --storage-driver=overlay2

or
docker network create gitlab-runner-net

docker run --privileged --name gitlab-runner-dind --network gitlab-runner-net --publish=2375:2375 --publish=2376:2376 -d docker:19-dind --storage-driver=overlay2

Then modify config.toml as follows:
[runners.docker]
  tls_verify = false
  image = "docker:19"   <--------
  privileged = false     <--------
  disable_cache = false
  volumes = ["/cache"]
  links = ["gitlab-runner-dind:docker"]   <-----------
  shm_size = 0
[runners.cache]

or respectively
[runners.docker]
  host = "tcp://gitlab-runner-dind:2375"    <--------
  tls_verify = false
  image = "docker:19"   <--------
  privileged = true     <--------
  disable_cache = false
  volumes = ["/cache"]
  network_mode = "gitlab-runner-net"   <-----------
  shm_size = 0
[runners.cache]

I'm tried with environment variable too (on config.toml and .gitlab-ci.yml):
DOCKER_TLS_CERTDIR=""
DOCKER_HOST=tcp://gitlab-runner-dind:2375

And remove from .gitlab-ci.yml:
services:
  - docker:19-dind
  alias: docker

The my current result is:
Running with gitlab-runner 12.4.1 (HASH)
  on NAME_OF_MY_RUNNER HASH
ERROR: Preparation failed: error during connect: Get http://gitlab-runner-dind:2375/v1.25/info: dial tcp: lookup gitlab-runner-dind on 172.31.0.2:53: no such host (executor_docker.go:980:0s)
Will be retried in 3s ...
ERROR: Preparation failed: error during connect: Get http://gitlab-runner-dind:2375/v1.25/info: dial tcp: lookup gitlab-runner-dind on 172.31.0.2:53: no such host (executor_docker.go:980:0s)
Will be retried in 3s ...
ERROR: Preparation failed: error during connect: Get http://gitlab-runner-dind:2375/v1.25/info: dial tcp: lookup gitlab-runner-dind on 172.31.0.2:53: no such host (executor_docker.go:980:0s)
Will be retried in 3s ...
ERROR: Job failed (system failure): error during connect: Get http://gitlab-runner-dind:2375/v1.25/info: dial tcp: lookup gitlab-runner-dind on 172.31.0.2:53: no such host (executor_docker.go:980:0s)

Using mounted docker.sock it works. But it is insecure, and the volumes have many problems to share files, artifacts, and cache.
root@GitlabRunner:/etc/gitlab-runner# gitlab-runner --version
Version:      12.4.1
Git revision: 05161b14
Git branch:   12-4-stable
GO version:   go1.10.8
Built:        2019-10-28T12:49:57+0000
OS/Arch:      linux/amd64

A: Maybe its better, when you use kaniko. Its not good, when you build with dind. (danger note @ gitlab reference)
kaniko offers the opportunity to use a cache-mechanism from the repository. kaniko@github
The only thing you need is a repository somewhere (I recommend Artifactory). With Artifactory you can also cache via the dind (see here).


text:
Q: Modeling a potential well I attempted to simulate the interaction of a moving particle and a potential well in Mathematica. The particle should experience a force of -$1/r^2$, if the equation for the potential well is -$1/r$. The inputs for the NDSolve function are:
  x''[t] == -x[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2),
  y''[t] == -y[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2),
  x[0] == -2,
  y[0] == -2,
  x'[0] == 2 ,
  y'[0] == 2,

A kind of spiraling motion or trapping should happen when the particle approaching to the well in a certain angle. But it does not happen in this simple simulation. The particle must experiences some centrifugal force when it is close to the well so that its direction is changed. What other terms should be added to represent this force in the NDSolve function? Any idea or any help would be much appreciated.
What I got is:

What expected to see is:

By adopting the suggestions given below, the terms for the NDSolve were now modified as follows:
soln[a_, b_, alp_, sp_] := Return[First@NDSolve[{
      x''[t] == x[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2) - alp*x'[t],
      y''[t] == y[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2) - alp*y'[t],
      x[0] == -2,
      y[0] == -2,
      x'[0] == sp,
      y'[0] == sp},
     {x, y}, {t, 0, 3}]];

and sliders were added for adjusting. Still, no conic trajectory was observed. The
particle moves as if in a straight line from the top view.

A: UPDATED: See below.
Your NDSolve inputs seem to be doing what I would expect for a mass around a gravitational center. Using:
a = 0;
b = 0;
traj = Table[
   s = NDSolve[{x''[t] == -x[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2),
      y''[t] == -y[t]/((x[t] - a)^2 + (y[t] - b)^2)^(3/2), x[0] == 1,
      y[0] == 0, x'[0] == 0, y'[0] == v}, {x, y}, {t, -20, 20}];
   {x[t], y[t]} /. s,
   {v, 0.1, 2.1, 0.2}];
ParametricPlot[traj, {t, -20, 20}, PlotRange -> {{-3, 2}, {-4, 4}}]

where the gravitational center is at 0,0 and the mass is at (x,y)=(1,0) at t=0, I get  a series of bounded and (probably) unbounded orbits of various sizes over a range of initial velocities:

As @alemi stated, there will be no spiraling in unless you include a damping term. The orbits for this type of potential are either unbound (fly-in then fly-out) or are closed loops.
UPDATE: the force in the equations of motion as written is always radial from (x,y)=(0,0). The force should be in the direction (a,b)-(x,y). The correct equations of motion are:
{x''[t] == (a - x[t])/((x[t] - a)^2 + (b - y[t])^2)^(3/2) - alp*x'[t],
  y''[t] == (b - y[t])/((x[t] - a)^2 + (y[t] - b)^2)^(3/2) -
   alp*y'[t], x[0] == -2, y[0] == -2, x'[0] == sp, y'[0] == sp}

Notice the shift by 'a' and 'b' in the numerators, not just the distance calculation in the denominator. The equations worked in my test because I placed the potential well at (0,0) and moved the mass off axis.

A: If your potential is $\propto 1/r$, you're effectively simulating gravity.  If it gives you better intuition, imagine it as the earth around the sun.
As long as your numerical solver is doing a decent job, you shouldn't expect the ball to spiral in, the correct solution would be a conic section, that is it would orbit the origin in an elliptical path if the initial conditions equate to a bound energy, or a hyperbolic one if the initial conditions equate to an unbound energy. The sketches you post suggest you are in the unbound case, so, even to see orbits you need to decrease the magnitude of your initial velocities.
This is of course only true long as you were using a symplectic integrator (one that conserves energy, which I imagine Mathematica uses by default).  A weak integrator like simple Euler would have the ball spiral in, but this is a purely an effect of the poor integration.
If you truly want it to spiral in, you need to add some kind of viscous damping term
$$ \vec F = -\alpha \vec v$$
or something like air resistance, a force of the form
$$\vec F = -\alpha v^2 \hat v= -\alpha |v| \vec v$$
Additionally, after you're update, it is clear that you are still shooting nearly straight at the origin with too high a speed. It is as if you are modelling gravitational scattering, not orbits. You are varying your initial speed, not your initial velocity.  To be completely general, why don't you set
x'[0] == v0 Cos[th]
y'[0] == v0 Sin[th]

And play around with the v0 and th sliders separately to get a feel for what's going on.  Here the th variable will control the initial direction of your initial velocity and v0 will control the initial speed.
As for what value the initial speed should be, you can consider the initial energy to get a sense of the appropriate magnitude.  At $t=0$, you have
$$ E = \frac 12 v^2 -\frac{1}{r} $$
If this energy is positive, ignoring the damping, the particle is unbound and should just shoot off to infinity.  Try using the initial settings Jason A used in his answer.  Put the center of the potential at zero, have the particle start at $x(0) = 1, y(0) = 0$ and set $\dot x(0) = 0, \dot y(0) = v$, where $v$ is near 1 or so.


text:
Q: Accessing an instance variable from another class -- can I use a class method? I need to access to a NSMutableArray, in class1, from another class (class2). The solution I tried was to create a class method in class1 and call it from class2. Obviously, it is not possible because this is a restriction of class methods. I cannot figure out the solution. What can I do?

A: Not surprisingly, you need an instance in order to access an instance variable. You can make that instance a singleton if it fits your design, or make the variable you increment static rather than ivar, which will make it accessible directly from a class method.
If there are multiple instances that you need to access from a class method, you need some sort of a registry for your objects, such as an NSDictionary that maps your objects by keys.

A: Generally you expose needed instance variables through properties.
This link covers properties.
http://cocoacast.com/?q=node/103
Once the correct variables are exposed then simply pass a reference to the needed class to a given method.

A: Passing the instance variable to a class method as a parameter should solve the problem.
Edit: If class1 and class2 are just instances then you will need a class variable.


text:
Q: Ruby on Rails: adding columns to existing database I'm getting an error:
SQLite3::SQLException: no such column: ideas.list_id:
SELECT "ideas".* FROM "ideas"
WHERE "ideas"."list_id" = 2

But I added
t.integer :list_id
to my db migration file:
class CreateIdeas < ActiveRecord::Migration
  def change
    create_table :ideas do |t|
      t.string :name
      t.text :description
      t.string :picture

      t.timestamps
    end
    add_foreign_key :ideas, :lists
  end
end

which gave me this:
class CreateIdeas < ActiveRecord::Migration
  def change
    create_table :ideas do |t|
      t.string :name
      t.text :description
      t.string :picture
      t.integer :list_id
      t.timestamps
    end
    add_foreign_key :ideas, :lists
  end
end

and then I typed
rake db:migrate

Any idea why I would be getting an error saying there's no column? I'm still new to RoRs. Do I have to add a column some other way?
Thanks

A: As Speransky suggested, you should never modify old migration files. Rather you should create a new migration that adds the desired column. For instance, in this case you would run the following command in your app to create the new migration:
rails generate migration AddListIdColumnToIdeas list_id:integer

And Rails would generate the migration file automatically and the only thing left to do is run rake db:migrate.
If you insist on modifying the old migration file, you can add the column as you did and run the following:
rake db:drop
rake db:create
rake db:migrate

Which will destroy your current database, create a new one and run all the migrations (which will include your new column).

A: If you want to add a new column to an exist database, you should use rails generate migration. So you can try rails generate migration add_list_id_to_ideas list_id:integer and then use rake db:migrate to commit this change.

A: You should not add new rows to old migrations. Migration is a step of building database. And number of last executed migration is stored in schema, and it will not be run or redone if you use will use rake db:migrate. If you run the migration with creating the table before, then you should create new migration where you may use add_column method.

A: migration file name has the datetime encoded in its name so rails run this migration one and do not run it again unless you do a rollback
and here come the magic of migration to build you db with small steps so no need to update a migration after run rake db:migrate , you should make a new migration to do the change you want to your db schema
and remember to
remove the added line form the old migration file as it might raise errors if you decided to rollback this migration

A: Rails 4.0 easy way to add single or multiple column
https://gist.github.com/pyk/8569812

A: You can also do this ..
rails g migration add_column_to_users list_id:string
then rake db:migrate
also add :list_id attribute in your user controller ;
for more detail check out http://guides.rubyonrails.org/active_record_migrations.html

A: If you already have files in your migrate folder, you could just add column you want there(just type the code), delete development.sqlite or whatever represents your db file, and run rake db:migrate.
It will then create a new sqlite file with new column in table, and you can check it in schema.rb
So, basically, everything you did seems good, except you didn't delete your database file.
Doing this seems the easiest for me, all though you will lose all the files in your database. If you're just testing and developing Rails app, this works.
Can anyone comment if there is something wrong with this approach, besides what i wrote?
Edit: I actually found an answer about that here
Editing Existing Rails Migrations is a good idea?


text:
Q: Java abstract type Class compile time check Is it possible somehow to check at COMPILE time do classType points to an abstract type?
Runtime check can be done:
void foo(Class<? extends SubType> classType) {
    Modifier.isAbstract(classType.getModifiers());
}

foo(AbstractType.class);    // this should pass
foo(NotAbstractType.class); // this should fail

If same could be done at COMPILE time?

A: You could write your own @MustBeAbstract  annnotation and then an annnotation processor that enforces that any class with that annnotation is abstract.
See this question on annnotation processing: What is annotation processing in Java?

A: To my knowledge, there is no automatic solution.
However, if you know in advance the list of classes that are passed to method foo, you can implement a manual solution.
i.e.
private ArrayList<Class> abstractTypes = new ArrayList<>();

void foo(Class<? extends SubType> classType) {
    boolean isAbstract = false;
    for(Class c: abstractTypes)
       if((classType.getName()).equals(c.getName()){
          isAbstract = true;
          break;
       }

    //Do something else...
}


text:
Q: Existe alguma maneira de detectar o segundo monitor/ecrã com Javascript? Eu gostaria de saber se existe alguma maneira de detectar a existência de um segundo monitor com Javascript.
Em um cenário onde eu estivesse usando dois monitores/ecrãs no meu computador, eu gostaria abrir uma popup através de window.open e movê-la para um segundo monitor/ecrã, em tamanho total.
Seria possível fazer isso com Javascript?
Sei que talvez não exista algo nativo, mas talvez deva existir alguma maneira engenhosa, com cálculos, para se detectar isso.
Andei dando uma pesquisada e vi que o objeto window.screen parece trazer alguma informação interessante sobre o monitor/tela do usuário.
Seria esse o caminho?

A: Não existe, é quase impossível mover para a segunda tela, deve ter uma meia dúzia de gambiarras que promovem por aí dizendo funcionar, mas não é algo que responda corretamente, variando não só de navegador para navegador, mas principalmente de sistema operacional para sistema operacional.
Coisas como calcular a largura e tentar definir o no left do window.open não vão funcionar. Talvez em sistemas antigos, talvez no Windows XP funcione, mas hoje o sistema de múltiplas telas é "mais complexo", então mesmo que teoricamente você consiga detectar que existe uma segunda tela (como calcular o ratio para supor que aquilo não é uma medida convencional) você não iria conseguir fazer de maneira programada o mover para a segunda tela.
O que realmente falta é uma API nativa para JavaScript que faça isso de maneira simples, na verdade devo dizer que até mesmo window.open poderia ter melhorado um pouco mantendo uma retro-compatibilidade para os códigos legados, mas realmente eu não creio que isto seja de interesse.
Vou lhe confessar, a mesma necessidade que você tem de controlar uma janela para ser exibida em outra tela eu tive, tantas foram as dificuldades com as limitações dos navegadores e APIs JavaScript que eu tomei uma simples e unica decisão: migrei para o Qt, inicialmente usando QtWebkit e posteriormente QtWebEngine (tecnologia do Chrome). Então criei uma interface JavaScript que se comunicava com a software, assim eu mesmo disponibilizei um controle de monitores/ecrã. A minha necessidade era simples, o sistema abre no navegador que eu criei e dentro do sistema tinha um link exibir produto para o cliente, que deveria exibir no monitor que fica em cada mesa apenas o produto, e foi assim que cheguei a única solução viável, pois penso eu que para criar sites controle de monitores é realmente dispensável e se for para usar em um sistema interno então você deveria pensar em uma solução menos "WEB", ao menos no caso desta situação especifica, já que exibir em outra tela realmente parece uma necessidade bem especifica e provavelmente não seria para todos usuários.
Eu não estou simplesmente dizendo, corram para as montanhas, abandonem o WEB, não é isso, entendo que tem muita gente que está no web pela praticidade, pela facilidade de correr a aplicação em diversos dispositivos, mas existem soluções para o mundo HTML e JavaScript de maneira fácil e descomplicada, sem ter que apelar para coisas como C++, Python, Java e ser obrigado a aprender algo novo, um exemplo ótimo disto é o Electron:

*

*https://electronjs.org
Com ele é possivel criar aplicações desktop com tecnologias HTML, css, js e que vai correr em diversas plataformas.
Aplicações de grande uso usam tal tecnologia, como:

*

*Github Desktop

*Skype

*Atom

*VisualStudio Code


text:
Q: Populate dropdownlist with datareader from database Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific dropdownlist that user selected before. Im using linqdatasource to show all the dropdownlist value.
public partial class Update : System.Web.UI.Page
{
    string cs = Global.CS;
    DataClasses1DataContext db = new DataClasses1DataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) // only during initial load
        {
            string id = Request.QueryString["Item_ID"] ?? "";

            string sql = "Select * FROM MenuItem WHERE Item_ID = @id";

            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand(sql, con);

            cmd.Parameters.AddWithValue("@Id", id);

            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
                {
                    DataBind();
                    lblId.Text = (string)dr["Item_ID"].ToString();
                    txtItemName.Text = (string)dr["ItemDesc"];
                    txtPrice.Text = (string)dr["Price"].ToString();
                    ddlCategory.Text = (string)dr["Category"];

                        //foreach (var checking in db.Sets)
                        //{
                        //    string setID = checking.Set_ID.ToString();
                        //    if (setID == (string)dr["Item_ID"])
                        //    {
                        //        ddlAlacarte.DataSourceID = "ldsAlacarte";
                        //        **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
                        //        ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
                        //    }
                        //}

                }
                else
                {
                    ddlAlacarte.Enabled = false;
                    ddlBeverage.Enabled = false;
                    ddlSide.Enabled = false;
                    DataBind();

                    lblId.Text = (string)dr["Item_ID"].ToString();
                    txtItemName.Text = (string)dr["ItemDesc"];
                    txtPrice.Text = (string)dr["Price"].ToString();
                    ddlCategory.Text = (string)dr["Category"];

                }
            }
            else
            {
                Response.Redirect("MenuAdmin.aspx");
            }
            DataBind();
            dr.Close();
            con.Close();
        }
    }
    protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
        {
            ddlAlacarte.Enabled = true;
            ddlBeverage.Enabled = true;
            ddlSide.Enabled = true;
            DataBind();
        }
        else
        {
            ddlAlacarte.Enabled = false;
            ddlBeverage.Enabled = false;
            ddlSide.Enabled = false;
            DataBind();
        }
    }

}

A: You need to add items in Dropdownlist while reading values.
Add the following code while you are reading values by using SqlDataReader.
while(dr.Read())
{
  ListItem listItem = new ListItem();

  listItem.Text = dr["Category"].ToString();
  listItem.Value = dr["Category"].ToString();

  categoryDropDownList.Items.Add(listItem);
}

A: I would use something like this
dropDownList.Items.Add(
    new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);

and iterate through, populating the dropdown list. Is that what you want ?


text:
Q: What do I need to develop SharePoint applications? I'm a .NET developer and I'm used to write standard WinForms and ASP.NET applications.
In a few months I'll engage in a project that requires Sharepoint development. Problem is... I'm on ground zero regarding Sharepoint, and I have no idea how Sharepoint works.
What software / tools do I need to have to be able to study and develop sharepoint applications? I've noticed there's a "SharePoint Server 2007", do I need that? What about Office, do I need a special version of Office to develop for Sharepoint?
And a second question is: how do these things connect and integrate? Visual Studio, IIS, SharePoint Server, Office... ?
Any overview on this would be highly appreciated :)

A: Pretty much a duplicate of:

*

*SharePoint development environment setup;

*Creating a development environment for SharePoint.;

*How to begin as a .net and SharePoint developer; and

*What setup do you use for SharePoint (WSS/MOSS) development?.

A: Read Inside Microsoft Windows SharePoint Services 3.0 (Pattison,Larson).  If you are already familiar with C# and ASP.NET, this book is THE book to read to ensure you are aware of how to develop WSS/MOSS applications.  This book is a MUST HAVE if you want to properly develop SharePoint solutions/applications.

A: I agree with Pete's recommendation of the Inside Microsoft Windows SharePoint Services 3.0 (Pattison,Larson) book.  I would also recommend the The Great SharePoint Adventure class taught by Ted Pattison (if/when that is an option for you).  I took the class and it helped fill in a lot of the gaps in my knowledge.  It follows his book closely.
I would also recommend that you look at SharePoint Designer too (now a free download).  While not a programming tool it fills the gap between the web interface and Visual Studio.  For some tasks it is the quickest approach.

A: Be careful with the Sharepoint Designer it is not development it is more customization of one site...
If you have a more mature deploy model then you need to write solutions see
http://technet.microsoft.com/en-us/library/cc262957.aspx
What is your requirements__ What should you write. My experience sitting in Sharepoint land the last 2 years is that is not a silver bullet. You can easily get much more problems with performance, deployment etc. because you tried to use Sharepoint for everything....


text:
Q: I have a problem understanding sklearn's TfidfVectorizer results Given a corpus of 3 documents, for example:
   sentences = ["This car is fast",
                "This car is pretty",
                "Very fast truck"]

I am executing by hand the calculation of tf-idf.
For document 1, and the word "car", I can find that:
TF = 1/4
IDF = log(3/2)
TF-IDF = 1/4 * log(3/2)

Same result should apply to document 2, since it has 4 words, and one of them is "car".
I have tried to apply this in sklearn, with the code below:
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd

data = {'text': sentences}
df = pd.DataFrame(data)
tv = TfidfVectorizer()
tfvector = tv.fit_transform(df.text)
print(pd.DataFrame(tfvector.toarray(), columns=tv.get_feature_names()))

And the result I get is:
        car     fast        is    pretty      this     truck      very
0  0.500000  0.50000  0.500000  0.000000  0.500000  0.000000  0.000000
1  0.459854  0.00000  0.459854  0.604652  0.459854  0.000000  0.000000
2  0.000000  0.47363  0.000000  0.000000  0.000000  0.622766  0.622766

I can understand that sklearn uses L2 normalization, but still, shouldn't the tf-idf score of "car" in the first two documents be the same? Can anyone help me understanding the results?

A: It is because of the normalization. If you add the parameter norm=None to the TfIdfVectorizer(norm=None), you will get the following result, which has the same value for car
        car      fast        is    pretty      this     truck      very
0  1.287682  1.287682  1.287682  0.000000  1.287682  0.000000  0.000000
1  1.287682  0.000000  1.287682  1.693147  1.287682  0.000000  0.000000
2  0.000000  1.287682  0.000000  0.000000  0.000000  1.693147  1.693147


text:
Q: IntelliJ: custom language: combine fragments in other languages I am creating a custom language plugin for IntelliJ.
I would like it to be possible for a file in the new language to contain fragments of text in other languages.
The specific languages I would like to support are HTML, JS, CSS, and SQL.
I would also like to support other custom languages (i.e. languages I would define the syntax for).
The main feature I want is syntax coloring, but if I can get stuff like "go to declaration" and refactoring out of the box then all the better.
My last requirement is that it would be possible to use my own code to tell IntelliJ which language a fragment contains; fragments containing different languages will not be distinguishable at the lexer / parser level.
In short, I would like to implement something similar to what PhpStorm does when it detects, say, SQL inside a string:

I looked at IntelliJ's source code and found the ILazyParseableElementType interface which seemed relevant, but I'm not sure if this is the way to go (and if so - how to use it in my code exactly...)
Any pointers would be highly appreciated...

A: The Intellij feature/terminology you are looking for is Language Injections.
Here is a github PR which implements a very similar feature for JFLex files.
In short you need to implement a LanguageInjector and add it to your plugin.xml as a <languageInjector implementation="YourImplClass">.


text:
Q: multiply table td value I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.Here is my code
(i.e) if i change quantity to 2 then the parent rows need multiply by 2

$(document).ready(function(){
  $('.quantity').on('change, keyup',function(){
  var tbvalue=$(this).parents('td').val();
    console.log(tbvalue);
    var val=$(this).val();
    var result=tbvalue*val;
    console.log(result);
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Table calculation

Calculaton

        value1
        value2
        value3
        Quantity

        10
        5
        4
        1

        8
        2
        3
        1

        20
        3
        5
        1

A: Try this.Get the text from each td using this $(this).text(); and multiply that with input value

$(document).ready(function(){
  $('.quantity').on('change, keyup',function(){
       var val=$(this).text();
 if(val =='' ||  isNaN(val) || val < 1){
 return;
 }
      $(this).siblings().each(function(){
          var tbvalue=$(this).text();

          var result= parseInt(tbvalue)*parseInt(val);

          $(this).text(result);
      })

  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Table calculation

Calculaton

        value1
        value2
        value3
        Quantity

        10
        5
        4
        1

        8
        2
        3
        1

        20
        3
        5
        1


text:
Q: In Powershell how can I change Label text after a successful copy files? I start building up a small winform with Copy button and a label under this button.
When I click on Copy button it starts to copy files from source to destination.
I would like to run this asynchroniously so I don't want form to be freezed while copy operation runs. That's why I use Job. After a successful copy I need feedback of copy and show an "OK" text with green color but it is not working.
Here is my code:
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles()

Function Copy-Action{

    $Computername = "testclient"

    $Source_Path = "C:\temp\"
    $Destination_Path = "\\$Computername\c$\temp"

    $job = Start-Job -Name "Copy" -ArgumentList $Source_Path,$Destination_Path –ScriptBlock {
           param($Source_Path,$Destination_Path)

           Copy-Item $Source_Path -Destination $Destination_Path -Recurse -Force

            }

    Register-ObjectEvent $job StateChanged -MessageData $Status_Label -Action {
        [Console]::Beep(1000,500)
        $Status_Label.Text = "OK"
        $Status_Label.ForeColor = "#009900"
        $eventSubscriber | Unregister-Event
        $eventSubscriber.Action | Remove-Job
        } | Out-Null
}

# DRAW FORM
$form_MainForm = New-Object System.Windows.Forms.Form
$form_MainForm.Text = "Test Copy"
$form_MainForm.Size = New-Object System.Drawing.Size(200,200)
$form_MainForm.FormBorderStyle = "FixedDialog"
$form_MainForm.StartPosition = "CenterScreen"
$form_MainForm.MaximizeBox = $false
$form_MainForm.MinimizeBox = $true
$form_MainForm.ControlBox = $true

# Copy Button
$Copy_Button = New-Object System.Windows.Forms.Button
$Copy_Button.Location = "50,50"
$Copy_Button.Size = "75,30"
$Copy_Button.Text = "Copy"
$Copy_Button.Add_Click({Copy-Action})
$form_MainForm.Controls.Add($Copy_Button)

# Status Label
$Status_Label = New-Object System.Windows.Forms.Label
$Status_Label.Text = ""
$Status_Label.AutoSize = $true
$Status_Label.Location = "75,110"
$Status_Label.ForeColor = "black"
$form_MainForm.Controls.Add($Status_Label)

#show form
$form_MainForm.Add_Shown({$form_MainForm.Activate()})
[void] $form_MainForm.ShowDialog()

Copy is successful but showing an "OK" label won't. I have placed a Beep but it doesn't work too.
What am I doing wrong ? Any solution to this?
Thank you.

A: Let me offer alternatives to balrundel's helpful solution - which is effective, but complex.
The core problem is that while a form is being shown modally, with .ShowDialog(), WinForms is in control of the foreground thread, not PowerShell.
That is, PowerShell code - in the form's event handlers - only executes in response to user actions, which is why your job-state-change event handler passed to Register-ObjectEvent's -Action parameter does not fire (it would eventually fire, after closing the form).
There are two fundamental solutions:

*

*Stick with .ShowDialog() and perform operations in parallel, in a different PowerShell runspace (thread).

*

*balrundel's solution uses the PowerShell SDK to achieve this, whose use is far from trivial, unfortunately.

*See below for a simpler alternative based on Start-ThreadJob

*Show the form non-modally, via the .Show() method, and enter a loop in which you can perform other operations while periodically calling [System.Windows.Forms.Application]::DoEvents() in order to keep the form responsive.

*

*See this answer for an example of this technique.

*A hybrid approach is to stick with .ShowDialog() and enter a [System.Windows.Forms.Application]::DoEvents() loop inside the form event handler.

*

*This is best limited to a single event handler applying this technique, as using additional simultaneous [System.Windows.Forms.Application]::DoEvents() loops invites trouble.

*See this answer for an example of this technique.

Simpler, Start-ThreadJob-based solution:

*

*Start-ThreadJob is part of the the ThreadJob module that offers a lightweight, thread-based alternative to the child-process-based regular background jobs and is also a more convenient alternative to creating runspaces via the PowerShell SDK.

*

*It comes with PowerShell (Core) 7+ and can be installed on demand in Windows PowerShell with, e.g., Install-Module ThreadJob -Scope CurrentUser.

*In most cases, thread jobs are the better choice, both for performance and type fidelity - see the bottom section of this answer for why.

*In addition to syntactic convenience, Start-ThreadJob, due to being thread-based (rather than using a child process, which is what Start-Job does), allows manipulating the calling thread's live objects.

*

*Note that the sample code below, in the interest of brevity, performs no explicit thread synchronization, which may situationally be required.

The following simplified, self-contained sample code demonstrates the technique:

*

*The sample shows a simple form with a button that starts a thread job, and updates the form from inside that thread job after the operation (simulated by a 3-second sleep) completes, as shown in the following screen shots:

*

*Initial state:

*

*

*After pressing Start Job (the form remains responsive):

*

*

*After the job has ended:

*

*

*The .add_Click() event handler contains the meat of the solution; the source-code comments hopefully provide enough documentation.
# PSv5+
using namespace System.Windows.Forms
using namespace System.Drawing

Add-Type -AssemblyName System.Windows.Forms

# Create a sample form.
$form = [Form] @{
  Text = 'Form with Thread Job'
  ClientSize = [Point]::new(200, 80)
  FormBorderStyle = 'FixedToolWindow'
}

# Create the controls and add them to the form.
$form.Controls.AddRange(@(

    ($btnStartJob = [Button] @{
        Text     = "Start Job"
        Location = [Point]::new(10, 10)
      })

    [Label] @{
      Text     = "Status:"
      AutoSize = $true
      Location = [Point]::new(10, 40)
      Font     = [Font]::new('Microsoft Sans Serif', 10)
    }

    ($lblStatus = [Label] @{
        Text     = "(Not started)"
        AutoSize = $true
        Location = [Point]::new(80, 40)
        Font     = [Font]::new('Microsoft Sans Serif', 10)
      })

  ))

# The script-level helper variable that maintains a collection of
# thread-job objects created in event-handler script blocks,
# which must be cleaned up after the form closes.
$script:jobs = @()

# Add an event handler to the button that starts
# the background job.
$btnStartJob.add_Click( {
    $this.Enabled = $false # To prevent re-entry while the job is still running.
    # Signal the status.
    $lblStatus.Text = 'Running...'
    $form.Refresh() # Update the UI.
    # Start the thread job, and add the job-info object to
    # the *script-level* $jobs collection.
    # The sample job simply sleeps for 3 seconds to simulate a long-running operation.
    # Note:
    #  * The $using: scope is required to access objects in the caller's thread.
    #  * In this simple case you don't need to maintain a *collection* of jobs -
    #    you could simply discard the previous job, if any, and start a new one,
    #    so that only one job object is ever maintained.
    $script:jobs += Start-ThreadJob {
      # Perform the long-running operation.
      Start-Sleep -Seconds 3
      # Update the status label and re-enable the button.
      ($using:lblStatus).Text = 'Done'
      ($using:btnStartJob).Enabled = $true
    }
  })

$form.ShowDialog()

# Clean up the collection of jobs.
$script:jobs | Remove-Job -Force

A: Start-Job creates a separate process, and when your form is ready to receive events, it can't listen to job events. You need to create a new runspace, which is able to synchronize thread and form control.
I adapted code from this answer. You can read much better explanation there.
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles()

Function Copy-Action{

    $SyncHash = [hashtable]::Synchronized(@{TextBox = $Status_Label})
    $Runspace = [runspacefactory]::CreateRunspace()
    $Runspace.ThreadOptions = "UseNewThread"
    $Runspace.Open()
    $Runspace.SessionStateProxy.SetVariable("SyncHash", $SyncHash)
    $Worker = [PowerShell]::Create().AddScript({
        $SyncHash.TextBox.Text = "Copying..."

        # Copy-Item
        $Computername = "testclient"

        $Source_Path = "C:\temp\"
        $Destination_Path = "\\$Computername\c$\temp"

        Copy-Item $Source_Path -Destination $Destination_Path -Recurse -Force

        $SyncHash.TextBox.ForeColor = "#009900"
        $SyncHash.TextBox.Text = "OK"

    })
    $Worker.Runspace = $Runspace
    $Worker.BeginInvoke()

}

# DRAW FORM
$form_MainForm = New-Object System.Windows.Forms.Form
$form_MainForm.Text = "Test Copy"
$form_MainForm.Size = New-Object System.Drawing.Size(200,200)
$form_MainForm.FormBorderStyle = "FixedDialog"
$form_MainForm.StartPosition = "CenterScreen"
$form_MainForm.MaximizeBox = $false
$form_MainForm.MinimizeBox = $true
$form_MainForm.ControlBox = $true

# Copy Button
$Copy_Button = New-Object System.Windows.Forms.Button
$Copy_Button.Location = "50,50"
$Copy_Button.Size = "75,30"
$Copy_Button.Text = "Copy"
$Copy_Button.Add_Click({Copy-Action})
$form_MainForm.Controls.Add($Copy_Button)

# Status Label
$Status_Label = New-Object System.Windows.Forms.Label
$Status_Label.Text = ""
$Status_Label.AutoSize = $true
$Status_Label.Location = "75,110"
$Status_Label.ForeColor = "black"
$form_MainForm.Controls.Add($Status_Label)

#show form
$form_MainForm.Add_Shown({$form_MainForm.Activate()})
[void] $form_MainForm.ShowDialog()


text:
Q: Showing $\int_{-\infty}^{\infty}\frac {\mathrm d x} {1+x+x^2}=3 \int_0^\infty \frac {\mathrm d x} {1+x+x^2}$ Is there an easy way to see why
$$\int_{-\infty}^{\infty}\frac {\mathrm d x} {1+x+x^2}=3 \int_0^\infty \frac {\mathrm d x} {1+x+x^2}$$
without having to evaluate the integrals explicitly? I was trying substitutions but nothing worked.

A: The key is the equality:
$$(x^2+x+1)(x^2-x+1)=x^4+x^2+1$$
Letting $$\begin{align}I&=\int_{0}^{\infty}\frac{dx}{1+x+x^2}\\J&=\int_{-\infty}^{0}\frac{dx}{1+x+x^2}\\&=\int_{0}^{\infty}\frac{dx}{1-x+x^2}\end{align}$$
Then you want to show that $I+J=3I.$ We'll show the equivalent $J-I=I.$
We can see that:
$$J-I=\int_{0}^{\infty}\frac{2x}{1+x^2+x^4}\,dx$$
Substituting $u=x^2$ you get:
$$J-I=\int_{0}^{\infty} \frac{du}{1+u+u^2}=I$$ or $J=2I.$

A: Let $\displaystyle x=\frac{1}{v}$.
$$\int_{-1}^0\frac{dx}{1+x+x^2}=\int_{-1}^{-\infty}\frac{\frac{-1}{v^2}dv}{1+\frac{1}{v}+\frac{1}{v^2}}=\int_{-\infty}^{-1}\frac{dv}{1+v+v^2}$$
Let $\displaystyle x=-1-u$.
$$\int_{-\infty}^{-1}\frac{dx}{1+x+x^2}=\int_\infty^0\frac{-du}{1+(-1-u)+(-1-u)^2}=\int_0^{\infty}\frac{du}{1+u+u^2}$$
Therefore,
\begin{align*}
\int_{-\infty}^{\infty}\frac{dx}{1+x+x^2}&=\int_{-\infty}^{-1}\frac{dx}{1+x+x^2}+\int_{-1}^{0}\frac{dx}{1+x+x^2}+\int_{0}^{\infty}\frac{dx}{1+x+x^2}\\
&=3\int_{0}^{\infty}\frac{dx}{1+x+x^2}
\end{align*}


text:
Q: How far $HOD_{A}(X)$ can be from $V$ if exist choiceless cardinals? If exist totaly Reinhardt or Berkeley cardinal then $V≠HOD_{A}(X)$, where $A$ predicate defined in some class.
If exist 0# then any uncountable cardinal large in $L$
$V$ also can be far from $HOD$, even any uncountable cardinal measurable in $HOD$.
How far cardials in $HOD_{A}(X)$ from $V$ or between different $HOD_{A_1}(X_1)$, $HOD_{A_2}(X_2)$?
How badly can be fail GCH in $HOD_{A}(X)$?


text:
Q: Why this Code Work in "Visual Studio 2017" BUT Dose NOT work in "Visual Studio 6.0" This Code Work 100% in Visual Studio 2017 But I Don't know why Does
    not Work in VS 6.0
The Result in Visual Studio 6.0
 The Result in Visual Studio 2017
    #include<iostream>
    #include<assert.h>
    using namespace std;

    class stack
    {
        struct Node
        {
            int info;
            Node *link;
        };
        Node *Top;
        int count;
        int *list1, *list2;
        int i, x;
    public:
        stack()
        {
            Top = NULL;
            count = 0;
            list1 = new int[count];
            list2 = new int[count];
        }
        bool isEmpty() { return Top == NULL; }

        int TopStack()
        {
            assert(Top != NULL);
            return Top->info;
        }

        void Push(int num)
        {
            Node *newNode = new Node;
            newNode->info = num;
            newNode->link = Top;
            Top = newNode;
            count++;
        }
        void Pop()
        {
            Node *temp;
            if (!isEmpty())
            {
                temp = Top;
                Top = Top->link;
                delete temp;
                count--;
            }
            else
                cout << "the Stack is Empty." << endl;
        }
        void Input()
        {
            int num, Stop;
            cout << "Enter the stop Value : ";
            cin >> Stop;
            cout << "Enter the number : ";
            cin >> num;
            while (num != Stop)
            {
                Push(num);
                cin >> num;
            }
        }
        void print()
        {
            stack temp;
            cout << "\n The Number is : ";
            while (!isEmpty())
            {
                temp.Push(TopStack());
                Pop();
            }

            while (!temp.isEmpty())
            {
                cout << temp.TopStack() << " ";
                Push(temp.TopStack());
                temp.Pop();
            }
        }

        void Palindrom()
        {
            stack temp1;
            bool found = false;

            while (!isEmpty())
            {
                list1[i] = TopStack();
                temp1.Push(list1[i]);
                Pop();
                i++;
            }
            while (!temp1.isEmpty())
            {
                list2[x] = temp1.TopStack();
                Push(temp1.TopStack());
                temp1.Pop();
                x++;
            }
            cout << "\n\nThe list 1 : ";
            for (int t = 0; t < count; t++)
                cout << list1[t] << " ";
            cout << "\nThe list 2 : ";
            for (int r = 0; r < count; r++)
                cout << list2[r] << " ";

            for (int e = 0; e < count; e++)
            {
                if (list1[e] != list2[e])
                {
                    found = true;
                    break;
                }
            }
            cout << endl << endl;
            if (found)
            {
                cout << "   -Not Palindrom" << endl;
            }
            else
                cout << "   -Palindrom " << endl;

        }
    };

    int main()
    {
        stack obj;
        obj.Input();
        obj.print();
        obj.Palindrom();
        return  0 ;
    }

If there is another way easier let me know.

A: You never initialize i or x before using them.  Thus you have undefined behavior.
Those variables shouldn't even be part of the stack class.  They should simply be local values used for holding temporary state.
You also have undefined behavior here:
count = 0;
list1 = new int[count];
list2 = new int[count];

You should not be allocating arrays with zero entries.  And furthermore, you should never be accessing those arrays outside their allocated memory.
There are many other things wrong with this code, but fixing these issues might help.


text:
Q: Displaying a PNG file over a OpenLayers v6 map I am having difficulty finding a clear solution to this, I may just be over complicating it but I am not sure how to just add a static PNG file over top of a OpenLayers map with a opacity of 0.5. I've been searching the documentation and other related question but none have seemed to clear things up.
Could someone point me in the right direction, the data bounds are N: 85.044, S: -85.044, E: 180, W: -180. The image is of SMAP (Soil Moisture Active Passive) data I have processed with Python and exported as a PNG to display over this map in OpenLayers. Would leaving it as girdded data (simply stored in a matrix) make it easier/simpler to project?
This is  my image to add to the mapand it's size is 3856x1624. I know the black of the image will make it hard to see teh rest of the map, however right now I am just trying to get an image to overlay on the map.

Below is my most recent attempt to get it too work:
// Create the map object
const map = new Map({
target: 'map',
layers: [
new TileLayer({
  source: new OSM
  })
],
view: new View({
  projection: 'EPSG:4326',
  center: [0, 0],
  zoom: 0
  })
});

// Extent of the SMAP data bounds
imageextent = [-180, -85.044, 180, 85.044];

// Creating a new image layer using my PNG image as a static source
var image_layer = new ImageLayer({
  source: new Static({
    url: 'dataImage.png',
    imageExtent: imageextent,
    projection: 'EPSG:4326',
    crossOrigin: ''
  }),
  className: 'Image_Layer',
  opacity: 0.5,
  extent: imageextent,
  map: map  // This should add the image as an overlay
})

So when I run this using Node.js I have a map in EPSG:4326, but no image on top.


text:
Q: Perform Login fail on some website with ScrapingHub's Dash When I try to perform login with ScrapingHub's Dash, I get the following error on some web site into the "log" section :
scraping hub exceptions.KeyError: 'No input element with the name None'

How to fix hit ?
EDIT : Here the authentication method :

A: This happens to be a bug in loginform library, it is fixed by this change
and I have tested this in Scrapinghub with success.


text:
Q: Helm function to set value based on a variable? I'm learning Helm to setup my 3 AWS EKS clusters - sandbox, staging, and production.
How can I set up my templates so some values are derived based on which cluster the chart is being installed at? For example, in my myapp/templates/deployment.yaml I may want
apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}

I may want replicas to be either 1, 2, or 4 depending if I'm installing the chart in my sandbox, staging, or production cluster respectively? I wanna do same trick for cpu and memory requests and limits for my pods for example.
I was thinking of having something like this in my values.yaml file
environments:
  - sandbox
  - staging
  - production
perClusterValues:
  replicas:
    - 1
    - 2
    - 4
  cpu:
    requests:
      - 256m
      - 512m
      - 1024m
    limits:
      - 512m
      - 1024m
      - 2048m
  memory:
    requests:
      - 1024Mi
      - 1024Mi
      - 2048Mi
    limits:
      - 2048Mi
      - 2048Mi
      - 3072Mi

So if I install a helm chart in the sandbox environment, I want to be able to do
$ helm install myapp myapp --set environment=sandbox

apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  {{- if not .Values.autoscaling.enabled }}
  # In pseudo-code, in my YAML files
  # Get the index value from .Values.environments list
  # based on pass-in environment parameter
  {{ $myIndex = indexOf .Values.environments .Value.environment }}
  replicas: {{ .Values.perClusterValues.replicas $myIndex }}
  {{- end }}

I hope you understand my logic, but what is the correct syntax? Or is this even a good approach?

A: You can use the helm install -f option to pass an extra YAML values file in, and this takes precedence over the chart's own values.yaml file.  So using exactly the template structure you already have, you can provide alternate values files
# sandbox.yaml
autoscaling:
  enabled: false
replicaCount: 1

# production.yaml
autoscaling:
  enabled: true
replicaCount: 5

And then when you go to deploy the chart, run it with
helm install myapp . -f production.yaml

(You can also helm install --set replicaCount=3 to override specific values, but the --set syntax is finicky and unusual; using a separate YAML file per environment is probably easier.  Some tooling might be able to take advantage of JSON files also being valid YAML to write out additional deploy-time customizations.)


text:
Q: django.db.utils.IntegrityError: duplicate key value violates unique constraint I have Country model
from django.db import models

class Country(models.Model):
    country = models.CharField(max_length = 20, primary_key=True)
    country_id = models.IntegerField()

I uploaded some data in Country table with following custom management command
from django.core.management.base import BaseCommand, CommandError
from data.models import Country
import json
from .extract_country import extracting

get_parsed_json = extracting()

def store_data():
    for key, value in get_parsed_json['api']['countries'].items():
        country_id_field = key
        country_name = value
        One_country = Country.objects.create(country_id = country_id_field , country = country_name)
        One_country.save()
        print(One_country)

class Command(BaseCommand):
    def handle(self, **options):
        extracting()
        store_data()

Now i am trying to upload to the Country table extended data which contain the same countries and another but when i am trying to upload data i get the following error. Here is my full traceback
Traceback (most recent call last):
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "data_co
untry_name_04df4fc7_uniq"
DETAIL:  Key (country)=(Algeria) already exists.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 23, in handle
    store_data()
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 14, in store_data
    One_country = Country.objects.create(country_id = country_id_field , country
 = country_name)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 413, in create
    obj.save(force_insert=True, using=self.db)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 718, in save
    force_update=force_update, update_fields=update_fields)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 748, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 831, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 869, in _do_insert
    using=using, raw=raw)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 1136, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\sql\co
mpiler.py", line 1289, in execute_sql
    cursor.execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 100, in execute
    return super().execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\utils.py", li
ne 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "
data_country_name_04df4fc7_uniq"
DETAIL:  Key (country)=(Algeria) already exists.

I found that is very frequent problem for django users but didnt find how to fix it. Any suggestions ?

A: Seems that you try to create County with same county name as it's your primary key.
Try to use get_or_create():
def store_data():
    for key, value in get_parsed_json['api']['countries'].items():
        country_id_field = key
        country_name = value
        one_country, created = Country.objects.update_or_create(
            country_id=country_id_field
            defaults={'country': country_name},
        )
        # one_country.save() <- no need to save after create or get_or_create method.
        print(one_country)

A: The primary key must be unique, if there is an instance with the key "Algeria" already exists, you cannot create a second instance with the same key.
Instead of:
One_country = Country.objects.create(country_id = country_id_field , country = country_name)

You could use get_or_create:
# ...
One_country, created = Country.objects.get_or_create(country=country_name)
One_country.country_id = country_id_field
One_country.save()
# ...


text:
Q: Perceptual (or average) image hashing I need to calculate the perceptual hash of an image and should do it without using any external libraries.
I tried using pHash (http://phash.org/) but I wasn't able to compile it for iOS (5) and I haven't found a real tutorial on how to do it.

A: One (library-dependent) solution is to use the pHashing functionality added to ImageMagick in version 6.8.8.3, which has iOS binaries available.  Usage examples are documented here.
Here's also a simple reference function (in C#) for generating your own comparable image average hash, found on this blog.
public static ulong AverageHash(System.Drawing.Image theImage)
// Calculate a hash of an image based on visual characteristics.
// Described at http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
{
    // Squeeze the image down to an 8x8 image.
    // Chant the ancient incantations to create the correct data structures.
    Bitmap squeezedImage = new Bitmap(8, 8, PixelFormat.Format32bppRgb);
    Graphics drawingArea = Graphics.FromImage(squeezedImage);
        drawingArea.CompositingQuality = CompositingQuality.HighQuality;
        drawingArea.InterpolationMode = InterpolationMode.HighQualityBilinear;
        drawingArea.SmoothingMode = SmoothingMode.HighQuality;
        drawingArea.DrawImage(theImage, 0, 0, 8, 8);

    byte[] grayScaleImage = new byte[64];

    uint averageValue = 0;
    ulong finalHash = 0;

    // Reduce to 8-bit grayscale and calculate the average pixel value.
    for(int y = 0; y < 8; y++)
    {
        for(int x = 0; x < 8; x++)
        {
            Color pixelColour = squeezedImage.GetPixel(x,y);
            uint grayTone = ((uint)((pixelColour.R * 0.3) + (pixelColour.G * 0.59) + (pixelColour.B * 0.11)));

            grayScaleImage[x + y*8] = (byte)grayTone;
            averageValue += grayTone;
        }
    }
    averageValue /= 64;

    // Return 1-bits when the tone is equal to or above the average,
    // and 0-bits when it's below the average.
    for(int k = 0; k < 64; k++)
    {
        if(grayScaleImage[k] >= averageValue)
        {
            finalHash |= (1UL << (63-k));
        }
    }

    return finalHash;
}


text:
Q: Add a formatting rule for a text in a form Is there any way of creating a formatting rule for a title or text?
I want to make a text appear when I set true a checkbox. I know how to do it with a texbox but not with plain text.
Thank you in advance.


text:
Q: OmniSharp server issue in VS Code I recently got VS Code and wanted to use C# but keep running into a problem which stops OmniSharp server from starting. Here is the OmniSharp Log:
Starting OmniSharp server at 12/7/2021, 08:40:08
    Target: c:\Users\epik\Downloads\projects\hjkl

OmniSharp server started.
    Path: c:\Users\epik\.vscode\extensions\ms-dotnettools.csharp-1.23.12\.omnisharp\1.37.10\OmniSharp.exe
    PID: 15908

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 6.2.9200.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
System.IO.FileNotFoundException: Retrieving the COM class factory for component with CLSID {177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D} failed due to the following error: 8007007e The specified module could not be found. (Exception from HRESULT: 0x8007007E).
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at OmniSharp.MSBuild.Discovery.Interop.GetSetupConfiguration() in D:\a\1\s\src\OmniSharp.Host\MSBuild\Discovery\Interop.cs:line 20
   at OmniSharp.MSBuild.Discovery.Providers.VisualStudioInstanceProvider.GetInstances() in D:\a\1\s\src\OmniSharp.Host\MSBuild\Discovery\Providers\VisualStudioInstanceProvider.cs:line 28
   at OmniSharp.MSBuild.Discovery.MSBuildLocator.GetInstances() in D:\a\1\s\src\OmniSharp.Host\MSBuild\Discovery\MSBuildLocator.cs:line 235
   at OmniSharp.MSBuild.Discovery.Extensions.GetBestInstance(IMSBuildLocator msbuildLocator, Version minimumMSBuildVersion, ILogger logger, Boolean& invalidVSFound, Boolean& vsWithoutSdkResolver) in D:\a\1\s\src\OmniSharp.Host\MSBuild\Discovery\Extensions.cs:line 109
   at OmniSharp.MSBuild.Discovery.Extensions.RegisterDefaultInstance(IMSBuildLocator msbuildLocator, ILogger logger, DotNetInfo dotNetInfo) in D:\a\1\s\src\OmniSharp.Host\MSBuild\Discovery\Extensions.cs:line 17
   at OmniSharp.CompositionHostBuilder.Build(String workingDirectory) in D:\a\1\s\src\OmniSharp.Host\CompositionHostBuilder.cs:line 71
   at OmniSharp.Stdio.Host..ctor(TextReader input, ISharedTextWriter writer, IOmniSharpEnvironment environment, IServiceProvider serviceProvider, CompositionHostBuilder compositionHostBuilder, ILoggerFactory loggerFactory, CancellationTokenSource cancellationTokenSource) in D:\a\1\s\src\OmniSharp.Stdio\Host.cs:line 47
   at OmniSharp.Stdio.Driver.Program.<>c__DisplayClass0_1.<Main>b__1() in D:\a\1\s\src\OmniSharp.Stdio.Driver\Program.cs:line 74
   at OmniSharp.HostHelpers.Start(Func`1 action) in D:\a\1\s\src\OmniSharp.Host\HostHelpers.cs:line 29

How do I fix it and what is causing it?

A: Repairing Visual Studio 2019 fixed it.


text:
Q: How to use all circle sizes in a punchcard? This VEGA-lite demo of Table Bubble Plot uses all sizes, from small to big circles.
My script, illustrated below, is not using, there are only 2 or 3 sizes. How to enforce or say to VEGA-lite use all circle sizes?

{
          "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
          "data": { "url":"/_sql/myTable"},
          "mark": "circle",
          "encoding": {
            "y": {
              "field": "instant",
              "type": "ordinal",
              "timeUnit": "day",
              "sort": ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
            },
            "x": {
              "field": "instant",
              "type": "ordinal",
              "timeUnit": "hours"
            },
            "size": {
              "field": "n_pmin",
              "type": "quantitative",
              "aggregate": "avg"
            },
            "color": {
              "field": "n_pmin",
              "type": "quantitative",
              "aggregate": "avg"
            }
          }
}

PS: ideal also change "only blue" gradient to "bluegreen", but I not see how to set color into color.

NOTES
for @Jim request, a sample:
[{"instant":"2020-04-23T14:46:42","n_pmin":2210086},
 {"instant":"2020-04-23T15:05:01","n_pmin":2214909},
 {"instant":"2020-04-23T16:05:01","n_pmin":2159652},
 {"instant":"2020-04-23T17:05:01","n_pmin":2290159},
 {"instant":"2020-04-23T18:05:01","n_pmin":2235739},
 {"instant":"2020-04-23T19:05:01","n_pmin":2505914},
 {"instant":"2020-04-23T20:05:01","n_pmin":2517069},
 {"instant":"2020-04-23T21:05:01","n_pmin":2492883},
 {"instant":"2020-04-23T22:05:01","n_pmin":2535839},
 {"instant":"2020-04-23T23:05:01","n_pmin":2519568},
 {"instant":"2020-04-24T00:05:02","n_pmin":2367309},
 {"instant":"2020-04-24T01:05:01","n_pmin":2384885},
 {"instant":"2020-04-24T02:05:01","n_pmin":2340421},
 {"instant":"2020-04-24T03:05:01","n_pmin":2369579},
 {"instant":"2020-04-24T04:05:01","n_pmin":2285203},
 {"instant":"2020-04-24T05:05:01","n_pmin":2206629},
 {"instant":"2020-04-24T06:05:01","n_pmin":2149411},
 {"instant":"2020-04-24T07:05:01","n_pmin":2218313},
 {"instant":"2020-04-24T08:05:01","n_pmin":2231320},
 {"instant":"2020-04-24T09:05:01","n_pmin":2163876},
 {"instant":"2020-04-24T10:05:01","n_pmin":2100388},
 {"instant":"2020-04-24T11:05:01","n_pmin":2040520},
 {"instant":"2020-04-24T12:05:02","n_pmin":2157928},
 {"instant":"2020-04-24T13:05:01","n_pmin":2099753},
 {"instant":"2020-04-24T15:05:01","n_pmin":2334844},
 {"instant":"2020-04-24T16:05:01","n_pmin":2430831},
 {"instant":"2020-04-24T17:05:01","n_pmin":2403722},
 {"instant":"2020-04-24T18:05:02","n_pmin":2468541},
 {"...":"..."},
 {"instant":"2020-05-13T16:05:01","n_pmin":2717164},
 {"instant":"2020-05-13T17:05:01","n_pmin":2794972},
 {"instant":"2020-05-13T18:05:01","n_pmin":2824981},
 {"instant":"2020-05-13T19:05:01","n_pmin":2852586},
 {"instant":"2020-05-13T20:05:01","n_pmin":2868170}]

A: Short answer to the main question,

How to enforce or say to VEGA-lite use all circle sizes?

Say "zero": false. But, let's see in more detail how to do it in a more handmade way, to understand when you can set scale.zero to false as faster solution.

You can adjust the properties you're interested using the scale specification in the relevant encodings.
For the color scheme, you can set scale.scheme to any of the options listed in Vega Color Schemes.
For the sizes, you can set the scale.domain and scale.range to desired values, where domain is the span of numbers in data space, and range is the area of associated legend marks in square pixels.
Alternatively, you can set scale.zero to false to automatically adjust the domain, and leave out the zero value (which is what is causing the "missing" circles in your chart).
Putting it together, it might look like this, using the sample data you provided (vega editor):
{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {
    "values": [
      {"instant": "2020-04-23T14:46:42", "n_pmin": 2210086},
      {"instant": "2020-04-23T15:05:01", "n_pmin": 2214909},
      {"instant": "2020-04-23T16:05:01", "n_pmin": 2159652},
      {"instant": "2020-04-23T17:05:01", "n_pmin": 2290159},
      {"instant": "2020-04-23T18:05:01", "n_pmin": 2235739},
      {"instant": "2020-04-23T19:05:01", "n_pmin": 2505914},
      {"instant": "2020-04-23T20:05:01", "n_pmin": 2517069},
      {"instant": "2020-04-23T21:05:01", "n_pmin": 2492883},
      {"instant": "2020-04-23T22:05:01", "n_pmin": 2535839},
      {"instant": "2020-04-23T23:05:01", "n_pmin": 2519568},
      {"instant": "2020-04-24T00:05:02", "n_pmin": 2367309},
      {"instant": "2020-04-24T01:05:01", "n_pmin": 2384885},
      {"instant": "2020-04-24T02:05:01", "n_pmin": 2340421},
      {"instant": "2020-04-24T03:05:01", "n_pmin": 2369579},
      {"instant": "2020-04-24T04:05:01", "n_pmin": 2285203},
      {"instant": "2020-04-24T05:05:01", "n_pmin": 2206629},
      {"instant": "2020-04-24T06:05:01", "n_pmin": 2149411},
      {"instant": "2020-04-24T07:05:01", "n_pmin": 2218313},
      {"instant": "2020-04-24T08:05:01", "n_pmin": 2231320},
      {"instant": "2020-04-24T09:05:01", "n_pmin": 2163876},
      {"instant": "2020-04-24T10:05:01", "n_pmin": 2100388},
      {"instant": "2020-04-24T11:05:01", "n_pmin": 2040520},
      {"instant": "2020-04-24T12:05:02", "n_pmin": 2157928},
      {"instant": "2020-04-24T13:05:01", "n_pmin": 2099753},
      {"instant": "2020-04-24T15:05:01", "n_pmin": 2334844},
      {"instant": "2020-04-24T16:05:01", "n_pmin": 2430831},
      {"instant": "2020-04-24T17:05:01", "n_pmin": 2403722},
      {"instant": "2020-04-24T18:05:02", "n_pmin": 2468541},
      {"instant": "2020-05-13T16:05:01", "n_pmin": 2717164},
      {"instant": "2020-05-13T17:05:01", "n_pmin": 2794972},
      {"instant": "2020-05-13T18:05:01", "n_pmin": 2824981},
      {"instant": "2020-05-13T19:05:01", "n_pmin": 2852586},
      {"instant": "2020-05-13T20:05:01", "n_pmin": 2868170}
    ]
  },
  "mark": "circle",
  "encoding": {
    "y": {
      "field": "instant",
      "type": "ordinal",
      "timeUnit": "day",
      "sort": ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
    },
    "x": {"field": "instant", "type": "ordinal", "timeUnit": "hours"},
    "size": {
      "field": "n_pmin",
      "type": "quantitative",
      "aggregate": "mean",
      "scale": {"domain": [2200000, 3000000], "range": [100, 500]}
    },
    "color": {
      "field": "n_pmin",
      "type": "quantitative",
      "aggregate": "mean",
      "scale": {"domain": [2200000, 3000000], "scheme": "bluegreen"}
    }
  }
}

Automatic non-zero fit for dynamical data
Dynamical data (e.g. new data when refresh web page) is a typical case where we can't use constant domain ranges. In this other chart on VEGA editor both scale.zero (of color and size) are setting to false, resulting in an automatic scale range adjust:
    "size": {
      "field": "n_pmin",
      "type": "quantitative",
      "aggregate": "mean",
      "scale": {"zero": false }
    },
    "color": {
      "field": "n_pmin",
      "type": "quantitative",
      "aggregate": "mean",
      "scale": {"scheme": "bluegreen", "zero": false}
    }


text:
Q: Reversibly merging sets of $k$ adjacent elements in an array Say I have an array of the form:
ExampleArray = {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}};

I'd like to be able to reversibly merge sets of $k$ adjacent elements together s.t. I can go back and forth from, for example, arrays of the form:
ExampleArray = {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}};

And, for $k = 2$:
ExampleArray2Star = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13}};

Or, for $k = 3$:
ExampleArray3Star = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13}};

As we can see here, "leftover" elements at the end of the array will strictly be in a subset of size $\leq k$.
Is there a name for this sort of operation, and is there an easy way to execute it in Mathematica 9.0?

A: Here's a way, using Partition:
func[l_, n_] := Partition[l, n, n, {1, 1}, {}]

(the key is to use proper padding, see also in documentation of Partition)
example:
func[Range@13, #] & /@ Range[5]

{
  {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}},
  {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13}},
  {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13}},
  {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13}},
  {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13}}
}

Note
For generality, I assumed that the input (l that is) is "flat". In your case, you want to Flatten it, e.g. func[Flatten[ExampleArray], #] & /@ Range[5].
Addendum:
You might want to look at this question, especially at the dynP function there - it discusses varying partition lengths.

A: Perhaps something like this:
ExampleArray = {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, \
{11}, {12}, {13}};

k = 3;
res = Join @@@ Partition[ExampleArray, k, k, 1, {}]
(* {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13}} *)

Going back:
Join @@ (Partition[#, 1] & /@ res)
(*{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}}*)

A: Two variations of using Partition have been presented.  Let me compare their performance, and offer a third method.
For simplicity I shall assume that the input is a packed array.  This can have a major impact on the ranking of methods as a described here.
SetAttributes[timeAvg, HoldFirst]
timeAvg[func_] := Do[If[# > 0.3, Return[#/5^i]] & @@ Timing @ Do[func, {5^i}], {i, 0, 15}]

a = {Range@500000}\[Transpose]; (*sample data, packed *)
k = 4;

Partition[Flatten @ a, k, k, 1, {}] // timeAvg  (* Pinguin Dirk *)
Join @@@ Partition[a, k, k, 1, {}]  // timeAvg  (* ruebenko *)

0.02496
0.1842

Flattening before partitioning is faster on this data.
From past experience I know that using non-default padding e.g. {} will slow Partition considerably when using packed arrays.  Therefore we can speed this process by separating that operation.
merge[a_, k_Integer] :=
  Module[{b = Partition[Flatten @ a, k, k, 1]},
    b[[-1]] = b[[-1]] ~Drop~ Mod[Length @ a, k, 1 - k];
    b
  ]

merge[a, k] // timeAvg

0.003368

On the packed data this is ~ 7.4X faster.  However, on unpackable data it is of no benefit, and in fact slightly slower:
a = List /@ RandomChoice["a" ~CharacterRange~ "z", 500000];
k = 7;

Partition[Flatten@a, k, k, 1, {}] // timeAvg

merge[a, k]                       // timeAvg

0.03056
0.03556


text:
Q: Python RegEx Meaning I'm new to python regular expressions and was wondering if someone could help me out by walking me through what this means (I'll state what I think each bit means here as well).
Thanks!
RegExp:
r'(^.*def\W*)(\w+)\W*\((.*)\):'

r'...' = python definition of regular expression within the ''
(...) = a regex term
(^. = match the beginning of any character
*def\W* = ???
(\w+) = match any of [a, z] 1 or more times
\W*\ = ? i think its the same as the line above this but from 0+ more times instead of 1 but since it matches the def\W line above (which i dont really know the meaning of) i'm not sure.
((.*)\): = match any additional character within brackets ()

thanks!

A: It seems like a failed attempt to match a Python function signature:
import re

regex = re.compile(r""" # r'' means that \n and the like is two chars
                        # '\\','n' and not a single newline character

    ( # begin capturing group #1; you can get it: regex.match(text).group(1)
      ^   # match begining of the string or a new line if re.MULTILINE is set
      .*  # match zero or more characters except newline (unless
          # re.DOTALL is set)
      def # match string 'def'
      \W* # match zero or more non-\w chars i.e., [^a-zA-Z0-9_] if no
          # re.LOCALE or re.UNICODE
    ) # end capturing group #1

    (\w+) # second capturing group [a-zA-Z0-9_] one or more times if
          # no above flags

    \W*   # see above

    \(    # match literal paren '('
      (.*)  # 3rd capturing group NOTE: `*` is greedy `.` matches even ')'
            # therefore re.match(r'\((.*)\)', '(a)(b)').group(1) == 'a)(b'
    \)    # match literal paren ')'
     :    # match literal ':'
    """, re.VERBOSE|re.DEBUG)

re.DEBUG flag causes the output:
subpattern 1
  at at_beginning
  max_repeat 0 65535
    any None
  literal 100
  literal 101
  literal 102
  max_repeat 0 65535
    in
      category category_not_word
subpattern 2
  max_repeat 1 65535
    in
      category category_word
max_repeat 0 65535
  in
    category category_not_word
literal 40
subpattern 3
  max_repeat 0 65535
    any None
literal 41
literal 58

more

A:
r'..' = Python's raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'.
(...) = a capture group which stores the captured value in a var to be used in replacement/mathing.
^ = the start of the string.
.* = 0 or more chars of any type.
def = the literal string def
\W* = 0 or more non word chars (Anything other than a-zA-Z or _)
\w+ = 1 or more word chars (see above)
\( = escapes the (, therefore means a literal (
\) = same as above.
: = literal :

PS: I like the effort that you made to try to understand the regex. It will serve you well, much better than people asking what does r'(^.*def\W*)(\w+)\W*\((.*)\):' mean.

A:
r'...' = python definition of regular expression within the ''

The r'' syntax has nothing to with regular expressions (or at least, not directly).  The r stands for raw and is simply an indicator to Python that no string interpolation should be performed on the string.
This is often used with regular expressions so that you don't have to escape backslash (\) characters, which would otherwise be eaten by the normal string interpolation mechanism.

(^. = match the beginning of any character

I'm not sure what "beginning of any character" means.  The ^ character matches the beginning of a line.

def\W = ???

def matches the characters def.  For \W, take a look at pydoc re, which describes the regular expression language.

\W*

As above.
Other than the above, your interpretation seems largely correct.

A: r'(^.*def\W\*)(\w+)\W*((.*)):'
==================================

r' tells python this is a raw string so you don't have to double escape all the \

^ match start of string

() in each case this means group this match where each () is a different group

.* match zero or more of any characters

def match the literal 'def'

\W* match zero or more of any non word character

() more grouping of the contained expression

\w+ match one or more of word character

\W* zero or more of any non word character

\( escape the left paren

() more grouping of the contained expression

.* zero of more of any character

\) escape the right paren

: match a single colon literal

This looks like it is trying to match a python method definition. Here is a link to play with this regular expression. Yes it is powered by Ruby, but the syntax is pretty much the same across all languages, I use this site to test regexes for Python, Java and Ruby.

A: *

*r'...' → the preferred way to define the string of a regular expression in Python

*(...) → regex term

*^ → matches only with the beginning of the string

So, in the first pair of parenthesis (^.def\W), firstly it matches with the string.

*

*. → matches any character

** → repeat the previous match 0 or more times

Then .* will match anything any number of times. The following 'def' is an exact match, that only matches with itself.

*

*\W → matches anything that is NOT a letter, nor a number, nor the underscore character.

Then \W* will match zero or more of these non-letter-number-underscore characters. The next pair of parenthesis (\w+) you got it right. In the last part \W*\((.*)\): the initial \W* means the same thing as the previous \W* . Next, \( matches with ( , then there is the group (.*) which means, as previously, anything any number of times, followed by \): that matches ): .
An example of string that is matched by this regular expression is:
thing_def = function_name (123 anything in here):

A: *

*Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it.

*( ) groups a statement, it's treated as ONE thing, so you can do ()? or ()* or ()+ if the things in the brackets need to handled together.

*^ matches it if it's the beginning of the string

*(Dot.) In the default mode, this matches any character except a newline.

*Since it is ".*" the * means match 0 or more matches of the previous thing, which in this case is any character.

*def\W* - lines beginning with the string "def" and then \W matches any non-alphanumeric characters and is equivalent to [^a-zA-Z0-9_]. Since we have the * again, this time it matches 0 or more non-alphanumeric characters.

*(\w+), the + is for 1 or more of the previous, which in this case is \w, equivalent to [a-zA-Z0-9_].
7.\W*, we know that one already.

*

*"(" - means just to match "(", differentiate it from () grouping things, same for ")/"

*(.*) - match 0 or more characters inside.

*: - the matched string ends with a colon at the end.
The whole thing seems to be matching a definition of a function in python i.e. "def foo(x):" will be matched. Dealing with regular expressions is hard - using tools such as http://www.pythonregex.com/ helps me to try out different things. And since RE are slightly different in different languages, it's nice to have tools for those too.


text:
Q: Android: insert datetime in Sqlite database I am trying to insert datetime field in Sqlite database in an Andoird project. Tried many ways like this but no luck in inserting datetime field.  Here are facts
1] My Sqlite field is type timestamp
2] database class
package com.gcm.pushandroid;
import java.util.Date;

public class Notifications {

     //private variables
      String _type;
      String _time_stamp;

       // Empty constructor
       public Notifications(){

       }
       // constructor
       public Notifications(String type, String timeStamp){
           this._type = type;
           this._time_stamp = timeStamp;
       }

      // getting ID
      public String getType(){
          return this._type;
       }

      // setting id
      public void setType(String type){
         this._type = type;
      }

     // getting timestamp
     public String getTimeStamp(){
        return this._time_stamp;
     }

     // setting
     public void setTimeStamp(String time_stamp){
          this._time_stamp = time_stamp;
     }

}

3] Here is code
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TYPE, notificationObj.getType());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
values.put("time_stamp", dateFormat.format(date));
db.insert(TABLE_CONTACTS, null, values);
db.close();

Don't know what is going wrong. Help is apprecited.
Thank you

A: You have to change your sqlite field type to String / Text.
The type 'timestamp' doesn't allow : or - Timestamp may only hold Integers
For more details please see http://www.sqlite.org/datatype3.html Point 1.2


text:
Q: Bash if statement to check for like 1 letter and 2 numbers Need some help with a script.  I am trying to make sure the user enters a valid school term, like F18, F19 etc.
The letters that can be used are F, S, M, N (which are Fall, Spring, Summer, Special) the numbers are years, 18, 19, 20, 21 etc.
The problem with my current setup if someone mistyped for example ff18, it's correct, or f181 it's correct. I want it to only accept 1 letter and 2 numbers.
#!/bin/bash

term_arg=$1
letter_range="[f|F|s|S|m|M|n|N]"
number_range="[10-99]"
if [[ "${term_arg}" = "" ]] || ! [[ "${term_arg}" =~ ${letter_range}${number_range} ]]; then
  echo "Please specify a valid term: e.g. F18, S19, M19, etc. "
  exit 1
else
  echo "The term id ${term_arg} is correct"
  exit 0
fi

A: Square brackets introduce character classes, so
[f|F]

matches any of the three characters: f, |, or F.
Similarly,
[10-99]

matches 1, 0 to 9, and 9, which is equivalent to [0-9] or [0123456789].
So, you need
[fFsSmMnN][0-9][0-9]

Note that this works with plain =, too, no need to use regular expressions, as the right hand side is interpreted as a pattern unless quoted:
$ [[ m18 = [fsmn][0-9][0-9] ]] && echo matches
matches

A: Please try to use Google, since there are a lot of examples of how to do an exact match.  A regex matches characters, not numbers.  Pay particular attention to how the numeric part is examined.  I've added capture groups to get the quarter and year to assign those parts to variables, and I am upper-casing the input so that you don't have to worry about matching case.  This also shows how to add individual words that you want to check.  And you can separate the quarter and the year with a space or a dash, or neither and it handles the input of these cases just fine.
Try:
#!/bin/bash

term_arg=$@
quarterRegex='FALL|SPRING|SUMMER|SPECIAL'
quarterAbbrevRegex='[FSMN]'
yearRegex='[1-9][0-9]'
separatorRegex='(-|[[:space:]])?'
termRegex="^(${quarterAbbrevRegex}|${quarterRegex})${separatorRegex}(${yearRegex})$"
declare termEntry
declare yearEntry
if [[ "${term_arg^^}" =~ $termRegex ]]; then
  termEntry="${BASH_REMATCH[1]}"
  yearEntry="${BASH_REMATCH[3]}"
  echo "The term id ${term_arg} is correct:"
  echo "  Term: ${termEntry}"
  echo "  Year: ${yearEntry}"
  exit 0
else
  echo "${term_arg} is in an incorrect format.  Please specify a valid term: e.g., F18, S19, M19, etc."
  exit 1
fi


text:
Q: How to create partitioned BigQuery table in Java https://cloud.google.com/bigquery/docs/creating-partitioned-tables shows how to create partitioned table in Python. I've been there, I've done that.
Now the question is, how to do the same thing with Java API? What is the corresponding Java code doing the same thing as the Python one below:
{
  "tableReference": {
    "projectId": "myProject",
    "tableId": "table1",
    "datasetId": "mydataset"
  },
  "timePartitioning": {
    "type": "DAY"
  }
}

Java with missing partitioning:
Job createTableJob = new Job();
JobConfiguration jobConfiguration = new JobConfiguration();
JobConfigurationLoad loadConfiguration = new JobConfigurationLoad();

createTableJob.setConfiguration(jobConfiguration);
jobConfiguration.setLoad(loadConfiguration);

TableReference tableReference = new TableReference()
    .setProjectId("myProject")
    .setDatasetId("mydataset")
    .setTableId("table1");

loadConfiguration.setDestinationTable(tableReference);
// what should be place here to set DAY timePartitioning?

I'm using the newest api version from Maven Central Repository: com.google.apis:google-api-services-bigquery:v2-rev326-1.22.0.

A: https://cloud.google.com/bigquery/docs/reference/v2/tables/insert
https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
Example Java code:
String projectId = "";
String datasetId = "";

Table content = new Table();
TimePartitioning timePartitioning = new TimePartitioning();
timePartitioning.setType("DAY");
timePartitioning.setExpirationMs(1L);
content.setTimePartitioning(timePartitioning);

Bigquery.Tables.Insert request = bigquery.tables().insert(projectId, datasetId, content);
Table response = request.execute();

A: Please let me share a more updated way to create partitioned tables (works with Java API 0.32):
Schema schema = Schema.of( newFields);
TimePartitioning timePartitioning = TimePartitioning.of(TimePartitioning.Type.DAY);
TableDefinition tableDefinition = StandardTableDefinition.newBuilder()
        .setSchema(schema)
        .setTimePartitioning(timePartitioning)
        .build();

TableId tableId = TableId.of(projectName, datasetName, tableName)
TableInfo tableInfo = TableInfo.newBuilder( tableId, tableDefinition).build();
bigQuery.create( tableInfo);

Update on 19/03/2018:
To load some data into a specific partition (or to insert the result as a Select into a specific partition), you just have to add the day of this partition (using the suffix: $yyyymmdd) to the name of the table when you construct the TableId object. Here is an example:
private void runJob(JobConfiguration jobConf) {
    BIG_QUERY.create(JobInfo.of(jobConf));
}

private TableId getTableToOverwrite(String tableToOverwrite, String partition) {
    return TableId.of(PROJECT, DATASET, tableToOverwrite  + "$" + partition);
}

void loadInDayPartition(String dayUrl, String dayPartition) {

    LoadJobConfiguration loadConf = LoadJobConfiguration.newBuilder(getTableToOverwrite(TABLE_LEGACY, dayPartition),
            dayUrl, FormatOptions.avro())
            .build();

    runJob(loadConf);
}

I don't have any example to insert data in streaming into a partition table, but I guess it is similar.

A: If you want to partition by field, the code would look like as below.
Schema schema = Schema.of( fields);
Builder timeParitioningBuilder = TimePartitioning.newBuilder(TimePartitioning.Type.DAY);
timeParitioningBuilder.setField("partition_column");
TableDefinition tableDefinition = StandardTableDefinition.newBuilder()
        .setSchema(schema)
        .setTimePartitioning(timePartitioning)
        .build();

TableId tableId = TableId.of(projectName, datasetName, tableName)
TableInfo tableInfo = TableInfo.newBuilder( tableId, tableDefinition).build();
bigQuery.create( tableInfo);


text:
Q: re.search not matching the byte string I have a string object got from pexpect's session.before.
From this I am trying re.search for getting the device id using the below regular expression. But it is not matching.
print (str(sess.before))
b'\r\n* daemon not running. starting it now on port 5037 *\r\n* daemon started successfully *\r\n353651\tdevice\r\n\r\n\r\n'

device_id = re.search ('([0-9a-zA-Z]+)[\t ]+device', str(sess.before))
print (device_id)
None

A: The str() call converts your bytes object to a representation. Tabs will be represented as the character sequence '\' and 't', not an actual tab:
>>> str(b'\t')
"b'\\t'"

Don't hammer your bytestring to a string like that. Either decode from bytes to a string, or just use a bytes regular expression:
device_id = re.search(b'([0-9a-zA-Z]+)[\t ]+device', sess.before)

Now device_id is the match object; you may want to call .group(1) on that:
>>> import re
>>> before = b'\r\n* daemon not running. starting it now on port 5037 *\r\n* daemon started successfully *\r\n353651\tdevice\r\n\r\n\r\n'
>>> re.search(b'([0-9a-zA-Z]+)[\t ]+device', before)
<_sre.SRE_Match object; span=(89, 102), match=b'353651\tdevice'>
>>> re.search(b'([0-9a-zA-Z]+)[\t ]+device', before).group(1)
b'353651'


text:
Q: ViewController lifecycle UINavigationController I have an array of UIViewControllers that I display in my Root View Controller of a UINavigationController... I have an issue with one of my controllers that I push on the stack. It needs to present a UIImagePickerController each time viewDidLoad, however only does so the first push. To get around this I implement UINavigationControllerDelegate in my Root View Controller:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [viewController viewDidAppear:animated];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [viewController viewWillAppear:animated];
}

The problem is it calls these messages twice the first push... otherwise would be great. What am I missing?

A: You probably want to show the UIImagePickerController in viewDidAppear: instead of viewDidLoad:. Since you are keeping your view controllers in an array, they are only instantiated once therefore viewDidLoad: will most likely only be called once on each view controller. viewDidAppear: will be called every time the view controller is pushed or presented.
If your app got into a low memory situation it is possible that viewDidUnload: would be called at some point leading to viewDidLoad: being called again at some later point but you cannot rely on this at all.


text:
Q: Prolog - sort results but return one by one How to sort results in prolog by the last element in list, but still return them one by one, when pressing ;, not just a list with all of them.
I have a predicate route_with_total_dist/3 that returns lists with intermediary routes between point A and point B plus the train and direction. The total distance is the last element. For example:
?- route_with_total_dist(alexanderplatz, prinzenstrasse, R).
R = [[[alexanderplatz, u2, wittenbergplatz, ruhleben], [wittenbergplatz, u1, prinzenstrasse, 'warschauer strasse']], 11400] ;
R = [[[alexanderplatz, u2, wittenbergplatz, ruhleben], [wittenbergplatz, u3, nollendorfplatz, nollendorfplatz], [nollendorfplatz, u1, prinzenstrasse, 'warschauer strasse']], 11400] ;
R = [[[alexanderplatz, u2, nollendorfplatz, ruhleben], [nollendorfplatz, u1, prinzenstrasse, 'warschauer strasse']], 9800] ;
R = [[[alexanderplatz, u2, nollendorfplatz, ruhleben], [nollendorfplatz, u3, wittenbergplatz, 'krumme lanke'], [wittenbergplatz, u1, prinzenstrasse, 'warschauer strasse']], 11400] ;
R = [[[alexanderplatz, u2, gleisdreieck, ruhleben], [gleisdreieck, u1, prinzenstrasse, 'warschauer strasse']], 6900] ;
R = [[[alexanderplatz, u2, stadtmitte, ruhleben], [stadtmitte, u6, 'hallesches tor', 'alt-mariendorf'], ['hallesches tor', u1, prinzenstrasse, 'warschauer strasse']], 5000] ;
R = [[[alexanderplatz, u8, 'kottbusser tor', hermannstrasse], ['kottbusser tor', u1, prinzenstrasse, uhlandstrasse]], 3900] ;
false.

Now I would like to sort these results by the last element which is the total distance (shortest distance first), but still leave the option of being returned one by one. I know that I can do findall/3 or bagof/3 and then sort/2, but this will leave me with a huge list that will be just printed all at once.
In the example above (coincidentally) the results are printed in the exact opposite order that I want it. Expected would be:
R = [[[alexanderplatz, u8, 'kottbusser tor', hermannstrasse], ['kottbusser tor', u1, prinzenstrasse, uhlandstrasse]], 3900] ;
[[[alexanderplatz, u2, stadtmitte, ruhleben], [stadtmitte, u6, 'hallesches tor', 'alt-mariendorf'], ['hallesches tor', u1, prinzenstrasse, 'warschauer strasse']], 5000] ;
R = [[[alexanderplatz, u2, gleisdreieck, ruhleben], [gleisdreieck, u1, prinzenstrasse, 'warschauer strasse']], 6900] ;
...
...

How to do it?

A: If by "one by one", you mean with backtracking, you can use member/2.
routes_one_by_one(A, B, R) :- route_with_total_dist(A, B, List), member(R, List).


text:
Q: Miller-Rabin Primality test in Java I am currently working on Project Euler and thought that it might be more interesting (and a better learning experience) if don't just brute force all of the questions. On question 3 it asks for prime factors of a number and my solution will be to factor the number (using another factoring algorithm) and then test the factors for primality. I came up with this code for a Miller-Rabin Primality test (after thoroughly researching primality test) and it returns true for all the composite odd number I have put in. Can anybody help me to figure out why? I thought I had coded the algorithm correctly.
    public static boolean isPrime(long num)
{
if(num % 2 == 0)
    return false;
else
{
    double d;
    int r=0;
    while((num-1) % Math.pow(2,r+1) == 0)
        r++;
    d = (num-1) % Math.pow(2,r);
    int[] a = {2,3,5,7,11,13,17,23,31,62,73,1662803};
    boolean primality = true;
    for(int k = 0; k < a.length; k++)
    {
        if((Math.pow(a[k],d)-1) % num != 0)
        {
            for(int s = 0; s < r-1; s++)
            {
                if((Math.pow(a[k],Math.pow(2,s)*d)+1) % num != 0)
                    primality = false;

            }
        }
    }
    return primality;
}

A: Given num > 3, you want: d, r s.t. pow(2,r) * d = num - 1, where d is odd.
You are effectively counting trailing zeroes from num - 1, to remove factors of 2. However, after that loop, you know pow(2,r) is a factor of num - 1. Hence:
d = (num-1) % Math.pow(2,r);

will always yield: d = 0. I suspect you meant to replace % (mod) with / (div) here; otherwise, Math.pow(a[k],d)-1 will always yield (0), and the inner loop will never be executed.
As others pointed out, some simple trace statements or assertions would have found these errors. I think you have other issues, such as integer overflow. The loop for testing against the a[] candidates (the a-SPRP test) looks completely wrong to me.
Perhaps you've got the algorithm from Wikipedia, I prefer the more detailed reference in The Handbook of Applied Cryptography: 4.2.3: Miller-Rabin test, Algorithm: 4.24.