java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference)

Question: Unfortunately app has stopped in Emulator
and showing this in log cat (java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference)
Image adapter.java
 package com.example.websoft.firstapp;

    import android.content.Context;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;

    /**
     * Created by websoft on 15/04/2020.
     */
    public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        public int[] imageArray={
          R.drawable.bani,R.drawable.kivsachiarahoiae,R.drawable.moolmantar,R.drawable.rehmat1
            };

        public ImageAdapter(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        public int getCount() {
            return imageArray.length;
        }

        @Override
        public Object getItem(int position) {
            return imageArray[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
           public View getView(int position, View convertView, ViewGroup parent) {

                    ImageView imageView = new ImageView(mContext);
                    imageView.setImageResource(imageArray[position]);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setLayoutParams(new GridView.LayoutParams(340, 350));

            return null;
        }

        }

MainActivity.java
  package com.example.websoft.firstapp;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;

    public class MainActivity extends AppCompatActivity {
    private Button button;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();

                }
            });

            button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivity2();
                }
            });
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

    public void openActivity2() {
        Intent intent = new Intent(this, Main22Activity.class);
        startActivity(intent);
    }}

Main22Activity.java
package com.example.websoft.firstapp;

import android.renderscript.RenderScript;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;

public class Main22Activity extends AppCompatActivity {
GridView gridView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main22);

        gridView=(GridView) findViewById(R.id.simpleGridView);
        gridView.setAdapter(new ImageAdapter(this));

    }
}

logcat
04-16 08:18:05.323 4955-4955/? I/art: Not late-enabling -Xcheck:jni (already on)
04-16 08:18:05.323 4955-4955/? I/art: Late-enabling JIT
04-16 08:18:05.325 4955-4955/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
04-16 08:18:05.634 4955-4955/com.example.websoft.firstapp W/System: ClassLoader referenced unknown path: /data/app/com.example.websoft.firstapp-1/lib/x86
04-16 08:18:06.163 4955-4962/com.example.websoft.firstapp W/art: Suspending all threads took: 5.533ms
04-16 08:18:06.637 4955-4955/com.example.websoft.firstapp D/gralloc_goldfish: Emulator without GPU emulation detected.
04-16 08:18:07.466 4955-4955/com.example.websoft.firstapp I/Choreographer: Skipped 85 frames!  The application may be doing too much work on its main thread.
04-16 08:18:08.654 4955-4966/com.example.websoft.firstapp I/art: WaitForGcToComplete blocked for 12.433ms for cause Background
04-16 08:18:08.701 4955-4955/com.example.websoft.firstapp D/AndroidRuntime: Shutting down VM
04-16 08:18:08.701 4955-4955/com.example.websoft.firstapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.websoft.firstapp, PID: 4955
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2363)
                                                                                at android.widget.GridView.onMeasure(GridView.java:1065)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
                                                                                at android.view.View.measure(View.java:18788)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-16 08:18:17.495 4955-4962/com.example.websoft.firstapp W/art: Suspending all threads took: 5.023ms
04-16 08:18:57.795 4955-4962/com.example.websoft.firstapp W/art: Suspending all threads took: 22.833ms
04-16 08:20:01.216 4955-4962/com.example.websoft.firstapp W/art: Suspending all threads took: 5.076ms

04-16 08:18:08.701 4955-4955/com.example.websoft.firstapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.websoft.firstapp, PID: 4955
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
activity_main22.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.websoft.firstapp.Main22Activity">
<GridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="3"
    android:columnWidth="90dp"
    android:id="@+id/simpleGridView"

    android:layout_gravity="center" />
</LinearLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.websoft.firstapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

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

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

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

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

Comment: can you point out line of error in above code
Answer: This part does not look right
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(imageArray[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(340, 350));

    return null;
}

You need to inflate the view first, something like this.
@Override
public View getView(int position, @Nullable View convertView, ViewGroup parent){
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.some_list_item, parent, false);
    }

    ImageView imageView = convertView.findViewById(R.id.imageView);
    imageView.setImageResource(imageArray[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(340, 350));

    return convertView;
}


Como faço para traçar o gráfico da função de produção de Cobb-Douglas no R?

Question: Gostaria de elaborar o gráfico para a função de produção de Cobb-Douglas no R,um exemplo seria a função:
P(L, K) = 1,01L^0,75 k^0,25
Onde  L e K variam entre 0 e 300.
Answer: Aqui vai uma das infinitas possibilidades para realizar o que você deseja:
# criar uma função
P = function(L, K) {
  return(1.01 * L^0.75 * K^0.25 )
}

# Variáveis
L = K = 0:300

# definir amostra de uma variável para plotar em função da outra
amostra <- seq(0, 300, 20)

# definir cores
cols <- rainbow(length(amostra))

# 2 plots
par(mfrow = c(1, 2), mar = c(3,3,0.5,0.5), mgp = c(1.5, 0.3, 0), tck = -.008)

# L
plot(0, pch = '', xlim = c(0, 300), ylim = c(0, 200), xlab = 'L', ylab = 'F(L, K)')
for(k in 1:length(amostra)) {
  points(L, P(L, K[k]), type = 'l', col = cols[k])
}
legend('topleft', legend = amostra, title = 'K', lty = 1, col = cols, bty = 'n', cex = 0.7)

# K
plot(0, pch = '', xlim = c(0, 300), ylim = c(0, 100), xlab = 'K', ylab = 'F(L, K)')
for(l in 1:length(amostra)) {
  points(K, P(L[l], K), type = 'l', col = cols[l])
}
legend('topleft', legend = amostra, title = 'L', lty = 1, col = cols, bty = 'n', cex = 0.7)

Comment: Perfeito,obrigado!
Answer: Esta resposta necessita do pacote plot3D instalado. Se ainda não o tiver instalado, pode fazê-lo com
install.packages("plot3D")

Primeiro defino uma função cobbDouglas bastante geral, que também aceita como argumentos a constante A e os expoentes alpha e beta.
cobbDouglas <- function(K, L, A, alpha, beta){
  A * L^beta * K^alpha
}

Agora é primeiro calcular os valores da função, com outer().
L <- 0:300
K <- 0:300
Z <- outer(K, L, cobbDouglas, A = 1.01, alpha = 0.25, beta = 0.75)

E traçar o gráfico com plot3D::persp3D. Antes disso redefino os valores das margens para ter mais espaço para o gráfico e no fim repõem-se os parâmetros gráficos tal como estavam.
op <- par(bg = "white", mar = c(1, 1, 1, 2) + 0.1)
plot3D::persp3D(L, K, Z, theta = 30, phi = 30,
                expand = 0.5, col = rainbow(100))
par(op)

Comment: Perfeito,obrigado!


Working with two dictionaries in one pickle file

Question: I would like to make this very clear so ill start off with the case i know so everyone knows exactly what i mean. When i'm storing just a single dictionary in a pickle file this is the method i use and it works great.
#open pickle file
with open("a_pickle_file", 'rb') as input:
  x = pickle.load(input)
#Now update the dict in your pickle file
a_dict.update(x)

Assume some arbitrary manipulation to this dictionary now i save like so:
#Save whatever u added to the dict
pickle.dump(open(a_dict,"a_pickle_file"))

Now moving on to the case that im unsure about and which seems to have little to no documentation from what i've found anyway. I want to do the same exact thing as above only this time i will be storing two dictionaries inside a list and then storing the list in the pickle file like so,
#Two dict
MyFirstDict = { 1: 'a' }
MySecondDict = { 2:'b' }

#Store them in a list
two_dict = [MyFirstDict, MySecondDict]

#save them
pkl.dump( two_dict, open( "two_dict_pkl_file", "wb" ) )

Now i have a two dictionaries inside a list and its stored in my pickle file. Now from here how does one load this pickle file for manipulation? Once it is loaded how can i access each dictionary inside for updating and manipulation. Finally, can i just use the same pkl.dump statement above to re-save it. Thanks
EDIT
So for the most part the procedure is generally the same when doing this except for the part where you need to update your dictionaries with previous info. This is the output of a list of two dict in one pkl file:
[{'I': 'D', 'x': 'k', 'k': [datetime.time(11, 52, 3, 514000)]}, {'I': 'D', 'x': 'k', 'D': [datetime.time(11, 52, 3, 514000)]}]

As you can see it is stored oddly, and i can't seem to properly access each dict separately for updating their must be some syntax to properly do this.
Answer: Just give it a try! Do pickle.load() and you'll see a list with two dicts in it. You can reference them in several ways, but this is a common way to do it:
MyFirstDict, MySecondDict = pickle.load(open("two_dict_pkl_file", "rb"))

And yes, you can just pickle.dump them again if you want to overwrite the existing contents.
EDIT
Here is a script illustrating the concept:
import pickle, datetime

test_file = "two_dict_pkl_file"

# store two dicts in a list
MyFirstDict = { 1: 'a' }
MySecondDict = { 2:'b' }
two_dict = [MyFirstDict, MySecondDict]

print "first pickle test"
print "this python list gets pickled:"
print two_dict
print
print "this is the pickle file"
pickle.dump( two_dict, open( test_file, "wb" ) )
print open(test_file, "rb").read()
print

print "update pickle test"
pickle_list = pickle.load(open(test_file, "rb"))
print "this python object is read back:"
print pickle_list
print
d1, d2 = pickle_list
two_dict = [d1, d2]
d1['time'] = d2['time'] = datetime.datetime.now().time()
pickle.dump( two_dict, open( test_file, "wb" ) )
print "this is the updated pickle:"
print open(test_file, "rb").read()
print

print "and this is the updated python:"
print pickle.load(open(test_file, "rb"))

