text:
Q: Analyzing/modelling discrete numerical responses and determining associations based on categorical co-variates I need and would be grateful for some advice regarding the analysis of some data that has been gathered and coded by a third party. The data is part of a project regarding performance in the health care sector and the person who has the data would like to perform some sort of analysis on it.
There are 4 variables in the data set as follows:
1.  hours: Hours worked (per week) from 1 – 37.5 (mostly numeric data but if a person works more than 37.5 hours worked this is coded as 37.5+).
2.  location: 11 locations in the sample (categorical).
3.  experience: Level of experience in years: 1-5, 6-9,… (categorical – but ordinal)
4.  number_activities: Number of activities performed: 1 – 8 (integer). 0 is a valid response but the data sample does not contain any 0 values for number_activities.
There are 65 "independent" observations on these variables.
Data User's Question:
Specifically, the data user has said he is interested in whether there is an association between the 3 variables hours, location, experience, based on the values in number_activities. The data user is not really interested in what the relationship is (at the moment at any rate) but just wants to know if one exists, and in particular if we can perform a hypothesis test for this.
From my initial investigation I do not think this is as easy an analysis as the data user assumes.
The data user, who is not a statistician, but who has performed statistical analyses in the past, specifically chi-squared tests for goodness-of-fit and for independence in categorical tables, thinks that something like this may be possible with the current data.
The data user has suggested converting hours to a categorical variable (e.g. (0 - 7.5], (7.5 - 15],…),  which I think may be necessary regardless of the analysis being performed, and using some form of chi-squared test approach.
Specifically he thinks:
1)  we could build a contingency table based on the levels of the three variables (hours, location, experience) using the totals of number_activities as the frequency counts for each of the levels of the three variables;
or
2)  analyse a number of 2x2 tables. For example we could build a number of 2 x 2 tables based on the levels of a third variable (partial tables) and try to perform a "goodness-of-fit" test for each of these multiple tables, assuming some null hypothesis regarding the distributions of number_activities at the different levels.
My opinion on this is as follows:
For option 1) from my understanding of contingency tables the approach is incorrect – we would be using the wrong counts, totals of number_activities for each level of the variables is not the correct count for this type of analysis – we would need instead to use the counts of the observations that occur at the different levels, and this won't tell us anything about the relationships based on number_activities. Further, given the number of levels in the variables compared to the 65 observations there would likely be a very large number of zero entries in the table.
For option 2) I'm not sure how this would work in practice. For the partial tables it would need a number of hypotheses to be formulated and there would be multiple tables with corresponding multiple hypotheses issues etc.
My initial opinion is that the data user would be better off using a modelling approach to the data with hours, location, experience as the explanatory variables and number_activities as the response/dependent variable. To answer the question of whether there is a relationship between the variables hours, location, experience we would need to include an interaction term in the model.
Specifically I could do with some advice as follows:
1) Is there any value in the approach suggested by the data user? What mean is there a single test one could do to test for association based on number_activities that I am clearly not aware of.
2)  Is the modelling approach the best way forward here?
3) If the modelling approach is a good way forward then the models I've been considering are:
a.  binomial – treat the number of activities as the number of successes in 8 independent trials – then for each observation number_activities then represents the of number of "successes"
b.  Poisson – the number_activities is a count, but it is restricted to 0 – 8, so would this be a problem?
c.  ordinal regression: ordered logistic or ordered probit models
4) Is there another approach – possibly simpler that I have just missed entirely?
It is a while since I've done this type of work and any advice/help would be most appreciated.


text:
Q: How to solve **TypeError : expected str, bytes or os.PathLike object, not WindowsPath** when importing matplotlib to python I am trying use matplotlib within Autodesk Revit software from the PyRevit Project
In this project, Pyrevit brings an embedded CPython interpreter (3.8.5) to Revit.
Until now, I've managed to import some packages (e.g. numpy, pandas), but unfortunately import matplotlib has been a big challenge.
When I try to import matplotlib, I got the following error:
CPython Traceback:
TypeError : expected str, bytes or os.PathLike object, not WindowsPath
File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 886, in <module>
 rcParamsDefault = _rc_params_in_file(
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 789, in _rc_params_in_file
 with _open_file_or_url(fname) as fd:
 File "contextlib.py", line 113, in __enter__
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 765, in _open_file_or_url
 fname = os.path.expanduser(fname)
 File "ntpath.py", line 293, in expanduser

...\matplotlib_init_.py
File ntpath.py
Doing the same, import matplotlib, from the Python 3.8.5 in the command line it works without any problem.
enter image description here
Thank you in advance for any suggestion from your side to solve this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upcase method not returning upcased string I keep getting false in these simple Ruby tests:
def large(string)
  if string.size > 20
    puts string.upcase!
  else
    puts string
  end
end

test:
p large("Hola vamos a la comida") == "HOLA VAMOS A LA COMIDA"
p large("Es hora de dormir") == "Es hora de dormir"

What is needed to make them work?

A: puts prints its argument, but it's return value is always nil:
> val = (puts "Hello World")
Hello World
=> nil
> val
=> nil

In your code, the return value of large is always nil, so the comparison with a string always returns false.
This is  probably closer to what you want:
def large(string)
  if string.size > 20
    string.upcase!
  else
    string
  end
end

A: puts prints on screen AND returns nil. nil and false in Ruby, in a boolean context, are false. Everything else is true. So your method largereturns nil. You should write it like this
def large(string)
    if string.size > 20
        string.upcase!
    else
        string
    end
end

A better way would be
def large(string)
  string.size > 20 ? string.upcase : string
end


text:
Q: Hide Toolbar and BottomBar in CoordinatorLayout when scrolling - visible under transparent status bar I have main activity with NavigationDrawer Toolbar and BottomBar. Inside the activity is container for fragments. And the fragment has RecyclerView. So when user is scrolling, I want to hide the Toolbar and BottomBar accordingly. I did that using layout behavior on recycler app:layout_behavior="@string/appbar_scrolling_view_behavior" and layout scroll flags app:layout_scrollFlags="scroll|enterAlways|snap" on Toolbar. For BottomBar I'm using this library: https://github.com/roughike/BottomBar
The problem is, that when the Toolbar and BottomBar are scrolled off the view, they are still visible under the StatusBar and NavBar
My code:
STYLE:
<style name="TranslucentStatusTheme" parent="AppTheme">
        <item name="android:windowTranslucentNavigation">false</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowContentOverlay">@null</item>
</style>

MAIN ACTIVITY CONTENT:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/app_bar_main_coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.activity.MainActivity"
    >

    <android.support.design.widget.AppBarLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomBar"
        android:fitsSystemWindows="true"
        />

    <com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/bottom_bar_menu_height"
        app:bb_activeTabColor="@color/colorAccent"
        app:bb_behavior="shifting|shy|underNavbar"
        app:bb_inActiveTabColor="@color/bottom_bar_inactive_tab_color"
        app:bb_tabXmlResource="@xml/bottombar_tabs"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom"
        android:layout_gravity="bottom"
        />

</android.support.design.widget.CoordinatorLayout>

AND IMAGES OF MY PROBLEM:
When no fitsSystemWindows flag is set - the toolbar is below stauts bar

When no fitsSystemWindows flag is set and content is scrolled - the toolbar is hide properly, but the bootom bar is still visible below nav bar

When fitsSystemWindows flag is set to root coordinator - the normal state looks ok

When fitsSystemWindows flag is set to root coordinator and content is scrolled - the status bar and bottom bare are visible below the transparent status bar and nav bar

Can anybody help me what I'm doing wrong? I already tried all possible combinations of fitsSystemWindows on different views.
EDIT:
I fixed the Toolbar below status bar issue, but I don't think that the solution is clean. I'm still looking for better one. And I still cannot solve the bottom bar issue
 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
 }
.....
 // A method to find height of the status bar
 private int getStatusBarHeight() {
      int result = 0;
      int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
      if (resourceId > 0) {
         result = getResources().getDimensionPixelSize(resourceId);
      }
      return result;
  }

A: To hide BottomBar on scroll, you need to set app:bb_behavior="shy"
<com.roughike.bottombar.BottomBar
    android:id="@+id/bottomBar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/bottom_bar_menu_height"
    app:bb_activeTabColor="@color/colorAccent"
    app:bb_behavior="shy"
    app:bb_inActiveTabColor="@color/bottom_bar_inactive_tab_color"
    app:bb_tabXmlResource="@xml/bottombar_tabs"
    app:layout_anchor="@id/container"
    app:layout_anchorGravity="bottom"
    android:layout_gravity="bottom"
    />


text:
Q: Overblown balloon: explode or burst? I want to describe how to blow and explode a balloon so do  we say balloon will explode or burst if you over blow it?
Which describe it better: "explode" or "burst"?
I checked online some sources say we can say "blow out" for both entering air to balloon or exploding it.

A: Blew out is understandable, but I don't think it's common. In my experience, the only thing I can think of that blows out (in the sense of "exploding") is a tire.

My tire blew out!

Between explode and burst, I think burst is better suited. Explode is more often used when the "explosion" was very violent, and it is especially apt when it was chemically induced.
You can also say that it popped. In my opinion, pop is softest, while explode is least soft (not soft at all): pop < burst < explode.
I provide relevant definitions and an Ngram search below.

*

*burst verb (used without object), burst or, often bursted, bursting.

*

*to break, break open, or fly apart with sudden violence:
  The bitter cold caused the pipes to burst.

*pop   verb (used without object), popped, popping.

*to burst open with such a sound, as chestnuts or corn in roasting.

*explode  verb (used without object), exploded, exploding.

*to burst, fly into pieces, or break up violently with a loud report, as a boiler from excessive pressure of steam.

  (Dictionary.com)

I redid the search with "balloon will pop" vs "balloon will explode" vs "balloon will burst" to try to better match the OP's "balloon will ____". Here are the results:

Notice that "balloon will explode" does not map. Between pop and burst, I think they're equally acceptable, with the slight distinction I made above.

A: The most common word for a balloon disintegrating on purpose is popping, because it's a sudden but fairly small event. Bursting is also acceptable, and is slightly more common when there's no deliberate attempt. (See frequencies below from Google Ngrams.    _DET_ means articles like a and the, and I used it for cases like "he popped the balloon"; _VERB_ means verbs like will, did, etc, most of which fit cases like "and then the balloon burst".)

