text:
Q: Select 4 last digits in any string I'm having an array of various string and I need to select from each of the strings last 4 digits that are not separated.
var example = ["eg3322-3748", "eg3322-3749_ABCD", "eg3750_5GHJ"];
The desired result should give these results:
var example = ["3748", "3749", "3750"]
Thanks! :)

A: This should do it:

const input = ['eg3322-3748', 'eg3322-3749_ABCD', 'eg3750_5GHJ'];

const result = input.map(item =>
  item
    .split('').reverse().join('') // Reverse string
    .match(/\d{4}/)[0]            // Find first 4 consecutive digits
    .split('').reverse().join('') // Reverse matches back
);

console.log(result);

PS: next time you ask a question, please show what you attempted. Thanks!
Edit: this will generate an error if any string does not contain 4 consecutive digits. You can easily fix that by adding a fallback to match (with [''], for instance, then it'll return that).

A: Logic:

*

*Based on given data, its obvious, you are looking for a batch of alphanumeric/numeric characters and wish to get last 4 digits.

*So you can create a regex that matches all such groups, and returns last one.

*Then, from this last group, just extract last 4 characters and Ta-da!!!

var example = ["eg3322-3748", "eg3322-3749_ABCD", "eg3750_5GHJ"];
var regex = /([a-z]*\d{4,})/g;

var output = example.map((str) => {
  const match = str.match(regex).pop();
  return match.substr(-4);
});

console.log(output)

A: You can use .substr() function to slice the length of string. Maybe "example(i).substr(example(i).length - 4)" will work.


text:
Q: Some fun with special infinite nested radicals Let us define the following functions:
$$f_n(x)=\sqrt{x^{n}-\sqrt{x^{n+1}- \sqrt{x^{n+2}-\cdots}}} $$
$$g_n(x)=\sqrt{x^{n}+\sqrt{x^{n+1}+ \sqrt{x^{n+2}+\cdots}}} $$
with $f(x)=f_1(x)$ and $g(x)=g_1(x)$. Very little is known about $f(x)$ and $g(x)$, except:

*

*The nested radical converges in both cases if $x > 1$

*$\lim_{x\rightarrow 1^+} f(x) = \frac{-1+\sqrt{5}}{2}$ and $g(1) =
   \frac{1+\sqrt{5}}{2}$

*$f(4)=1$ and $g(4)=3$
Let us now focus on the case where $x>1$ is an integer. The goal here is to obtain more advanced, interesting results about these nested radicals, maybe even a closed form or some asymptotic formulas.
1. Integer part of the infinite nested radicals
Let $\lfloor\cdot\rfloor$ denotes the integer part function. We have:
$$\lfloor f_{2n}(x) \rfloor = x^{n}-\phi(x)\\ \mbox{ } \lfloor g_{2n}(x) \rfloor = x^{n}+\psi(x)$$
with $\phi(x)=k$ if $x\in A_k$, $\psi(x)=k$ if $x\in B_k$. The sets $A_k, B_k$ are as follows:

*

*$A_1=[2,5[, A_2=[5,15[, A_3= [15,33[, A_4=[33,61[,
   A_5=[61,96[, \cdots$

*$B_0=[2,4[, B_1=[4,17[, B_2= [17,38[, B_3=[38,67[,
   B_4=[67,104[, \cdots$
2. Fractional part of the infinite nested radicals
Let $\{\cdot\}$ denotes the fractional part function. We seem to have:
$$\lim_{n\rightarrow\infty} \{ f_{2n}(x)\}=1-\Big\{\frac{\sqrt{x}}{2}\Big\}\\
\lim_{n\rightarrow\infty} \{ g_{2n}(x)\}=\Big\{\frac{\sqrt{x}}{2}\Big\}
$$
Also, the roots of $\{g_1(x)\}$ have a very peculiar quadratic distribution. The first few ones, for
$x>0$, are $\rho_1=4.0000$, $\rho_2=7.3370$, $\rho_3=11.6689$, $\rho_4=16.9982$, $\rho_5=23.3260$, $\rho_6=30.6526$, $\rho_7=38.9787$. Furthermore, it seems that
$$\lim_{k\rightarrow\infty} (\rho_{k+2}-2\rho_{k+1} +\rho_k) = 1.$$
Finally, values of $\{g_1(x)\}$ for large successive integers $x$ lying between two successive roots of $\{g_1(\cdot)\}$ tend to be equally spaced as $x\rightarrow\infty$. See table below.

3. My question
Actually a few related questions. Feel free to answer the one(s) you are most interested in.

*

*Many of my results are experimental (thus I often use the word "it
seems"). Can you prove some of them?

*Obtain an explicit closed form for all sets $A_k,B_k$ used in the
definition of $\phi(x)$ and $\psi(x)$ in section 1. Not sure if it is easy or not.

*We focused on $n$ even. What happens for $n$ odd? Do we have
interesting results? For instance, if $x=2$, the successive values of
$\lfloor g_{2n+1}(x)\rfloor$ are $2, 3, 6, 12, 23, 45, 91, 181, 362,
   \cdots$ (for $n=0, 1, \cdots$). I did a reverse lookup on that
sequence (see here) but it did not return any result despite the
semi-obvious pattern.

*What happens if $x$ is not an integer? Any interesting pattern or
result?

*Can you derive even more intriguing insights from the empirical
results I presented here?

*It looks like the larger $x$, the faster my limits are converging.
Worth exploring.

A: I am focusing here on $g(x)$, with $x$ a strictly positive integer. All the results below have been obtained empirically. A proof (or rebuttal) would be welcome. Again, $\{ \cdot \}$ represents the floor function.
Let $b_k=4k^2 + k - 1$. We have $B_k=[b_k,b_{k+1}[$ if $k>0$, and $B_0=[2, 4[$. Thus we now have a closed form for $\psi(x)$ and thus for $\lfloor g_{2n}(x)\rfloor$, regardless of $x$ and $n$, assuming $x$ is an integer. In particular, for $x>0$, we have:
$$\lfloor g_{2n}(x)\rfloor = x^{n}+\psi(x), \mbox{ with }
\psi(x)=\Big\lfloor \small \frac{-1+\sqrt{17+16x}}{8}\Big\rfloor.$$
It also works for $n=0$. Let $\eta(x)=\psi(x) -\lfloor\sqrt{x}/2\rfloor$. It is equal either to zero (for most $x$'s) or one (for $x=16, 36, 37$, $64, 65, 66,\cdots$).
Also, for $x<16$, we have the following approximation:
$$\{ g_{0}(x)\} \approx \Big\{\frac{\sqrt{x}}{2}\Big\}+\frac{2-\sqrt{5}}{6} (x-4)$$
resulting in
$$g_0(x)=\lfloor g_0(x)\rfloor + \{ g_{0}(x)\}  \approx \frac{\sqrt{x}}{2}
+\frac{2-\sqrt{5}}{6} (x-4) + 1.$$
The approximation is exact if $x=1$ or $x=4$. It is also pretty good even if $x$ is not an integer. Note that $g(x)=g_1(x)=g_0^2(x)-1$.
Another potentially interesting result is this:
$$\lim_{n\rightarrow\infty} \frac{ \{ g_{2n}(x)\}-\{\frac{\sqrt{x}}{2}\}
}{ \{ g_{2n+2}(x)\}-\{\frac{\sqrt{x}}{2}\} } = x.$$
Asymptotics and distribution of roots
A better approximation to $g_0(x)$, especially for large $x$, is the only real, positive solution of the equation $(y^2−1)^2−y=2x−1$ with respect to $x$. This approximation is also exact for $x=1$ and $x=4$ and it works for non-integer values of $x$. For large $x$, we have the following asymptotic expansion for $g(x)=g_1(x)$:
$$g(x) =\sqrt{2}\cdot\Big(\sqrt{x}+\frac{1}{8}-\frac{5}{128 \sqrt{x}}+O\Big(\frac{1}{x}\Big)\Big) .$$
The above formula is easy to derive (see Mathematica computation here) and is particularly useful to study the roots of $\{ g(x)\}$. If $x$ is very large, $x$ is a root of $\{g(x)\}$ if and only if $\sqrt{2} (\sqrt{x} + \frac{1}{8})$ is very close to an integer. Since the first root is $\rho_1=4$, an (excellent) approximation to the $k$-th root $\rho_k$ is the value of $x$ satisfying  $\sqrt{2} (\sqrt{x} + \frac{1}{8})=k+2$. In order words,
$$\rho_k = \frac{(k+2)^2}{2} -\frac{k+2}{4\sqrt{2}}+\frac{1}{64} + O\Big(\frac{1}{k}\Big).$$
So, $g(\rho_k)=k+2$ and thus $\{g(\rho_k)\}=0$ and there is no other root beyond those discussed here. Note that using my approximation, we have $\rho_1\approx 3.9853$ while the exact value is $4$. The larger $k$, the better the approximation since the error term is of the order $1/k$ and thus tends to zero as $k\rightarrow\infty$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why not to use switch case statments? I just want to get some information before I go ask my teacher during his offices hours tomorrow.
We have have project to do thats something like an iclicker question answer collector. He told us to avoid using switch case statements. I was just wondering why and why don't people in the field like using them, what alternative is there to do? and I doubt he wants us to use if statements either.
I think we have to use polymorphism/interfaces but I just cant rap my head around that, switch cases seems so much straight forward.
Thank you.

A: Usually when an instructor asks "don't use feature X", it's because they want you to learn how to do something without using a feature that might be a shortcut. In your case, it sounds like your instructor wants you to wrap your head around polymorphism. If you don't, you won't learn that bit and will have much more trouble later in the class.

A: It depends upon the project.  For example, in using a RESTful APi, you do have switch statements because there is a limit, known set.  But, with your program there might be a lot of different options and that option can change, increase (or decrease), so while you started out with three cases, then something else is wanted, that's four, then five, and so on.  You end up with 50 cases, and that's probably not good or easy to maintain.
With your OOP class, the instructor is probably going to show you that.  Come back and show the whole problem and the final result, and maybe others can shed light.
There's an example that I've seen in my old Java book, and did a search and see it is still decent.  Consider employees and salaries.  You have three types of employees, then you have 50 types.
On a small scale, there appears to be not much difference.  It requires enlarging the problem and considering consequences.
Ways to eliminate switch in code
That is a good example.  Sure, there's only two cases in that example.  But, again, what if it were 50?  How easy will it be to maintain that?  A lot of things in programming are about saving time and making things logical in the long run, as you will be coming back to your code or someone else's, and you have to maintain and support it.


text:
Q: How to save spanCount of RecyclerView on Shared Preferences? my question is is there a way to save the SpamCount of a ReciclerView in SharedPreferences?
I try to make a List that can change the view from a "List mode" to "Grid mode" and save that information in SharedPreferences so that the "List View" will remain after killing the app.
The example of what I am trying to do would be the following ...
example of what i try to do on button click
And the code that I try to change is the following ...

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static RecyclerView recyclerView;
    private ReciclerAdapter reciclerAdapter;
    ImageView viewGridS, viewListS;

    SharedPreferences vSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recicler_main);

        vSettings =  this.getSharedPreferences("Vision", 0);

        notesRecyclerView = findViewById(R.id.recycler_view);
        notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        viewListS = findViewById(R.id.viewList);
        viewGridS = findViewById(R.id.viewGrid);

    @Override
    public void onClick(View v) {
        SharedPreferences vSettings =  this.getSharedPreferences("Vision", 0);
        SharedPreferences.Editor viEdit = vSettings.edit();

        switch (v.getId())
        {
            case R.id.viewList:
                viewGridS.setVisibility(View.GONE);
                viewListS.setVisibility(View.VISIBLE);
                viEdit.putString("Vision",listView());
                viEdit.apply();
                break;
            case R.id.viewGrid:
                viewListS.setVisibility(View.GONE);
                viewGridS.setVisibility(View.VISIBLE);
                listWiew();
                viEdit.putString("Vision",gridView());
                viEdit.apply();
                break;
          }
     });
    }

    public int gridView(){
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        return null;
    }

    public int listView(){
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        return null;
    }
}

When trying to start the Activity the RecyclerView does not show anything and the button does not work.
if someone could help me I would appreciate it in advance ... thanks

A: You have done couple of things wrong here.

Incorrect use of SharedPreferences
Adapter on RecycleView not setup
Manage LinearLayout and StaggeredGridLayoutManager

I will try to accomplished kind similar end result which you are looking for, a simple button which is switching layout on click. Code as follows -
MainActivity.java
public class MainActivity extends AppCompatActivity {

    private String LIST_VIEW = "List View";
    private String GRID_VIEW = "Grid View";
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private SharedPreferences sharedPreferences;
    private RecycleViewAdapter recycleViewAdapter;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Simple List setup for data to show in recycle view
        List<String> stringList = new ArrayList<>();
        stringList.add("Monday\nI'll ask her out.");
        stringList.add("Tuesday");
        stringList.add("Wednesday\nI'll take her to garden to talk.");
        stringList.add("Thursday\nI'll give her a gift");
        stringList.add("Friday");
        stringList.add("Saturday");
        stringList.add("Sunday\nI'll propose her. ");

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        recyclerView = findViewById(R.id.recycler_view);
        recycleViewAdapter = new RecycleViewAdapter(this, stringList);

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);

        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        /*
        * SharedPreferences value will be null for very first install of app
        * ELSE SharedPreferences will have use last saved value
        * */

        String CURRENT_VIEW = sharedPreferences.getString("LAYOUT_TYPE", null);
        if (CURRENT_VIEW == null) {
            CURRENT_VIEW = LIST_VIEW;
            sharedPreferences.edit().putString("LAYOUT_TYPE", LIST_VIEW).apply();
            recyclerView.setLayoutManager(linearLayoutManager);
            recyclerView.setAdapter(recycleViewAdapter);
        } else
            switchView(CURRENT_VIEW);

        Button buttonPanel = findViewById(R.id.buttonPanel);
        buttonPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sharedPreferences.getString("LAYOUT_TYPE", null).equals(LIST_VIEW))
                    switchView(GRID_VIEW);
                else
                    switchView(LIST_VIEW);
            }
        });
    }

    /*
    * Method will switch Layout on RecycleView and update new Adapter
    * @param: Required Layout Type (LIST_VIEW or GRID_VIEW)
    * */
    private void switchView(String layoutTypeValue) {
        if (layoutTypeValue.equals(LIST_VIEW))
            recyclerView.setLayoutManager(linearLayoutManager);
        else if (layoutTypeValue.equals(GRID_VIEW))
            recyclerView.setLayoutManager(staggeredGridLayoutManager);

        sharedPreferences.edit().putString("LAYOUT_TYPE", layoutTypeValue).apply();
        recyclerView.setAdapter(recycleViewAdapter);
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <Button
        android:padding="8dp"
        android:layout_margin="16dp"
        android:layout_gravity="end|bottom"
        android:id="@+id/buttonPanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:background="@android:color/holo_orange_dark"
        android:text="Change Layout"/>
</FrameLayout>

RecycleViewAdapter.java
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.CustomViewHolder> {

    private Context context;
    private List<String> stringList;

    public RecycleViewAdapter(Context context, List<String> stringList) {
        this.context = context;
        this.stringList = stringList;
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.recycle_item_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        holder.textView.setText(stringList.get(position));
    }

    @Override
    public int getItemCount() {
        return stringList.size();
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {

        private TextView textView;

        public CustomViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text);
        }
    }
}

recycle_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="8dp">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:background="@android:color/holo_blue_dark"
        android:textColor="@android:color/white"
        android:textSize="24sp" />

</LinearLayout>

Above code will give you following result -

Happy Coding !


text:
Q: Problem in Installing xdman in Ubuntu via terminal I downloaded xdman in Ubuntu via the terminal using the command,
apt-get install xdman

However upon downloading when I try to run xdman using the "xdman" command in the terminal I got error message as,
java.io.FileNotFoundException: /home/shabirmean/.xdmconf (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:140)
at org.sdg.xdman.core.common.XDMConfig.load(XDMConfig.java:118)
at org.sdg.xdman.gui.MainWindow.main(MainWindow.java:2724)
Config port: 9614
XDM Module running on: 9614
java.io.FileNotFoundException: /home/shabirmean/.xdmlist (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:140)
at org.sdg.xdman.gui.DownloadList.loadDownloadList(DownloadList.java:169)
at org.sdg.xdman.gui.DownloadList.<init>(DownloadList.java:44)
at org.sdg.xdman.gui.MainWindow.main(MainWindow.java:2746)
Exception in thread "main" java.awt.HeadlessException
at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:173)
at java.awt.Window.<init>(Window.java:547)
at java.awt.Frame.<init>(Frame.java:419)
at java.awt.Frame.<init>(Frame.java:384)
at javax.swing.JFrame.<init>(JFrame.java:174)
at org.sdg.xdman.gui.MainWindow.<init>(MainWindow.java:166)
at org.sdg.xdman.gui.MainWindow.main(MainWindow.java:2748)

Can anyone please help me get past this??

A: The problem was with the OpenJDK's java distribution. I installed Oracle JDK 8 and tried installation and it worked perfectly fine!!!!! So the error messages printed doesn't mean much at all (atleast for my case) as suggested in many of the other websites as a solution for this problem,

A: Problem is "Exception in thread "main" java.awt.HeadlessException which means the Java Runtime is Console only [Headless] (does not supports GUI application).
Please install correct JRE (i.e Full OpenJDK instead of OpenJDK headless) to solve the problem.
sudo apt-get install openjdk-7-jre


text:
Q: Using matplotlib in GAE My tags and title quite clearly state my problem. I want to use matplotlib to create real-time plots in Google App Engine. I've read the documentation and searched on SO and Google. I found a post, pointing to this working demo. But when I try it on my own, it doesn't work for me.
I created a simple application, consisting only of a handler-script hello_world.py
import numpy as np
import os
import sys
import cStringIO

print "Content-type: image/png\n"

os.environ["MATPLOTLIBDATA"] = os.getcwdu()  # own matplotlib data
os.environ["MPLCONFIGDIR"] = os.getcwdu()    # own matplotlibrc
import matplotlib.pyplot as plt

plt.plot(np.random.random((20))) #imshow(np.random.randint((10,10)))

sio = cStringIO.StringIO()
plt.savefig(sio, format="png")
sys.stdout.write(sio.getvalue())

and a a configuration file app.yaml
application: helloworldtak
version: 1
runtime: python27
api_version: 1
threadsafe: no

handlers:
- url: /.*
  script: hello_world.py

libraries:
- name: numpy
  version: "latest"
- name: matplotlib
  version: "latest"

I want to plot something and then return the content as png-image. This procedure works fine for a normal web-server like Apache or IIS, I did this a million times.
The problem is rather: when I run my script locally within the development server, I get an error that is probably due to my MPL version 1.1.1, which is only "experimental" in GAE. But when I deploy my app to GAE, I get a completely different, uncorrelated error.
Looking at the looks, the traceback is:
Traceback (most recent call last):
  File "/base/data/home/apps/s~helloworldtak/1.364765672279579252/hello_world.py", line 16, in <module>
    import matplotlib.pyplot as plt
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/pyplot.py", line 23, in <module>
    from matplotlib.figure import Figure, figaspect
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/figure.py", line 18, in <module>
    from axes import Axes, SubplotBase, subplot_class_factory
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/axes.py", line 14, in <module>
    import matplotlib.axis as maxis
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/axis.py", line 10, in <module>
    import matplotlib.font_manager as font_manager
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/font_manager.py", line 1324, in <module>
    _rebuild()
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/font_manager.py", line 1278, in _rebuild
    fontManager = FontManager()
  File "/python27_runtime/python27_lib/versions/third_party/matplotlib-1.1.1/matplotlib/font_manager.py", line 995, in __init__
    self.defaultFont['ttf'] = self.ttffiles[0]
IndexError: list index out of range

It seems to have to do something with the fonts-cache of MPL. I read in the docs that caching and file-access is one of the problems with MPL in GAE, but obviously, the import works for others.
What am I doing wrong?
Edit
Based on the answer below, I changed my code to be
import numpy as np
import cStringIO
import matplotlib.pyplot as plt

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        plt.plot(np.random.random((20)),"r-")
        sio = cStringIO.StringIO()
        plt.savefig(sio, format="png")
        self.response.headers['Content-Type'] = 'image/png'

        self.response.out.write(sio.getvalue())

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)

and like this, it's working.

A: I'm not familiar with sys module. To give an answer to the question I prefer using webapp2. This is a working handler:
import webapp2
import StringIO
import numpy as np
import matplotlib.pyplot as plt

class MainPage(webapp2.RequestHandler):
    def get(self):
        plt.plot(np.random.random((20)))
        sio = StringIO.StringIO()
        plt.savefig(sio, format="png")
        img_b64 = sio.getvalue().encode("base64").strip()
        plt.clf()
        sio.close()
        self.response.write("""""")
        self.response.write("" % img_b64)
        self.response.write(""" """)

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

Alternatively, you could write the sio.getvalue() in the blobstore with files api and use  the method get_serving_url() of images api for avoid to encode in base64.

A: The problem was that you were setting the MATPLOTLIBDATA and MPLCONFIGDIR environment variables to your app directory before importing matplotlib. Since you didn't have any fonts in your app directory, it couldn't load any fonts.


text:
Q: CSS animation is not working on safari but good on chrome I have designed a page which contains many animations and all are working good on browsers like chrome and firefox, but when the same is opened on the safari (MAC) and safari(Windows), it doesn't show the animation. I am not getting, what's the exact problem.
I have added the html which contains three animations animation1, animation2 and animation3. I have only added the animation2 css. And the remaining animations are almost same.
Here is Html:-

    $(document).on("scroll", function () {
        if (isScrolledIntoView1($elem1, $window1)) {
            $elem1.addClass("animate1")
        }
    });

    $(document).on("scroll", function () {
        if (isScrolledIntoView($elem, $window)) {
            $elem.addClass("animate2")
        }
    });

    $(document).on("scroll", function () {
        if (isScrolledIntoView2($elem2, $window2)) {
            $elem2.addClass("animate3")
        }
    });

     var $window = $(window);
        var $elem = $(".animation2")

        function isScrolledIntoView($elem, $window) {
            var docViewTop = $window.scrollTop();
            var docViewBottom = docViewTop + $window.height();

            var elemTop = $elem.offset().top;
            var elemBottom = elemTop + $elem.height();

            return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
        }

     var $window1 = $(window);
        var $elem1 = $(".animation1")

        function isScrolledIntoView1($elem1, $window1) {
            var docViewTop1 = $window1.scrollTop();
            var docViewBottom1 = docViewTop1 + $window1.height();

            var elemTop1 = $elem1.offset().top;
            var elemBottom1 = elemTop1 + $elem1.height();

            return ((elemBottom1 <= docViewBottom1) && (elemTop1 >= docViewTop1));
        }

     var $window2 = $(window);
        var $elem2 = $(".animation3")

        function isScrolledIntoView2($elem2, $window2) {
            var docViewTop2 = $window2.scrollTop();
            var docViewBottom2 = docViewTop2 + $window2.height();

            var elemTop2 = $elem2.offset().top;
            var elemBottom2 = elemTop2 + $elem2.height();

            return ((elemBottom2 <= docViewBottom2) && (elemTop2 >= docViewTop2));
        }
.animation2.animate2 {
                animation-name: pulse2;
                animation-duration: 2s;
                animation-iteration-count: 1;
                animation-fill-mode: forwards;
                animation-delay: 0s;

                -webkit-animation-name: pulse2;
                -webkit-animation-duration: 2s;
                -webkit-animation-iteration-count: 1;
                -webkit-animation-fill-mode: forwards;
                -webkit-animation-delay: 0s;
        }
        @keyframes pulse2 {
            0% {
                position: relative;
                top: -500px;
                left: 100px;
                background-color: #94D6E2;
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
                width: 750px;
                height: 300px;
                margin-top: 150px;
                z-index: -1;
            }
            100% {
                position: relative;
                top: -600px;
                left: 100px;
                background-color: #94D6E2;
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
                width: 850px;
                height: 400px;
                margin-top: 150px;
                z-index: -1;
            }
        }

        @-webkit-keyframes pulse2 {
            0% {
                position: relative;
                top: -500px;
                left: 100px;
                background-color: #94D6E2;
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
                width: 750px;
                height: 300px;
                margin-top: 150px;
                z-index: -1;
            }
            100% {
                position: relative;
                top: -600px;
                left: 100px;
                background-color: #94D6E2;
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
                width: 850px;
                height: 400px;
                margin-top: 150px;
                z-index: -1;
            }
        }

Custom

Top culinary chefs from across the country have prepared a highly delectable keto menu, comprising of dishes such as Hyderabadi Biryani, Butter Chicken, Thin Crust Pizza, Pasta and Chocolate Mousse amongst others.


text:
Q: insert into using same row(same primary key) mysql php pdo INSERT INTO courses1 (sys_id,name, location)
SELECT *
FROM courses
WHERE sys_id= $sysid

I have the two tables above and I want to insert in course1 what I have in course. But I get problem with sys_id because I get Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'' in so what I did is a added a column in courses1 named system_id but then I get another error saying column not match.
Tried
INSERT IGNORE INTO but ther result is not what I am expecting. The result I want is to have the data from course to course1 everytime I make a transaction. I want the data not to be overriden.

*

*What is the best solution for insert into when inserting same row(same primary key)?

UPDATE
My aim is to back-up the data (historical data). I want to record the data before editing it. basically what i am doing is inserting the data in another table before updating it

A: This question is a perfect example that demonstrates the fact that to give an answer, one have to understand the context of the question, not just write an automated post triggered by some keyword in the question.
If you want a history table, it have to have a different structure from the main table. At least it should have a non-unique key for the id from the main table.
So, make a history table of the same structure, but add a main_id field. That gives you a structure like
id
manin_id
name
location

Then, to add a record into a history table,
INSERT INTO courses_history SELECT NULL, * FROM courses  WHERE sys_id=?

you may want also to add an index (non-unique) for the main_id field.
This way it will allow to store multiple "replicas" of the same row from the main table.
To get the last replica, you need a query like this:
SELECT * FROM courses_history WHERE sys_id=? ORDER BY id desc


text:
Q: how to apply strftime on localtime I want to get the day of the month from a datetime column in my Sqlite database. I could use simply
select strftime('%d',myColumn) from myTable

But the values are stored in UTC in the database and i want to get the dates based on the localtime. So i can do the below to get the localtime.
select date(myColumn, 'localtime') from myTable

Now how do i do both these operations together? The only way i can think is by doing inner query with the date() and outer query with strftime(). Is there another way?

A: The documentation says that modifiers like localtime are used with all date and time functions:
SELECT strftime('%d', myColumn, 'localtime') FROM myTable


text:
Q: Removing last blank line There is a para break at the end of my .csv file. I tried to remove the blank line that is at the end of the file using the following command.
sed -i '/^$/d' combined.csv

But it does not work and a blank line is still there. I can remove the last line using the following command.
sed -i '$d' combined.csv

But is it possible to check if the last line is really empty before removing it?
Update:
I am using the following command to check if each line start with a number.
sed -i '1s/^[^0-9]*//' combined.csv

This checks only for the first line and not the rest of the lines. How do I make it check all the lines in the file? This might solve my problem.

A: Try ${/^$/d;} this will only match an empty line if it is the last line of the file.
Update: for your second question, just remove the 1 before the s, i.e.: sed -i 's/^[^0-9]*//' combined.csv

A: Found this ages ago somewhere and saved the snippet. Do not ask me how it works:
perl -i -pe "chomp if eof" combined.csv

A: To remove blank lines you can use grep . or sed '/^$/d'
It will remove any blank line in the file. I hope you file does not have any blank lines in the middle but this will work in your case.
cat combined.csv | grep .
or
cat combined.csv | sed '/^$/d'

A: If you know for sure that last line is empty, then just use: ...| head -n -1 | ...

A:
Try ${/^$/d;} this will only match an empty line if it is the last line of the file.

I tried it with sed (GNU sed) 4.2.2 and got all blank lines deleted not only the empty line if it is the last line of the file.
I found the following Command, that worked for myself that does the Job.
sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'

This Command is from a Collection of useful SED-Oneliners:
http://sed.sourceforge.net/sed1line.txt


text:
Q: Durandal and MVC4 Areas for multiple SPAs I have a internet application mvc4 with areas, for my organization each area represent a SPA and through "Manage NuGet Package" I installed "Durandal 1.2.0", "Durandal Transitions 1.2.0" and "Durandal Router 1.2.0". I organized the folders and quit the "views" and "viewmodels" from folder "App" of Durandal and put the new views in folder "VIews" of mvc4 area for example:
Areas-->NewArea-->Views-->ControllerFolder-->views-->shell.html
Then I put the '"viewmodels" in "Script" folder for example:
Scripts-->NewArea-->ControllerFolder-->viewmodels-->shell.js
Scripts-->NewArea-->ControllerFolder-->main.js
Then I changed paths for JS of durandal, for example in main.js:
define(['../../../App/durandal/app',
    '../../../App/durandal/viewLocator',
    '../../../App/durandal/system',
    '../../../App/durandal/plugins/router',
    '../../../App/services/logger'],

And I changed main.js in the next line:
viewLocator.useConvention('viewmodels', '../Areas/NewArea/Views/ControllerFolder/views');

But that configuration of folders fails because the next line calls various times the module "viewLocator" in its definition and rewrite the configuration of "useConvention" with default value:
app.setRoot('viewmodels/shell', 'entrance');

That behavior only happen when the folders "views" and "viewmodels" don't stay under "App" folder of "Durandal".
Please help me, how to have various SPAs in the same project?

A: I ran into the exact same problem this morning.  I originally formatted the project to be:

*

*app/spa1/viewmodels

*app/spa1/views

*app/spa2/viewmodels

*app/spa2/views

Using this structure I hit the exact same wall you did.  After reading your post, I restructured the project to be:

*

*app/viewmodels/spa1

*app/viewmodels/spa2

*app/views/spa1

*app/views/spa2

Using this structure, navigation works fine.  I set up three SPAS and was able to navigate all three. The other benefit of this structure is that you are now following the standard convention so you don't have to configure the view locator.  Just make sure the main.js file for each spa uses:

*

*app.setRoot('view models/spa1/shell), app.setRoot('view models/spa2/shell), etc.

Finally, by structuring this way, you move the main.js files up the structure which eliminates the ../../../ in all your defines.
I hope this helps.

A: You might want to consider your deployment strategy. For example, if you need to optimize this app, both SPAs will end up in the same file. However, instead of having them both under the app folder, you can make separate folders, and give each SPA it's own main.js file.
In more advanced scenarios, you may create a "bootstrapper" app that loads one or another of the SPAs. The bootstrapper would contain code that is common to both SPAs. But each SPA (and the bootstrapper) can be optimized independently.
There are many options. Mainly, consider your final deployment strategy and that will help guide you here.
Also, the issue you have above is probably related to the fact that the standard conventions may not work in your setup, and you would need to override some functions with your own mapping.


text:
Q: How can I assign a middle button press to a specific key in my laptop? How can I attach a middle button press to a specific key in my laptop?
I can do middle-button if I tap on the top right corner of the touchpad, but I would like to associate it to a key, like the "windows" key or the "menu" key.
Is there a way to do that?
The current answer doesn't work for Ubuntu 11.10 with a classic gnome-failsafe desktop. I would need someone to figure out how can this be done for the updated Ubuntu version.

A: First, install xautomation:
sudo apt-get install xautomation
You can send a middle-click event using xte:
xte 'mouseclick 2'
You can create a custom shortcut for that under Preferences -> Keyboard Shortcuts (or 'Keyboard Shortcuts' from the Unity search). Click 'Add', enter a name and the above command and click 'Apply'. Scroll to the bottom and set a shortcut as you would for any other action.
When I tried this, I wasn't able to bind the action to just the Windows key. You can try it by doing the following, but there seems to be a bug that prevents this from working:
Open a terminal and run
gconf-editor
Hit Ctrl+f, select the 'Search also in key values' box and enter the following to the search box:
xte 'mouseclick 2'
There should be only one result in the bottom pane. If there's more, select the one that contains '/desktop/gnome/keybindings/custom*/action' in its name. In the top-right pane, enter '' (without quotes) next to the 'binding' field. If you get the same result that I did, all your window appearances will change, and the new keybinding won't do anything. Change that back to whatever it was (or make it blank) and open Appearance (Preferences -> Appearance or 'Appearance' under unity search). That should fix the issue.

A: To remap the menu key you will need to-do the following.
install prerequisites
Install package xkbset:
sudo apt-get install xkbset

define keyboard layout
Next you need to define what keyboard layout you are using.  In my case gb for a british/united kingdom keyboard layout or us for United States
setxkbmap -layout gb

Note: if you run
setxkbmap -query

it will give you the output as follows - if the model and layout is your keyboard then you are using the correct layout
rules:      evdev
model:      pc105
layout:     gb

Next define that we will be next mapping mouse keys:
xkbset m
xkbset exp =m

find Menu key-code
Map the Menu key.  To do this we need the Menu key-code.   In a terminal run xev, move your mouse inside the square and press the Menu key.

End Result
In my case my Menu key-code is the value 135 and this will be mapped to Mouse Button 2
xmodmap -e "keycode 135 = Pointer_Button2"

Tested as follows:

*

*Copy some text in a terminal  - Paste action initiated

*Hover mouse over title bar - Window move to background

Putting this all together:
Ok, once we've worked out the correct keycodes, we can put this together to start from login.
First create a file in your home folder called remapkeys
gedit ~/remapkeys

now copy and paste the following
#!/bin/sh
setxkbmap -layout gb
xkbset m
xkbset exp =m
xmodmap -e "keycode 135 = Pointer_Button2"

Save.  Give the file execute rights
chmod +x ~/remapkeys

Then from Dash search for Startup Applications or if using Gnome Classic - Applications - Other - Startup Applications
Add a new Startup Applications entry

The command should be:
bash -c "sleep 5 && ~/remapkeys"

The command sleeps for 5 seconds to allow your desktop to appear before running your new script - if your desktop doesnt appear within 5 seconds (maybe you are using a slow netbook?) then increase this timeout to 10 or 15 seconds.
Logout and login to test.

A: I'd note, for others (since I found this several times while looking for my own mouse) that some Logitech mice have a few buttons (on my MX1100, they were by default "DPI +/-" buttons) that do not send a signal to the USB receiver.
It is possible to override this and have the mouse report the button presses to your mouse driver, but the process is not even close to user-friendly (or even easily replicable, since it appears to be different for each mouse). The "lomoco" package will apparently work for some users, but has not been updated for newer mice in a while.


text:
Q: Custom Validator on phone number and further information on it I'm looking for a good site that explains CustomValidator in detail.  If anyone has a go to please let me know.  The following code checks that there are at least 10 numbers in the result. However, I'm looking to also have it validate that the values are numbers.  Using CustomValidator in vb.net is there a way to do this as an "and if" statement?
Thank you
Sub AtLeastTenNumbers_ServerValidate(ByVal source As Object, _
ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)

    If area_code.Text.Length + phone_1.Text.Length + phone_2.Text.Length > 9 Then
        args.IsValid = True
    Else
        args.IsValid = False
    End If

End Sub

A: This is a bit of an old article, but Scott Mitchell knows his stuff:
https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx

is there a way to do this as an "and if" statement?

You can always nest an if statement inside of your current statement.
If area_code.Text.Length + phone_1.Text.Length + phone_2.Text.Length > 9 Then
    args.IsValid = True
    'Check to see if this part is numeric
    If IsNumeric(phone_1.Text) Then
       ' Do Logic here
    End If
Else
    args.IsValid = False
End If


text:
Q: jasmine 2.0 testing angularjs factory method which returns a promise when i am trying to test a function which returns a promise i get the following error:

"Error: Timeout - Async callback was not invoked within timeout
  specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

"
my spec is as follows:
describe('async promise test', function () {

    beforeEach(module('app'));

    beforeEach(function () {
         jasmine.DEFAULT_TIMEOUT_INTERVAL = 6 * 1000;
    })

    it('should match the name', function (done) {
        inject(function ($rootScope,promiseTest) {
          $rootScope.$apply(function(){
             var promise =promiseTest.checkPromise();
            promise.then(function(data){
           console.log(data);
           done();
          })
        })
      })
    })
});

please check the plunker link for the complete code plunker link

A: You are using the mock module, which overrides $timeout, so that tests are repeatable (ref)!
You have to use $timeout.flush(1000); (and the $apply() is redundant):
it('should match the name', function (done) {
  inject(function (promiseTest,$timeout) {
    var promise =promiseTest.checkPromise();
    promise.then(function(data){
      console.log(data);
      done();
    });
    $timeout.flush(1000);
  });
});

See forked plunk: http://plnkr.co/edit/J1EmU7yuCETBd8w9mS1R?p=preview

A: You have to inject the $timeout into your test, and flush it:
 inject(function ($rootScope,promiseTest, $timeout) {
      $rootScope.$apply(function(){
         var promise =promiseTest.checkPromise();
         console.log("Created promise")
        promise.then(function(data){
       console.log(data);
       done();
      })
    });
    $timeout.flush();

See the modified plunker here:
http://plnkr.co/edit/psBl6nROkXHrD1iExKAQ?p=preview


text:
Q: Hide/Unhide Div on the basis of picklist selected value using javascrippt I am trying to hide one DIV if the selected value is not 50 . On salesforce view page I have added Visual Force Page through standard layout option. I want to display that page only if selected vale of Months is not 50 . Below is the code with which I am trying to achieve this. Please note Months is the custom field on Opportunity.
Visual Force Page
<apex:page standardController="Opportunity">

A: You can simply achieve this through standard tags. I don't see any reason to go for JavaScript for this.
<apex:page standardController="Opportunity">

<apex:outputPanel rendered="{!Opportunity.months__c == '(50) Fifty'}">
    <apex:outputLabel>Some Sample Text Here</apex:outputLabel>
</apex:outputPanel>

</apex:page>


text:
Q: Need to update from 18.04 to 20.04 but SU does not show this option I have Ubuntu 18.04 DELL laptop (where Ubuntu was preinstalled) with RTX 2060 GPU. I need to update its version to 20.04 but somehow (maybe it is too late Ubuntu 18.04 support ended in 2021 August) software updater does not show me this option (/etc/update-manager/release-upgrades set to normal)
~$ sudo do-release-upgrade -d -f DistUpgradeViewGtk3
Checking for a new Ubuntu release
Upgrades to the development release are only
available from the latest supported release.

So basically SU does not see update option.
What I should do in such situation to have smooth update from 18.04 to 20.04?
UPDATE
removing -d helped, but now
~$ sudo do-release-upgrade -f DistUpgradeViewGtk3
Checking for a new Ubuntu release
Please install all available updates for your release before upgrading.

Maybe some updates I can skip?

A: You don't need -d switch. It is to upgrade to a development release.
Run do-release-upgrade. It should work.
If you are asked to install all available updates, run
sudo apt update
sudo apt upgrade

and try again
do-release-upgrade


text:
Q: Can we create texture views with 1 of the dim(width/height/depth) smaller than that of base texture but same number of mipmap levels and layers? I know that we can use certain mipmap levels and/or layers of a texture as views.
e.g, If we have a texture 2d array of size 64x64 with 12 layers and 7 mipmpap levels, I can create as view the following:

*

*texture 2d of size 64x64 with n mipmap levels (n= 0 to 6).

*texture 2d of size 16x16 with n mipmap levels (n= 0 to 4).

*and so on..

*texture 2d array of size 64x64 with  n mipmap levels (n= 0 to 6) and x layers(x=0 to 11)

*texture 2d array of size 32x32 with  n mipmap levels (n= 0 to 5) and x layers(x=0 to 11)

*and so on..

But the glTextureView command does not ask the individual dimension of the view that must be created. Is it understood from the mipmap levels that we choose? Taking the exammple above, cant we create a texture 2D view with size say 64x32 and 7 mipmap levels, and 12 layers?
i.e it will be using exactly half subimage of the original texture for all mipmap levels and layers..?

A: No, GL_ARB_texture_view does not provide the functionality you are looking for (and also no other feature of the GL does) . What do you need this for? If you only want to use a sub-image of the texture, you can work with texture coordinates.


text:
Q: Cannot execute Raw Sql in .Net COre I am using Core 2.0 using entity framework.
I have successfully generated context using scaffold DBContext.
I have DBSet for table EMployee.
I need to execute SToredProcedure which will give list of employee.
I cannot see .FromSql nor.ExecuteCommand option.
I have added EntityFrameworkCore.SqlServer(2.0.1),EntityFrameworkCore.SqlServer.Design(1.1.5),Microsoft.VisualStudio.Web.CodeGeneration.Design(2.0.2) and EntityFrameworkCore.Tools(2.0.1) but to no awail.
Please guide for mentioned concerns.

A: If you want to execute row SQL using EF Core, try the following.
var employees = context.Employees
.FromSql("SELECT * FROM dbo.Employees")
// If you want to execute a stored procedure, then below
// .FromSql("EXECUTE {SP_NAME}")
.ToList();

But note, there are certain limitations present as described here:
https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#limitations

A: This is the only way to execute Raw SQL in .NET at the moment:
var conn = _context.Database.GetDbConnection();
try
{
    await conn.OpenAsync();
    using (var command = conn.CreateCommand())
    {
        command.CommandText = "SELECT * From Table1 WHERE sender = @sender";
        DbParameter sender = command.CreateParameter();
        sender.ParameterName = "sender";
        sender.Value = "Value";
        command.Parameters.Add(sender);
        DbDataReader reader = await command.ExecuteReaderAsync();

        if (reader.HasRows)
        {
            while (await reader.ReadAsync())
            {
                int SubscriptionID = reader.GetInt32(0);
            }
        }
        reader.Dispose();
    }
}
finally { conn.Close(); }

You can use it for stored procedures as well.


text:
Q: How can I learn about rewriting recursive functions into linear ones? I'm trying to learn about converting recursive functions into linear ones.
For instance
$a_n = b a_{n-1} + c$
I converted to
$a_n = (a + \frac{c}{b-1})b^n - \frac{c}{b-1}$
But I have no clue why it works.
Is there any place where I can see the operations that can be applied to recursive functions?

A: If we consider the following sequence defined by recursion :
$\left\{
    \begin{array}{ll}
        a_0 & = a\\
        a_{n} & = ba_{n-1} + c
    \end{array}
\right.$
Then by running some recursion steps, as did @peterwhy, we obtain:
\begin{eqnarray}
a_n &=& ba_{n-1} + c \nonumber\\
&=&b(ba_{n-2}+c)+c = b²a_{n-2}+bc+c\nonumber\\
a_n&=&b(b(a_{n-3}+c)+c = b³a_{n-3}+b²c+bc+c\nonumber\\
\end{eqnarray}
After $n$ iterations we have : $a_n = b^na_0+b^{n-1}c + ... + bc +c$ (remark the pattern) for $n>0$.
Then
\begin{eqnarray}
a_n &=& b^na_0 + c(1+b+b²+...+b^{n-1})
\end{eqnarray}
Now we have two cases :

*

*$b = 1$, then $1+b+b²+...+b^{n-1} = 1+1+...+1 = n$, so $a_n = a_0+nc$ (you recognize an arithmetic sequence).

*$b \neq 1$, then $1+b+b²+...+b^{n-1} = \frac{1-b^{n}}{1-b}$, so $a_n = b^na_0 + c\frac{1-b^{n}}{1-b} = (a_0 + \frac{c}{b-1})b^n-\frac{c}{b-1}$ as you found.

Note : if you're solving recurrences look at Concrete Mathematics as suggested @MJD.


text:
Q: How to use RDMA between two RDMA capable instances on Azure I have created 2 Standard HB120rs v2(RDMA capable) Virtual Machines on Azure with centos-based HPC,
On "ifconfig" I am getting below ips for 2 machines

I tried testing rping using the below commands
On instance 1 executed
rping -v -s -a 172.16.1.66 -C 10

On instance 2 executed
rping -v -c -a 172.16.1.66 -C 10

On doing this I am getting below error
cma event RDMA_CM_EVENT_ADDR_ERROR, error -110
waiting for addr/route resolution state 1

rping is not working. How to connect between two Mellanox devices from 2 VMs in azure.


text:
Q: Is there a built-in function that extracts values unequal to zero in MATLAB? I was wondering if there is a function like the one (smaller) below, but instead extracts values that are unequal to zero?
a = [67 0 8 25 0 20 0 90 7 2 9];

smaller10 = a(a < 10)

smaller10 =

 0     8     0     0     7     2     9

A: Either use
a(a~=0)

or
nonzeros(a).'

You can find the documentation for nonzeros here.


text:
Q: $\cos\gamma+\sin\gamma$ in a 3-5-7 triangle ($\gamma$ is the greatest angle) Clearly $\gamma$ has to be the angle oposite to the side of lenght 7. The law of cosines gives me $$7^2 = 5^2+3^2 - 2\cdot 5\cdot3\cos{\gamma}\Longleftrightarrow\cos{\gamma}=-\frac{7^2-5^2-3^2}{2\cdot5\cdot 3}=-\frac{1}{2}.$$
This value of $\cos{\gamma}$ means there can be two values of $\gamma$ satisfying it in $0\leq\gamma \leq 2\pi$. So $\sin{\gamma}$ can be either negative or positive. Using the trigonometric identity $\sin^2{\theta}+\cos^2{\theta}=1$, I obtain $$\sin{\gamma}=\pm\sqrt{1-\cos{\gamma}}=\pm\sqrt{1-\left(-\frac{1}{2}\right)^2}=\pm\frac{\sqrt{3}}{2}.$$
Using the positive value I get the correct answer of $$\cos{\gamma} + \sin{\gamma}=-\frac{1}{2}+\frac{\sqrt{3}}{2}=\frac{\sqrt{3}-1}{2}.$$
Why is it incorrect to use the negative value of $\sin{\gamma}$ ?

A: As $0<\gamma<\pi$ (actually $\frac{\pi}{2}<\gamma<\pi$), we have $\sin\gamma>0$

A: For $0^\circ<\gamma<180^\circ$ – the range of an angle in a non-degenerate triangle – $\sin\gamma$ must be positive.


text:
Q: Using Node.js to list all users in a Firebase iOS App I am trying to create a list of all my firebase users in node.js. I am following the description as offered on https://firebase.google.com/docs/auth/admin/manage-users
When running the below code, I throws an error saying
TypeError: admin.auth(...).listUsers is not a function

I have a suspicion that the firebase documentation uses 'admin' in different ways in different places and that the 'admin' I use below from initialisation is not the one I should be using to list the users, but I can't quite work out how to correct it. The documentation is not very clear.
Please note that for the .initializeApp({...}) code I added some '...' where otherwise I have the correct text.
var admin = require('firebase-admin');
var serviceAccount = require('../serviceAccountKey');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://...',
  databaseAuthVariableOverride: {
    uid: ' ... ',
  },
});

const db = admin.database();
const refUsersServer = db.ref('usersServer');

function listAllUsers(nextPageToken) {
  // List batch of users, 1000 at a time.
  // admin.auth().listUsers(1000, nextPageToken)

  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log("user", userRecord.toJSON());
      });

      // List next batch of users.
      if (listUsersResult.pageToken) {
        listAllUsers(listUsersResult.pageToken)
      }
    })
    .catch(function(error) {
      console.log("Error listing users:", error);
    });
}

// Start listing users from the beginning, 1000 at a time.
listAllUsers();

A: The code works fine but only in the latest firebase-admin version. In the earlier versions, the listUsers function didn't exit.
My mistake was that I didn't run the latest firebase-admin version which thanks to David 'G' I realised. Thanks.


text:
Q: IIS 7.5 login failed for user login failed to open explicitly specified database? I am hosting asp.net application in iis 7.5 and i am using sql server 2008 R2 its is running fine if i host it outside Default Website and turn its application pool identity to local system at that time my connection string is,
<add name="In****" connectionString="Data Source=PC\SQLEXPRESS;Database=*****;Integrated Security=SSPI;           Persist Security Info=false; Trusted_Connection=Yes;" providerName="System.Data.SqlClient"/>

when i tried to run it under default website i deploy it as same but change connection string like,
<add name="In*****" connectionString="Data Source=PC\SQLEXPRESS;Database=*****;User ID=****;Password=****;Trusted_Connection=False;"/>

but i get error,
Login failed for user 'IIS APPPOOL\DefaultAppPool'. Reason: Failed to open the explicitly specified database. [CLIENT: <local machine>]

i check it alot and get many solution like,
1) Change database name and then try it with sa user by restarting sql services.
2) I also create another user other then sa and attach it with database require for this application.
But error remain same :(
3) I also got solution that in Application pool click default website and then its advance setting then change its identity to Network services.
On this try i got this error,
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database. [CLIENT: <local machine>]

Hopes for you suggestion thanks in Advance.

A: The connection to the database will be established using the security context of the user that is running the IIS application pool. In this case, it is the Network Service local account, which is the one used by default.
I assume that this was working fine during development because you were running Visual Studio with your own user and your user has permissions to this database.
There are a number of solutions for this, some of them not recommended for a production environment, and the final one is my actual recommendation:

*

*If this database is local, you can give the Network Service account permissions to the database.

*You can use your own account as the user your site's Application Pool will run with, or

*THIS IS THE ONE RECOMMENDED: For production environments, you typically create a domain service account (or local if this is not in the scope of a domain  controller), give it non-admin permissions in the database, but enough to run your app. And then use the same account to run the application pool.

Give permissions to the user to access the DB:http://technet.microsoft.com/en-us/library/ms172405(v=SQL.105).aspx
Assign user to app pool: http://technet.microsoft.com/en-us/library/cc771170(v=WS.10).aspx
Hope this clarifies

A: Since a little while I'm having the same problem. MY connection string specifically states a user and password to use for logging in. However on one of my application pages I'm getting the same error, all others are working perfectly fine.
It worked perfectly fine on my test server previously so I thought it might be due to a received update? So I started de-installing some recent .NET updates and found this:
Initial error:
 Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
Then after de-installing KB2901126 & KB2898869 the error changes to:
 Login failed for user 'DOMAIN\COMPUTERNAME$'.
Note that both of those updates are security patches which prevent users of getting elevated rights:
From KB2901126

This update resolves vulnerabilities that could allow elevation of privilege if a user visits a specially crafted website or a website that contains specially crafted web content.

So I then wanted to re-install both updates again but I get this message:
Windows update error message
Notice the error, 80244022. The error occurs because of a connection interruption between my server and the update server. Bit weird since the other updates successfully manages to download and install itself.
MS might have removed the updates? I'm not sure what's happening but I'm fairly sure this is happening because of a MS update. No way my "working" app went from working to 1 broken page within 2 weeks without me even updating code from that specific page (or references behind it).
I'm going to try to see whether the same update on my DEV machines could have broken my build.
As a workaround I created a domain account and granted it access to the database, then I switched the app pool to this domain account. Without DB rights, and without editing the connecting string, the error on the specific page changed to "DOMAIN\new account" is unable to access the db. This confirms that for some reason that specific page, and the code behind, disregards the UID & PW in the connection string and uses integrated security.


text:
Q: How can I use a compressed PyTables CArray with R? with PyTables I have created a compressed CArray:
f = tables.openFile('/myPath/test.h5', 'w')
atom = tables.Atom.from_dtype(myNumpyArray.dtype)
ds = f.createCArray(f.root, 'myArray', atom, myNumpyArray.shape, filters=tables.Filters(5, 'blosc'))
ds[:] = myNumpyArray
f.close()

How can I load the array into R? I have tried the 'rhdf5' package but get this error:

Error in H5Dread(h5dataset = h5dataset, h5spaceFile = h5spaceFile, h5spaceMem = h5spaceMem,  :
    HDF5. Dataset. Read failed.

Is it possible to use this kind of array in R? If yes, is it possible to load only a part of the array and not the whole array?
Hope someone can help me. Thank you.

A: PyTables has metadata stored. You will need a customized function, see
https://support.bioconductor.org/p/64483
for details.


text:
Q: Optional group not working in regex I have the following strings:
"What version is installed on production server?"
"What appserver version is installed on production server?"
"What system version is installed on production server?"
"What os version is installed on production server?"

And the following regex:
 /(?:what|which).*(appserver|system)?.*version.*\son\s(\w*).*/i

I would expect to get appserver or system or undefined as the first matching group but I always get undefined.
If I remove the ? from the first matching group, I get appserver and system but the first and last string does not match anymore.
What is wrong?
See http://jsfiddle.net/ZVQTb/5/ for test bench.

A: The problem is that you're trying to look for anything up to "appserver" or "system", but when it's not there, there isn't another group before "version".
/(?:what|which).+?(appserver|system)?.*version.*\son\s(\w*).*/i

FIDDLE
Note: changed + to +? per Evan's keen eyes.


text:
Q: error Removing child entity; deleted child entity is marked as Modified instead of Deleted i've an unexpected issue trying to remove child entity from parent single database record.
After doing some tests we have replicated the problem.
Our C# code use Northwind database.
NWModel context = new NWModel();
Orders order = context.Orders.Where(w => w.OrderID == 10248).FirstOrDefault();
context.Entry(order).Collection(typeof(Order_Details).Name).Load();
order.Order_Details.RemoveAt(1);
System.Data.Entity.Infrastructure.DbChangeTracker changeset = context.ChangeTracker;
var changes = changeset.Entries().Where(x => x.State == System.Data.Entity.EntityState.Modified).ToList<Object>();
var detetions = changeset.Entries().Where(x => x.State == System.Data.Entity.EntityState.Deleted).ToList<Object>();

All works fine with original Order_Details table setup.
var deletions correctly has got deleted record.
In order to reproduce the issue, we have added on Order_Details table a new PK identity int field (OrderDetailId int identity); after doing that:
var deletions contain no record while var changes contain Order_Detail record.
EF set Orders property of Order_Detail to null and mark the record as Updated.
I've found a lot of articles regarding this issue, all of them suggests to mark Order_Detail Orders property to [Required].
I've tried to set [Required] attribute on FK entity as suggested in this post, (this article describe EFCore behaviour that is the same as EF6 behaviour) but is does not solve my issue.
Is this behaviour expected?
we would appreciate any comments or suggestions.
Thanks

A: AFAIK this is the correct behavior.
Indeed, you do not delete the detail. You remove it from the order details collection, that is you cut the relation between the order and the detail. As this relation is materialized by a navigation property on the detail side, then two things occur:

*

*the collection is updated,

*the navigation property is set to null.

Logically from this point if you SaveChanges you should have an exception because a detail cannot exist without an order, and you haven't yet deleted the detail, only cut the relation. So you should ctx.Set<orderDetail>().Remove(detail). (a bit annoying)
This is why in this case, I usually use composit key for details: detailId + orderId.
So when you remove the detail, the orderId is set to null <=> the PK is considered as null => the entity is marked for deletion.

A: Following tschmit007 suggestion, finally we have implemented this workaround.
On Orders entity we have used ObservableListSource<> instead of ICollection<>; into ObservableListSource<> class, void RemoveItem override method, we could manage ctx.Set<orderDetail>().Remove(detail) method.
In this way all child record deletion works as expected.
Here is implemented code:
public partial class Orders
{
public Orders()
{
    Order_Details = new ObservableListSource<Order_Details>();
}
[Key]
public int OrderID { get; set; }
……………
public virtual ObservableListSource<Order_Details> Order_Details { get; set; }
}

public class ObservableListSource<T> : ObservableCollection<T>, IListSource
        where T : class
{
    private IBindingList _bindingList;

    bool IListSource.ContainsListCollection { get { return false; } }

    IList IListSource.GetList()
    {
        return _bindingList ?? (_bindingList = this.ToBindingList());
    }
    private bool _bRemoveInProgress = false;
    protected override void RemoveItem(int index)
    {
        if (!_bRemoveInProgress && index>=0)
        {
            _bRemoveInProgress = true;
            DbContext cntx = this[index].GetDbContextFromEntity();
            Type tp = this[index].GetDynamicProxiesType();
            cntx.Set(tp).Remove(this[index]);
            base.RemoveItem(index);
        }
        _bRemoveInProgress = false;
    }
}

public static class DbContextExtender
{
    public static Type GetDynamicProxiesType(this object entity)
    {
        var thisType = entity.GetType();
        if (thisType.Namespace == "System.Data.Entity.DynamicProxies")
            return thisType.BaseType;
        return thisType;
    }
    public static DbContext GetDbContextFromEntity(this object entity)
    {
        var object_context = GetObjectContextFromEntity(entity);

        if (object_context == null)
            return null;

        return new DbContext(object_context, dbContextOwnsObjectContext: false);
        //return object_context;
    }

    private static ObjectContext GetObjectContextFromEntity(object entity)
    {
        var field = entity.GetType().GetField("_entityWrapper");

        if (field == null)
            return null;

        var wrapper = field.GetValue(entity);
        var property = wrapper.GetType().GetProperty("Context");
        var context = (ObjectContext)property.GetValue(wrapper, null);

        return context;
    }
}


text:
Q: Open ranges in Ruby using floats? Is it possible to create ranges in ruby that exclude one or both of the endpoints.  So handling the concept in mathematics of open and closed interval boundaries?
For example, can I define a range from 1.0 to 10.0 that excludes 1.0
Say (with pseudo-ruby)
range = [1.0...10.0)

range === 1.0
=> false

range === 10.0
=> true

A: The Range class in Ruby only supports closed and half-open (right-open) ranges. However, you can easily write your own.
Here's an example of a half-open range in Ruby:
range = 1.0...10.0

range === 1.0
# => true

range === 10.0
# => false

The total line count for the Ruby 1.9 compliant Range class in Rubinius is 238 lines of Ruby code. If you don't need your open range class to support every wrinkle, corner case, special case, idiosyncrasy, backwards-compatibility quirk and so on of the Ruby Language Specification you can get by with a lot less than that.
If you really only need to test for inclusion, then something like this should suffice:
class OpenRange
  attr_reader :first, :last

  def initialize(first, last, exclusion = {})
    exclusion = { first: false, last: false }.merge(exclusion)
    @first, @last, @first_exclusive, @last_exclusive = first, last, exclusion[:first], exclusion[:last]
  end

  def first_exclusive?; @first_exclusive end
  def last_exclusive?;  @last_exclusive  end

  def include?(other)
    case [first_exclusive?, last_exclusive?]
    when [true,  true]
      first <  other && other <  last
    when [true,  false]
      first <  other && other <= last
    when [false, true]
      first <= other && other <  last
    when [false, false]
      first <= other && other <= last
    end
  end

  alias_method :===, :include?

  def to_s
    "#{if first_exclusive? then '(' else '[' end}#@first...#@last#{if last_exclusive? then ')' else ']' end}"
  end

  alias_method :inspect, :to_s
end

A: you can exclude rightmost element of the range with .... See example below
(1..10).to_a # an array of numbers from 1 to 10 - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(1...10).to_a # an array of numbers from 1 to 9 - [1, 2, 3, 4, 5, 6, 7, 8, 9]

A: Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value.
('a'..'e').to_a    #=> ["a", "b", "c", "d", "e"]
('a'...'e').to_a   #=> ["a", "b", "c", "d"]

See more here
You could easily write your own Range to exclude the start value too.
For float ranges:
(1.0..10.0).step.to_a # => [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
(1.0...10.0).step.to_a # => [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
(1.0..10.0).step(2.0).to_a # => [1.0, 3.0, 5.0, 7.0, 9.0]
(1.0...10.0).step(2.0).to_a # => [1.0, 3.0, 5.0, 7.0, 9.0]

A: a few years later but...
what about taking advantage of the facts that a case statement evaluates each criteria in order of appearance and follows the path based on it's first match.
In the sample 1.0 always does nothing even though it's technically a valid value for the second "when".
case myvalue
    when 1.0
      #Don't do anything (or do something else)
    when 1.0...10.0
      #Do whatever you do when value is inside range
      # not inclusive of either end point
    when 10.0
      #Do whatever when 10.0 or greater
    end


text:
Q: Cannot run docker container with non root user for mariadb image Without a non root user the docker container that is running out of the dockerfile is working without error but when I add a user then I am getting following error:
    Initializing database 2019-07-17 21:28:05 0 [Warning] Can't create test file /var/lib/mysql/9e79cb48a1f0.lower-test 2019-07-17 21:28:05 0 [ERROR] mysqld: Can't create/write to file '/var/lib/mysql/aria_log_control' (Errcode: 13 "Permission denied") 2019-07-17 21:28:05 0 [ERROR] mysqld: Got error 'Can't create file' when trying to use aria control file '/var/lib/mysql/aria_log_control' 2019-07-17 21:28:05 0 [ERROR] Plugin 'Aria' init function returned error. 2019-07-17 21:28:05 0 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed. 2019-07-17 21:28:05 0 [ERROR] InnoDB: Operating system error number 13 in a file operation. 2019-07-17 21:28:05 0 [ERROR] InnoDB: The error means mysqld does not have the access rights to the directory. 2019-07-17 21:28:05 0 [ERROR] InnoDB: Operating system error number 13 in a file operation. 2019-07-17 21:28:05 0 [ERROR] InnoDB: The error means mysqld does not have the access rights to the directory. 2019-07-17 21:28:05 0 [ERROR] InnoDB: Cannot open datafile './ibdata1' 2019-07-17 21:28:05 0
 [ERROR] InnoDB: Could not open or create the system tablespace. If you tried to add new data files to the system tablespace, and it failed here, you should now edit innodb_data_file_path in my.cnf back to what it was, and remove the new ibdata files InnoDB created in this failed attempt. InnoDB only wrote those files full of zeros, but did not yet use them in any way. But be careful: do not remove old data files which contain your precious data!

Dockerfile
FROM mariadb:10.3.5

RUN apt-get update & apt-get upgrade -y

ENV MYSQL_USER=user1 \
    MYSQL_PASSWORD=pass5 \
    MYSQL_DATABASE=db \
    MYSQL_ROOT_PASSWORD=XXX

RUN useradd -ms /bin/bash newuser
USER newuser
WORKDIR /home/newuser
RUN sudo chown -R newuser:newuser /var/lib/mysql
ADD . /home/newuser

I would like to see the container to run as non root user

A: If you look into the content of Dockerfile, They already adding one no-root user in the Dockerfile, then why you need the other one?
# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN groupadd -r mysql && useradd -r -g mysql mysql

your this step also ignored,
RUN sudo chown -R newuser:newuser /var/lib/mysql

But it fails when it comes to the offical docker entrypoint, they run DB initialization or other stuff as a MySQL user so the new user will not permit for the following file so defiantly it will throw permission denied.

If you really want to do this you have to override docker-entry point or might be some part of dockerfile.
Here is code form offical Dockerfile
rm -rf /var/lib/mysql; \
        mkdir -p /var/lib/mysql /var/run/mysqld; \
        chown -R mysql:mysql /var/lib/mysql /var/run/mysqld; \
    # ensure that /var/run/mysqld (used for socket and lock files) is writable regardless of the UID our mysqld instance ends up having at runtime
        chmod 777 /var/run/mysqld; \


text:
Q: Rails and Stripe Payments Having trouble in the early stages of setting up Rails and Stripe and I'm following this Railscast: http://railscasts.com/episodes/288-billing-with-stripe
Trying to get the form to be detected by the javascript (coffeescript) on submit but it just submits to the create action and ignores the javascript.
Here is my coffeescript (borrowed from Railcasts):
jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  subscription.setupForm()

  subscription =
    setupForm: ->
      $('#new_subscription').submit ->
        $('input[type=submit]').attr('disabled', true)
        subscription.processCard()
        false

    processCard: ->
      card =
        number: $('#card_number').val()
        cvc: $('#card_code').val()
        expMonth: $('#card_month').val()
        expYear: $('#card_year').val()
      Stripe.createToken(card, subscription.handleStripeResponse)

    handleStripeResponse: (status, response) ->
      if status == 200
        alert(response.id)
      else
        alert(response.error.message)

I have generated my form like this but not too sure about this part...
<%= form_tag accounts_path, {:id => 'new_subscription'} do %>

this creates:
<form accept-charset="UTF-8" action="/accounts" id="new_subscription" method="post">

notice that it does have the right id. I had to set the ID specifically even though in Ryan's tutorials he did not seem to have to.
Any ideas where I'm going wrong?

A: I think you should watch your JavaScript console for errors. I think you're getting a JavaScript TypeError right here:
subscription.setupForm()

Both JavaScript and CoffeeScript will hoist a variable declaration to the top of the scope but neither will hoist the definition. For example, this CoffeeScript:
pancakes.m()
pancakes =
    m: -> console.log('pancakes')

becomes this JavaScript:
var pancakes;

pancakes.m();

pancakes = {
  m: function() {
    return console.log('pancakes');
  }
};

so pancakes exists when I say pancakes.m() but pancakes is still undefined at the point and so it has no m method until later when we assign it a value. Demo
Applying that to your code tells us that subscription is undefined when you try to subscription.setupForm(). Try putting things in the right order:
jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  subscription = ...
  subscription.setupForm()

If you look at the Railscast code, you'll see that the structure is like this:
jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  subscription.setupForm()

subscription = #...

Notice that subscription is defined outside the jQuery -> function? jQuery -> delays execution until after the page is loaded but by that time, the subscription = ... part of the code will have been executed already and subscription will have a non-undefined value.


text:
Q: How to decompile ASP.NET web application I have a web application that runs on ASP.NET. The code which was developed in C# is compiled. The company that originally wrote the application is no longer trading. We now need to make changes to the functionality of the application, and of course we can;t because of the source code is compiled.
Is there a way to decompile all of this code so that we can work with it?


text:
Q: What is the better way for converting lists to dictionary for bigger data without using pandas? let's say I got data from API like
data = [['monday', '1:00 PM', 60 ],['tuesday', '2:00 PM', 70 ],['wednesday', '3:00 PM', 65 ]] columnNames = ["Day", "Time", "temperature"]

How do I easily convert it to:
data = {""Day" : ["monday", "Tuesday", "Wednesday"], "Time": ["1:00PM", "2:00PM", "3:00PM"],"temperature": [60, 70, 65]}

I tried this:
def to_dict(name, index):
    for i in range(index, data_size):
        name.append(data[i][index])
to_dict(day, 0)
to_dict(time,1)
to_dict(temperature,2)
_list = [day, time, temperature]
dict(zip(columnNames, _list))

for bigger datasets what is better python way to do the above?


text:
Q: @Query annotation with custom Class Spring Boot Java question for JPA-Users, is the following somehow possible?
@Query(value = "SELECT * FROM Users u WHERE u.status = :sampleClass.status",
  nativeQuery = true)
List<SampleClass> findBySampleClass(SampleClass sampleClass);

Notice the way I am trying to access SampleClass in the @Query annotation. Wasn't able to get this going, instead went for Criteria and constructed my query old-school.

A: You could use the approach as mentioned in the JPA docs:
    @Query(value = "SELECT * FROM Users u WHERE u.status = ?1",
 nativeQuery = true)
    List<SampleClass> findBySampleClass(String status);

Please refer to the official docs for further options : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_native_queries
Not sure why you are trying to pass the whole object though.Would you care to explain?

A: There should not be any space in between = and : so change the query to below one.
SELECT * FROM Users u WHERE u.status =: sampleClass.status

Also as your mathod name findBySampleClass, you are trying to find based on SampleClass then why only passing one parameter of SampleClass instead of object??
see this for much clarity.
You can use like below also by indexing parameters like ?1.
@Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);

Refer : Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.

A: What you are trying to do is not possible because in native queries you have support just for binding direct variables, you can not do fancy access on objects. You could do something similar to your attempt by using either JPQL or HQL (in case you are using hibernate as an ORM provider).
But there is a problem on higher level. You are calling your method findBySampleClass, you are passing SampleClass as an input parameter and expect SampleClass as an output.This means that you would be returning the object itself from semantic point of view. This is suspicious. But going further on, you are doing something different inside the actual query specfication; you are using the status property of the object you passed in. This deviates from the convention that the method name should say what the query will be. In this case the correct(and most natural) way to go is to pass the status as a parameter, rename the method to findBySampleClassStatus or findByStatus.


text:
Q: How to get long text field in django models 1.3 with sql 2005 what is the field name that should be given in the models to get long text field.
I'm using django 1.3 and sql 2005

A: in your model write this
name = models.CharField(max_length=200)

links
1)for reference visit this.
2)and this might be usefull

A: If you need longer text then this should help:
your_field = models.TextField("your field name")

see: https://docs.djangoproject.com/en/dev/ref/models/fields/#textfield


text:
Q: How to rebase with merges? Let's say I have a mix of commits and merges on top of master in my clone. Now I want to push it somewhere, but I get a message that my changes cannot be fast-forwarded.
If I had only commits, I'd just do a pull --rebase, push and I'd have it done. But if I have merges in the way, pulling with rebase would destroy them. How do I deal with this situation?

A: If I'm understanding you correctly, you will want to do a git fetch. Once you have pulled in the remote branch tip, manually rebase/merge/cherry-pick your local work on top of it. Once you have arranged it the way you want, push your changes back to the remote.
Here is some great reasoning on why you would want to use fetch instead of pull.

A: To rebase and preserve merges, you can specify the --preserve-merges option to the rebase command. Depending on how easily each commit applies as a patch, this may or may not be easy to do.
I would fetch changes first, then inspect and take action.


text:
Q: Entering Decimal value in Edit text dynamically I am working in an Android application.In my application there is a edit text. in that
     edit text if user enters 12, it has to change dynamically as 12.00. which means it only
     accept decimal values. if user enters as 12.3 then it should become 12.30.and if 12.35
     then it should be 12.35 only. it will not allow user to enter more than two after dot.
      Please help in this scenario?

A: Use a TextWatcher to handle dinamically the input, then inside the TextWatcher use something like DecimalFormat to change the text.
yourEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void afterTextChanged(Editable s) {
        // do something here
        DecimalFormat form = new DecimalFormat("0.00");
        String FormattedText=form.format(s.toString());
    }
});


text:
Q: Get List from InputStream What I'm trying to do is to get List<byte[]> from InputStream. I'm sending HTTP request to an API that returns List<byte[]> and I want to get that list from the content body.
HttpPost httpPost = new HttpPost(endPoint);
CloseableHttpClient httpclient = HttpClients.createDefault();
httpPost.setEntity(new ByteArrayEntity(ReqBody));
CloseableHttpResponse response = httpclient.execute(httpPost);
System.out.println(response.getStatusLine());
System.out.println(response.getEntity().getContentType());

return response.getEntity().getContent();


text:
Q: How to round a small negative double to not cause minus zero in Java I need to round a small negative number to return 0.0. However, the value I'm getting is minus zero. The following code demonstrates the problem:
double value = -0.000000001;
double roundedValue = Double.valueOf(String.format(Locale.US, "%.4f", value));
System.out.println(roundedValue); // I need the roundedValue to be equal 0.0 (not -0.0)

There is a way to fix this?

A: You can explicitly handle the negative zero case:
roundedValue = (roundedValue == 0.0 && 1 / roundedValue < 0) ? 0 : roundedValue;

(1 / roundedValue < 0 to check for negative zero, from this answer)

Nit: use Double.parseInt rather than valueOf, to avoid the unnecessary boxing and immediate unboxing.

A: First, you have to realize that double values are semantically different from integers. They are imprecise, so there is always ever-so-slight error in every double value. The error, however, is small, but in unfortunate case it could be on the other side of zero - technically correct, but not what you want. This understanding is essential; if you need digit-exact arithmetic, you shouldn't be using doubles anyway, but integers/longs. Part of IEEE specification for double values also defines "negative zero", "NaN", "infinity" and so on, so technically the software is correct, but you are not using it the right way for what you want to achieve.
Second, like other people already mentioned, never use string formatting for rounding. If you need 4 decimal places, a much better way is to multiply the number by 10000, take floor/round of it and divide it by 10000 again. However, due to the facts mentioned above, you might again get some small decimal off (such as the 15th decimal digit).
On the other hand, if you just want to get rid of "rounding noise" which is sufficiently close to zero, you can also use this approach which is very robust:
if (Math.abs(x) < 0.000001d) x = 0d;

A: Much convenient would be:
double roundedValue = value < 0 ? (Math.ceil(value) == -0 ? 0 : Math.ceil(value)) : value;

In this case, you are going to preserve - values: for example -1.5 the result would be -1, but -0.00000001 is 0.0.


text:
Q: Golang question Array sudoku - grid[i][j][0] Hi I have a doubt with this code exactly with this seenRow[grid[i][j][0] - 49]. what does this ?

func sudoku2(grid [][]string) bool {
    for i := 0; i < 9; i++ {
        var seenRow [9]bool
        var seenCol [9]bool
        var seenSub [9]bool
        for j := 0; j < 9; j++ {
            if grid[i][j] != "." {
                if seenRow[grid[i][j][0] - 49] {
                    return false
                }
                seenRow[grid[i][j][0] - 49] = true
            }
            if grid[j][i] != "." {
                if seenCol[grid[j][i][0] - 49] {
                    return false
                }
                seenCol[grid[j][i][0] - 49] = true
            }
            x := i%3*3 + j%3
            y := i/3*3 + j/3
            if grid[y][x] != "." {
                if seenSub[grid[y][x][0] - 49] {
                    return false
                }
                seenSub[grid[y][x][0] - 49] = true
            }
        }
    }
    return true
}

A: seenRow[grid[i][j][0] - 49]

seenRow is a slice of slice of string, hence the first two indices [i][j]. grid[i][j] is a string, and grid[i][j][0] is the numeric value of the first byte value as an integer.
The subtraction -49 and the 9-element slice seenRow makes me think that the string's first byte is a value between 49 and 57 (ascii value '1' to '9'). At this point it's worth looking at the other parts of the code to understand what data is stored in grid and what are its semantics.
If I had to guess, grid is a 9-by-9 Sudoko board where each value is represented as a 1-byte string with values '1' to '9', with a special value '.' This is a rather odd representation, but it's what the code suggests.

A: It looks like it is an emulation of a hashmap. 49 is the ASCII character value of character 1, so if a cell has value 1, cell-49 will give 0, if the cell has 2, cell-49 will give 1, etc. And seenSub array keeps track of which digits were seen. If seenSub[i] is true, then the digit i+1 has been seen.


text:
Q: Efficient SQL table merge and paginate I have 5 distinct tables namely:

*

*deposits

*withdrawals

*payments

*transfers

*exchanges

I need to merge these tables and return a paginated result from a Nodejs API to clients. I don't know how to do this efficiently, given that the tables are really big(>100K rows each).
I was thinking of 2 approaches that I can take.

*

*Stream individual query results from each table to the node js backend and implements some merging logic there.

OR

*Somehow perform the merging at DB level, by creating some sort of virtual table or some persisted view, and perform a query on that.

What do you guys think?
Thank you for your time!

A: If you plan to manipulate with DB data then from my perspective the most efficient way accomplishing this would be on DB level, composing the specific SQL view or preparing advanced query leveraging combine techniques via JOIN, UNION or Sub queries. Saying above, and assuming Node.js Streaming concept, it is always good practice adopting streaming against large datasets.
const request = new sql.Request()
request.stream = true // You can set streaming differently for each request
request.query('select * from verylargetable')

If you will expect to further use this data for some other client applications, you may consider using CSV stringifier Node.js package, converting SQL output data into CSV text format.

A: it is difficult to provide a solution without knowing the structure of tables. You can use a view created by using INNER JOIN and use that view to select the attributes to return data to API requests Or U can Directly use INNER JOIN to return data. Return Data using procedure.


text: Q: Wordpress theme is not appearing I installed a new theme in WordPress. When I go to activate this theme from dashboard, I got all previously and currently installed theme is lost. Now it is showing only one theme which is currently active. I am working on localhost. What's the matter?


text:
Q: How to avoid chrome external dialog in WebdriverIO testing Chrome external protocol dialog
The first step of the e2e WebdriverIO test is to goto the login page. But the dialog stopped the test case from going further. I didn't find a way to either close the dialog using WebdriverIO or disable the dialog. Any one can help?

A: Try add this to your wdio.conf file
  "capabilities": [
    {
      ...
      "goog:chromeOptions": {
        "args": [
          "disable-infobars",
          "disable-popup-blocking",
          "disable-notifications"
        ]
      }
    }
  ]

or check this link: wdio github issue


text:
Q: PageAdapter, findViewById return null, what's the other way I have used PageAdapter as described by this post.
In one of my layout pages there's a ListView in which I want to add items at the run time. Normally I'd do:-
lv = (ListView) findViewById(R.id.list);

but that doesn't work as the ContentView is not set

Is there any other way to get the listview

A: You have to use the layoutinflator to get views which are not set by setContent view for example ListView lv = Layoutinflator.from(mContext).inflate(R.id.list, null);


text:
Q: Python: how to calculate the bucket points import numpy as np
import math

length = 10

points = [(1,2,3),(1,1,1),(23, 29, 0),(17, 0, 5)]

bucketed_points = {}

max_x = max([x for (x,y,z) in points])
max_y = max([y for (x,y,z) in points])
max_z = max([z for (x,y,z) in points])

x_buckets = int(max_x)/length + 1
y_buckets = int(max_y)/length + 1
z_buckets = int(max_z)/length + 1

for x in range(0, int(x_buckets)):

  for y in range(0, int(y_buckets)):

    for z in range(0, int(z_buckets)):

      bucketed_points["{0},{1},{2}".format(x, y, z)] = []

for point in points:
 # Here's where we actually put them in buckets
  x, y, z = point
  x, y, z = map(lambda a: int(math.floor(a/length)), [x, y, z])
  bucketed_points["{0},{1},{2}".format(x, y, z)].append(point)

print(bucketed_points)

I have four points (1,2,3), (1,1,1),(23, 29, 0), (17, 0, 5), what I need to do is moving all the points to the new location (0,0,0), (0,0,0), (20,30,0), (20,0,10) which represent the center points for a cube whose side length equals 10 (length = 10).


text:
Q: How can I disable Perl warnings for svnnotify? I'm using svnnotify. It works (sends email and all that) but it always outputs some error messages, such as

Use of uninitialized value in substr at /usr/lib/perl5/site_perl/5.8.8/SVN/Notify.pm line 1313.
substr outside of string at /usr/lib/perl5/site\_perl/5.8.8/SVN/Notify.pm line 1313.
Use of uninitialized value in index at /usr/lib/perl5/site\_perl/5.8.8/SVN/Notify.pm line 1313.
Use of uninitialized value in concatenation (.) or string at /usr/lib/perl5/site\_perl/5.8.8/SVN/Notify.pm line 1314.

I've tried running it with > /dev/null but no luck. I've tried running it > bla and file bla comes up empty, and the output is shown on screen. Since svnnotify does not have a quiet switch, how can I do this?

A: It looks like this happens when there is no log message for the commit. Some users may need to have a LART session to fix that. Barring that, the right thing to do is fix the SVN::Notify module and submit the patch to the SVN::Notify RT queue, but too late, I've already submitted the ticket.
Here's the patch:

diff --git a/lib/SVN/Notify.pm b/lib/SVN/Notify.pm
index 3f3672b..5387dd2 100644
--- a/lib/SVN/Notify.pm
+++ b/lib/SVN/Notify.pm
@@ -1308,7 +1308,7 @@ sub prepare_subject {
     }

     # Add the first sentence/line from the log message.
-    unless ($self->{no\_first\_line}) {
+    if (!$self->{no\_first\_line} and defined $self->{message}[0] and length $self->{message}[0] )
         # Truncate to first period after a minimum of 10 characters.
         my $i = index substr($self->{message}[0], 10), '. ';
         $self->{subject} .= $i > 0

I think that takes care of the warnings, but I suspect it's only a band-aid because the design around $self->{no\_first\_line} seems dodgy.

A: While the accepted answer certainly works, it isn't (in my opinion) the best answer, because one day you're going to have to maintain this code (or worse, someone else will), and getting it to run with no warnings will make your code that much better. Given the warnings, it looks like the problem isn't you, but it's hard (but not impossible) to imagine that a module in version 2.79 would give errors. Maybe your copy of SVN::Notify is old? Maybe your code (or someone's code) is mucking with the module's internals? It's hard to tell with the few warnings I can see, and I have a feeling there's a bit more to this problem than meets the eye.

A: The error is printed on stderr, you can redirect it to /dev/null with 2> /dev/null. Alternatively you can make it not use perl -w.


text:
Q: HTML side by side divs, while one has fixed width and the second one fits remaining space I have that code:
<!DOCTYPE html>

       123123123123123123123123

    aasdasdasdasdasdasdasdasdasd

 11111111

 222222222222222222222222222222

 3333333333333333

    aaaaaa aaaaa aaaaaa aaaaa aaaaaa

It looks good.
http://i.cubeupload.com/yOz2zu.png
However if i add more words to the third div, it goes down.
http://i.cubeupload.com/pZ65dr.png
Is there any way to make div not going down without adding fixed width? I want to have only the first div with fixed width, the second one has to fill. I don't want to use JS. Thanks for help.

A: You only need to float one of the div tags.  You can also get rid of the table style display CSS.  As other comments have mentioned, you don't want to use  and  tags.  They are depricated and no longer supported.

     123123123123123123123123

    aasdasdasdasdasdasdasdasdasd

 11111111

 222222222222222222222222222222

 3333333333333333

    aaaaaa aaaaa aaaaaa aaaaa aaaaaa
    aaaaaa aaaaa aaaaaa aaaaa aaaaaa
    aaaaaa aaaaa aaaaaa aaaaa aaaaaa
    aaaaaa aaaaa aaaaaa aaaaa aaaaaa
    aaaaaa aaaaa aaaaaa aaaaa aaaaaa

A: I'd generally put all my style in CSS

body {
    margin: 0;
}
.header {
    background-color:rgb(150, 200, 255);
    height:50px;
    width:100%;
    font-size: 35px;
    font-weight: bold;
    text-align: center;
}
.left {
    background-color:rgb(180, 215, 255);
    float:left;
    width:300px;
    height: 90vh;
}
.content {
    float:right;
    width: calc(100% - 300px);
}

123123123123123123123123

aasdasdasdasdasdasdasdasdasd

11111111

222222222222222222222222222222

3333333333333333

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id nisi ultrices, egestas erat vitae, laoreet lorem. Suspendisse sed mi placerat dolor lacinia maximus. Nullam sem tellus, facilisis sed tristique in, faucibus eu ligula. In hac habitasse platea dictumst. Mauris sed ex id ipsum pharetra dignissim. Donec vitae pulvinar est. Suspendisse placerat turpis vel arcu semper vulputate. Cras laoreet purus ac facilisis sodales. Vestibulum blandit, justo sed porta bibendum, lectus nisi rhoncus tortor, quis dapibus urna nulla et nibh.


text:
Q: How are listitems being darkened when touched in "Bluetooth Le Gatt" sample project provided by Android Studio Looking through stackoverflow, I've found answers as to how to darken a listitem when its being touched so that the user knows which item in the list view is about to be selected.
How to change color of ListView items on focus and on click.
But I cannot find any sort of implementation for that type of function in the Bluetooth Le Gatt sample project provided by Android Studios.

A: I gave my listitems backgrounds which change their colour from the regular white using an xml file in my drawable folder. This prevented the list item from darkening when touching it.
edit: you can also set your background as selectable to give it an effect when selected/pressed.
android:background="?android:attr/selectableItemBackground"