...and its output
first pickle test
this python list gets pickled:
[{1: 'a'}, {2: 'b'}]

this is the pickle file
(lp0
(dp1
I1
S'a'
p2
sa(dp3
I2
S'b'
p4
sa.

update pickle test
this python object is read back:
[{1: 'a'}, {2: 'b'}]

this is the updated pickle:
(lp0
(dp1
I1
S'a'
p2
sS'time'
p3
cdatetime
time
p4
(S'\n2;\x02s\x95'
p5
tp6
Rp7
sa(dp8
I2
S'b'
p9
sg3
g7
sa.

and this is the updated python:
[{1: 'a', 'time': datetime.time(10, 50, 59, 160661)}, {2: 'b', 'time': datetime.time(10, 50, 59, 160661)}]

Comment: So i took your advice and just gave it a try and iv'e figured everything out besides the updating part. Things here are different then just having a single dictionary stored see edit for the output.
Comment: Looking at your edit, that's python source code, not a pickle file. If this is the result of `print pickle.load(...)` then that's exactly what you want - two dicts inside a list. I'm adding a test script for more details.
Comment: I'm giving it a try now, but why doesn't your final line have the updated info in it? I was under the impression i had to use `.update` to update the dictionaries.
Comment: My bad, I was adding print statements and accidentally deleted the line where two_list is reassigned. I've supplied an edit.
Comment: ...and dict.update() is only used if you want to update a dict with the contents of another dict. If you just want to change individual entries, `mydict[somekey] = someval` is sufficient.
Comment: Yes, i need to update the dictionary. I need it to have the information already stored in it plus the added information saved. It works but still it is not updating the information its just over writing it. I need to do exactly what i have in my first example.
Comment: I think you made some edits, i have work but when i get home tonight ill be sure to try it again and mark as correct if it works.
Comment: Thanks so much for the time and effort i really appreciate it, this worked perfect and it makes sense i just wasn't thinking about the problem correctly. Thanks again man.


Python script... I need to take API Key from the command prompt into Main.py

Question: Need help to take an API key from the command prompt and insert it into a particular cell of an excel sheet. I plan to add it into Main.py. but not sure where in the script.
 API_key = input("What is the API key? \n")

Then I plan to use Openpyxl to add this into the cell on the excel sheet. But where do I add this code? In the Main.py script? Taken directly from the Openpyxl docs:
from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = API_key

# Save the file
wb.save("sample.xlsx")

Comment: If you're going to enter this at the keyboard anyway, why not just bring up Excel and type it into the cell?  What are you saving here?  The answer is that you need to ask for the input any time before you USE the value.
Comment: The Excel will be a shared document. However, AIP Key is unique for each employee. (just like a password).
Answer: The code in your description works.
You can do it like this:
from openpyxl import Workbook
book = Workbook()
sheet = book.active
API_key = input("What is the API key? \n")
sheet['A1'] = API_key
book.save("sample.xlsx")


Example of function of a single random variable.

Question: Take a look at this document: Functions of random variables; Abdel-Hamid Soubra, Emilio Bastidas-Arteaga
In the section $2.2$, they have given an example about application for an exact distribution of a function of a single random variable using Normal Distribution where,
$$f_X(x) = \frac{1}{\sigma \sqrt{2 \pi}} \cdot e^{\displaystyle - \frac{1}{2}  \cdot \left (\frac{x -
 \mu}{\sigma}\right)  ^2 }$$
and,
$$f_Y(y) = \frac{1}{\sigma \sqrt{2 \pi}} \cdot e^{\displaystyle  \left [\frac{ \frac{1}{2}( \sigma y + \mu -\mu)  ^2 }{\sigma^2}\right] } \left| \sigma \right| $$
Note: to me, the above equation is apparently incorrect.
Can anyone explain the same concept of function of random variables using a simpler equation? How about $y=mx+c$ ?
Comment: Your placement of $|\sigma|$ is wrong.
Answer: The function used in the book is precisely a linear one, written
$$y=\frac{x-\mu}\sigma$$ or $$x=\sigma y+\mu.$$
If you plug this in the initial distribution,
$$f_X(x)=\frac{1}{\sigma \sqrt{2 \pi}} \cdot e^{\displaystyle - \frac{1}{2}  \cdot \left (\frac{x -
 \mu}{\sigma}\right)  ^2 }$$
the expression simplifies to
$$f_X(x)=f_X(\sigma y+\mu)=\frac{1}{\sigma \sqrt{2 \pi}} \cdot e^{\displaystyle - \frac{y^2}{2} }.$$
The purpose of this section is to explain why the $\sigma$ at the denominator needs to vanish to obtain the distribution $f_Y(y)$ from $f_X(x)$ (this is because the distribution must remain normalized.)
$$f_X(x)=\sigma f_Y(y)$$ (absolute value omitted.)


How to show popup in tvOS?

Question: I am trying to show a popup when a UICollectionView cell, but I'm having no luck...
In iOS, I would usually use the modalPresentationStyle like this:
popoverContent.modalPresentationStyle = .Popover

but in tvOS this is not available.
I think showing a popup is possible by using
UIPopoverController

but it is giving me a warning that it is deprecated in tvOS 9.0. Is this something I can ignore and just use it?
I'm wondering if anyone has an idea how to make popup to work in tvOS?
p.s.
Does anyone know if there is a way for tvOS app to read data from external hardware through Apple TV USB?
Comment: I've used popover successfully using storyboard segue's.  I created a UIViewController and set the segue to be a Popover and it worked fine.  I have no depreciation warnings in Xcode either.   That being said I only added this to my codebase after tvOS 9.1 came out so maybe they recently added support?
Answer: I think what you are searching for is the UIAlertController introduced in TvOS 9.0
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                                                               message:@"This is an alert."
                                                        preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {}];

[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];

Answer: Popovers are not available on tvOS.  You could probably build a custom presentation that had a similar appearance, but it would probably be non-trivial.

How to show popup in tvOS?


Socket: premature end of JPEG file

Question: I'm trying to send an image file from a server to a client via a socket.  The socket was previously used to send some strings from the server to the client (with buffered input/output streams).
The trouble is the image file can't be received properly, with "Premature end of JPEG file" error.
The server first sends the file size to the client, the client then creates a byte[] of that size, and starts to receive the file.
Here are the codes:
Server:
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        //Send file size
        dos.writeInt((int) file.length());

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] fileBytes = new byte[bis.available()];
        bis.read(fileBytes);
        bis.close();

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(fileBytes);
        bos.flush();

Client:
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        //Receive file size
        int size = dis.readInt();

        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] fileBytes = new byte[size];

        bis.read(fileBytes, 0, fileBytes.length);

More interestingly, if I let server sleep for about 2 seconds between sending the file size and writing the byte[], then the image is received properly.  I wonder if there's some kind of race condition between the server and the client
Comment: You can't use Read/Writers AND Streams. Use one type or the other or your application is bound to get confused.
Comment: Why does your server have `BufferedReader` ? Is there something coming back?
Answer: Please check commons-io with FileUtils and IOUtils. This should make work a lot easier.
http://commons.apache.org/io/
Answer: The error is most likely here:
byte[] fileBytes = new byte[bis.available()];

The method available does not return the size of the file. It might return only the size of the input buffer, which is smaller than the size of the file. See the API documentation of the method in BufferedInputStream.
Also, read in the line below is not guaranteed to read the whole file in one go. It returns the number of bytes that were actually read, which can be less than what you asked for. And in the client code, you are using read in the same way, without actually checking if it read all the data.
Comment: Jesper is absolutely right about this.  On the client side, I decided to use a loop to receive, with guard bis.read(buffer)==-1, and it worked.
Answer: The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // more if you like, but over a network it won't make much difference
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

Your code fails to logically match this at several points.
Also available() is not a valid way to determine either a file size or the size of an incoming network transmission - see the Javadoc. It has few if any correct uses and these aren't two of them.

Socket: premature end of JPEG file


Finding what distribution a random variable has.

Question: Mike has a gold coin with fair probability, and a silver coin with $1\over 3$ probability for Heads and $2\over 3$ for tails. He tosses the gold coin 120 times and the number of heads is denoted N. Then he tosses the silvered on N times. The number of heads is denoted S and the number of tails is denoted T. How does S distributes given T=30?
I already computed S's expeted value, which is 20. It has the binomial distribution of Bin(120,$1\over 6$). I don't know, however, how to find what kind of distribution S has given T has a known value. I would really appreciate your help.
Comment: I have 120 experiments with two levels. For me to get a head in the silvered coin, I have to get in one experiment a head in the gold coint and then a head in the silvered one. I has the probability of $1\over 6$ to succeed. I don't get a head on the silvered one if I either get a tail in the gold one, or get a head in gold one but tail in the silvered one.It has a probability of $5\over 6$.
Comment: Can you elaborate on how you get the distribution of $T$ to be $\text{Bin}(120,1/6)$? You toss the silver coin $N\leq 120$ times (a random number), and each of these times, the probability of tails is $2/3$.
Comment: Isn't it $S$ that's $\text{Bin}(120,1/6)$? After all, it's the combination heads-heads (gold then silver) that has probability $1/6$. The combination heads-tails has probability $1/3$, which makes $T$ distributed as $\text{Bin}(120, 1/3)$.
Comment: You are right. I switched S and T because there original question is not in English and I thought it would confuse if I kept it that way.
Answer: You allready found that $S$ has binomial distribution with parameters
$120$ and $\frac{1}{2}\frac{1}{3}=\frac{1}{6}$.
Likewise you can find that $T$ has binomial distribution with parameters
$120$ and $\frac{1}{2}\frac{2}{3}=\frac{1}{3}$.
That enables you to find an expression for $P\left(T=30\right)$.
We have $$P\left(S=s\mid T=30\right)=\frac{P\left(S=s\wedge T=30\right)}{P\left(T=30\right)}$$
so what remains is finding an expression for $P\left(S=s\wedge T=30\right)$.
$P\left(S=s\wedge T=30\right)=P\left(S=s\wedge N=s+30\right)=P\left(S=s\mid N=s+30\right)P\left(N=s+30\right)$
Of course $N$ has binomial distribution $\left(120,\frac{1}{2}\right)$
and under condition $N=s+30$ the distribution of $S$ binomial with parameters $s+30$ and $\frac{1}{3}$.
If I didn't make mistakes then you will end up with again a binomial
distribution. This time with parameters $90$ and $p=\frac{1}{4}$.
It would not surprise me if there is a more elegant route to this
result.
Comment: (+1) Your answer looks good to me. Another way to view it (whether or not it's elegant is up to the reader :-) is as follows. If you label the gold coins $1,\ldots,120$ and do the same for the silver coins, you have $120$ pairs that can be HH, HT, or T*: $P(HH)=1/6,P(HT)=1/3,P(T*)=1/2$. (Trinomial dist'n) Given $T=30$ there remain $90$ pairs that must be HH or T*, with respective probabilities $\frac{1/6}{1/6+1/2}=1/4$ and $\frac{1/2}{1/6+1/2}=3/4$, so that $S\mid T=30$ is $Bin(90,1/4)$.
Comment: @MickA Ah, yes. This is a nice confirmation and exhibits indeed a more elegant route. I somehow *knew* there had to be one. Thank you.


Print entire path of Maximum cost in a maze from first cell to last cell when moving right and bottom is allowed

Question: I need a help in a enhancement to very popular dynamic programming question. Min/Max cost path
Question : There is a 2D matrix which has values (0,1,-1).
0 -> no cherry. can go here
1 ->  cherry present. can go here
-1 -> thorn present. can't go here

we need to print maximum cherrys collected and entire path in which we can collect maximum cherrys.
input :
{{0, 1, -1}, {1, 0, -1},{1,1,1}};

output :
4
(0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2)

I can write the code to print the maximum cherrys collected but not able to get the logic to how to store the entire path. Since we decide which cell to be choosen while backtracking, it appears little tough. didnt find any web help in this regard. I'm stuck, Any help would be appreciated.
public int cherryPickup(int[][] grid) {
    if (grid.length == 0) {
        return -1;
    }
    int[][] dp = new int[grid.length][grid[0].length];
    setDp(dp);
    int forwardMax = getForwardMax(grid, dp, 0, 0);
    return forwardMax;
}

private void setDp(int[][] dp) {
    for (int i = 0; i < dp.length; i++) {
        for (int j = 0; j < dp[0].length; j++) {
            dp[i][j] = -1;
        }
    }
}

private int getForwardMax(int[][] grid, int[][] dp, int i, int j) {
    if(dp[i][j] != -1) {
        return dp[i][j];
    }
    if (grid[i][j] == -1) {
        dp[i][j] = 0;
        return dp[i][j];
    }
    if (i == grid.length - 1 && j == grid[0].length - 1) {
        dp[i][j] = grid[i][j];
        return dp[i][j];
    }
    if (i == grid.length - 1) {
        dp[i][j] = grid[i][j] + getForwardMax(grid, dp, i, j + 1);
        return dp[i][j];
    }
    if (j == grid[0].length - 1) {
        dp[i][j] = grid[i][j] + getForwardMax(grid, dp, i + 1, j);
        return dp[i][j];
    }
    dp[i][j] = grid[i][j] + Math.max(getForwardMax(grid, dp, i + 1, j), getForwardMax(grid, dp, i, j + 1));
    return dp[i][j];

}

As per suggestion in the comment for having the path[][] and storing the index which is maximum.
Below code stores (1,1) also 1, which is incorrect.

private int getForwardMax(int[][] grid, int[][] dp, int i, int j, int[][] path) {
    if(dp[i][j] != -1) {
        return dp[i][j];
    }
    if (grid[i][j] == -1) {
        dp[i][j] = 0;
        return dp[i][j];
    }
    if (i == grid.length - 1 && j == grid[0].length - 1) {
        dp[i][j] = grid[i][j];
        return dp[i][j];
    }
    if (i == grid.length - 1) {
        dp[i][j] = grid[i][j] + getForwardMax(grid, dp, i, j + 1, path);
        path[i][j] =1;
        return dp[i][j];
    }
    if (j == grid[0].length - 1) {
        dp[i][j] = grid[i][j] + getForwardMax(grid, dp, i + 1, j, path);
        path[i][j] =1;
        return dp[i][j];
    }
    int left = getForwardMax(grid, dp, i + 1, j, path);
    int right = getForwardMax(grid, dp, i, j + 1, path);
    int max = Math.max(left, right);
    if(max == left) {
        path[i+1][j] = 1;
    } else {
        path[i][j+1] = 1;
    }
    dp[i][j] = grid[i][j] + max;
    return dp[i][j];
}

Comment: So since it is either right or down, just keep the index of the cell that gives you a higher value. You can store them in `path[][]` and just print them later.
Comment: Any sample case?
Comment: Added sample input and output to description
Comment: ok, could we travel in all 4 directions or is it just right and down? Also is it from (0,0) to (m-1,n-1) ?
Comment: sorry, doesn't work yet with the input provided.. correct me if my understanding is incorrect. will add the code that I wrote taking clue from your above comment
Answer: Well if you write your dynamic programming top down (as you did), restoring actual answer is actually very easy.
So you have a function getForwardMax which for given cell, return maximum amount we can collect moving right or down
You also know starting position, so all you need to do is build the answer step by step:

Let's say you're in some cell (r,c)
if there is only one possible move (you're at border) just do it
otherwise we can either move to (r+1,c) or (r,c+1)
we also know how much we will earn by moving to those cells and completing our path to the goal from getForwardMax function
So we just pick move that gives better result
Comment: Can you please have a look at the edited code..path[][] solution suggested still doesn't work. Please do help
Answer: Ok, bottom up DP is a correct solution as yours. I just realized you won't need separate path[][] to store the path and iterate over them.
You can use a simple while loop and choose the best among the 2 options of right and down.
If both happen to have same values, you need not worry as one grid could have multiple correct solutions. So, choosing either one in case of clash will still give you a correct solution.

We start from (0,0).
If value contained in dp[x][y+1] cell at the right + current grid[x][y] gives us the value same as dp[x][y], we move right, else we move down.

Snippet:
int x = 0,y = 0;

while(x != rows-1 || y != cols-1){
    System.out.println("( " + x + " , " + y + " )");
    if(x+1 < rows && grid[x][y] + dp[x+1][y] == dp[x][y]){
        x++;
    }else if(y + 1 < cols && grid[x][y] + dp[x][y+1] == dp[x][y]){
        y++;
    }
}

System.out.println("( " + x + " , " + y + " )");

Full Code: https://ideone.com/lRZ6E5


Raid 1 Rebuilding sync fail

Question: I manage Raid 1 with LSI Controller ( SAS9211-8i ).
Recently one of the Hard drives failed, I replaced it and booted the machine, Entered the LSI utility, and I noticed it's 'Rebuilding' and syncing the raid.
But, after about 30% of syncing, I received 'Failed' status over the 'Rebuilding' on the new hard drive.
I also tried to replace the new hard drive with a different new one, Same error.
Picture:
https://i.stack.imgur.com/vaSV2.jpg
I have no clue why is it Failing all the time.
and because the raid 1 is in status 'Degraded', My OS booting as 'read-only' mode and won't function properly.
Thanks a lot for the help!
Comment: As a quick troubleshooting step, try to plug the new drive in another slot than the original one.
Comment: Hi, I don't have another free slot, All the other slots are used for software raid by OMV system.
Comment: Have you thought about checking the single still working drive for the errors (chkdsk)?
Answer: It is likely the other disk has issues as well which is causing the rebuild to fail. I would suggest the first thing to do is to try to create a disk image from the existing disk. It's best to use a cdrom or usb stick to boot knoppix or something.
Then assuming the drive is located at /dev/sda and you have space available on a different (USB mounted) drive mounted at /mnt/data run something like:
dd bs=200M conv=noerror if=/dev/sda of=/mnt/data/sda.img

I use bs=200M to speed up the copy, it will copy 200MB chunks at once, I use conv=noerror to allow dd to continue if it finds a disk error. See the dd man page for more information.
If you want to use ssh to copy the image over while it is created see: https://unix.stackexchange.com/questions/132797/how-to-dd-a-remote-disk-using-ssh-on-local-machine-and-save-to-a-local-disk
If dd is not working and throws too many errors the disk is close to being unsalvagable and you want to try ddrescue or something: https://help.ubuntu.com/community/DataRecovery#Imaging_a_damaged_device.2C_filesystem_or_drive
To create a bootable disk out of that image find a disk of equal or bigger size and connect it through USB for example. Let's say the new disk is at /dev/sdd:
dd bs=200M conv=noerror if=/mnt/data/sda.img of=/dev/sdd

Once done, shut down the system and replace the existing raid disk with the new one and boot the system to see whether it boots. You may have to (re)-configure the raid controller, not sure. It may boot into read-only mode again, since the raid is still degraded.
Now insert another disk and allow the raid to rebuild. It may now finish successfully. It is possible the raid controller will see the disk as a JBOD and you will need to add it again into a raid before you can have a fully working raid1.
Comment: I would strongly recommend the use of ddrescue first. You only get a finite amount of opportunities to grab intact data from a failing drive, which this one probably is.
Comment: Not a bad idea at all :-)

Raid 1 Rebuilding sync fail


Enzyme/Jest React Testing - Shallow connected component with react-redux > 6

Question: We use Enzyme and Jest for testing.
Updated to the latest version of react-redux in our code base, and all of the connected component test cases started failing (Version 6).
Using
import { createMockStore } from 'redux-test-utils';

to create store
Test cases that worked with older version:
const wrapper = shallow(<SomeConnectedComponent />, {context: { store }});

This fails giving error
Invariant Violation: Could not find "store" in the context of "Connect(SomeConnectedComponent )".
Reading few posts, got a suggestion to mount and wrap with provider wrapper
const wrapper = mount(<Provider store={store}><SomeConnectedComponent /></Provider>);

Above code works, but I want it to work with swallow for unit testing.
Edit :
const wrapper = shallow(<Provider store={store}>
<SomeConnectedComponent />
</Provider>)

Above code returns empty shallowWraper object.
What is the best way to swallow connected component with react-redux version > 6
Answer: shallow does work on redux 7 but the implementation changed.
so instead of
const wrapper = shallow(<Provider store={store <SomeConnectedComponent/></Provider>)

you now do
const wrapper = shallow(<SomeConnectedComponent store={store}/>)

Wrapping in a provider is no longer necessary and prevents unnecessary dives. You are then able to traverse the shallow wrapper like so:
wrapper.children().dive().find(<ChildComponent>))

Answer: Shallow does not work with the latest version of react-redux.
From Version 6.x, it causes the mentioned problem.
The best solution I found was to use a older version of react-redux for testing,
and the newer one for actual code.
1) Add the older version as a dev dependency. Because a newer version of react-redux is there you will need to use a alias. This can be any version 5.x This will install "react-redux-test"
yarn add react-redux-test@npm:firstname.lastname@example.com -D

2) Under the _ mocks _ folder, create a new file react-redux.js and export the older version from within
export * from 'react-redux-test';

This mock will be used in every test case file by default, so the old testing code no longer breaks.
If however you want to test with the new react-redux library, you can use
jest.unmock('react-redux')

above the new test file.
After upgrading there were hundreds of tests failing, this approach works for me as i want to use the Hooks Api in new components as well.
This way you can use features the new library until enzyme / react-redux come up with a fix.
Comment: Got me on the right path. I had to do jest.mock('react-redux', () => {
  return require('react-redux-test');
}) in setupTests.js. For some reason it didn't work if it was under the __mocks__ folder.
Comment: seems like this version dont have the `useDispatch()` hook react-redux has in ver 8?


How to redirect based on views results?

Question: I have a view that shows a list of nodes and has a contextual filter.
If the number of nodes shown is only 1 then I want to redirect to that node page instead of showing the view.
Can I do that in views or do I have to code it?
Comment: **See also:** http://drupal.stackexchange.com/questions/74060
Answer: I don't think Views does anything like that by default, but a quick...
if (count($view->result)==1) {
  drupal_goto('node/' . $view->result[0]->nid);
}

...at the beginning of a display output template for the view in question should do it for you.
Or better yet, per @MPD...
function MOTOMODULE_views_pre_render(&$view) {

  if ($view->name=='JUSTONEPLEASE' && count($view->result)==1) {
    drupal_goto('node/' . $view->result[0]->nid);
  }

  // any other pre_render()ing here

}

Comment: Do it from a view hook.  Try [hook_views_pre_render](http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7)
Comment: great idea. I wonder if I could use a views_php field for that as well.
Comment: Dunno :) Check it out and let us know.  I tend to think if it works it to be a matter of personal preference;  I like to use templates so I can quickly look at them without going into UIs and such and thus I shy away from php fields that are in the DB.
Comment: D'oh!  I keep on forgetting about that bad boy.  Definitely the right call.

How to redirect based on views results?


Is maps.google.com accessible from a Silverlight app?

Question: maps.google.com's crossdomain.xml file is as follows:
<code><?xml version="1.0"?>
<!DOCTYPE cross-domain-policy
  SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">

<cross-domain-policy>
  <site-control
     permitted-cross-domain-policies="by-content-type" />
</cross-domain-policy>
</code>
Can you confirm that this effectively means "Access Denied" for Silverlight (and Flash), since there are no elements 'allow'ing any kind of access?
Answer: A Silverlight 4 Out-of-Browser application can ignore the crossdomain.xml policy file.
Answer: Does it have to be Google Maps?  Bing Maps has a great Silverlight Control.  There is a good article about it on CodeProject as well as a nice Interactive SDK.
If it has to be Google Maps, check out the flagged answer in this thread which references another CodeProject article that may be helpful.
Comment: Yep, gotta be google maps - I am using the geocoding API that's on that server, rather than working with tiles.
Answer: Well, it seems that Silverlight will not grant access to the domain given the content of this crossdomain.xml. I would still like an explanation of what the crossdomain.xml means, mind you.


Imagepicker doesn't appear as block

Question: I would like the Image Picker to be available on a node (page) as a block so that users can upload images without clicking on 'edit' where they can edit the actual page itself.
I have definitely enabled the setting in the configuration:

Do I need to do it via the Views module (which I do have installed also)?
Answer: U want a block for image picker, I have checked it and found that it creates iframe for the same. so what we can do, is create a block either programmatically or manually and alter its content, by using hook_block_view_alter, and load image picker in it, and hide rest of element in drupal 7.

Imagepicker doesn't appear as block


How is $x^\frac{9}{4} \cdot x^\frac{1}{2} = x^\frac{11}{4}$

Question: How is $x^\frac{9}{4}  \cdot x^\frac{1}{2} = x^\frac{11}{4}$?
I don't really understand it.
Comment: $$ x^n \cdot x^m = x^{n + m } $$ In your case, $1/2 = 2/4$ and so $9/4 + 2/4 = 11/4 $.
Comment: @Anonaki ok thank you I did not think you could convert the denominators like that
Answer: $$x^{9/4}=(x^{1/4})^9.$$
$$x^{1/2}=(x^{1/4})^2.$$  Letting $y=x^{1/4}$, we get:
$$x^{9/4}\cdot x^{1/2} = y^9\cdot y^2=y^{11} = (x^{1/4})^{11}=x^{11/4}$$
Comment: Didn't downvote, but to me this seems overly complex -- just reminding the exponent rule and that 9/4+1/2 = 11/4 seems sufficient. This answer doesn't make totally clear (on first glance at least) that you are just adding the exponents
Comment: I'm showing why $x^a\cdot x^b = x^{a+b}$ when $a,b$ rational. That does need to be shown. Anyway, the other answer gave your approach, and it got $5$ downvotes, too. (That answerer deleted his answer.) @ZachEffman
Comment: @ZachEffman That doesn't mean this is a wrong answer. I have never seen this behavior, and I'm not buying that explanation. Somebody is engaging in some sort of bad behavior here.
Comment: The OP accepted that simple explanation in the comments. I also didn't downvote this answer, and I agree that the negative response seems unreasonable.
Answer: Use the exponent rule $x^a\cdot x^b = x^{a + b}$ with $a = 9/4$ and $b = 1/2$. Since $b = 2/4$, $a + b = 9/4 + 2/4 = 11/4$.
Comment: @Anonaki Then you don't understand the site, if you think answering in comments is enough. The point is to create an archive of answers, and comments are not the place for finding answers. As for my complicated answer, some people don't know why $x^{a}\cdot x^{b}=x^{a+b}$ when $a,b$ rational, but it is "obvious" when $a,b$ integers. Since kobe's answer already existed, I gave a different answer which only used the integer version.
Comment: @Anonaki, the concensus on meta is that you shouldn't leave questions open with answers in the comments: the comment should be made an answer and accepted so the question is closed: http://meta.math.stackexchange.com/questions/1148/what-should-one-do-when-ones-question-has-been-answered-in-the-comments/1149#1149 http://meta.math.stackexchange.com/questions/1559/dealing-with-answers-in-comments
Comment: I really don't know why people are downvoting this like crazy, nor why the question has 5 upvotes. I think someone is experimenting with something illicit here.
Comment: no need to write an answer for this question. you can just answer it in the comments.
Comment: I did downvote both answers because they could have been just answered in comment box.(Like my answer)
Comment: @ThomasAndrews I just find it funny that the question was receiving so many upvotes, while at the same time our answers were receiving so many downvotes.  I'm upvoting your answer. :)
Comment: @ZachEffman I'm not sure, but it might've been removed because I flagged for being non-constructive.
Comment: I'm curious to see what happens...
Comment: @kobe That's why I wondered if something odd/illicit was happening. Not sure what. But I think it is more likely that, for some reason, this question made the StackExchange front page, and we got lots of newbs here.
Comment: I think given the vitriol coming from Anonaki, that second explanation is much more likely
Comment: @ZachEffman Not sure I'd call Anonaki's posts"vitriol." He's wrong about answers in comments, of course, but he's also not a newb. At least, not in the sense I meant - somebody who'd literally never been to this site.
Comment: The comment about your answer being terrible and wishing the site allowed multiple downvotes has since been removed, I see
Comment: It certainly wasn't


Function to return nothing for a defined range of input values

Question: If I have the function f(x) = 2x + 1, is there something I can do to the function that will make it undefined for certain input values, for example input values where x ≥ 1. This would give the graph an endpoint. It is easy enough to just write {2x + 1 | x ≥ 2} but I am looking for a one line equation. The type of answer I am looking for, if you were to graph it, would look like a line that goes from the point (1,3) to infinity to the right and nothing but an endpoint on the left. First, is this even possible and second, how would we achieve this?
Thanks in advance.
Edit: I am looking for an approach that would work in a graphing calculator or a program like Wolfram|Alpha or Symbolab; something generalized.
Comment: Do you need a formula for use in a graphical calculator or some computer program? Or do you want to know the mathematical notation?
Comment: A formula for use in a computer program that is a graphical calculator.
Comment: What program? An approach that works in multiple programs is possible, but maybe there's an easier way for that specific program.
Comment: I am looking for a generalized approach, so something that I can use for multiple programs.
Answer: For the example you've described:
$\frac{(2x+1)\sqrt{x-1}}{\sqrt{x-1}}$ is probably the simplest solution.
You can generalize it to limit the domains of other functions.
Comment: This works on paper for me, but for example when I put it into Wolfram|Alpha or Symbolab it cancels the terms out so it doesn't work. Is there something that might work in a program like W|A or Symbolab?
Comment: Also, this doesn't work if the program supports complex numbers, good answer otherwise.
Comment: I graphed it on Wolfram|Alpha and I think it's something to do with the program; if you scroll down it does correctly identify the domain but simply graphs it for all real numbers.
Comment: I graphed it on Symbolab and it seems to work.
Comment: Ok thanks. I think this will work well for me. I agree that it works on symbolab but I didn't check the domain on Wolfram|Alpha; I probably should've.
Answer: This should work on many systems:
$$
(2x+1) \cdot \frac{1-x}{\max(1-x,0)}
$$
Whenever $x \ge 1$, there is division by zero.
Unfortunately Wolfram Alpha does not give a plot when entering this formula.
Answer: Something like:
$g(x)  = \frac{f(x)(x-a)(x-b)(x-c)}{(x-a)(x-b)(x-c)} = \begin {cases} f(x)&x\notin\{a,b,c\}\\\text{undef.}&x \in\{a,b,c\}\end{cases}
$


Advanced search - combine "expressions"?

Question: Is it doesn't work - or i'm too stupid for ...
Put this into search user:me is:answer score:0 and you'll get all your zero score answers.
It is possible to use multiple IDs and apply simple filters user:A user:B is:question ..., but how to search for my answers for a specific user?
Some like user:me is:answer <author>:<userid> or user:me is:answer user:ID is:question ...
Answer: I may be wrong on this, but I think the search functions work with AND without combining criteria. I mean something like user:me is:answer user:ID is:question will translate into something like user = me and is_answer = true and user = ID and is_question = true. Which will always return nothing because user = me and user = id exclude each other.
But I think you can achieve what you want here: https://data.stackexchange.com/magento/queries.
First look if something similar to what you need already exists. If not, try to build one query.


How to delay sending emails using Rules to avoid being considered as a spammer?

Question: I created a rule for users, who subscribed on another user to get messages of this user new content:
<code>Events
  EVENT
    After saving new content
Conditions
  ELEMENTS
    None
Actions
  ELEMENTS
    Fetch users who have flagged a user
      Parameter: Flag: subscribe_this_user, user: [node:author]
      Provides variables: subscribers (user)

    Loop
      Parameter: List: [user]
      List item: Current list item (liker)

     Send mail
       Parameter: To: [liker:mail], Subject: New event on [site:name]!, Message: New content [node:title] by..., From: [site:name
</code>
How can I send these emails with delay? I heard that sending a lot of emails is spamming. I heard about Rules Scheduler, but don't know how to integrate that in my rule.
Comment: check this http://stackoverflow.com/questions/18682859/drupal-7-rules-delay-sending-or-group-emails-to-users
Comment: https://drupal.org/project/pet
Answer: Below is a summary of how you can get this to work:

Introduce an additional flag to allow "flagging" these (new) nodes by all users "who subscribed on another user to get messages" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Adapt the rule you already have, like so:

Remove the Rules Action "send eMail".
Flag the newly saved content, using the new flag (from step 1) for each of the users you already have in your existing list in your existing Rules Action.

Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rules Action "send eMail" that you already had, but removed in step 2).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested".
Answer: I think that deferring emails is the wrong solution for you here. A question like this often indicates the hosting may not be suitable for the site profile.
Unless it's part of your site model, a workaround of delaying delivery will just show user engagement. Over the course of a day you'll end up sending the same number of emails, so this won't reduce your chances of being flagged as a spammer.
What will work better is to ensure you use a reliable mail delivery mechanism, and avoid spam behavior (like sending excessive or unwanted notifications).
If your existing hosting limits outbound email, and you need to send more emails than the limits they offer, find a provider who does suit your needs (and will scale for future success). There are plenty of mail providers on the market for you to choose from, and options for reliable self hosted systems too.
Comment: I'm aware this doesn't answer the question at hand, I'm trying to assist OP by addressing the underlying issue rather than the symptom.


What is the sample size and variance for the mean that is a simple, unweighted average of two independent groups' means?

Question: We have two groups: N1 = 10 and N2 = 100
Their means on some measurement are: Mean1 = 4 and Mean2 = 5
Their variances are Var1 = 3 and Var2 = 2.5.
Let's further assume we have no access to the individual level data.
Some guy wants to combine the two groups' means into one. However, instead of taking a weighted mean of two groups, as would have done anyone reasonable, he calculates a simple unweighted mean:
UnweighedMean = (4 + 5)/2 = 4.5
(Please don't tell me it's very wrong. I know it is.)
So, if we stick to this incorrect method, what would you say is the sample size for that total mean of 4.5? Is it 20?
And what is the variance of that mean?
Thank you for your thoughts!
Answer: There is no such thing as a "sample size" for a statistic, such as, in your case, the unweighted mean. Rather you can discuss the standard error. If the distribution in the two populations is normal, then this mean would have a T-distribution, but calculating the effective degrees of freedom (or an approximation thereof) analytically is probably too challenging to get a sound answer. Even for Fisher Behren's problem, the Satterthwaite degrees of freedom for the correctly calculated "pooled" (null) mean is just an approximation). A simply variance rule for independent samples could lead us to:
$$\bar{X}_{pooled} = \frac{1}{2}(\bar{X}_1 + \bar{X}_2)$$ has
$$\text{var}(\bar{X}_{pooled}) \approx \frac{1}{4}\left(\hat{\sigma^2_1} + \hat{\sigma}^2_2 \right)$$
Comment: Thank you! I realize, the bootstrap would probably be the way to go. But I was interested in people's opinion about what to do when there is no access to the raw data.


Professional way to send images from server to client

Question: We are planning our final school project and I need to find out a way to send images from server to client (Flutter App). Due to a lack of experience in a professional environment, I'm struggling to do so.
I've always saved the image name or image path in the database in my smaller projects, got the data via an API, and then just called for the image, which was located on a web server, via HTTP or HTTPS. Pretty easy in Flutter with Image.Network.
However, that doesn't sound like the best option
We are planning on using:

Ubuntu or Microsoft Server (still to decide)
MariaDB alone or with MongoDB, or even MS SQL Server(still to decide)
ASP.NET Core for the API
Flutter App and Web-Interface for client-side

Any suggestions are appreciated!
Answer: You are doing correctly in your smaller projects. This is a best way to do. When frontend(mobile app or web app) uploads image using an API, backend(in your case ASP.NET Core) simply stores that in server(in your case case Ubuntu or Microsoft Server). But I would say stores all media files like audio, video, images, documents, etc on AWS S3 bucket because it would be difficult to you increase server disk space if its low where AWS-S3 can store any amount of data.
And after saving that media files on S3 or server store its file url in database. Send this url via API to client when it requests it and from client side you just need to use that url to show or download.


In Drupal 7 Views what is the php code to validate a field against a contextual filter argument?

Question: Currently I am using the path url to pass in arguments:
path: /%/%/%
On the 3rd argument I am loading a Taxonomy term. I also have a field loaded called: field: device type
What do I have to put in my contextual filter validation PHP code? I did a dsm($view), but my device type shows recursion. I'm not sure how to reference the field properly to create a conditional to compare it to the contextual argument.
Comment: you're asking about how to get or use the third argument from the URL or all of them?
Answer: Below is a code sample of my contextual filter validation code for drupal 7 views 3 validation.
My view contains a page display with the following path set: blog/%/%/%
Here is a sample path argument of what I'm trying to accomplish:
Path URL: blog/7/node-title/taxonomy-name
<code>if ( is_numeric(arg(1)) && is_string(arg(3)) ) {
//check to make sure arg 1 is text and arg 2 is a string

  $node = node_load(arg(1));
//load the node

  $terms = taxonomy_get_term_by_name(arg(3));
//get the terms array and TID from arg 3.

  if (!empty($terms)) {
    $first_term = array_shift($terms);
    foreach($node->field_repair_states_region['und'] as $x => $y) {
      if( $y['tid'] == $first_term->tid ) { return TRUE; }
//make sure the TID matches the TID to the node.

    }
  }
}
</code>
Screenshot of Validation Page: http://prntscr.com/1dcl4v
Screenshot of View: http://prntscr.com/1dclly


Lecture notes of complex analysis

Question: I just want to go through the topics of complex analysis, in order to get an overview of the subject. Does there exists any good lecture notes for complex analysis which covers all the topics quickly? Like Milne's notes in Algebraic number theory. I am currently referring Tao's lecture notes on complex analysis, but at many points he has referred to Wikepedia so everything is not covered there...
Answer: Try Donald Sarason's Complex Function Theory.!
In preface:
These are the notes for a one-semester introductory course in the theory of
functions of a complex variable. The aim of the notes is to help students
of mathematics and related sciences acquire a basic understanding of the
subject, as a preparation for pursuing it at a higher level or for employing
it in other areas. The approach is standard and somewhat old-fashioned.
As these notes are a rather bare-bones introduction to a vast subject, the
student or instructor who uses them may well wish to supplement them with
other references

Lecture notes of complex analysis


Seed Rails SQLite Database from a JSON file

Question: I'm new to Rails (using 5.0.2). I want to seed my empty SQLite db from a JSON file.
I scaffolded my Product resource, in seed.rb added:
records = JSON.parse(File.read('/home/projects/test1/public/products.json'))
records.each do |record|
  ModelName.create!(record)
end

Then launched rake db:seed.
I got an error:
rake aborted!
JSON::ParserError: 409: unexpected token at '{
My JSON consists of products with various properties:
    [
  {
    "model": "Brand",
    "brand": "Brand",
    "price": 19.99,
    "currency": "GBP",
    "link1": "https://www.amazon.co.uk/Call-Duty-Ghosts-Hardened-Xbox/dp/B00ECQJ0BS/ref=pd_sim_107_4?_encoding=UTF8&psc=1&refRID=9GE6A8BW61S1FG4H3ZRJ",
    "link2": "",
    "size1": "{min: "5",max: "90"}",
    "net_weight": "263 kg",
    "size2": "{w: "19.4",h: "11.7",z: "12.7"}",
    "d1": "",
    "color": "['Black','White']",
    "materials": "plastic+concrete, glass ceiling",
    "models": "['model 1',  'model 2',  'model 3', 'model 100']",
    "props": "['prop1',  'Prop1',  'Prop1']",
    "": "",
    "size3": "{w: "100",h: "200",z: "500"}"
  },
  ]

How can I fix this JSON file and correctly seed my db with the products data from it?
Is it the best way to import manually created JSON files into Rails, or it's better to try some other approach?
Comment: That is invalid JSON http://jsonlint.com/
Answer: The problem is with the size1, size2, and size3 properties. For each of those keys, the value contains a double-quote. If you convert those to single quotes or escape them by putting a \ before them, your JSON should parse correctly.


Printing math with user input: Can't convert float to str implicitly

Question: Here's the code :
import time
time.sleep(0.7)

while True:
    print("Enter the word 'quit' to quit the calculator :(")
    print("Enter the word 'freenet' to enroll the SSHcrack")
    user_input = input(": ")

    if user_input == "quit":
        break
elif user_input == "freenet":
    num1 = float(input("Enter a Port to Crack:"))
    num2 = input("Enter a Network Name")
    num3 = float(input("Enter an IP-Address,(without symbols!):"))
    result = num3 / num1
    result2 = result / 13
    print("Injectable SSH "+ result2 +"for the Network "+num2)

Of course this is just a calculator (I only added the problem code block) and I wanted to test around with the print statement, but it gives me this TypeError:
Traceback (most recent call last):
  File "<mypath>", line 51, in <module>
    print("Injectable SSH "+ result2 +"for the Network "+num2)
TypeError: Can't convert 'float' object to str implicitly

Answer: As the error message states: You have to convert 'float' to str explicitly.
This fixes your problem:
print("Injectable SSH "+ str(result2) + " for the Network " + str(num2))

Even better, use format strings:
print("Injectable SSH {} for the Network {}".format(result2, num2))

They help you keeping your message formatting clean, structured and transparent.
Comment: This solved my problem thanks
Answer: You have to explicitly convert result2 and num2 to strings.
print("Injectable SSH "+ str(result2) +"for the Network "+ str(num2))

Answer: The problem is that you're attempting to add a float (decimal) to a string in the line
print("Injectable SSH "+ result2 +"for the Network "+num2)

"Interjectable SSH " is a string and result2 is a float, and python has no way of knowing how to add a decimal to a string.  Some languages will automatically convert the float into a string, but python will not, hence the error "Can't convert 'float' object to str implicitly".
What you need to do is explicitly convert both result2 and num2 into strings using the built in str() method.  With the necessary changes, the line wil look something like this:
print("Injectable SSH "+ str(result2) +"for the Network "+str(num2))

There are a couple other ways that you can do this in python.  If you want to look into that, look up a tutorial in "python string formatting".
Comment: Wow, this is more in-depth, thanks!
Answer: In python, '+' is used to concatenate string objects.
Ofcourse in python 2.7, you would have done concatenation/joining of any type of object for a print using a ','.
So, the solution may be like:
   print("Injectable SSH "+ str(result2) +"for the Network "+num2)


Foreach get_field_object for ACF

Question: I have a custom field on wordpress that defines a select option
one : First
two : Second
three : Third
four : Fourth

I am trying to call these options on the frontend in a select form i.e.
<select id="filters">
  <option value="*">show all</option>
  <option value="one">First</option>
  <option value="two">Two</option>
  <option value="three">Third</option>
  <option value="four"Fourth</option>
</select>

This is what i got so far and it doesnt seem to be working:
<?php
$field_name = "team_category";
$field = get_field_object($field_name);

foreach($field){
  echo $field['label'] . ': ' . $field['value'];
}
?>

Answer: The ACF documentation says get_field_object() can have up to three parameters, while the second one is the Post ID. If no Post ID is used, it will use the current one, which you also retrieve with get_the_ID().
But probably, you want these options on another page (for example, a search page, you develop). So lets say, you create a page template. What you want to search are posts with the post_type 'teams'. So, the post_type 'page' has no custom fields called "team_category" and with the current post ID no object will be returned.
What you need is a Post ID of a post which actually contains the searched field. And this should work dynamically.
Lets try
<?php
global $wpdb;
$field_name = "team_category";
$sql = $wpdb->prepare( "select post_id from " . $wpdb->prefix . "postmeta where meta_key = %s limit 0,1 ", $field_name);
$post = $wpdb->get_results( $sql );

$field = get_field_object( $field_name, $post[0]->post_id );

if( $field )
{
    echo '<select name="' . $field['key'] . '">';
        foreach( $field['choices'] as $k => $v )
        {
            echo '<option value="' . $k . '">' . $v . '</option>';
        }
    echo '</select>';
}
?>

Answer: I think this might be something closer to what you're looking for.

    foreach($field as $field_item){
    echo '<option value="'.$field_item['value'].'">' . $field_item['label'] . ': '</option>;
    }
?>

Comment: How did it not work? Maybe you could supply some more information. Generally, when working with ACF's, I don't use the `get_field_object()` function. I usually just use `get_field()` or in the case of a repeater field `get_sub_field()`. The ACF site has some great resources. http://www.advancedcustomfields.com/resources/getting-started/displaying-custom-field-values-in-your-theme/
Comment: This didnt work, i think it might be the query itself which is not working.
Answer: I know this is an old question, but wanted to throw out my answer for others who may find this. There are a couple problems with your code:

According to the ACF docs for get_field_object(), they say that "In some circumstances it may be necessary to load a field by its key, such as when a value has not yet been saved." I have found that the field name does not work when trying to retrieve a field object outside of a loop (which is what you're doing here with trying to show all options within a field, not just those related to a specific post).
Another challenge is that the field key can differ across environments (local, staging, production, etc) unless you sync your databases. So here's a function that can help you find the field key by field name anytime you need to use it in a function such as get_field_object():

if (! function_exists('acf_field_from_name')) {

   function acf_field_from_name($field, $group)
   {
       global $wpdb;

       return $wpdb->get_var($wpdb->prepare("
           SELECT post.post_name as field_name
           FROM $wpdb->posts AS post
           LEFT JOIN $wpdb->posts AS parent
               ON post.post_parent = parent.id
           WHERE post.post_excerpt = %s
               AND post.post_type = 'acf-field'
               AND parent.post_excerpt = %s
               AND parent.post_type = 'acf-field-group'
       ", $field, $group));
   }
}

Will return the field key from name and group, or null if none exists.
Usage:
acf_field_from_name('title', 'movie-fields'); // returns field_3333333333333

acf_field_from_name('title', 'book-fields'); // returns field_4444444444444

acf_field_from_name('plumbus', 'movie'); // returns null

See full answer by @Chris about why the group name is important in How to get Advanced Custom Fields field key from WordPress database?
Then your code would be:
$field_name = "team_category";
$group_name = "team_fields";
$field_key = acf_field_from_name($field_name, $group_name);
$team_category_field = get_field_object($field_key);

The second problem is the options for select, checkbox, and radio fields are stored as an array inside an item within the field object array under the key choices. So to get those you need to use:

  $team_category_choices = $team_category_field['choices'];

The third problem is your foreach() function is incorrect. You need to pass the array and define how each of the array item keys (choice value saved to DB) and values (choice label shown in UI) in it will be referenced within the inner function, like so:

foreach($team_category_choices as $choice_value => $choice_label) {
  echo '<option value="' . $choice_value . '">' . $choice_label . '</option>';
}

Foreach get_field_object for ACF


Late entry in Survival Analysis

Question: 1
I would like to ask how to deal with new entries of individuals in Survival Analysis. I have a study about the time to event of several individuals who suffer from a disease. The study starts on a specified date (let's assume 1/1/2019). The individuals on this date are 50. The study lasts 6 months. In these 6 months, more individuals must be included but they were not present on the starting date. In this study I use the number of days to the event of each participant (calculated from the day he/she enters the study)
I have not any left censoring because, for the new individuals, the time they enter the study, is the time the symptoms appeared.
Should I deal with this late entry in the study differently or proceed with the common type?
I repeat the fact that, the date they enter, coincides with the manifestation of the disease. We can imagine the individuals as patients if that makes things easier.
Comment: Please say more about the 50 individuals at the start date of the study. Was that also the date each of them first had disease symptoms? Or did they develop symptoms at some time before that start date? If so, do you know their individual dates of developing symptoms? Please provide that information by editing the question, as comments are easy to overlook and can get deleted.
Comment: In the last sentence I clearly state that the date they enter the study is the date the symptoms developed.
Answer: If time = 0 for the survival analysis is the time at which symptoms developed for each individual, the question is less with the late-entry cases and more with the initial 50 cases.
Clinical studies, for example, typically accrue participants over time. In cancer survival studies, the study entry date for each participant might be set as the date of definitive pathologic diagnosis, providing the participant-specific time = 0 reference for survival analysis. There is no problem in principle with including late entrants, it's just that there is shorter follow up for the later entrants. One might include the date of study entry as a covariate to account for any influence of the actual calendar date of diagnosis.
The major question has to do with the initial 50 participants as of the administrative start date of the study. If you have actual dates of symptom development and corresponding covariate values for each of those 50 (which presumably would be well before the administrative start date) and use those dates as each participant's time = 0 reference, then there is no problem. If you don't know their actual dates of symptom development, or if your analysis involves unavailable covariate values in place at their dates of symptom development, then you need to take that into account in your analysis.
Comment: Thanks. Your answer clarifies some things that were fuzzy in my mind.

Late entry in Survival Analysis


Métodos alternativos para armazenamento em Servidor de Aplicação

Question: Boa Tarde Pessoal,  gostaria de algumas sugestões de formas alternativas de acesso a dados em um servidor de aplicação, mais especificamente um JBoss 6. Ocorreu que eu possuo uma aplicação hospedada em um JBoss 6 e preciso de tempos em tempos recuperar dados armazenados em BD ou arquivo (como a quantia de dados não é muito grande estou utilizando atualmente a solução de leitura de arquivo). Porém com certeza a leitura frequente ao arquivo e/ou consulta ao BD, além de consumir memória, também afeta o desempenho do sistema. Saberiam de alguma forma alternativa de leitura aos dados ? Por ex, alguma forma de manter os dados lidos de BD/arquivo em memória (Cache) ? Somente esclarecendo, a leitura ao arquivo/BD é feita de tempos em tempos, por ex de 2 em 2 horas,e é necessário que um projeto web tenha a informação disponível a todo momento. Alguma sugestão ?
 Só para constar,  o projeto web em questão é este aqui:  http://allinyourhandsweb.com  Resultado de um projeto meu de cerca de 8 meses de desenvolvimento, fiquem a vontade para qualquer sugestão referente ao mesmo.
Obrigado.
Answer: Cache em memória é bastante comum. Você pode usar ferramentas como:

Memcached: usado pelo Youtube e Wikipedia. Funciona com diversas plataformas e não só Java. Independe de um servidor de aplicação.
Apache Java Cache Systems: implementação em Java de um sistema de cache em memória.
EhCache: outra implementação em Java, mantida por uma empresa que oferece outros produtos relacionados, caso você necessite de mais capacidade.

Em geral, todos esses sistemas de cache funcionam em um ou mais servidores de forma distribuída. São processos (programas) a parte que a aplicação acessa via comunicação entre processos ou algum outro protocolo configurável.
As implementações em Java podem também ser colocadas embutidas na aplicação, porém isso faz com que se perca a vantagem da distribuição e da durabilidade dos dados no caso de reinicialização da aplicação.
Outra alternativa é usar um banco de dados em memória, como o MariaDB, um fork do MySQL.
O MySQL possui diferentes mecanismos que você pode usar para gerenciar as tabelas, por exemplo, o InnoDB e o MyISAM. Cada mecanismo possui características, capacidades e restrições diferentes.
O MariaDB estende essas funcionalidades e possui outras engines de tabelas, como a MEMORY storage engine. Com isso, você pode criar um banco de dados em memória para fazer cache dos dados e ainda aproveitar as mesmas queries usadas nas tabelas "normais", persistidas em disco.
Comment: Muito Obrigado pela resposta, utluiz.  Tentei iniciar a implementação utilizando o "Apache Java Cache Systems", no entanto ao subir o jboss percebo um erro relacionado ao TransactionManager. Você teria uma idéia do que poderia ser ?
Comment: @rbertani Assim é muito genérico. É mais fácil o erro de transações estar ligado a configuração do banco de dados. Sugiro que poste outra pergunta aqui no SO com detalhes de configuração e com o trecho de código (método ou classe) onde o erro ocorre, mais as pilhas de erro. Abraço.
Comment: Cara, vou tentar implementar usando "Memcached", me pareceu uma solução melhor. De qualquer forma, se eu descobrir o erro no JCS posto aqui.  Obrigado pelo apoio.


how to append string in a HtmlTextWriter asp.net c# webform

Question: Let say i have a function like below, which returns option tag as a string.
 public static string writeDropDownOptionHTML(string tablename, string id_col, string value_col)
        {
            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
            DataTable dt1 = BAL.setDropDown(tablename, id_col, value_col);
            if (dt1.Rows.Count > 0)
            {
                foreach (DataRow row in dt1.Rows)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Value, row[0].ToString());
                    writer.RenderBeginTag(HtmlTextWriterTag.Option);

                    writer.Write(row[1].ToString());
                    writer.RenderEndTag();
                }
            }

            return stringwriter.ToString();
        }

now i have another function like below
public static string writeWalkReverseTableData(DataTable dt1)
        {
            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringwriter);

            if (dt1.Rows.Count > 0)
            {
                foreach (DataRow row in dt1.Rows)
                {

                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.RenderBeginTag(HtmlTextWriterTag.Select);
                    // now i want to call  writeDropDownOptionHTML which will return option html code
                    // writer += writeDropDownOptionHTML("xyz","abc","def");
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                }
            }
            return stringwriter.ToString();
        }

how to append string in a HtmlTextWriter?
Answer: I'm not too familiar using the HtmlTextWriter but according to msdn you should be able to do
writer.Write(writeDropDownOptionHTML("xyz","abc","def"));

Answer: I'd pass writer from writeWalkReverseTableData to writeDropDownOptionHTML as a parameter, like this:
    public static void writeDropDownOptionHTML(HtmlTextWriter writer, string tablename, string id_col, string value_col)
            {
                DataTable dt1 = BAL.setDropDown(tablename, id_col, value_col);
                if (dt1.Rows.Count > 0)
                {
                    foreach (DataRow row in dt1.Rows)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Value, row[0].ToString());
                        writer.RenderBeginTag(HtmlTextWriterTag.Option);

                        writer.Write(row[1].ToString());
                        writer.RenderEndTag();
                    }
                }
            }