Exploding is too strong a word. Blowing out could theoretically be used, but it's usually used in cases where there's no confusion, and especially when the failure occurs in only one direction instead of all directions at once (for example, a seal on a pipe can "blow out", sending whatever's inside out in a jet).

A: You can't really use overblown, because it has another meaning: bigger or more important or impressive than it should be.
According to the Oxford dictionary (see meaning 2), overinflated would work as an adjective. If you want a verb, you can use over-inflate: it's not really a standard word, so you should really use a hyphen.

If you over-inflate a balloon, it will burst.

A: You could say either

Inflate the ballon until it explodes.
  Inflate the balloon until it bursts.

and both sentences would be understood with the same meaning.
When a balloon bursts it creates an explosive sound.
However, the word you are looking for is

burst

especially since you making the balloon fail by purposely increases the internal air pressure.
If there is too much rain water buildup

a dam will burst open

Container boxes have

burst ratings

to describe the amount of internal pressure they can take before failing.

A: To my mind, I would use burst if the balloon failed while inflating. Popped would be once the balloon has been inflated and tied off. Another way to think of it in my mind is burst is accidental, while popping is more a purposeful action.


text:
Q: Filtering pandas Series with a condition on the elements of a list I want to filter my Series based on a condition on the elements of a list. I did this but it returns "Invalid syntax". crtitc1 is my DataFrame and elem1 is my list.
critic1 = critic1.loc[critic1["deltaP"] >= elem1[i] for i in range(len(elem1))]

Is there any method to do it ?
Thanks in advance

A: The comparison operators of Series can use lists as reference.
Assuming equal length of critic1 and elem1, you should be able to do:
critic1 = critic1.loc[critic1["deltaP"] >= elem1]

Or if elem1 is longer than critic1["deltaP"]:
critic1 = critic1.loc[critic1["deltaP"] >= elem1[:len(critic1)]]

If critic1["deltaP"] is longer than elem1 and you want to drop the last rows, you could try:
m = critic1["deltaP"].iloc[:len(elem1)] > elem1

critic1.loc[m[m].index]

alternative understanding of the question
test if elements of critic1["deltaP"] are in elem1:
Use isin:
critic1[critic1["deltaP"].isin(elem1)]


text:
Q: Arithmetic Mean of a set of critical points Consider the following functions: $f(x) = \sin(x)$and $g(x) =x^3 + 1$.
Let set $A$ include only the critical point(s) of $f$ across all reals and set $B$ include only the critical points of $g$ across all reals. Let $A\cup B$ denote the union of sets $A$ and $B$. Find the Arithmetic Mean of $A\cup B$.
Edit: So the mean of an infinite sit seems more like a measure, or so to speak, Infinite averages

A: We have $f'(x)=\cos(x),g'(x)=3x^2$  thus $f'(x)=0$ at $\frac {2n+1\pi}{2} $ where $n$ takes values of all integers. And $g'(x)=0$ only at $x=0$ hence the set $AUB={....,-\frac {3\pi}{2},-\frac {\pi}{2},0,\frac {\pi}{2},\frac {3\pi}{2},.....} $ We have 0 and on each of its side we have symmetric values with opposite sign hence they cancel out. Thus the mean of this set is $\frac {0}{n} $ hence the mean is $0$.

A: Think about the derivative of $f(x)$, which is $cos(x)$. Think about the symmetry of this function. When is it zero (i.e. where are $f(x)$'s critical points?) At $\pi/2, 3\pi/2, 5\pi/2 $, etc, but also at the negatives of those numbers, due to $cos(x)$'s symmetry. So when you sum them all up for the arithemtic mean, they all cancel. So the only contributions to the mean are from $g(x)$ (in other words, the sum of all the critical points converges to zero). It's a polynomial of degree 3 so clearly, there will be a finite number of critical points. So then you have the sum of three numbers (the critical points of $g(x)$), let's call it N, and N is a real number. Since there were infinite critical points in $f(x)$, you would be dividing this by infinity to get the mean. So essentially you have the limit of "N" divided by x, as x goes to infinity; i.e., zero. So the mean would be zero.

A: Critical points of sine function are $x=\frac{\pi}{2}+k\pi, k\in Z$. Critical point of the cubic function is $0$. So the sum of all critical points is $0$, hence mean is $0$ as well.


text:
Q: How to set css to custom tag (datepicker) in jsviews? It might be a simple question for those who are already familiar with jsviews. It is taking me more than a hour to figure out how to set/append the CSS class to datepicket tag.
I am following this example: http://www.jsviews.com/#samples/tag-controls/datepicker/with-validation
                    <div class="col-md-3">
                        {^{validate enddate
                        required=false
                        ^minday=startdate
                        }}
                        {^{datepicker numberOfMonths=2 /}}
                        {{/validate}}
                    </div>

It is working fine but how to set the custom css to datepicker tag? I want to set "class="form-control"" .. I tried the following code but it doesn't work.
                        {^{validate startdate
                        required=false
                        ^maxday=enddate class="form-control"
                        }}
                        {^{datepicker numberOfMonths=2 class='form-control'/}}
                        {{/validate}}

I am trying a few different ways as well.. As jsviews datepicker is using jquery ui and validation, I am looking at this post as well How to add a custom class to my JQuery UI Datepicker..
Until now, I am not able to set the custom css tag to {^{datepicker yet. I will keep on looking but let me know if you know how to do this. Thanks!

A: JsViews tags that wrap HTML elements generally allow you to optionally provide the element declaratively (as HTML markup wrapped by the tag) - and if you do then you can trivially add a class property to the wrapped element. You don't need to write any script code.
See this example http://www.jsviews.com/#samples/tag-controls/datepicker/variants.
So you can write:
Tag syntax
{^{datepicker .../}}

Tag syntax, wrapping input element:
  {^{datepicker ...}}
      <input ... [class="foo"] />
  {^{/datepicker}}

Tag syntax, wrapping div element:
  {^{datepicker ...}}
      <div ...[class="foo"] > ... </div>
  {^{/datepicker}}

In your case you are also wrapping in the validate tag, so you can write:
{^{validate endDate required=true ^minday=startDate}}
  {^{datepicker numberOfMonths=2}}
    <input class="form-control"/>
  {{/datepicker}}
{{/validate}}


text:
Q: Inheritance, polymorfism, interfaces, Java coding excercises I'm pretty new in this world and, I'm learning how to make codes by trying to do exercises that a friend sent me but I have a problem and I don't know exactly what it is.
The topic is inheritance, polymorphism, and interfaces
I am supposed to have these 3 animals and give them food (fish, meat, garbage) and they will answer if they like it or not.
This is my "Gato" subclass
package Animal; public class Gato implements Animal {

String nombre;

public Gato() {

    this.nombre = "Missi";
}

public Gato(String nombre) {
    this.nombre = nombre;
}

@Override
public String hablar() {
    return "Miauuuuu";
}

@Override
public String giveFood(String food) {
    if(alimento.equals("fish")) {
    return "ñam ñam"; }else{
    return "i dont like it";

    }

}

public String toString(){ return "Soy un Gato y me llaman "+ nombre; }

}

This is my interface
package Animal; public interface Animal {
String DEFINICION = "Ser orgánico que vive, siente y se mueve por propio impulso";

public String hablar();

public String giveFood(String alimento); }

And this is my main
Public class Main {
static Scanner entrada = new Scanner (System.in).useLocale (Locale.US);

    public static void main(String[] args) {
        int operacion;
        boolean salir = false;
        // CREAR OBJETOS
        Gato gat = new Gato();
        Perro per = new Perro();
        Tigre tig = new Tigre();

        while (!salir) {

            System.out.println("\nElige el tipo de animal: ");
            System.out.println(" 1 - Perro / 2 - Gato / 3 - Tigre " + " / 4 - Salir");
            // Permite capturar lo que se escribe por teclado y lo deja en la
            // variable operación.

            operacion = entrada.nextInt();

            switch (operacion) {

            case 1:
                System.out.println(per.toString());
                System.out.println(per.hablar());
                System.out.println(giveFood(per));
                break;

            case 2:
                System.out.println(gat.toString());
                System.out.println(gat.hablar());
                System.out.println(giveFood(gat));
                break;

            case 3:
                System.out.println(tig.toString());
                System.out.println(tig.hablar());
                System.out.println(giveFood(tig));
                break;

            case 4:
                System.out.println("Bye bye");

                salir = true;

                break;

            default:

                System.out.println("Seleccione otra operación");

            }
        }
    }

    public static String darDeComer(Animal ani) {

        boolean salir = false;
        while (!salir) {

            System.out.println("What do we give them? ");
            System.out.println(" 1 - fish / 2 - meat / 3 - garbage " + " / 4 - Salir");
            int comida = entrada.nextInt();

            switch (comida) {

            case 1:
                System.out.println(giveFood(ani));

                break;

            case 2:
                break;

            case 3:
                                break;
            case 4:
                salir = true;

                break;
            }

            return "";
        }

    }
}

So how do I proceed? I can't get the answer from my subclasses, and I don't know how to give the "animals" specific "food" to gain and specific answer.

A: I'm going to avoid writing the exact code because you are close and it will be better to work it out yourself...
giveFood() is a method that belongs to each animal, just like toString() and hablar(). So you need to call it in each case, just like the other two functions.
At the beginning of your program, after you prompt for animal type, you should next prompt "What type of food would you like to give?" (use nextLine() for that input instead of nextInt()). Save that input in a string variable called: "food".
Then under each case you print out the result of giveFood(), passing in the food variable:
System.out.println(gat.giveFood(food));

For "gato" type, you'd expect that if you type "fish" when prompted for food, he will reply with "nom nom". If you reply with anything else he will say: "i don't like it".
You could stop reading at this point and just get your code working as described above, but then you may wish to go a little further since you are trying to learn. The way the 3 cases are setup above, it's not really taking advantage of the inheritance/polymorphism.
The point of polymorphism is that you can have objects with different "guts under the hood" but treat them the same on the outside because the public interface to them is identical. To better illustrate that, you want your code to create a single animal object variable. Your case statement would then just initialize the variable to one of the three types. Then after the case, you can call the three methods on the object and the output will be different based on the type:
Animal someAnimal;

switch (operacion) {
    case 1:
        someAnimal = new Perro();
        break;
    case 2:
        someAnimal = new Gato();
        break;
    case 3:
        someAnimal = new Tigre();
        break;
}

System.out.println(someAnimal.toString());
System.out.println(someAnimal.hablar());
System.out.println(someAnimal.giveFood(food));


text:
Q: Remove Boost libstdc++ dependency with clang++/libc++? The answer to this question How to compile/link Boost with clang++/libc++? states to build Boost with clang++ and libc++, the following should do:
./b2 clean
./b2 toolset=clang cxxflags="-stdlib=libc++" linkflags="-stdlib=libc++"

I tested the above tip on a Scientific Linux 6.4 x86_64 host and it works "mostly" building the full Boost 1_53_0 distribution, with clang++ 3.3sv and libc++ 3.3svn. I said mostly, as I really like to remove all libstdc++ dependency.
Nevertheless, the following:

*

*libboost_graph

*libboost_locale

*libboost_regex
still shows libstdc++ dependencies (the ldd output makes it quite obvious).  I would like to know a good way to remove such and would appreciate any hint.

A: I found out how to do it.  Thanks to @Howard Hinnant for his mentioning of libc++abi. After RTFM http://libcxx.llvm.org/, it's trivial to build the entire boost libraries free of any libstdc++ dependencies. Yes, all I had to do is to RTFM!


text:
Q: Гексагональная сетка для google map Привет, кто сталкивался с добавлением гексагональной сетки для google карт?
Вот такую сетку нужно добавить на всю ширину карты, которая вмещается в экран:

A: Идея вкратце
Упрощённо говоря, Google Maps – это всего лишь слой в HTML, который обрабатывает действия пользователя и на их основе манипулирует содержимым карты (по большей части изображениями).
Ничего не мешает наложить поверх этого свой HTML слой с любым содержанием. Напротив, разработчики карт к этому и призывают, предоставляя функционал для преобразования географических координат к координатам внутри этого слоя (и больше ничего существенного не дают).
Поэтому наложить можно вообще что угодно, главное – чтобы это было полезно и удобно в рамках Вашей задачи.

Нюансы
Вы действительно указали очень мало деталей. Например, зачем Вам это? Помимо любопытства это важно для ответа, из области применения вытекают важные моменты. Как минимум, у меня есть такие вопросы:

*

*Должна ли эта сетка быть привязана ко всему земному шару или только к каким-то регионам, с которыми Вы планируете работать? Варианты: глобус / регион.
На мой взгляд, фраза "на всю ширину карты, которая вмещается в экран" не совсем отвечает на этот вопрос.

*Нужно ли Вам учитывать проекцию Меркатор? (Как упомянул @sanmai) Варианты: Меркатор / не Меркатор.

*Нужна ли Вам эта сетка с фиксированным масштабом, или же при приближении она должна увеличиваться и разделяться на более мелкие шестиугольники? Варианты: фикс / раздел.

*Должно ли быть какое-то взаимодействие с этими шестиугольниками? Должны ли они отображать цвета, текст? Варианты: взаимод / без взаимод.

*С технической стороны, как лучше реализовать наложение на Гугл-карты для Вашей задачи? По большей части, ответ на этот вопрос вытекает из ответов на предыдущие. Варианты: картинка / холст canvas  или svg.
Некоторое время назад я разрабатывал библиотеку GMapsTable для наложения таблицы на Google Maps (описание на Хабре), и могу сказать, что в любом случае это весьма непростая задача. В качестве наложения я использовал таблицу, так как шестиугольники мне не были нужны, а Меркатор не учитывался (данные не по глобусу, а регионам, искажения слабо заметны). Также, в таблицу легко добавлять текст (простым HTML) или взаимодействие (можно наляпать JS события отдельным ячейкам).

Предлагаемые варианты решения
В зависимости от комбинаций ответов:

*

*фикс, без взаимод – можно взять любую PNG картинку с сеткой и наложить на нужный участок карты. Это не зависит от проекции (Меркатор или нет) и от местоположения (глобус или регион), просто нужно подобрать / сгенерировать оптимально подходящее изображение. Довольно лёгкий, но на столько же мало функциональный способ.

*В большинстве остальных случаев я бы использовал холст или svg. Это сложно, особенно если погнаться за точностью, красотой, плавностью, зато возможности ничем не ограничены.
Вне зависимости от фикс / раздел лучше задать готовый массив точек, а не вычислять всё в коде. Если нужны разделяющиеся шестиугольники, это также проще реализовать на основе имеющихся начальных вершин. В таком случае задача сводится всего лишь к созданию этого набора точек и алгоритма для их отрисовки, преобразования шестиугольников к координатам на экране.
Вывод текста и цветов в таком случае относительно лёгок. Если нужно взаимодействие, то можно просто перехватывать событие клика и реализовать функцию обратного преобразования: от координаты на экране к конкретному шестиугольнику.
Как создать набор исходных точек? Например, можно банально взять одну из картинок с шестиугольниками (Меркатор или нет, на Ваш выбор) и вручную или с кодом перевести все вершины в координаты широты/долготы. Можно составить их в отдельные объекты шестиугольников или же просто отдельно прописать линии между точками, если работы с шестиугольниками не планируется. Муторно, но альтернатива не проще: написать код для генерации сферы с поверхностью из шестиугольников и перевода этих же вершин, линий / шестиугольников в координаты карты.

Полезные ссылки:

*

*Google Maps API: собственные наложения на карту – простой пример с наложением картинки.

*Исходный код GMapsTable – большой пример с динамическим наложением табицы.

A: Прямо так, как вы хотите, у вас не получится так сделать на всех увеличениях потому что на Гугл-картах используется проекция Меркатора. Это значит ближе к полюсам ваша сетка будет искажена, будто бы натянута на шар. Примерный вид:

Картинка отсюда.


text:
Q: Move a window back into the visible area in Xubuntu? On my laptop, after I use a higher-resolution external monitor, applications will sometimes place themselves outside the visible area of my desktop. How do I move them back into the visible area?
(No part of the window is visible, so I can't use the mouse.)
I'm running Xubuntu 9.10 (XFCE)

A: Found it, I'm answering just in case someone else get confused.
Under:
settings -> Window manager -> Keyboard
There is shortcut called "Move window"
And if I first cykle the app into focus with Alt+tab and then Alt+F7 (the move window), the app jumps to the mouse pointer and then I could just place it where I wanted it..


text:
Q: Sinatra + Paperclip; uploaded images have no extension When uploading images Paperclip is saving files wo/ extensions. I'm using ActiveRecord
photo.rb (model):
require "sinatra"

class Photo < ActiveRecord::Base
    include Paperclip::Glue

    attr_accessible :image

    has_attached_file :image,
        :styles => {
            :small => "100x100#",
            :medium => "500x300"
        },
        :path => "#{settings.root}/public/system/:class/:attachment/:attachment/:id_partition/:style/:filename"
end

photos.rb (controller):
post "/photos/?" do
        params[:photo][:image] = params[:photo][:image][:tempfile] if params[:photo][:image]
        @photo = Photo.new(params[:photo])
        if @photo.save
            { :status => "OK"}.to_json
        else
            { :status => "NOK"}.to_json
        end
    end


text:
Q: MVC4 .Net , controls on hidden fields I wonder if it's possible to have controls (dataanotation) on hidden fields (HiddenFor or hidden EditorFor) ?
I don't think so, but we never know.
There are a lot of posts on how to hide EditorFor such as :
TextBoxFor vs EditorFor, and htmlAttributes vs additionalViewData
In my case,in a view I have a jquery call to a WCF REST service, that in success case fill my EditorFor. I would like that the Required DataAnotation to be applied on that EditorFor, would it be possible ?
I think that as long as the EditorFor is invisible the DataAnotation cannot be applied. Would it have a way to apply the DataAnotation on the hidden EditorFor ?

Here is the code :
To hide the EditorFor :
@Html.EditorFor(model => model.VilleDepart, "CustomEditor", new {style = "display:none;" })

The CustomEditor :
@{
    string s = "";
    if (ViewData["style"] != null) {
        // The ViewData["name"] is the name of the property in the addtionalViewData...
        s = ViewData["style"].ToString();
    }
}

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { style = s })

the model :
string _VilleDepart;
[Required]
[Display(Name = "Ville Départ")]
public string VilleDepart
{
    get
    {
        if (Commune != null) {
            return Commune.Commune1;
        }

        return _VilleDepart;
    }
    set {
        _VilleDepart = value;
    }
}

The JQuery call to WCF REST Service :
$(document).ready(function () {
    $([document.getElementById("IVilleDepart"), document.getElementById("IVilleArrivee")]).autocomplete({
        source: function (request, response) {
            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                dataType: "json",
                url: GetSearchCommunetURl + "(" + request.term + ")",
                success: function (data) {
                    //alert(data);
                    response($.map(data, function (item) {
                        return {
                            label: item['Commune'] + ' (' + item['CodePostal'] + ')',
                            val: item
                        }
                    }))
                },
                error: function (response) {
                    alert("error ==>" + response.statusText);
                },
                failure: function (response) {
                    alert("failure ==>" + response.responseText);
                }
            });
        },
        select: function (e, i) {
            if (e.target.id == "IVilleDepart") {
                VilleDepart = i.item.val;
                EVilleDepart.value = VilleDepart.Commune;
                ECodePostalDepart.value = VilleDepart.CodePostal;
                ECodeINSEEDepart.value = VilleDepart.CodeINSEE;

            }
            if (e.target.id == "IVilleArrivee") {
                VilleArrivee = i.item.val;
                EVilleArrivee.value = VilleArrivee.Commune;
                ECodePostalArrivee.value = VilleArrivee.CodePostal;
                ECodeINSEEArrivee.value = VilleArrivee.CodeINSEE;
            }
        },
        minLength: 2
    });
});

If I don't hide the EditorFor I can see it is correctly filled after the WCF REST service call and the Required DataAnotation is applied.
There are other way to hide the EditorFor, for instance to apply the style='width:0px;height:0px'
It hides but disable the Required DataAnotation,
if I apply the style='width:0px;height:1px', we don't see a lot of the EditorFor but the Required DataAnotation is active.

A: I've seen an answer at http://www.campusmvp.net/blog/validation-of-hidden-fields-at-the-client-in-asp-net-mvc
(but it seems i had badly searched precedently, the validation of hidden field is treated in some blogs and sites).
To active the validation of hidden fields, you just have to add this little javascript line :
$.validator.setDefaults({ ignore: null });

and it works !
Apparently it doesn't work with mvc2, but works since mvc3.


text:
Q: Show/hide subview when changing button state What i'm trying to achieve
I have two buttons, yes/no. When yes is pressed a subview needs to be generated right under it and when no is pressed the subview need to disappear(not just hide, but remove itself).
After doing some search i have reached the conclusion that what i need is a dynamic view.
What i tried to do
I have created the buttons and now i'm trying to write the code for the view, so at the end i will have to connect the buttons to the code.
This is my UIView Class:
class FormView: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    viewSetup()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

private func viewSetup() {
    self.backgroundColor = .red
}
}

and this is how i tried to create the view:
    var formViewOrigin = selectFormView.frame.origin
    formViewOrigin.y += selectFormView.frame.height

    let formViewWidth = selectFormView.frame.width
    let formViewHeight = selectFormView.frame.height
    let formViewSize = CGSize(width: formViewWidth, height: formViewHeight)

    let myview = FormView(frame: CGRect(origin: formViewOrigin, size: formViewSize))

    myview.leadingAnchor.constraint(equalTo: descriptionLabel.leadingAnchor)
    myview.topAnchor.constraint(equalTo: selectFormView.bottomAnchor, constant: 24)
    myview.trailingAnchor.constraint(equalTo: selectFormView.trailingAnchor)
    myview.bottomAnchor.constraint(equalTo: descriptionTextField.topAnchor, constant: 50)

    let bigView = scrollView.viewWithTag(1)
    bigView!.addSubview(myview)

The problem
The view is being generated, but it is not in the place that i want it to be(right under my buttons), instead it is at the end of the bigview. I have tried to change the constraints but i think they don't have any impact, because i also commented them and nothing happened. Does anyone have any idea on why is this happening?
To give you a better visual understading of what i'm trying to do here is an image: formview
FormView has to appear between description and selectFormView.
selectFormView is the view that contains the buttons.

A: Sol1
let myview = FormView(frame: CGRect(origin: formViewOrigin, size: formViewSize))
myview .translatesAutoresizingMaskIntoConstraints = false
let bigView = scrollView.viewWithTag(1)
bigView!.addSubview(myview)
myview.leadingAnchor.constraint(equalTo: descriptionLabel.leadingAnchor).isActive = true
myview.topAnchor.constraint(equalTo: selectFormView.bottomAnchor, constant: 24).isActive = true
myview.trailingAnchor.constraint(equalTo: selectFormView.trailingAnchor).isActive = true
myview.bottomAnchor.constraint(equalTo: descriptionTextField.topAnchor, constant: 50).isActive = true
myview.heightAnchor.constraint.heightAnchor.constraint(equalToConstant: 300).isActive = true
self.view.layoutIfNeeded()

Note : this also involves removing the constraint between the description and select view as not to have constraint confliction  , and after removing myView reAdd it
Sol2
make a view in IB and set it height constraint to 0 and make this to toggle show/hide
self.myViewH.constant = show ? 300 : 0
self.view.layoutIfNeeded()

A: you should make autoLayout constraints after adding UIView into view

remember that if you add UIView with constraints before adding that in another view , the UIView lose your constraints when its add to the destination view


text:
Q: Reference project causes "Could not load file or assembly" within my own solution I have 2 projects within my solution. In my second project I want to use some of my classes from my first project. I added a reference in my second project to my first project, however when I try and call/invoke/instantiate any object in my second project from my first project I get a:
Could not load file or assembly 'MyFirstProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
For example, if I try and create a List it will throw the error above
Any ideas?
Thomas


text:
Q: Reactjs: Stop autoscrolling when component is not mounted I have a react app, and I have a two routes, /home and /items which renders ListComponent
Items have a bool property scrollHere, which I am using to scroll to a list item automatically and it works well with the code as shown below. The problem that I have is that when I go back to /home then it tries to scroll down to the position that list item was. How can I prevent this behaviour?
export const ListComponent = (items: ItemObject) => {
  const itemToScroll = useRef<null | HTMLDivElement>(null);
  const mounted = useRef(false);

  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
    } else {
      scrollToItem();
    }
  });

  const scrollToItem = () => {
    itemToScroll.current?.scrollIntoView({ behavior: "smooth" });
  };

  return (

        {
        items.map(item =>
          item.scrollHere ? (
{itemName}
) : <></>
        }

  );
};


text:
Q: Prove that $K = \cap_{g \in G} g^{-1}G_xg$ Relevant definitions:

$$G_x = \{g \in G \mid \rho_g(x) = x\}$$

Question:

Let $\rho: G \to S(X): g \mapsto \rho_g$ be a transitive group
  action. Let $K := \ker \rho$. Then $K = \cap_{g \in G} g^{-1}G_xg$

My attempt (which I know is wrong, since I didn't use transitivity!):

$\boxed{\supset}$
Let $k \in \cap_{g \in G} g^{-1}G_xg$. Then, for all $g \in G$, there
  exists $l \in G_x$ such that $k = g^{-1}lg$, such that $\rho_k =
 \rho_{g^{-1}lg} = 1_X$, meaning that $k \in K$
$\boxed{\subset}$
Let $k \in K$ and $g \in G$. Then, consider the group element $h :=
gkg^{-1}$. Then, we have $\rho_h(x) = x$, such that $h \in G_x$. Now,
  it follows that $k = g^{-1}hk \in g^{-1}G_xg$ for any $g \in G$, as
  desired.

Can someone point out where my mistake is? I am quite sure I made a mistake since I never used transitivity.

A: You can't conclude that $\rho_k = 1_X$ just from what you've written.  However, it follows from the fact the $k = g^{-1} l g$ that $k \in G_{\rho_{g^{-1}}(x)}$.  Can you see how to use transitivity now?
The second part looks ok except for a typo (I guess you meant $k = g^{-1}h g \in g^{-1}G_xg$ instead of $k = g^{-1}h k \in g^{-1}G_xg$).


text:
Q: Could any one please point out the mistake in the IF statement I am very new to JAVA and couldn'y figure out the problem with the IF statement
class SpaceRemover {

    public static void main() {

        String mostFamous= "This is a test";
        char[] mfl = mostFamous.toCharArray();

        for (int dex = 0; dex < mfl.length; dex++) {
            char current = mfl[dex];

            if (current != "") {
                System.out.print(current);
            } else {
                System.out.print(".");
            }
        }
        System.out.println();
    }
}

A: current is defined as a char but you're trying to compare it to a String. Quite simply, that is an error in your code, and the Java compiler will have informed you of such with an error message to the effect of

incomparable types: char and java.lang.String

The error message is saying that you can not compare a char to a String. Learn to read these error messages, it will pay immense dividends for you in the future.
Right now you have the empty String, there is no corresponding value for char but it appears that you meant to compare to space "' '" anyway. Thus:
if (current != ' ') {
    System.out.print(current);
}
else {
    System.out.print(".");
}

A: Judging from the class name and code provided, I assume you are trying to remove all spaces from a string and replacing them with periods?
Your issue lies in the line
if (current != "") {

Firstly, that's not a space, that's an empty string.
Secondly, you should compare it to a char.
It should be like this:
if (current != ' ') {

A: you should compare characters with current.equals(' ') method
and you are comparing character with a string here


text:
Q: SSL connect error/crash under strange circumstances When using libQuickMail in the shared object, the application crashes when loading from that so.
Say I have two programs:
program 1 is a program that loads a shared object. We'll call this program "prog1" and the shared object "so1". If relevant, the whole thing is a C++ Crow framework (multithreaded) application.
program 2 is just a single file main function. We'll call this "prog2".
Both so1 and prog2 use the same libquickmail code specified in the docs, specifically this one:
quickmail_initialize();
quickmail mailobj = quickmail_create("[SENDER_EMAIL]","libquickmail test e-mail");
quickmail_set_body(mailobj, "This is a test e-mail.\nThis mail was sent using libquickmail.");
quickmail_add_to(mailobj, "[RECEIVER_EMAIL]");

const char *errmsg = quickmail_send(mailobj, "[SMPT_ADDRESS]", [SMTP_PORT], "[SENDER_EMAIL]", "[PASSWORD]");
if (errmsg != NULL) {
    fprintf(stderr, "Error sending e-mail: %s\n", errmsg);
}

quickmail_destroy(mailobj);

prog2 runs just fine, however when prog1 tries to run the loaded so1, it either crashes or throws an SSL connect error. This doesn't happen when I move the code directly to prog1, though, however that isn't a viable solution.
Any suggestions/reasons as to why this would happen?
Thanks for reading


text:
Q: Modifications of BFS/DFS to check simple paths I have to design an algorithm as from BFS or DFS to do the following, given G=(V,E) a directed graph:
Check whether there is at most one simple path from s to any other vertex u in V. This algorithm has to be on O(|V|+|E|).
And from the previous algorithm, I have to design another one O(|V||E|) algorithm to check whether there is at most one simple path between any two vertices u and v.
I hope you can help me! Thanks a lot in advance!

A: Hint: What if all the edges on the path from s to u are cut edges (bridge)? What if any of them are not cut edge? :)
Note: We can find all the bridges in a graph O(V+E) time


text:
Q: How can I insert to another table using the insert id? I've got a problem like this , I cannot get the id of the parent table .
table_name : transaction_tbl

- transaction_id
-file_name
-file_path
-description

table_name : transaction_details
-details_id
-transaction_id
- details

here is my code to insert :
$sql = "INSERT INTO transaction_tbl (`file_name`,`file_path`,`description`) VALUE('$file_name','$file_path','$description') " ;

$query = $conn->query($sql);
$transaction_id = mysqli_insert_id($conn);
if ($query === True ){
      $sql = "INSERT INTO transaction_details (`transaction_id`,`details`) VALUES ($transaction_id,$details) ";
}else {
      trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error, E_USER_ERROR);
}

Now I can insert in my transaction_tbl but not in transaction_details. what should I do? Can somebody help me?

A: Add $query = $conn->query($sql); inside if condition as below
if ($query === True ){
      $sql = "INSERT INTO transaction_details (`transaction_id`,`details`) VALUES ($transaction_id,$details) ";
      $query = $conn->query($sql);
}
else {
          trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error, E_USER_ERROR);
}