public static string writeWalkReverseTableData(DataTable dt1)
        {
            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringwriter);

            if (dt1.Rows.Count > 0)
            {
                foreach (DataRow row in dt1.Rows)
                {

                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.RenderBeginTag(HtmlTextWriterTag.Select);
                    writeDropDownOptionHTML(writer, "xyz","abc","def");
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                }
            }
            return stringwriter.ToString();
        }

Comment: This is how I would go about it as well, rather than injecting html from another writer.  But for this to work you would have to pass it the reference of the writer...  public static void writeDropDownOptionHTML(ref HtmlTextWriter writer, string tablename, string id_col, string value_col) and then call it via writeDropDownOptionHTML(ref writer, "xyz","abc","def");


Construction of two dimensional numpy array from unequally shaped one dimensional arrays | Numpy

Question: In python have three one dimensional arrays of different shapes (like the ones given below)
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])

I am assuming that the array a0 corresponds to an index i=0, a1 corresponds to index i=1 and a2 corresponds to i=2. With these assumptions I want to construct a new two dimensional array where the rows would correspond to indices of the arrays (i=0,1,2) and the columns would be entries of the arrays a0, a1, a2.
In the example that I have given here, I will like the two dimensional array to look like
result = np.array([ [0,5], [0,6], [0,7], [0,8], [0,9], [1,1], [1,2],\
           [1,3], [1,4], [2,11], [2,12]  ])