text:
Q: Object movement issues in python If youre reading this I appreciate your time and would like to thank you in advance.
So the current goal of mine is to have neutrons shooting in random directions with random speeds at a source (x,y).
Ive ran into a bunch of related problems that I cant fix with my knowledge in the moment (im quite inexperienced in programming)
The Problems are the following:
1.
The "move" method in the Program is not working as intended = With every generation of a new object (Neutron class) the objects get faster.
2.
I cant assign the move methon to the objects in the "neutrons" list individually. Its either that all objects move in the same direction
with the same speed or only the last element of the "neutrons" list moves and the rest stay still.
The example in the program:
for n in neutrons:
    n.draw(screen)
    neutrons[-1].move(angle_list, neutr_v_list)  #newest neutron moves, the rest stays still

    n.move(angle_list, neutr_v_list)    #Every Neutron moves the same

*

If I define the "move" method as the following:
self.x += math.cos(random.randint(0,360)) \* 2
self.y += math.sin(random.randint(0,360)) * 2

What happens is that in this loop:
for n in neutrons:
    n.move()

the random values get generated over and over again which causes the individual objects not move in a straight line. They move like a bee thats been fed some caffeine.
The ultimate goal at the moment is when an object (neutron in this scenario) hits another object (a uranium atom) it should generate 3 new neutrons in the x,y of the collision and the neutrons should fly off in random directions and potentially hit another Uranium atom.
Github link to the program: https://github.com/Magicalsauce69/Nuclear-simulation-in-python.git
Full code:
#imports

from typing_extensions import Self
import pygame

#Imports

import pygame as py
import os
import random
import math
import time
from random import *
import random

#Framerate

FPS = 60

#Creating the lists

angle_list = []
neutrons = []
neutr_v_list = []

#Colors

RED = (255, 0, 0)
BLUE = (51, 51, 255)
LIGHT_BLUE = (173,216,230)
WHITE = (255, 255, 255)
PURPLE = (204, 0, 204)
GRAY = (128, 128, 128)

#Creating a window

py.init

WIDTH, HEIGHT = 700, 700  #aspect ratio is  ...
screen = py.display.set_mode((WIDTH, HEIGHT))
py.display.set_caption("Starting to loose it")

#function that gets called in the mainloop that draws stuff on the screen

def draw_screen():
    screen.fill(WHITE)
    py.display.update()

#The Neutron class

class c_Neutron():
    def __init__(self, x, y, r, v, name,):
            self.x = x
            self.y = y
            self.r = r
            self.v = v
            self.name = name
            self.color = LIGHT_BLUE

    def draw(self, screen):
        py.draw.circle(screen, self.color, (self.x - self.r, self.y - self.r), self.r, 10)

    def move(self, angle_list, neutr_v_list):
            self.x += math.cos(angle_list[-1]) * neutr_v_list[-1]    #Im trying to generate random directions and speeds for every neutron specifically
            self.y += math.sin(angle_list[-1]) * neutr_v_list[-1]     #Another issue is that they get faster with every neutron generated

#The Uran class

class n_Uran():

    def __init__(self, x, y, r,):
        self.x = x
        self.y = y
        self.r = r

        self.color = [RED]

    def draw(self, screen):
        py.draw.circle(screen, self.color, (self.x - self.r, self.y - self.r), self.r, 10)

#Amount of Neutrons
Anz_neutronen = len(neutrons)   #Should return how many elements are in the list
print(Anz_neutronen)

#Mainloop

def main():

    clock = pygame.time.Clock()
    keydown_list = []

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    keydown_list.append(1)
                    print(len(keydown_list))
                    neutrons.append(c_Neutron(200,200,5,random.randint(1,3),"")  )
                    angle_list.append(random.randint(0, 360))
                    neutr_v_list.append(random.randint(1, 3))

                    print(neutrons)

        screen.fill(WHITE)

        for n in neutrons:
            n.draw(screen)
            neutrons[-1].move(angle_list, neutr_v_list)           #Only the newest neutron moves and the rest stays still
            n.move(angle_list, neutr_v_list)                       #Every Neutron moves the same

        py.display.update()
        clock.tick(FPS)

#Run the main game loop

if __name__ == "__main__":
    main()

A: Problem 1
I didn't encounter this problem; it may have just happened by chance in your test. Either way, it doesn't happen with the code I have created.
Problem 2
You have tried two ways of doing this, but neither of them work, for the following reasons:

*

*When you use n.move(angle_list, neutr_v_list), you are passing the same parameters to each neutron, so of course they all move in the same way.

*When you use neutrons[-1].move(angle_list, neutr_v_list), neutrons[-1] refers to the last object in the list neutrons, so only the last neutron ever gets moved.

The correct way to get this to work would be to store the angle and velocity of each neutron as an attribute of that neuron, and not make the move method take any attributes.
Problem 3
Here you tried a different way of solving problem 2, which also didn't work, for the reason you stated in your question.
The right way of doing this is to just generate a random value once when each neutron is created, and store it as an attribute of that neutron, as I said above.
The working code
Here is my working version of your code. I also changed a few other things about it:

*

*The formatting and variable names, to fit PEP8

*I added a base Particle class for both Neutron and Uranium to inherit from, to avoid code duplication

*pygame.init -> pygame.init() and is now inside main()

*Moved some other code to be inside main()

*Removed duplicate imports and made all uses of PyGame be pygame not py

*Instead of calculating how much the X and Y of each neutron should change every time, used a cached_property for each one to only calculate them once

*Some other minor things that have little effect

import os
import random
import math
import time
import sys

import pygame

try:
    # Python 3.8+ only
    from functools import cached_property
except ImportError:
    # Does the same exact thing, but works on all python versions
    # Remove this if guaranteed to be using Python 3.8+
    from functools import lru_cache
    cached_property = lambda method: property(
        lru_cache(maxsize=None)(method)
    )

RED = (255, 0, 0)
BLUE = (51, 51, 255)
LIGHT_BLUE = (173, 216, 230)
WHITE = (255, 255, 255)
PURPLE = (204, 0, 204)
GRAY = (128, 128, 128)

FPS = 60
WIDTH, HEIGHT = 900, 600