I will very appreciate to have an answer as to how I can achieve this. In the actual problem that I am working with, I am dealing more than three one dimensional arrays. So, it will be very nice if the answer gives consideration to this.
Answer: One way to do this would be a simple list comprehension:
result = np.array([[i, arr_v] for i, arr in enumerate([a0, a1, a2])
                             for arr_v in arr])

>>> result
array([[ 0,  5],
       [ 0,  6],
       [ 0,  7],
       [ 0,  8],
       [ 0,  9],
       [ 1,  1],
       [ 1,  2],
       [ 1,  3],
       [ 1,  4],
       [ 2, 11],
       [ 2, 12]])

Adressing your concern about scaling this to more arrays, you can easily add as many arrays as you wish by simply creating a list of your array names, and using that list as the argument to enumerate:
.... for i, arr in enumerate(my_list_of_arrays) ...

Comment: Many thanks. This answer is very helpful. Since I have thousands of one dimensional arrays, I am trying to see if I can avoid having to manually create my_list_of_arrays. But, still, many thanks for the answer. :)
Answer: You can use numpy stack functions to speed up:
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T

Comment: @liliscent: Thanks for the answer. It is very helpful. I am dealing with thousands of arrays. So, I am also trying to see if I can find ways to avoid manually listing all arrays in `aa`. But still, thank you very much. :)
Answer: Here's an almost vectorized approach -
L = [a0,a1,a2] # list of all arrays
lens = [len(i) for i in L] # only looping part*
out = np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L)))