class Particle:

    def __init__(self, x, y, radius, color):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color

    def draw(self, screen):
        pygame.draw.circle(
            screen,
            self.color,
            (int(self.x - self.radius // 2), int(self.y - self.radius // 2)),
            self.radius,
        )

class Neutron(Particle):

    def __init__(self, x, y, radius, velocity, angle):
        super().__init__(x, y, radius, color=LIGHT_BLUE)

        self.velocity = velocity
        self.angle = angle

    @cached_property
    def dx(self):
        return math.cos(self.angle) * self.velocity

    @cached_property
    def dy(self):
        return math.sin(self.angle) * self.velocity

    def move(self):
        self.x += self.dx
        self.y += self.dy

class Uranium(Particle):

    def __init__(self, x, y, radius):
        super().__init__(x, y, radius, color=RED)

def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Starting to lose it")

    clock = pygame.time.Clock()
    neutrons = []

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    neutrons.append(Neutron(
                        x=int(WIDTH // 2),
                        y=int(HEIGHT // 2),
                        radius=5,
                        velocity=random.randint(1, 3),
                        angle=random.randint(1, 360)
                    ))

        screen.fill(WHITE)

        for n in neutrons:
            n.draw(screen)
            n.move()

        pygame.display.update()
        clock.tick(FPS)

if __name__ == "__main__":
    main()


text:
Q: taking date as dd/mm/yy in c language     # include <stdio.h>
int main(){
    int d1, d2, m1, m2, year;
    printf("Enter date (dd/mm/yy): ");
    scanf("%d,%d/%d,&,d/%d", &d1,&d2,&m1,&m2,&year);

**Hello guys I am new in c programming so I'm trying to take the date as dd/mm/yy format but when I write it like this it gives me an output as 191/033/0 for 19/07/14 input how can i fix this? **

A: # include <stdio.h>
int main(){
    int d, m, year;
    printf("Enter date (dd/mm/yy): ");
    scanf("%d/%d/%d", &d,&m,&year);
    if (d%10==1 && d!=11) printf("%d st",d);
    else if (d%10==2 && d!=12) printf("%d nd",d);
    else if (d%10==3 && d!=13) printf("%d rd",d);
    else printf("%d th",d);
    return 0;
}

By the way, dd/mm/yy does not mean 'two days, two months and two years'. This means 'two digits for day, month and year'. That's why you don't need so many variables.

A: You need the strftime() function, and handle the input correctly so nothing unexpected happens
This is an example of how to do it
#include <stdio.h>
#include <time.h>
#include <string.h>

int main()
{
    char      buffer[100];
    struct tm date;

    memset(&date, 0, sizeof(date));

    printf("Enter date (dd/mm/yy): ");
    if (fgets(buffer, sizeof(buffer), stdin) == NULL)
        return -1;
    if (sscanf(buffer, "%d/%d/%d", &date.tm_mday, &date.tm_mon, &date.tm_year) == 3)
    {
        const char *format;

        format = "Dated %A %dth of %B, %Y";
        if (strftime(buffer, sizeof(buffer), format, &date) > sizeof(buffer))
            fprintf(stderr, "there was a problem converting the string\n");
        else
            fprintf(stdout, "%s\n", buffer);
    }
    return 0;
}


text:
Q: Configure rsyslog to log all commands I have a CentOS 6.6 and I want to configure rsyslog to log in /var/log/secure every command inserted by root or normal user.

A: Try this without rsyslog configuration
Snoopy is a tiny library that logs all executed commands (+ arguments) on your system.
https://github.com/a2o/snoopy
These are default output locations on CentOS: /var/log/secure
This is what typical Snoopy output looks like:
 2015-02-11T19:05:10+00:00 labrat-1 snoopy[896]: [uid:0 sid:11679 tty:/dev/pts/2 cwd:/root filename:/usr/bin/cat]: cat /etc/fstab.BAK
 2015-02-11T19:05:15+00:00 labrat-1 snoopy[896]: [uid:0 sid:11679 tty:/dev/pts/2 cwd:/root filename:/usr/bin/rm]: rm -f /etc/fstab.BAK
 2015-02-11T19:05:19+00:00 labrat-1 snoopy[896]: [uid:0 sid:11679 tty:/dev/pts/2 cwd:/root filename:/usr/bin/tail]: tail -f /var/log/messages

with rsyslog config
For BASH shells, edit the system-wide BASH runtime config file:
sudo -e /etc/bash.bashrc

Append to the end of that file:
 export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

Set up logging for "local6" with a new file:
 sudo -e /etc/rsyslog.d/bash.conf

And the contents...
 local6.*    /var/log/secure

Restart rsyslog:
sudo service rsyslog restart

https://askubuntu.com/questions/93566/how-to-log-all-bash-commands-by-all-users-on-a-server


text:
Q: Difference between CRF and Fully Connected CRF? Can anyone explain me the difference between Conditional Random Fields and Fully Connected Conditional Random Fields for semantic segmentation?
I only understand so far, that with CRF you try to use two kinds of information to improve the segmentation mask:

*

*Pixel Intensity: A good guess for a edge between to classes is pixel intensity. So with this we can weight the edges of objects

*Pixel proximity: For pixel close together, there is a high chance that they blong to the same class. With out this, we would interpret edges inside a object at instances of another class, e.g. backround.

Are my assumptions right? Is this true for CRFs or Fully connected CRFs, or both?
Thanks!

A: You are kind of correct, but I will try to make it more precise and explain their differences.
First, Conditional Random Fields (CRFs) is a graphical model for classification where you have two penalties, one for the node classification (your item 1) and another for the edges, where the neighboring nodes disagreement are penalized (your item 2).
For image segmentation, it is usual to consider each pixel as a node in the graph, and their adjacent pixels are their neighbors (4 or 8-neighbors in a 2D image), the edges' weights will try to enforce those adjacenct pixels will have similar labels.
The graph resulting is very sparse, and the CRF computation is fast.
When the CRF is fully connected, every node is adjacent to each other, this makes the computation much more expensive! However, it was found in [1], that the optimization can be done efficiently in image graphs with gaussian edge weights.
In this case, you are not only considering each pixel's neighborhood to obtain its class but every other pixel in the image.
You can find more information about this in [1].
[1] Krähenbühl, P., & Koltun, V. (2011). Efficient inference in fully connected CRFs with gaussian edge potentials. In Advances in neural information processing systems (pp. 109-117).


text:
Q: Generalization of counting measure is a measure Let $X, \mathcal{P}(X) = M$ be a $\sigma$-algebra. Let $f: X \rightarrow [0,\infty]$ be a function. Define $\mu : M \rightarrow [0,\infty]$ by $\mu(E) = \sum_{x \in E} f(x)$, which Folland defines as $$\sup_{\substack{F \subset E \\ F \text{ finite}}} \sum_{x \in F} f(x).$$ Prove that $\mu$ is a measure.
It's easy to show that $\mu(\varnothing) = 0$ -- the empty sum is defined to be 0, but I'm having trouble showing $\sigma$-additivity. Here's what I've got so far:
Let $\{E_i\}_{i=1}^\infty \subset M$ be a collection of mutually disjoint sets, and let $E = \bigsqcup_{i=1}^\infty E_i$. For a fixed finite $F \subset E$, we have that $F = \bigsqcup_{i=1}^\infty F \cap E_i = \bigsqcup_{i=1}^k F\cap E_i$ and so: $$\sum_{x \in F} f(x) = \sum_{i=1}^k \left(\sum_{x \in F_i} f(x) \right)...$$ but it seems like this isn't a nicer expression I can work with.
Does anyone have any ideas? This is a homework question, so a strong hint will be appreciated over a full answer.

A: Is this strong enough of a hint?
$\sum_{x \in F_i} f(x) = 0$ except for a finite number of indices, so $$\sum\limits_{i=1}^k \left(\sum\limits_{x \in F_i} f(x) \right) = \sum\limits_{i=1}^\infty \left(\sum\limits_{x \in F_i} f(x) \right)$$


text:
Q: Button appearing at wrong place I have a button that appears one to the left too much, how do I make it appear under the position I am at? This will probably be something so simple but I really am struggling today, I'm having an awful day today. Someone please help me
        public class CognitiveTreeBuilderViewModel : INotifyPropertyChanged
{
    private CognitiveTreeRoot root;
    private readonly IDiagramBuilder diagramBuilder;

    public CognitiveTreeBuilderViewModel(IDiagramBuilder diagramBuilder)
    {
        this.diagramBuilder = diagramBuilder;
    }

    public void Bind(CognitiveTreeRoot treeRoot)
    {
        root = treeRoot;
        this.diagramBuilder.BuildDiagram(root);
    }

    public void Rebuild()
    {
        this.diagramBuilder.BuildDiagram(root);
    }

    public void Expand(PropertyNode propertyNode)
    {
        if (!propertyNode.ScenarioNodes.Any())
        {
            return;
        }

        propertyNode.IsExpanded = true;

        diagramBuilder.Hide(propertyNode.DiagramId);
        foreach (var scenarioNode in propertyNode.ScenarioNodes)
        {
            diagramBuilder.Show(scenarioNode.DiagramId);
        }
    }

    public void DisplayAddScenarioButton(double p)
    {
        int propertyNodeIndex = Convert.ToInt32(p/210);

        foreach (var property in root.Nodes)
        {
            property.IsAddButtonVisible = false;
        }
        if (propertyNodeIndex < root.Nodes.Count)
        {
            root.Nodes[propertyNodeIndex - 1].IsAddButtonVisible = true;
        }
    }

    public void Collapse(PropertyNode propertyNode)
    {
        propertyNode.IsExpanded = false;
        foreach (var scenarioNode in propertyNode.ScenarioNodes)
        {
            diagramBuilder.Hide(scenarioNode.DiagramId);
        }
        diagramBuilder.Show(propertyNode.DiagramId);
    }

    public void CreateScenario(PropertyNode propertyNode)
    {
        propertyNode.IsExpanded = true;
        propertyNode.AddScenario();
        this.diagramBuilder.BuildDiagram(root);
    }

    public void RenameScenario(ScenarioNode scenarioNode)
    {
        var shouldEdit = scenarioNode.IsEditing == false;
        if (!shouldEdit)
        {
            scenarioNode.IsEditing = false;
            return;
        }

        foreach (var node in scenarioNode.Parent.ScenarioNodes)
        {
            node.IsEditing = false;
        }
        scenarioNode.IsEditing = true;
    }

    public void ToggleExpanded(PropertyNode propertyNode)
    {
        if (propertyNode.IsExpanded == true)
        {
            Collapse(propertyNode);
        }
        else
        {
            Expand(propertyNode);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: I want to update my column attributes names without changing their values 1.I want a query to update my column attribute names without changing my attribute values.
This is what i have....
my table name is CheckIn and my column is name cravings:
my attributes:
`"Magic box"=>nil, "Play Store, fruits"=>nil, "Chocos"=>nil, "Sauces"=>nil, "Sugar"=>nil`

What i want is to rename my:
"Magic box"=>'Boundry wall',
"Play Store, fruits"=>'B Area',
"chocos"=>'raffle',
"Sauces"=>'ketchup',
"Sugar"=>'wheat'

just want to change/update my attributes names.

A: Try this:
CheckIn.where.not(cravings: nil).each do |r|
  r.cravings['dairy'] = r.cravings.delete('Dairy products')
  .
  .
  .
  r.save!
end

Please, consider to use a transaction to rollback the updates upon failure.
Also note that it can take a long time depending on the size or your table. Check each_record to improve performance.


text:
Q: Lua - "attempt to compare number with nil" error a={51,31,4,22,23,45,23,43,54,22,11,34}
colors={"white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white"}
function try(f, catch_f)
    local status, exception = pcall(f)
    if not status then
        catch_f(exception)
    end
end
function refreshColors(yellowEndIndex,redIndex,blueIndex)
        for ccnt=1,table.getn(a),1 do
                if ccnt < yellowEndIndex then
                    colors[ccnt] = "yellow"
                elseif ccnt == redIndex then
                    colors[ccnt] = "red"
                elseif ccnt == blueIndex then
                    colors[ccnt] = "blue"
                else
                    colors[ccnt] = "white"
                end
        end
end
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)
refreshColors(1,1,1)
print(colors[1])

When the refreshColors() function is called, it throws an exception and the error message is "Error Occured - trial.lua:11: attempt to compare number with nil". Why the exception occurs although there is no such comparisons in the refreshColors() function?

A: The error is on line 11, which means:
if ccnt < yellowEndIndex then

There's your comparison with a number. We know ccnt is a number (it's initialised at the start of the loop), so yellowEndIndex must be nil. 1 < nil is nonsense so that's an error.
Since the error message starts with "Error Occured - " we know it must be coming from your try function error handler. This makes sense. You call:
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)

try then invokes:
pcall(f)

where f is refreshColours. This invokes refreshColours without any arguments, i.e. all the arguments are initialised to nil. Of course, invoking refreshColouts with a nil value will naturally attempt to compare 1 (ccnt) to nil (yellowEndIndex)!
You probably want to modify your try function like so:
function try(f, catch_f, ...)
    local status, exception = pcall(f, unpack(arg))
    if not status then
        catch_f(exception)
    end
end

So you can call it like:
try(refreshColours, function(e)
    print("Error Occured - "..e)
end), 1, 2, 3);

To pass 1, 2 and 3 in as arguments to refreshColours.

A: Is the error happening because you are calling:
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)
and, the refreshColors has no parameters so that it is indeed nil?


text:
Q: Loop through longlistselector to get checkbox in itemtemplate I have This Long list selector :
<phone:LongListSelector Background="Transparent"  x:Name="DocSummaries" ItemTemplate="{StaticResource DataTemplate_Header}" ItemsSource="{Binding DocumentHeaders}" Margin="33,0,-5,0"/>

and that list uses this itemtemplate :
<Viewbox x:Name="viewboxHeader" Tag="0">
                <StackPanel Orientation="Vertical" x:Name="listStackpanel" Height="330" Width="410" Margin="0,10,0,8">
                    <Grid x:Name="HeaderGrid"  Margin="0,0,0,0" Height="325" Width="410" Background="#FF4A4A4A" >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="150"/>
                        </Grid.ColumnDefinitions>
                        <!--<TextBlock x:Name="txtduration" TextWrapping="Wrap"  RenderTransformOrigin="0.5,0.5" FontSize="{StaticResource PhoneFontSizeNormal}" Text="{Binding Transaction.Duration}" Foreground="{Binding Transaction.Urgency, Converter={StaticResource converttocolor}}" TextAlignment="Left"  Width="60" Height="28" Canvas.Left="-26" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="-18,0,0,25" >

                        </TextBlock>
                        <TextBlock x:Name="txtdays" TextWrapping="Wrap" Text="days" Foreground="{Binding Transaction.Urgency, Converter={StaticResource converttocolor}}" RenderTransformOrigin="0.5,0.5" FontSize="{StaticResource PhoneFontSizeSmall}"  TextAlignment="Left"  Width="45" Height="28" Canvas.Left="-26" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3,0,0,10" >

                        </TextBlock>-->
                        <CheckBox x:Name="chkSelect" Grid.Row="0" Grid.Column="0" Grid.RowSpan="6" VerticalAlignment="Center" Width="Auto" Checked="chkSelect_Checked" Unchecked="chkSelect_Unchecked"/>

                        <StackPanel Grid.Row="0" Grid.Column="2"  Margin="15,0,0,5" x:Name="Durationpanel" Background="#FF4A4A4A" HorizontalAlignment="Right" Orientation="Horizontal">
                            <TextBlock TextWrapping="Wrap" Margin="2" FontSize="22" x:Name="txtDuration" Text="{Binding Duration}" Foreground="{Binding Urgency, Converter={StaticResource converttocolor}}" HorizontalAlignment="Right"></TextBlock>
                            <TextBlock TextWrapping="Wrap" Margin="2,4,2,2" FontSize="22" Foreground="{Binding Urgency, Converter={StaticResource converttocolor}}" Text="days" HorizontalAlignment="Right"></TextBlock>
                        </StackPanel>

                        <TextBlock Grid.Row="1" Grid.Column="1" Tap="btnViewDetail_Tap" Margin="0" Grid.ColumnSpan="2" TextWrapping="Wrap" Text="{Binding DocDesc}" FontSize="30" Foreground="#FFDFDFDF" >
                        </TextBlock>

                        <TextBlock TextWrapping="Wrap" Margin="0" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="1" Text="{Binding Created}" FontSize="16" Foreground="#FFDFDFDF">
                        </TextBlock>

                        <TextBlock TextWrapping="Wrap" Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="1" Margin="0" Text="{Binding Actioned}" Foreground="#FFDFDFDF" FontSize="16">
                        </TextBlock>

                        <TextBlock Grid.Row="4" Grid.Column="1" Margin="0,5,0,0" Foreground="#FFDFDFDF" FontSize="16" Text="{Binding Info1Label}"></TextBlock>
                        <TextBox Grid.Row="4" HorizontalAlignment="Stretch" Grid.Column="2" Height="55" FontSize="16" Margin="0,0,0,-15" Text="{Binding Info1Value}"></TextBox>

                        <TextBlock Grid.Row="5" Grid.Column="1" Foreground="#FFDFDFDF" FontSize="16" Text="{Binding Info2Label}" ></TextBlock>
                        <TextBox Grid.Row="5" HorizontalAlignment="Stretch" Grid.Column="2" Height="55" FontSize="16" Margin="0,0,0,-15" Text="{Binding Info2Value}"></TextBox>

                        <TextBlock Grid.Row="6" Grid.Column="1" Foreground="#FFDFDFDF" FontSize="16" Text="{Binding Info3Label}"></TextBlock>
                        <TextBox Grid.Row="6" HorizontalAlignment="Stretch" Grid.Column="2" Height="55" FontSize="16" Margin="0,0,0,-15" Text="{Binding Info3Value}"></TextBox>
                    </Grid>
                </StackPanel>
            </Viewbox>

Now my problem is, i want to get the checkbox in that itemtemplate that is in the longlistselector, so that if the user clicks on a checkbox, the other checkboxes get unchecked.
in the code below i get the longlistselector, but now i have no idea how to get the checkbox form the itemtemplate.
 foreach (var thisthing in LayoutRoot.Children)
        {
            if (thisthing.GetType() == typeof(Grid))
            {
                Grid myGrid = (thisthing as Grid);

                foreach (var Mylist in myGrid.Children)
                {
                    if (Mylist.GetType() == typeof(LongListSelector))
                    {
                        LongListSelector FoundList = (Mylist as LongListSelector);

                    }
                }

            }
        }

if anyone can help me here i would appreciate it.
Using Visual Studio 2012, c# Windows phone 8 Application

A: While you can certainly do that in the code-behind like you tried, I advice you to look for an MVVM implementation.
The code will be much cleaner an maintainable.
The idea is that you would create a MainViewModel that contains a List of ChildViewModel.
Each ChildViewModel contain all the information you need in the ItemTemplate, including a boolean property that the CheckBox will be bound on.
You bind the LongListSelector.ItemsSource to the ChildViewModels property of the MainViewModel.
That way, you can easily intercept the moment that a CheckBox is checked/unchecked (via the boolean property Setter) and pass the info to the other ChildViewModels for them to change.
EDIT, based on your comment indicating that the code has to live in the code-behind:
You could create a function that will search for ChecBoxes recursively with the help of the VisualTreeHelper class:
LongListSelector FoundList = (Mylist as LongListSelector);
SearchElement(FoundList);

Here is the function:
        private void SearchElement(DependencyObject targeted_control)
        {
            var count = VisualTreeHelper.GetChildrenCount(targeted_control);
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    var child = VisualTreeHelper.GetChild(targeted_control, i);
                    if (child is CheckBox) // Only search for ChecBoxes
                    {
                        CheckBox targeted_element = (CheckBox)child;
                        // check/uncheck
                    }
                    else
                    {
                        SearchElement(child);
                    }
                }
            }
            else
            {
                return;
            }
        }


text:
Q: Harbor Registry: Failed to pull image in Kubernetes I set up a Harbor registry which worked successfully for a couple of weeks now. For each deployment and namespace I a have a secret with the credentials from my ~/.docker/config.json file to get access to the registry. Since last weekend I was not able to pull images from that registry anymore and I didn't change anything! The cluster is running on GKE v1.12.5 btw.
What works?
I can pull and push images from my local machine witch docker.
What does not work?
My Kubernetes cluster cannot pull images anymore and runs in a timeout.
Events:
  Type     Reason          Age                  From                                                       Message
  ----     ------          ----                 ----                                                       -------
  Normal   Scheduled       13m                  default-scheduler                                          Successfully assigned k8s-test7/nginx-k8s-test7-6f7b8fdd79-2ffmp to gke-k8s-cloudops-test-default-pool-72fccd21-hrhk
  Normal   SandboxChanged  12m                  kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  Pod sandbox changed, it will be killed and re-created.
  Warning  Failed          11m (x3 over 12m)    kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  Failed to pull image "core.k8s-harbor-test.my-domain.com/nginx-test/nginx:1.15.10": rpc error: code = Unknown desc = Error response from daemon: Get https://core.k8s-harbor-test.my-domain.com/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
  Warning  Failed          11m (x3 over 12m)    kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  Error: ErrImagePull
  Normal   BackOff         11m (x7 over 12m)    kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  Back-off pulling image "core.k8s-harbor-test.my-domain.com/nginx-test/nginx:1.15.10"
  Normal   Pulling         10m (x4 over 13m)    kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  pulling image "core.k8s-harbor-test.my-domain.com/nginx-test/nginx:1.15.10"
  Warning  Failed          3m2s (x38 over 12m)  kubelet, gke-k8s-cloudops-test-default-pool-72fccd21-hrhk  Error: ImagePullBackOff

deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-k8s-test7
  namespace: k8s-test7
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx-k8s-test7
    spec:
      containers:
      - name: nginx-k8s-test7
        image: core.k8s-harbor-test.my-domain.com/nginx-test/nginx:1.15.10
        volumeMounts:
          - name: webcontent
            mountPath: /usr/share/nginx/html
        ports:
        - containerPort: 80
      volumes:
        - name: webcontent
          configMap:
            name: webcontent
      imagePullSecrets:
      - name: harborcred
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: webcontent
  namespace: k8s-test7
  annotations:
    volume.alpha.kubernetes.io/storage-class: default
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 5Gi

The secret "harborcred" is part of every namespace so that the deployment can access it. The secret was created per kubernetes documentation:
https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
kubectl create secret generic harborcred \
    --from-file=.dockerconfigjson=~/.docker/config.json \
    --type=kubernetes.io/dockerconfigjson \
    --namespace=k8s-test7

Any help would be appreciated!

A: Hi at first look could you please:

*

*Change image source and use some public one f.e. nginx to verify your deployment doesn't have other issues.

*https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ provide also more details about inspecting the "Secrets".

*Please also perform additional tests related to connectivity directly from your node as described within this post [How to debug "ImagePullBackOff"?
Additional steps to find the root cause:

 1. Convert your secrets data:
   kubectl get secret harborcred -n k8s-test7
    --output="jsonpath={.data.\.dockerconfigjson}" | base64 --decode

 2. Compare the result of decoding your "auth" field from the 1 step  with your docker credentials using:

    echo "your auth data" | base64 --decode

 3. To find the root cause please use also:

    kubectl get events -n k8s-test7 | grep pull

Please share with your logs.


text:
Q: If you suddenly increase the force, is the reaction force equal to the force? If you suddenly increase the force, is the reaction force equal to the force? Press a force on the object, and then suddenly increase the force. In this process, is the reaction force equal to the force? I don't think they are equal. Because in the process of increasing the force, the reaction force will not increase immediately. Only in the inertial system is the force equal to the reaction force.
For example, if you put a 1 kg object on the rubber block, the force of the object on the rubber block must be less than 9.8 N at first, and then when the object is still, the force of the object on the rubber block is 9.8 N.

A:
I don't think they are equal. Because in the process of increasing the force, the reaction force will not increase immediately. Only in the inertial system is the force equal to the reaction force.
For example, if you put a 1 kg object on the rubber block, the force of the object on the rubber block must be less than 9.8 N at first, and then when the object is still, the force of the object on the rubber block is 9.8 N

The reaction force is equal and opposite at all times as required by Newton's 3rd law. If that were not the case then momentum would not be conserved. Let's analyze the example more carefully.
There are two forces acting on the object. There is the 9.8 N downwards force of gravity (the weight) and the variable upwards contact force.
The third law pair of the 9.8 N weight is an upwards gravitational force on the earth. This is also a constant 9.8 N, so it is equal and opposite at all times.
The third law pair of the upwards contact force on the object is a downward contact force on the rubber block. These forces vary over time, but at each moment they are equal and opposite to each other. When the object first touches the block the forces are much smaller than 9.8 N, but as the block rapidly decelerates they quickly become larger than 9.8 N before reducing back down.
The contact forces are independent of the gravitational force except in the special case when the system is in equilibrium. It seems in your scenario that you are trying to analyze the contact force and the gravitational force as a 3rd law pair, which is incorrect. Third law pairs always act on different objects and are the same "type" of force.

A: Since you are using the Newtonian mechanics tag here, then we will stay in that regime.
According to Newton's third law, all forces have an equal but opposite reaction force. There is no additional condition of "after enough time has passed". In other words if you have two bodies interacting by some force, the force of body 1 on body 2 is always equal and opposite to the force body 2 exerts on body 1.
You might be getting mixed up with how bodies aren't exactly rigid. So that if you start pushing on an object, then it takes a finite time for the entire body to start moving, as the part of the body closer to the point of application will start moving before the parts farther away, and the body will initially compress. But this doesn't mean the reaction force is not equal to the applied force, as this action-reaction pair is only concerned with what is happening right at the application point, not with what the entire body is doing.

For example, if you put a 1 kg object on the rubber block, the force of the object on the rubber block must be less than 9.8 N at first, and then when the object is still, the force of the object on the rubber block is 9.8 N.

The weight and the rubber block will interact via an action-reaction force pair. There is no time delay to this. I think you are confused about what a reaction force is. This pair isn't the weight of the 1 kg and the reaction force of the block. That's not a valid action-reaction force pair. The two relevant pairs are 1)"gravity from Earth on 1k weight and gravity from 1kg weight on Earth" and 2)" Force from 1kg weight on rubber block and force from rubber block on 1kg weight". Just because the rubber block isn't pushed on by a force of 9.8N at all times doesn't mean the reaction force is delayed. The weight of the 1kg weight isn't linked to the force experienced by the rubber block through Newton's third law.