*The looping part is simply to get the lengths of the arrays, which should have negligible impact on the total runtime.
Sample run -
In [19]: L = [a0,a1,a2] # list of all arrays

In [20]: lens = [len(i) for i in L]

In [21]: np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L)))
Out[21]:
array([[[ 0,  5],
        [ 0,  6],
        [ 0,  7],
        [ 0,  8],
        [ 0,  9],
        [ 1,  1],
        [ 1,  2],
        [ 1,  3],
        [ 1,  4],
        [ 2, 11],
        [ 2, 12]]])

Another way could be to avoid np.repeat and use some array-initialization + cumsum method, which would be better for large number of arrays, as shown below -
col1 = np.concatenate(L)
col0 = np.zeros(len(col1), dtype=col1.dtype)
col0[np.cumsum(lens[:-1])] = 1
out = np.dstack((col0.cumsum(), col1))

Or use np.maximum.accumulate to replace the second cumsum -
col0[np.cumsum(lens[:-1])] = np.arange(1,len(L))
out = np.dstack((np.maximum.accumulate(col0), col1))

Comment: Many thanks for the post. It is super fast and very useful. =)


Does Hibernate Envers creates revision to audit tables if you update without changing any field values?

Question: I am currently testing hibernate envers and I am confused with its behavior. Sometimes when we do updates without doing any changes, it does not record an audit. But currently, it does. Just like to make sure.
Answer: This can occur if Hibernate does not have access to the old state of the entity to compare to the new state. This typically occurs with when persisting detached entities. When there is no old state to compare, Hibernate assumes that the audited property has changed and logs a revision.
You can get around this issue by re-attaching detached entities using the merge() method before persisting the entity.
Comment: Awesome explanation!
Answer: From my experience, it only creates an entry in the revision table if you have made changes to the entity.