text:
Q: iOS application font size related to iOS font size/type? In my application I want to change all the UILabel, UITextField etc font size based on the OS font size/type. In iOS7 we can change the font size from device Settings.

*

*Go to Settings > General > Text Size.

*Drag the slider to the preferred size. The text on the screen will adjust as you move the slider.

So if the OS font size is changed to small, then I need to change all the text in my applications to little smaller, similar case for the other font type also (Large, Extra large).
Any suggestions as to how I can change the font size w.r.t OS font type? Thanks a lot!

A: You should set fonts all the UILabel, UITextField like below
yourLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

you can use whatever the TextStyle you want. so the text size will be w.r.t OS font size


text:
Q: Update Parent table from Child table in ASP.NET CORE I have 2 tables; WorkSchedule(Parent) and WorkShiftBid(Child). Right now, I am able to update WSBidStatus to "Approved" when the button in my WorkShiftBid view page is pressed.
I have a status column (WorkScheduleStatus&WSBidStatus) in both tables and what i want is for example when the button is pressed, both Status will be updated to "Approved" where WorkScheduleID in both tables are the same.
How should my controller look like to do this?
Model:
namespace Website.Models
{
    public class WorkScheduleModel
    {
        [Key]
        public Guid WorkScheduleID { get; set; }

        public string WorkScheduleStatus { get; set; }
    }

    public class WorkShiftBidModel
    {
        [Key]
        public Guid WorkShiftBidID { get; set; }

        public string WSBidStatus { get; set; }

        public Guid WorkScheduleID { get; set; }
        [ForeignKey("WorkScheduleID")]
        public WorkScheduleModel WorkSchedules { get; set; }
    }
}

Controller:
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> WorkShiftBid(Guid? id)
        {
            SqlConnection con = new SqlConnection();
            SqlCommand com = new SqlCommand();
            SqlDataReader dr;

            connectionString();
            con.Open();
            com.Connection = con;
            com.CommandText = "update WorkShiftBid set WSBidStatus ='Approved' where WorkShiftBidID = @id ";
            com.Parameters.AddWithValue("@id", id);
            dr = com.ExecuteReader();

            var workShiftBidModel = await _context.WorkShiftBid.FindAsync(id);

            if (dr.Read())
            {
                con.Close();
                return RedirectToAction(nameof(WorkShiftBid));
            }
            else
            {
                con.Close();
                return RedirectToAction(nameof(WorkShiftBid));
            }

            void connectionString()
            {
                con.ConnectionString = ".........................";
            }
        }

View:
@model IEnumerable<WorkShiftBidModel>

                .
                .
                .

            <form method="post">
                <input type="submit" class="btn btn-success btn-block" value="Approve" asp-route-id="@item.WorkShiftBidID" asp-action="WorkShiftTab" asp-controller="Manager" />
            </form>

        }

A: I don't have enough reputation to comment, but are you utilizing both Entity Framework and SqlCommands?
Nevertheless, you can find the Parent Key and update it via a SQL Command like so:
UPDATE WorkScheduleModel SET Status = 'Approved' WHERE Id = {ID}

Replace {Id} with the Key of your parent record.


text:
Q: Trying to get decibel levels from an audio file through javascript I've been looking at the information here:
Is there a way get something like decibel levels from an audio file and transform that information into a json array?
But when I try to run the JSBin here:
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Get Audio Data</title>
    <link rel="stylesheet" type="text/css" href="index.css">

#meter {
    width: 500px;
    height: 15px;
    margin: 2px 0;
    background: green;
    -webkit-transition;
    width .05s;
}

function() {
    var ctx = new webkitAudioContext(),
    url = 'test.mp3',
    audio = new Audio(url),
    processor = ctx.createJavaScriptNode(2048, 1, 1),
    meter = document.getElementById('meter'),
    source;

    audio.addEventListener('canplaythrough', function() {
        source = ctx.createMediaElementSource(audio);
        source.connect(processor);
        source.connect(ctx.destination);
        processor.connect(ctx.destination);
        audio.play();
    }, false);

    processor.onaudioprocess = function(evt) {
        var input = evt.inputBuffer.getChannelData(0),
        len = input.length,
        total = i = 0,
        rms;
        while(i<len)
            total += Math.abs(input[i++]);
        rms = Math.sqrt(total/len);
        meter.style.width = (rms*100) + '%';
    };
};

I'm not really sure what it's doing. Can anyone give me more info?

A: Your code does generate RMS output once you replace defunct API calls
old    webkitAudioContext
new

try {

    window.AudioContext = window.AudioContext ||
        window.webkitAudioContext ||
        window.mozAudioContext ||
        window.oAudioContext ||
        window.msAudioContext;

    ctx = new AudioContext();

    console.log("cool audio context established ... ctx ");

} catch (e) {

    alert("Web Audio API is not supported by this browser\n ... http://caniuse.com/#feat=audio-api");
}

and
old    createJavaScriptNode
new    createScriptProcessor


text:
Q: Marker over Infobubble in google maps v3 I'm trying to put a google.maps.Marker object over (z-index positioning) an Infobubble object
but i am having no success.
Basically what i'm doing is assigning zIndex: n to the markerOptions object which I pass to the Marker constructor as follow:
var markerOptions = {
    position: store.getLocation(),
    title: store.getDetails().title,
    icon: DEFAULT_MARKER,
    anchorPoint: new google.maps.Point(20,5),
    zIndex: 2
};
var marker = new google.maps.Marker(markerOptions);

I have already read this answer Google Maps v3 marker over infowindow but actually it has not got any votes. Can somebody tell me more about?
Thanks a lot

A: The problem, as commented by  shaunhusain is the fixed pane where particular elements will be drawn.
It's correct that you need to use a custom overlay, but you must use it to draw the marker, not the infobubble.
The reason: infobubble is an implementation of a custom overlay, it will be drawn inside the floatPane. To put the marker on top the infobubble must be drawn into a pane with a zIndex equal or lower than the zIndex of the pane where the marker will be drawn.
But here comes the problem: all these panes do not receive mouse-events, you wouldn't be able to interact with the infobubble(select tabs, select text, click links, close the infobubble).
Therefore you must use a custom overlay to draw the markers, and you must put these overlays into  the  floatPane(it's the pane with the highest zIndex)


text:
Q: Using git repo as a common base Say I have some code that forms the basic framework for something cool. I put it in a repo I'll call cool-app-base.
Now, I have a few good ideas for some cool apps. I'd like them to use cool-app-base, and build from there. Naturally, I have the options to clone and orphan, and fork and rename, etc. For the sake of examples, let's say I do the best thing for what I want, and create cool-app-1.
I don't plan to contribute back into cool-app-base from cool-app-1, so either one would work. But I do want to be able to bring any updates I may make to cool-app-base into cool-app-1.
The thing is, cool-app-1 shouldn't care about the history of cool-app-base. I want to treat these updates as squashed commits, so an update can have a commit message of "update with latest cool-app-base" and be done. This makes fork less appealing, but it also sounds like my only option is manually merging the cool-app-base code changes into cool-app-1 so I can control the commit history.
My question is: How can I do this better/"correctly"? I'm sure there are some funky git merge options I could use, but I'm not well-versed enough yet to confidently explore them.
Clarification: cool-app-base isn't a library, but a set of config files. While they could certainly be broken up and imported individually, my intent is to maintain them bundled together. I want to have the files of cool-app-base form the root of cool-app-1, not be nested in a sub-directory. The actual problem I'm trying to solve is not needing to recreate my package file, directory structure, and a set of carefully-and-generically-constructed scripts every time I want to spin-up a new project. If my configs were in a sub-directory, I'd still need to create references down to them, in what I would consider just more boilerplate code.
Also, while I consider the concept to be language-agnostic, I'm working in JavaScript with node and npm.

A: In my opinion, you can use Git Submodules, make cool-app-base as a submodule of cool-app-1. Then cool-app-1 will have the subfolder cool-app-base in physical file resource, with both repository's Git history not interferenced.

Git addresses this issue using submodules. Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.

A: You are not mention your programming language. But most languages come with some kind of package manager:

*

*JavaScript: npm

*Java: Maven, Gradle

*Python: pip

If you have such a package manager in your language use this in your app projects to include your base project.
If not, I would suggest subtree instead of submodules. You are able to include the base project into a subdirectory of your app projects. It's like copying the whole file system of one commit into another repo. You can choose if you need the history or not (squash).
And later on you can update to a newer version with one command.