Trigonometric inequality $\frac{\cos x -\tan^2(x/2)}{e^{1/(1+\cos x)}}>0$

Question: How can I solve the following inequality?

$$\frac{\cos x -\tan^2(x/2)}{e^{1/(1+\cos x)}}>0$$
Comment: See [Weierstrass substitution](http://en.wikipedia.org/wiki/Tangent_half-angle_substitution#The_substitution). The denominator is never negative.
Answer: I'll post what I have so far so that it may give you an idea of what to do. It's not complete and I'll try and finish it of when I have more time.
$e^{1/(1+\cos x)}$ will always be positive, so we only have to worry about the numerator.
Using the Weierstrass substitution, as @Lucian suggested, $t=\tan{\frac{x}{2}}$ and keeping in mind that $\displaystyle \cos x = \frac{1-t^2}{1+t^2}$ we get:
$\displaystyle {\cos x -\tan^2(x/2)} = {\frac{1-t^2}{1+t^2} - t^2}$
$\displaystyle \frac{1-t^2}{1+t^2} - t^2 = \frac{1-t^2-t^2(1+t^2)}{1+t^2}$
So the fraction is going to be negative only when $1-t^2-t^2(1+t^2)$ is negative.
$1-t^2-t^2(1+t^2) \lt 0$, I´ll do another substitution to ease the calculations:
$u=t^2, 1-u-u(1+u)= -u^2-2u+1$
The roots are $u=-1 \pm \sqrt2 $ and because $-u^2-2u+1$ is concave downwards so it´s positive in $[-1 - \sqrt2,-1 + \sqrt2]$
Substituting back, and I'm assuming you are working in $\mathbb R, t=\pm \sqrt{-1 + \sqrt2}$
So $\displaystyle \frac{1-t^2}{1+t^2} - t^2 \gt 0, \  \ \forall t \in \left[-\sqrt{-1 + \sqrt2},\sqrt{-1 + \sqrt2} \right] $
Answer: Note that
$$\frac{\cos x -\tan^2(x/2)}{e^{1/(1+\cos x)}} =\frac{ (-1 + 2 \cos x+ \cos^2 x)}{(1 + \cos x)} \cdot e^{-1/(1+\cos x)}$$
$\frac{e^{-1/(1+\cos x)}}{(1 + \cos x)} $ should be taken as a whole, because it is defined everywhere. It is $>0$ everywhere except at $(2k+1)\pi$ where it's zero. Therefore, we can focus  on the numerator
$-1 + 2 \cos x+ \cos^2 x$, which will be $>0$ exactly on the countable union of intervals
$$( - \arccos(\sqrt{2}-1) + 2 k \pi, \arccos(\sqrt{2}-1) + 2 k \pi)$$
and this gives the solution for $x$.
It correlates with the answer of @Gonate: since $\tan ( \frac{1}{2}\cdot \arccos(\sqrt{2}-1)) = \sqrt{ \sqrt{2}-1}$.
$\arccos(\sqrt{2}-1)= 1.1437.. $ radians  or approximately $65.53^{\circ}$ degrees.

The factor $e^{-1/(1+\cos x)}$ flattens away the singularities arising from the denominator around $(2k+1)\pi$.


How to interpret a significant moderation model with nonsignificant $X$, $W$, and $XW$, and only significant covariates?

Question: First time data analyst, working on my thesis.
Below is a portion of the PROCESS output for one of my moderation analyses. I have been trying to make sense of this.
Alcohol use = DV

JVQ = IV

PWB = Moderator

Gender = Covariate 1

SU_7R = Covariate 2

How can it be that my summary is significant and the only significant variable in the model is SU_7R_pu (Likert type variable ranging 1-7)? Is this telling me that the 15.25% variance accounted for in the model is mostly accounted for by the covariate SU_7R_pu?  Also, how do I interpret the conditional effect of the covariates impact of X->Y?
For $b_1$, $b_2$, and $b_3$ Hayes' book is quite clear, but when it comes to making sense of the output for the covariates, I'm a little lost.  Does it even make sense to say that there was an conditional effect of the covariates on the model, or only to say that it was controlled for and the model was adjusted? Does the model still get adjusted if the covariate is nonsignificant?
Is it possible to have a significant model F statistic and no significant coefficients?

In an other case, with a different DV, the model is nonsignificant; however the same covariate is significant ... what is the difference between these two cases in terms of interpretability?
Answer: There is a lot of questions, let break them out.
Regarding the title itself, your models imply that the only good predictor is SU_7R_pu. Maybe it is related too much with other VIs so it is the one taking most of the variance in the DV. However, the models, as they stand, imply that your IV and moderator has no effect (statistically) when you control for SU_7R_pu.

How can it be that my summary is significant and the only significant
variable in the model is SU_7R_pu (Likert type variable ranging 1-7)?

The model summary is about all the variables in the models. It is not specifically about a moderation model (or the IVs and moderators) being significant. So if a single variable is significant, then the model should, in most cases, also be.

Is this telling me that the 15.25% variance accounted for in the model
is mostly accounted for by the covariate SU_7R_pu?

Like previous question, the 15.25% is about all the variables. But it is pretty fair to guess that most comes from SU_7R_pu.

Also, how do I interpret the conditional effect of the covariates impact of X->Y?

According to the results in OP, there is likely no moderation effects :Int_1 is not significant.

Does it even make sense to say that there was an conditional effect of
the covariates on the model, or only to say that it was controlled for
and the model was adjusted?

The statistical model do not care if the variable is "covariate" or an "IV", it is treated as an IV. You can say that there is relation between your covariate on the outcomes.

Does the model still get adjusted if the covariate is nonsignificant?

Yes.

Is it possible to have a significant model F statistic and no
significant coefficients?

Yes it is. It is even possible to have R^2 near 100% with no regression coefficients being significant. You just need a lot of them.

In an other case, with a different DV, the model is nonsignificant;
however the same covariate is significant...what is the difference
between these two cases in terms of interpretability?

It is the exact same interpretation.


Errors displayed during core upgrade

Question: When I am updating Drupal core, and uploading files via FTP, how can I prevent mydomain.com/install.php trying to load and displaying WSOD errors like "Fatal error: require_once() [function.require]: Failed opening required..."?
I'd like to display a static page with a BRB message instead.
Comment: Welcome to Drupal Answers! Why would you want to do such a thing? If you are getting the error, then probably there is something to fix, not to hide.
Comment: Thanks for your reply, but the error comes because the upload is in progress and files are missing, not because there is anything actually wrong.
Comment: Upload the files, and then update Drupal by going to mydomain.com/update.php. Why are you trying to do two things at the same time?
Answer: Just move your entire Drupal root somewhere else, and put something else in its place (with a "Be Right Back"-message) while the upgrade goes on.
For instance, if your Drupal root is /var/www/html, prepare a directory named /var/www/brb and put a static index.html-file in it with your BRB message.
Then execute the following pair of commands:
mv /var/www/html /var/www/pending_upgrade
mv /var/www/brb /var/www/html

Now, make sure that your ftp job puts the files in below /var/www/pending_upgrade.
When done, restore your site with the following pair of commands:
mv /var/www/html /var/www/brb
mv /var/www/pending_upgrade /var/www/html

The above assumes that you have CLI access.  If you don't, most ftp tools have built-in commands to move directories around.
Comment: The OP is talking about mydomain.com/install.php. How does moving the files into a different directory avoid the OP gets WSODs?
Comment: @kiamlaluno, because when `settings.php` is missing or unreadable, or the DB is missing, Drupal redirects *any* attempts to access the site to `install.php`.  By making Drupal inaccessible for page requests (by moving it somewhere else), this redirection don't happen.
Comment: So, is the user saying that he is uploading the new files to the server, and users accessing the site get a WSOD? (I guess the question is not clear, to me.) I have never overridden the settings.php file to avoid problems with remembering the right credentials. Is there any good reason to update that too?
Comment: Thanks, Free Radical. That is exactly the issue. @kiamlaluno, I am sorry if my question is vague.

Errors displayed during core upgrade