text:
Q: How does correlation between independent variable and error term imply dependence of the independent variable on the dependent variable? We know that a crucial assumption of employing OLS is that the independent variable and the error terms are uncorrelated. That is the "textbook" definition. I've seen in many (1, 2) online sources that if the independent variables and the error terms are correlated, violating strict exogeneity, this also means that the dependent variable $X$ is dependent on the independent variable, $Y$. What I don't understand is how correlation between $X$ and $\mu$ translates into a depdendence of $X$ on $Y$. For example,
Consider the model: $$ Y = \beta Y_{t-1} + \mu_t $$
For this model the independent variables are correlated with the terror term:
$$ E[y_t \epsilon_t]=E[(\beta y_{t-1}+ \epsilon_t)\epsilon_t] \qquad (by \ \ \ y_t=\beta y_{t-1}+ \epsilon_t) $$
$$ \quad \qquad =\beta E[y_{t-1} \epsilon_t]+E[\epsilon_t^2] $$
$$ \quad  \qquad =E[\epsilon_t^2] \qquad \qquad \qquad \quad (by \ \ \ E[y_{t-1} \epsilon_t]=0) $$
$$ \quad  \qquad =\sigma^2 \qquad \qquad \qquad \quad \quad (by \quad  \epsilon_t \sim N(0, \sigma^2)) $$
That is, for $ y_{t+1} $, $y_t$ is an independent variable but is correlated with an error term.
My question is: This doesn't mean in anyway that $y_t$ is dependent on $y_{t+1}$. Is that statement wrong or am I missing something?

A: Hi: When dealing with lagged dependent variables in time series models, things can become clearer if you write the model out this way: ( at first you used $u$ and then later you used $\epsilon$. I will use $\epsilon$ ).
First, use the lag operator:
$ Y_t(1- \beta L) = \epsilon_t$
Then, divide both sides by $(1-\beta L)$:
$ Y_t = \sum_{i=0}^{\infty} \beta^{i} \epsilon_i$
So, $Y_t$ is dependent on the current $\epsilon$ and all past $\epsilon$ but $\epsilon$ is the only thing on the RHS so the OLS orthogonality condition doesn't really apply because there aren't any regressors for $\epsilon$ to be correlated with. Does that make sense ? $\epsilon$ is the only regressor in the model really.
Note: This AR(1) model still cannot be estimated by OLS because the $\beta$ estimate will be biased but its not due to the condition you mentioned. The biased-ness arises in a complicated way and I can't remember how at the moment.  There was another thread where someone explained how it arises but I forget the name of the thread.
maybe search for "Why is AR(1) OLS estimate biased ?".
UPDATE: Below is not what I was looking for but still quite useful-interesting.  It explains the biasedness using your argument but the dependence is on PAST $\epsilon$ rather than the current $\epsilon$. That dependence also violates the OLS condition. So, if you want to think of the reason as stemming from the argument below, that might be more suitable for you since it's closer to yours. Still,  there's another argument for how the biasedness arises that focuses on the formula for $\hat{\beta}$ in OLS but I failed to find it. Anyway, sorry for confusion and maybe below is the best way to think about it since I failed to find the other argument !!!!!
What's wrong if I fit the auto-regression with OLS?


text:
Q: consolidate multiple time series I'm currently have a problem with interpreting the trend for 1000+ entries.

*

*Each entry has varying amount of periods (30~50)

*A scatterplot of the entries look like a giant blob all across the graph.

*Most of the dots is at y=0. However, the data looks unkept.

*I tried using a mean or median for each month and doing a regression. However, I don't think the result doesn't tell much.

Thus, do you think it'd be helpful if I divide the dataset into more specific category to isolate the data?

A: If you want to do time series analysis then you'll need of the three packages: Pandas, Scikit-learn, or Statsmodels. It all comes down to personal opinion but I listed them in the order I believe is best.
Once you have chose one of the three you'll need to foucs on Ordinary Least Square method (OLS), Regressive Analysis, and Autoregressive Moving Average.
The method that you approach from the top ones is really based on the results you'll get.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to assign query to GridItem in SearchView? I am trying to create a SearchView that searches for GridItems that each launch a specific second activity. However I cannot figure out the code that will help me with this. I have already set an onQueryTextChangeListener for the SearchView which should allow me to show results manually and whilst typing.  Here's what I want to happen:
When I type a specific query, let's say "car", I want to show the GridItem (which is just a clickable ImageView) of a car to the user. When I type "Camera", I want to show the user my GridItem with the image of a Camera on it.
I also want to display results to the user whilst typing, so when I have only typed "c" yet, I want to show the user both the "car" and "Camera" GridItems. I want to stay in the same activity, so I need some sort of way to delete all GridItems except for the ones with a camera or a car picture on it depending on what the user typed, I don't want to launch a search activity.
Now what makes this just a little harder is that I configured my BaseAdapter in a separate class, which means that I have to indirectly mention the GridItems in some way. Here's what I've done so far:
 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater =  getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    final MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView)
            MenuItemCompat.getActionView(searchItem);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
        if (query.equals(R.string.Coconut)){
        //here I need some code that will tell the system that I want to show the GridItem with a picture of a coconut on it
        }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }

This is the separate class that initialises the Images in the GridView:
class SingleItem{
int image;
double nutritional_value;

    SingleItem(int image, double nutritional_value){
    this.image = image;
    this.nutritional_value = nutritional_value;

}
}
public class objectAdapter extends BaseAdapter {
ArrayList<SingleItem> list;
Context context;
Bundle myBundle;

objectAdapter(Context context) {
    this.context = context;
    myBundle = new Bundle();
    double[][] nutritional_value = {
            {89, 22.8, 0.3, 1},
            {61, 1.5, 0.5, 1.1},
            {375, 6.8, 0.6, 1.2},
            {767, 0, 9.3, 0},
            {580, 9.1, 42, 36.5}

    };
    myBundle.putSerializable("array_array", nutritional_value);

    int[] image_id = {
            R.drawable.Bananas, R.drawable.Kiwis, R.drawable.oatmeals, R.drawable.coconuts,
            R.drawable.dark_chocolate
    };
    for (int i = 0; i < image_id.length; i++) {
        SingleItem tempSingleItem = new SingleItem(image_id[i], nutritional_value[i][i]);
        list.add(tempSingleItem);
    }
}

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

    View row = convertView;
    ViewHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.single_item, parent, false);
        holder= new ViewHolder(row);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }
        SingleItem temp = list.get(position);
        holder.myItem.setImageResource(temp.image);
    holder.myItem.setTag(temp);
    return row;
    }

@Override
public long getItemId(int position) {
    return position;
}
class ViewHolder
{
    ImageView myItem;
            ViewHolder(View v){
myItem = (ImageView) v.findViewById(R.id.imageView2);

            }
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public int getCount() {
    return list.size();
}

}

Thanks in advance!
Vidal

A: You need some sort of a link between adapter items and string value (name or the index in string array). For example:
class SingleItem{
int image;
double nutritional_value;
String name;

    SingleItem(int image, double nutritional_value,String name){
    this.image = image;
    this.nutritional_value = nutritional_value;
    this.name = name;

}
}

If you want to make changes while user typing the query, you need to override
@Override
    public boolean onQueryTextChange(String newText) {
        adapter.filter(newText);
        return true;
    }

in ObjectAdapter class make changes. You need additional list of currently displaying items.
public class objectAdapter extends BaseAdapter {
ArrayList<SingleItem> list;
ArrayList<SingleItem> filteredItems;
Context context;
Bundle myBundle;

objectAdapter(Context context) {
    this.context = context;
    myBundle = new Bundle();
    double[][] nutritional_value = {
            {89, 22.8, 0.3, 1},
            {61, 1.5, 0.5, 1.1},
            {375, 6.8, 0.6, 1.2},
            {767, 0, 9.3, 0},
            {580, 9.1, 42, 36.5}

    };
    myBundle.putSerializable("array_array", nutritional_value);

    int[] image_id = {
            R.drawable.Bananas, R.drawable.Kiwis, R.drawable.oatmeals, R.drawable.coconuts,
            R.drawable.dark_chocolate
    };

    int[] name_id = {R.string.Bananas, R.string.Kiwis, R.string.oatmeals, R.string.coconuts,
            R.string.dark_chocolate
    };
    for (int i = 0; i < image_id.length; i++) {
        SingleItem tempSingleItem = new SingleItem(image_id[i], nutritional_value[i][i],context.getResources().getString(name_id[i]));
        list.add(tempSingleItem);
    }

    filteredItems = new ArrayList<>(list.size());
    filteredItems.addAll(list);
}

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

    View row = convertView;
    ViewHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.single_item, parent, false);
        holder= new ViewHolder(row);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }
        SingleItem temp = filteredItems.get(position);
        holder.myItem.setImageResource(temp.image);
    holder.myItem.setTag(temp);
    return row;
    }

@Override
public long getItemId(int position) {
    return position;
}
class ViewHolder
{
    ImageView myItem;
    ViewHolder(View v){
       myItem = (ImageView) v.findViewById(R.id.imageView2);
    }
}

@Override
public Object getItem(int position) {
    return filteredItems.get(position);
}

@Override
public int getCount() {
    return filteredItems.size();
}

public void filter(String text) {
    filteredItems.clear();
    for(int i=0; i < list.size(); ++i) {
        SingleItem item = list.get(i);
        if (item.name.toLowerCase().contains(text.toLowerCase()) {
           filteredItems.add(item);
        }
    }
    notifyDataSetChanged();
    }
}


text:
Q: Jquery Scrolltop - undentified top I've got a question about scollTop. I've looked at other topics here, but that doesn't fix my problem.
This is the code i'm using:
var id = location.search.replace('?').split('=');

$('html,body').animate({
  scrollTop: $("#"+id[1]).offset().top
},
'slow');

But i got a console error: Uncaught TypeError: Cannot read property 'top' of undefined.
But i really don't know what i'm doing wrong, because the var id is working correctly, even when i change 'html,body' to #container it doesn't change a thing.
Thanks in advance!

A: error happens because object
$("#"+id[1])

is not found


text:
Q: Confidence interval for sample mean (possible error in text) I am working through a problem on CI for a sample mean and I cannot get the answer listed in the  text I have. I am wondering if I am missing something or whether the text may be incorrect.
We are given a sample of 10 scores:
45,38,52,48,25,39,51,46,55,46

I get a mean of 44.5 and SD of 8.68 which is the same as the solutions listed. I also get a standard error of the mean of 2.75 which is the same as the solutions.
However I cannot get the final answer. We are asked to calculate a 95% CI for the mean. When I calculate the margin of error (standard error of the mean * tcritical) I get the answer 2.75*2.262=6.2. (I choose df= 9). Thus the CI I get is 38.3 - 50.7.
However, the text says it is 28.35-60.65. Am I missing something? I would be really grateful for any comments. Thanks.

A: The answer that your book gives can be computed (almost exactly) from mean +- 1.96 * standard deviation of the population.
=AVERAGE(data)    44.5
=STDEV.P(data)     8.237
=1.96 * STDEV     16.144
=44.5 - 16.14     28.356
=44.5 + 16.14     60.644

That's the answer that was given to within 0.01.
I am not saying this is right - but I'm pretty sure that's where the author got his/her numbers from. It is not the answer to the question that was asked ("what is the confidence interval of the mean"). I believe your approach to that question was correct, as earlier comments stated.


text:
Q: Opportunity to using native methods systemwide. How to call method or how it should be named? I want to use one native library for a plurality of applications. Library has compiled through android build system and now located in /system/lib/. It can be loaded in application through System.LoadLibrary("libexample"). But method in library which should be declared like
JNIEXPORT jstring JNICALL Java_application1_MainActivity_method1

turning out unusable because library should be used by several applications. And of course this several applications have their own unique names. So I tried to named my method just like
 JNIEXPORT jstring JNICALL method1

and call
public native String method1(String string);

But of course my application trying to find it as Java_application1_MainActivity_method1
How to call this method or how it should be named?
Updated:
I tried to use this(see post with green tick) tutorial to complete my project. I wrote
a library for using native method:
package com.example.mylib;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MyClass extends Activity {
public native static String MyMethod(String string);
    static {
        System.loadLibrary("nativeLibrary");
    }
}

Then I trying to use it in my application:
// Some no interesting inclusions
import com.example.mylib.MyClass;

public class MainActivity extends ListActivity {
// Some no interesting code.
MyMethod(file.getAbsolutePath())
//Some no interesting code
}

And it working as I need! But now I confused that my import com.example.mylib.MyClass;
"never used" in eclipse. And if I will create image with this "Is Library" project the latest will no resolving. Any idea?

A: Yes, you can use the same JNI signature in many applications. Your class may not belong to the default package of the application, as defined in AndroidManifest.xml. So what?

Example:
Start with HelloJni sample from NDK (in Eclipse, use Import -> Android -> existing Android Code, and point to the ${android-ndk-root}/samples/hello-jni).
Build it and run on device or emulator.
Open a new Android Application project, call it TestCrossJni.
The package name for our app will be: test.cross.jni - no relation to com.example.hellojni!
Choose "Create Activity" -> create Blank Activity.
Add new Java class to this project (src/com/example/hellojni/HelloJni.java):
package com.example.hellojni;

public class HelloJni
{
    public static String gets() {
        return stringFromJNI();
    }

    /* A native method that is implemented by the
     * 'hello-jni' native library, which is packaged
     * with this application.
     */
    private native String  stringFromJNI();

    /* this is used to load the 'hello-jni' library on application
     * startup. The library has already been unpacked into
     * /data/data/com.example.hellojni/lib/libhello-jni.so at
     * installation time by the package manager.
     */
    static {
        System.load("/data/data/com.example.hellojni/lib/libhello-jni.so");
    }
}

Edit res/layout/activity_main.xml: replace
    line 12 android:text="@string/hello_world" />
    with android:id="@+id/hello_world" />
In src/test/cross/jni/MainActivity.java, add the following after
    line 12 setContentView(R.layout.activity_main);
((android.widget.TextView)findViewById(R.id.hello_world)).setText(com.example.hellojni.HelloJni.gets());

Profit!


text:
Q: Single Point of Failure - data stream consumer (AWS) I'm designing an architecture of a simple service that analyzes data (near-real-time analysis).
I have a data source which is my only data source and I assume that it is highly-available.
The current way I consume the data from this stream is by running an EC2 machine (AWS) that reads the data from that stream and produces it to another stream (Kinesis).
My problem is that I cannot assume high-availability for the EC2 machine.
Running more than one machine in parallel is bad idea since my data will be duplicated and each record will be processed twice (or as the number of EC2 instances I run).
The availability of that machine is highly important as it provides me a continuous flow of data, which without it - my service worths nothing.
What can I do in order to achieve high-availability in this part of my architecture?


text:
Q: Image picker not showing image iOS Xcode 6.1.1 I have created a simple application for image picker in Xcode 6.1.1 for iOS and it's working on Mac at my home but the same code is not working on Mac at my office Please can anyone tell me why is that ?
here is the github link for the source code of the same application.
https://github.com/varun-naharia/ImageUploader
media info from computer 1 where everything working correctly
2015-02-18 09:19:35.212 ImageUploader[3785:12959] info = {
    UIImagePickerControllerMediaType = "public.image";
    UIImagePickerControllerOriginalImage = "<UIImage: 0x7fd6f9d334a0> size {834, 1250} orientation 0 scale 1.000000";
    UIImagePickerControllerReferenceURL = "assets-library://asset/asset.JPG?id=E2741A73-D185-44B6-A2E6-2D55F69CD088&ext=JPG";
}
2015-02-18 09:19:35.212 ImageUploader[3785:12959] mediaUrl = (null)
2015-02-18 09:19:35.212 ImageUploader[3785:12959] image = <UIImage: 0x7fd6f9d334a0> size {834, 1250} orientation 0 scale 1.000000

A: After updating xcode it is now working fine


text:
Q: How does Google ARcore find which phone you are using? So I have been trying to figure this out for the past week and I am lost, mainly for my own personal hacking.
I understand ARCore needs to be configured per hardware it is running on. Its important that ARcore knows the camera hardware, and its position and orientation with respect to the gyros and accelerometers.
There is probably some config that does this, but I have not found it yet. Does anybody have a clue.
I am an Android dev btw, so keep it Android specific in technology.


text:
Q: How to separate slices to be independent frames in multiple slices h264 stream? I have a 4-slices h264 stream, which looks like
0x000001[sps] 0x000001[pps] 0x000001[IDR] 0x000001[IDR] 0x000001[IDR] 0x000001[IDR]

How to separate each slice to be a frame with 1/4 height, maybe look like
0x000001[sps] 0x000001[pps] 0x000001[IDR] 0x000001[sps] 0x000001[pps] 0x000001[IDR] 0x000001[sps] 0x000001[pps] 0x000001[IDR] 0x000001[sps] 0x000001[pps] 0x000001[IDR]

I have tried to modify the first_mb_in_slice in the slice header to be 0, the height pic_height_in_map_units_minus1 from 119 to 29 and insert sps and pps before each slice.
I got 2 slices to decode success but another 2 slices were broken for each frame.
How do I fix it?
Thanks for any help.


text:
Q: Vue composition API watch object How to watch object, and get previous and new value? Code below, after call changeName(), I got same n and o.
And can someone explain what is "flush" do? I can't find good document online.
setup(){
        const users=ref([{ name: 'John' }]);
        const changeName=(name)=>{ users.value[0].name='Alex'; };
        watch(
           ()=>users.value,
           (n,o)=>{ console.log(n,o); },
                {
                    lazy: false,
                    deep: true,
                    flush: 'post'  // pre,post,sync
                }
            );
        return {users, changeName};
    }

A: I don't know what you really want to do with it. But to actually get it to fire the watch you could do:
watch(
  () => user.value.map(u => u.name),
  (n, o) => console.log(n,o),
)


text:
Q: Concatenated string in python in the loop area I face a problem of concatenating values in a loop:
I have the following code:
Array:
[(1,2), (1,2), (1,2)]
mc1 = mydb.cursor()
mc2 = mydb.cursor()

mc1.execute("SELECT * FROM pdf WHERE id_primarie = 1 LIMIT 10")
myresult = mc1.fetchall()

for x in myresult:
  id_pdrimarie = x[1]
  id_pdf = x[0];

  sql = "SELECT * FROM proprietari WHERE id_pdf = %s"
  adr = (id_pdf, )
  mc2.execute(sql, adr)
  result = mc2.fetchall()

  prop = "";
  for y in result:
    #print(y)
    nume = y[3]
    prenume = y[4]
    #print (nume)
    nume_firma = y[29]

    #prop1+=" %s %s + " % (nume, prenume)
    if nume == "":
        prop+= nume
        prop+=" "
        prop+= prenume
        prop+= " + "
        print"-------"
    else:
        prop+= nume_firma
        prop+=" + "
  print(prop)

And in the prop variable it should look like this:
1 2 + 1 2 + 1 2
I need to concatenate from position 1 and from 2 and from 3 but between positions to be an + insert
I can't even do that :(

A: You can do this:
arr = [(1,2), (1,2), (1,2)]
arr_str = []

for i in arr:
    arr_str.append((f'{i[0]} {i[1]}'))

arr_str = ' + '.join(arr_str)

# or single line

arr_str = ' + '.join(f'{i[0]} {i[1]}' for i in arr)

print(arr_str)

Output:
1 2 + 1 2 + 1 2

A: Use the join() method with a generator.
result = [(1,2), (1,2), (1,2)]
arr_str = " + ".join(" ".join(map(str, nums)) for nums in result)
print(arr_str)


text:
Q: ArrayList issues I'm trying to get all possible word couples from a sentence and store it to an ArrayList
where MyClass.java
class MyClass{

private static ArrayList<String> wordList;
private static ArrayList<Integer> wordListCode;
private static int frequency;
private static int timeId;

public MyClass(ArrayList<String> words, int tid, int freq){
    wordList = new ArrayList<String>();
    wordListCode = new ArrayList<Integer>();

    if(words.get(0).hashCode()> words.get(1).hashCode()){
        wordList.add(words.get(0));    wordListCode.add(words.get(0).hashCode());
        wordList.add(words.get(1));    wordListCode.add(words.get(1).hashCode());
    }else{
        wordList.add(words.get(1));    wordListCode.add(words.get(1).hashCode());
        wordList.add(words.get(0));    wordListCode.add(words.get(0).hashCode());
    }
    frequency = freq;
    timeId = tid;
}}

My problem is that when I'm trying to add an MyClass object to the ArrayList, adds one node but replaces all the other nodes with the values of the last one...
Here is some code:
 ArrayList<MyClass> couples = new ArrayList<MyClass>();
    ArrayList<String[]> couplesList = new ArrayList<String[]>();
    couplesList = getWordCouplesList("demanding forensic technical comms systems");
    for(int o=0; o<couplesList.size(); o++){
        String word1, word2;
        if(couplesList.get(o)[0].hashCode()> couplesList.get(o)[1].hashCode() ){
            word1 = couplesList.get(o)[0];
            word2 = couplesList.get(o)[1];
        }else{
            word1 = couplesList.get(o)[1];
            word2 = couplesList.get(o)[0];
        }
        ArrayList<String> items = new ArrayList<String>(Arrays.asList(couplesList.get(o)));
        MyClass temp = new MyClass((ArrayList)items, 1, 1);
        couples.add( temp);
    }

    for(int i=0; i<couples.size(); i++){
        System.out.println((i+1)+"couple = "+couples.get(i).getWordList().get(0)+" , "+couples.get(i).getWordList().get(1));
    }

This gives output :
1couple = comms , systems
2couple = comms , systems
3couple = comms , systems
4couple = comms , systems
5couple = comms , systems
6couple = comms , systems
7couple = comms , systems
8couple = comms , systems
9couple = comms , systems
10couple = comms , systems

A: class MyClass {

  private ArrayList<String> wordList;
  private ArrayList<Integer> wordListCode;
  private int frequency;
  private int timeId;
  ...
  .....
}

remove the static modifier on your fields.
it means you use the same instance for every object of that MyClass, which you don't want. You want every instance to have it's own lists and attributes.
read more about it

A: Remove the static modifier.
From JLS 8.3.1.1. static Fields

If a field is declared static, there exists exactly one incarnation of
  the field, no matter how many instances (possibly zero) of the class
  may eventually be created. A static field, sometimes called a class
  variable, is incarnated when the class is initialized (§12.4).
A field that is not declared static (sometimes called a non-static
  field) is called an instance variable. Whenever a new instance of a
  class is created (§12.5), a new variable associated with that instance
  is created for every instance variable declared in that class or any
  of its superclasses.

For more info refer,  static Fields
So change your code to,
class MyClass{

  private ArrayList<String> wordList;
  private ArrayList<Integer> wordListCode;
  private int frequency;
  private int timeId;
  ...
  .....
}}


text:
Q: Object reference error during custom session state provider initialization I have written a custom session state provider which works fine in debug mode but once deployed on the server (IIS 6) i get the following error:
Event code: 3008
Event message: A configuration error has occurred.
Event time: 10/7/2011 3:05:02 PM
Event time (UTC): 10/7/2011 9:35:02 AM
Event ID: 00e2c8b1368b45608bb062eb2ba9d0db
Event sequence: 2
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/1/Root/bizapp-1-129624536989844520
    Trust level: Full
    Application Virtual Path: ...
    Application Path: ...
    Machine name: ...

Process information:
    Process ID: 7556
    Process name: w3wp.exe
    Account name: ...

Exception information:
    Exception type: ConfigurationErrorsException
    Exception message: Object reference not set to an instance of an object. (E:\Program Files\BizAPP\WebClient\web.config line 282)

Request information:
    Request URL: http://localhost:8080/bizapp/login.aspx
    Request path: /bizapp/login.aspx
    User host address: 127.0.0.1
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: ...

Thread information:
    Thread ID: 1
    Thread account name: ...
    Is impersonating: False
    Stack trace:    at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType)
   at System.Web.SessionState.SessionStateModule.InitCustomStore(SessionStateSection config)
   at System.Web.SessionState.SessionStateModule.InitModuleFromConfig(HttpApplication app, SessionStateSection config)
   at System.Web.SessionState.SessionStateModule.Init(HttpApplication app)
   at System.Web.HttpApplication.InitModulesCommon()
   at System.Web.HttpApplication.InitModules()
   at System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
   at System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context)
   at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
   at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)

EDIT
line 282 is from web.config having the provider info, 3rd line below
<sessionState mode="Custom" customProvider="SessionStateStoreProvider" timeout="180">
            <providers>
                <add name="SessionStateStoreProvider" type="type full name" />
            </providers>
        </sessionState>

A: It means the "Object reference not set to an instance of an object" exception happens in one of your provider's methods (for example in the Initialize method). There's a bug in that code.
So you can either put a breakpoint in there and debug, or surround overridden methods with a try catch that can transform the exception in text, like this:
public class YourSessionState : SessionStateStoreProviderBase
{
    public override void Initialize(string name, NameValueCollection config)
    {
        try
        {
            // your original Initialize code here
        }
        catch (Exception e)
        {
            throw new Exception("Error in initialize: " + e);
        }
    }
}

If you put the .PDB files aside the .DLL, you should now see the error line number.

A: You're not specifying the type correctly in your configuration.
Example:
<sessionState mode="Custom" customProvider="SessionStateStoreProvider">
  <providers>
    <add name="SessionStateStoreProvider"
         type="Namespace.To.Your.SessionStateStoreClass" />
  </providers>
</sessionState>

Unless you intentionally omitted the type.


text:
Q: System.ArgumentException : Duplicate dynamic module name within an assembly in Nhibernate 3.3.0.4000 I'm having an issue I cannot reproduce and I cannot track down.  It happens for one client, in one area of the site, on one environment only.

System.ArgumentException : Duplicate dynamic module name within an assembly.

StackTrace
at System.Reflection.Emit.AssemblyBuilderData.CheckNameConflict(String strNewModuleName) at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) at
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) at
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name) at
NHibernate.Proxy.DynamicProxy.DefaultProxyAssemblyBuilder.DefineDynamicModule(String moduleName) at NHibernate.Proxy.DynamicProxy.ProxyFactory.CreateUncachedProxyType(Type baseType, Type[] baseInterfaces) at
NHibernate.Proxy.DynamicProxy.ProxyFactory.CreateProxyType(Type baseType, Type[] interfaces) at NHibernate.Proxy.DynamicProxy.ProxyFactory.CreateProxy(Type instanceType, IInterceptor interceptor, Type[] baseInterfaces) at
NHibernate.Proxy.DefaultProxyFactory.GetProxy(Object id, ISessionImplementor session)

There are numerous posts saying that it's a problem with Castle.DynamicProxy but the version of nhibernate I am using does not need/use the castle library.  I am using NuGet for my FluentNHibernate reference and everything is up to date.
I checked the bin on the server and there is no castle dll.  The nhibernate dll is the correct version.

A: This is a race condition bug in NHibernate, see https://nhibernate.jira.com/browse/NH-3172.
It is fixed in 3.3.1GA which should be available for download within a few hours.


text:
Q: How to use bootstrap or css for never appear scrollbar The question is in the title, on React Application, i want to never see the window scrollbar, i would like to the content never overflowing for each screen size.
      // App.js
      <BrowserRouter>

          <Navbar/>
          ...
          // some routes

      </BrowserRouter>

      //App.css
     * {
         box-sizing: border-box !important;
     }

    .site {
        height: 100%;
        margin-bottom: -40px;
    }

    footer {
       height:40px;
       background-color:red;
    }

For example, i have a table, if content overflow, only scroll table appear but never this of window.

     ...

```

A: I think you can simply do it with CSS like :
::-webkit-scrollbar {
    display: none;
}

If you can't with this, play with the overflow, for me it's the only answers.

A: To prevent overflow you can disable overflow for body element.
body {
  height: 100vh;
  overflow: hidden;
}

When hiding scrollbar you have to remember not only about chrome, but also firefox and safari.

A: When i say never see the scrollbar, i would like just ajust the height property for each screen not only masked it.

A: To solved it, i wrapped my site in a div
// App.js

  <Navbar/> //navbar component
  <BrowserRouter>
    <Switch> // from react router dom
      <Route/> // some many routes
   ...

// App.css
.site {
  height:100%
}

And after in component who contain my table
<Container style={{height:"calc(100% - 120px)", display:"flex", flexDirection:"column"}}>

    ...

I hope so this answer can help another developers


text:
Q: PHP XML - Find out the path to a known value Here is an XML bit:
[11] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [id] => 46e8f57e67db48b29d84dda77cf0ef51
                                            [label] => Publications
                                        )

                                    [section] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [@attributes] => Array
                                                        (
                                                            [id] => 9a34d6b273914f18b2273e8de7c48fd6
                                                            [label] => Journal Articles
                                                            [recordId] => 1a5a5710b0e0468e92f9a2ced92906e3
                                                        )

I know the value "46e8f57e67db48b29d84dda77cf0ef51" but its location varies across files. Can I use XPath to find the path to this value? If not what could be used?
Latest trial that does not work:
$search = $xml->xpath("//text()=='047ec63e32fe450e943cb678339e8102'");

while(list( , $node) = each($search)) {

    echo '047ec63e32fe450e943cb678339e8102',$node,"\n";

}

A: PHPs DOMNode objects have a function for that: DOMNode::getNodePath()
$xml = <<<'XML'
<root>
  <child key="1">
    <child key="2"/>
    <child key="3"/>
  </child>
</root>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$nodes = $xpath->evaluate('//child');

foreach ($nodes as $node) {
  var_dump($node->getNodePath());
}

Output:
string(11) "/root/child"
string(20) "/root/child/child[1]"
string(20) "/root/child/child[2]"

SimpleXML is a wrapper for DOM and here is a function that allows you to get the DOMNode for an SimpleXMLElement: dom_import_simplexml.
$xml = <<<'XML'
<root>
  <child key="1">
    <child key="2"/>
    <child key="3"/>
  </child>
</root>
XML;

$structure = simplexml_load_string($xml);
$elements = $structure->xpath('//child');

foreach ($elements as $element) {
  $node = dom_import_simplexml($element);
  var_dump($node->getNodePath());
}

To fetch an element by its attribute xpath can be used.
Select all nodes using the element joker anywhere in the document:
//*
Filter them by the id attribute:
//*[@id = "46e8f57e67db48b29d84dda77cf0ef51"]
$dom = new DOMDocument();
$dom->loadXml('<node id="46e8f57e67db48b29d84dda77cf0ef51"/>');
$xpath = new DOMXpath($dom);

foreach ($xpath->evaluate('//*[@id = "46e8f57e67db48b29d84dda77cf0ef51"]') as $node) {
  var_dump(
    $node->getNodePath()
  );
}

A: Is this string always in the @id attribute? Then a valid and distinct path is always //*[@id='46e8f57e67db48b29d84dda77cf0ef51'], no matter where it is.
To construct a path to a given node, use $node->getNodePath() which will return an XPath expression for the current node. Also take this answer on constructing XPath expression using @id attributes, similar to like Firebug does, in account.
For SimpleXML you will have to do everything by hand. If you need to support attribute and other paths, you will have to add this, this code only supports element nodes.
$results = $xml->xpath("/highways/route[66]");

foreach($results as $result) {
    $path = "";
    while (true) {
        // Is there an @id attribute? Shorten the path.
        if ($id = $result['id']) {
            $path = "//".$result->getName()."[@id='".(string) $id."']".$path;
            break;
        }
        // Determine preceding and following elements, build a position predicate from it.
        $preceding = $result->xpath("preceding-sibling::".$result->getName());
        $following = $result->xpath("following-sibling::".$result->getName());
        $predicate = (count($preceding) + count($following)) > 0 ? "[".(count($preceding)+1)."]" : "";
        $path = "/".$result->getName().$predicate.$path;
        // Is there a parent node? Then go on.
        $result = $result->xpath("parent::*");
        if (count($result) > 0) $result = $result[0];
        else break;
    }
    echo $path."\n";
}


text:
Q: Textbox control from gridview column is returned but gives empty value I have succeeded in retrieving Textbox from textbox column of Gridview, but it can't retain the value I have put there. It simply returns reference to textbox but miss the encapsulated value; Following is sample code I'm using to retrieve the textbox and its value; Please help me out of handling such problem.
protected void Submit_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        int RowIndex = int.Parse(e.CommandArgument.ToString());
        string userId = ApprovalParentGridView.DataKeys[RowIndex]["UserID"].ToString();
        GridViewRow row = ApprovalParentGridView.Rows[RowIndex];

        TextBox remarks = (TextBox)row.Cells[6].FindControl("txtRemark");
        string remarks = remarks.Text.Trim();

        ...
    }

Thanks in advance!!!

A: I have had this in the past and found it to be because the Gridview is loaded in Page_Load and the textbox had its value set in that routine, and Submit_RowCommand is fired afterwards.
You need to rebuild the gridview so that the control is in the controls collection but you need to be careful that you do not put the value in the textbox at the same time or else the code behind will overwrite the value that you user has entered from their browser.


text:
Q: Translation invariance of Lebesgue integral I am looking at the following statement: Let $u:\mathbb{R^3} \rightarrow \mathbb{S}^1$ and $z\in \mathbb{R}^3$ and $h>0$ small. Then the integral $\int_{\mathbb{T}^3} dx$ is translation invariant and therefore
$\int_{\mathbb{T}^3} u(x)-u(x-\sqrt{h}z) dx = \int_{\mathbb{T}^3} u(x-\sqrt{h}z)-u(x-2\sqrt{h}z) dx$.
I understand that the Lebesgue-measure is invariant under translation and this implies that the Lebesgue Integral is translation invariant as well, in the sense that for a measurable set $D \subset \mathbb{R}^3$ we have
$\int_D u(x) dx = \int_{D-z} u(x+z) dx$.
The torus is defined as the quotient of the cartesian plane with the identifications $(x,y,z)\text{~}(x+1,y,z)\text{~}(x,y+1,z)\text{~}(x,y,z+1)$. The thing I don't understand in the first statement is that we have both times the integral over $\mathbb{T}^3$. I thought that on the righthand side it should be $\mathbb{T}^3+\sqrt{h}z$ for $\sqrt{h}z \notin \mathbb{Z}^3$ after our definition of $\mathbb{T}^3$. Am I not understanding the notion of the three-torus correctly or where is my mistake?

A: The torus $\mathbb{T}^n$ is mapped to itself upon a translation of it's native periodic coordinates. Think about the circle (less commonly noted as $\mathbb{T}^1$) for example- if you shift the angle coordinate by any amount, you will still traverse the whole circle on the interval $[0,2\pi)$.
Of course, when a function is defined on the torus, in order for this to still hold true under integration, we need to equip the function with the same symmetry as the torus, in other words we must make it periodic in all directions with the same period as the torus. This makes sense if you want your function to be single-valued on the manifold.
Proof for the Riemann integral, with some simplifying assumptions
Here's a proof for the Riemann integral on $\mathbb{T}_1$ that generalizes well to higher dimensions:
Assume $f(x+1)=f(x)~\forall x$. Then we define the following Riemann integral
$$I(a)=\int_{0}^{1}f(x-a)dx=\int_{a}^{a+1}f(x)dx$$
We compute it's derivative and we find that:
$$\frac{dI(a)}{da}=f(a+1)-f(a)=0\iff I(a)=I(0)$$
and thus we proved
$$\int_{\mathbb{T^1}}f(x)dx=\int_{\mathbb{T^1}}f(x-a)dx~ \forall a\in\mathbb{R}$$
Generalizing in higher dimensions is easy. Denoting $\mathbf{a}=(a_1,a_2,...a_n)$ and generalizing the periodicity property on $f$ accordingly, we define
$$I(\mathbf{a})=\int_{(0,1)^n} dx_1...dx_n~f(\mathbf{x+a})$$
Taking the gradient, we note that
$$\begin{align}\frac{\partial}{\partial a_i}I(\mathbf{a})&=\int_{(0,1)^n} dx_1...dx_n~\frac{\partial}{\partial a_i}f(\mathbf{x+a})\\&=\int_{(0,1)^n} dx_1...dx_n~\frac{\partial}{\partial x_i}f(\mathbf{x+a})\\&=F_i(a_i+1)-F_i(a_i)\end{align}$$
where we defined
$$F_i(t)=\int_{(0,1)^{n-1}}dx_1...dx_{i-1}dx_{i+1}...dx_nf(x_1+a_1,...,x_{i-1}+a_{i-1}, t,...,x_n+a_n)$$
Due to the periodicity condition in all coordinates, it is clear that
$$F_i(t+1)=F_i(t)~,~\forall i,t$$
and hence all first-order partial derivatives of $I$ identically vanish and the integral is shown to be a constant with respect to shift parameters. By setting $\mathbf{a}=0$ we conclude that
$$\int_\mathbb{T^n}d\mathbf{x}f(\mathbf{x+a})=\int_\mathbb{T^n}d\mathbf{x}f(\mathbf{x})$$
as desired. These ideas should have an analogue on the Lebesgue integral that I haven't been able to exactly pinpoint, but I hope they provide with a good starting point.
EDIT: Proof for Lebesgue integral, only assumes positivity and measurability
I came up with a Lebesgue-measure style outline of a proof for $\mathbb{T}^1$:
Consider the measure of the following set $\mu(x\in (0,T)|f(x)>t)$. If f is positive definite and measurable, the Lebesgue integral exists and is equal to $\int_{0}^{\infty}\mu(x\in (0,T)|f(x)>t)dt$.
However we note that if we shift the argument by an amount $a=mT+r, 0<r<T$ and assume $f$ is $T$-periodic,
$$\begin{align}\mu(x\in (0,T)|f(x+a)>t)&=\mu(x\in (0,T)|f(x+r)>t)\\&=\mu(x\in (r,T)\cup(T,T+r)|f(x)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(x\in (T,T+r)|f(x)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(y\in (0,r)|f(y+T)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(x\in (0,r)|f(x)>t)\\&=\mu(x\in (0,T)|f(x)>t)\end{align}$$
and we are done. This can be readily generalized to higher dimensional analogues of the statement, since all we need to show is that what shifts do is to merely  rearrange the interval of integration (in your case the whole higher dimensional torus). In fact the previous proof goes through completely by just adding indices where appropriate, $a_i=m_iT+r_i$ and applying the one-dimensional procedure repeatedly!
Here's the outline of the proof for $\mathbb{T}^n$:
$$\begin{align}\mu((x_1,...,x_n)\in (0,T)^n|f(x_1+a_1, ...x_n+a_n)>t)&=\mu((x_1,...,x_n)\in (0,T)|f(x_1+r_1, ..., x_n+r_n)>t)\\&=\mu(x_1\in (0,T),(x_2,...x_n)\in(0,T)^{n-1}|f(x_1,x_2+r_2,...,x_n+r_n)>t)\\&=\mu((x_1,x_2)\in (0,T)^2,(x_3,...x_n)\in(0,T)^{n-2}|f(x_1,x_2+r_2,...,x_n+r_n)>t)=...\\...&=\mu((x_1,...,x_n)\in (0,T)^n|f(x_1, ...x_n)>t)\end{align}$$


text:
Q: Dimensionality of shapes in two space I'm having trouble properly understanding the dimension of shapes. Take a square or triangle. Are the boundaries of these two-dimensional shapes one-dimensional? Is the entire figure two dimensional? I think the answer is yes to both of these, but I'm not sure. Furthermore, would the boundaries of these then shapes need to exist in a dimension higher than it? (e.g. a sphere, the boundary of a ball, is two dimensional but needs three dimensions to "exist").

A: Basically, yes : the boundary of a $n$-dimensional "object" (for instance, a simplicial complex, or a manifold with boundary) is a $(n-1)$-dimensional object.
And in general, a $n$-dimensional object cannot be embedded in $\mathbb{R}^n$ (but it can always be embedded in $\mathbb{R}^{2n}$ for instance). But it can exist as an object without any embedding : this is called "intrinsic" geometry, as opposed to "extrinsic" geometry which is when you only consider subobjects of $\mathbb{R}^n$.


text:
Q: How do I apply Tfidf_vectorizer to the whole pandas column? First of all I'm kinda new to NLP, so I might have understood a concept in a wrong way or something
I am trying to find a way to vectorize the whole column as 1 text, and then after getting the results, I would like to fit the model I'm using to my target set.
I am currently using a pipeline to vectorize my dataframe columns, but I believe that they are being vectorized 1 by 1, instead of joining all the columns together and then doing it.
Here's an exaggerated example of my dataset:
   data                                                 target
1 "conventional normal breast cancer test"              breast cancer test
2 "regular and conventional normal lung cancer test"    lung cancer test

Basically, I would like to give the terms "breast" and "lung" a high tfidf score because it is unique, and I don't want my model to mistake these 2 types of data because they seem similar
My Current Code:
vectorizer = feature_extraction.text.TfidfVectorizer(ngram_range=(1, 3),
                         analyzer='word',)

pipe = pipeline.Pipeline([
('vectorizer', vectorizer),
('clf', linear_model.LogisticRegression())])

pipe.fit(X_train, y_train)

y_predicted = pipe.predict(X_test)


text:
Q: Why can't I use a defined function inside another defined function,when creating an js object? The code goes like this
var ob = {
    a: function() {
        b()
    },
    b: function() {
        console.log("hi")
    }
};

As you can see, you can't do
ob.a() //returns error

Can someone explain the reason in depth?

A: Becuase b does not exist in the current scope (which is the global one in this case).
This works, however:
var ob = {
  a: function () {
    this.b()
  },
  b: function () {
    console.log('hi')
  }
};

because this refers to the ob object.

A: The b is a property of the object called ob. That being said, if you use
ob.b

instead of b you will solve your problem.
var ob = {
    a:function(){
        ob.b()
    },
    b:function(){
        console.log("hi")
    }
};

Another way to do achieve this is to use the this operator.
var ob = {
    a:function(){
        this.b()
    },
    b:function(){
        console.log("hi")
    }
};

The this holds a reference to the object you define. Hence using it you can access is properties. It is a better way that the first way, because if you decide later to alter the name of ob to obj, you will not have change it in two places.

A: There is no function b defined anywhere, it's a property of object ob, so you can refer it as this.b from inside a:
var ob = {
    a: function () {
        this.b();
    },
    b: function () {
        console.log("hi");
    }
};

ob.a();

You could also access b as ob.b().


text:
Q: Custom concurrent TcpOutboundGateway in spring integration I am trying to communicate with an external TCP server using TcpOutboundGateway and a client TcpConnectionFactory. In my scenario, each connection should be associated with different thread (each connection on the thread might be used for more then one request/response).
So I used a ThreadAffinityClientConnectionFactory from this topic: Spring Integration tcp client multiple connections
It worked fine until I tried to open more than 4 concurrent connections, the fifth (and over) connection is failing on timeout.
I figured out that org.springframework.integration.ip.tcp.TcpOutboundGateway uses semaphore in handleRequestMessage method to acquire a connection, so I overridden TcpOuboundGateway like this:
public class NoSemaphoreTcpOutboundGateway extends TcpOutboundGateway {

    private volatile AbstractClientConnectionFactory connectionFactory;
    private final Map<String, NoSemaphoreTcpOutboundGateway.AsyncReply> pendingReplies = new ConcurrentHashMap();

    @Override
    public boolean onMessage(Message<?> message) {
        String connectionId = (String)message.getHeaders().get("ip_connectionId");
        if(connectionId == null) {
            this.logger.error("Cannot correlate response - no connection id");
            this.publishNoConnectionEvent(message, (String)null, "Cannot correlate response - no connection id");
            return false;
        }

        if(this.logger.isTraceEnabled()) {
            this.logger.trace("onMessage: " + connectionId + "(" + message + ")");
        }

        NoSemaphoreTcpOutboundGateway.AsyncReply reply = (NoSemaphoreTcpOutboundGateway.AsyncReply)this.pendingReplies.get(connectionId);
        if(reply == null) {
            if(message instanceof ErrorMessage) {
                return false;
            } else {
                String errorMessage = "Cannot correlate response - no pending reply for " + connectionId;
                this.logger.error(errorMessage);
                this.publishNoConnectionEvent(message, connectionId, errorMessage);
                return false;
            }
        } else {
            reply.setReply(message);
            return false;
        }

    }

    @Override
    protected Message handleRequestMessage(Message<?> requestMessage) {
        connectionFactory = (AbstractClientConnectionFactory) this.getConnectionFactory();
        Assert.notNull(this.getConnectionFactory(), this.getClass().getName() + " requires a client connection factory");

        TcpConnection connection = null;
        String connectionId = null;

        Message var7;
        try {
            /*if(!this.isSingleUse()) {
                this.logger.debug("trying semaphore");
                if(!this.semaphore.tryAcquire(this.requestTimeout, TimeUnit.MILLISECONDS)) {
                    throw new MessageTimeoutException(requestMessage, "Timed out waiting for connection");
                }

                haveSemaphore = true;
                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("got semaphore");
                }
            }*/

            connection = this.getConnectionFactory().getConnection();
            NoSemaphoreTcpOutboundGateway.AsyncReply e = new NoSemaphoreTcpOutboundGateway.AsyncReply(10000);
            connectionId = connection.getConnectionId();
            this.pendingReplies.put(connectionId, e);
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Added pending reply " + connectionId);
            }

            connection.send(requestMessage);

            //connection may be closed after send (in interceptor) if its disconnect message
            if (!connection.isOpen())
                return null;

            Message replyMessage = e.getReply();
            if(replyMessage == null) {
                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("Remote Timeout on " + connectionId);
                }

                this.connectionFactory.forceClose(connection);
                throw new MessageTimeoutException(requestMessage, "Timed out waiting for response");
            }

            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Response " + replyMessage);
            }

            var7 = replyMessage;
        } catch (Exception var11) {
            this.logger.error("Tcp Gateway exception", var11);
            if(var11 instanceof MessagingException) {
                throw (MessagingException)var11;
            }

            throw new MessagingException("Failed to send or receive", var11);
        } finally {
            if(connectionId != null) {
                this.pendingReplies.remove(connectionId);
                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("Removed pending reply " + connectionId);
                }
            }
        }
        return var7;
    }

    private void publishNoConnectionEvent(Message<?> message, String connectionId, String errorMessage) {
        ApplicationEventPublisher applicationEventPublisher = this.connectionFactory.getApplicationEventPublisher();
        if(applicationEventPublisher != null) {
            applicationEventPublisher.publishEvent(new TcpConnectionFailedCorrelationEvent(this, connectionId, new MessagingException(message, errorMessage)));
        }
    }

    private final class AsyncReply {
        private final CountDownLatch latch;
        private final CountDownLatch secondChanceLatch;
        private final long remoteTimeout;
        private volatile Message<?> reply;

        private AsyncReply(long remoteTimeout) {
            this.latch = new CountDownLatch(1);
            this.secondChanceLatch = new CountDownLatch(1);
            this.remoteTimeout = remoteTimeout;
        }

        public Message<?> getReply() throws Exception {
            try {
                if(!this.latch.await(this.remoteTimeout, TimeUnit.MILLISECONDS)) {
                    return null;
                }
            } catch (InterruptedException var2) {
                Thread.currentThread().interrupt();
            }
            for(boolean waitForMessageAfterError = true; this.reply instanceof ErrorMessage; waitForMessageAfterError = false) {
                if(!waitForMessageAfterError) {
                    if(this.reply.getPayload() instanceof MessagingException) {
                        throw (MessagingException)this.reply.getPayload();
                    }

                    throw new MessagingException("Exception while awaiting reply", (Throwable)this.reply.getPayload());
                }
                NoSemaphoreTcpOutboundGateway.this.logger.debug("second chance");
                this.secondChanceLatch.await(2L, TimeUnit.SECONDS);
            }
            return this.reply;
        }

        public void setReply(Message<?> reply) {
            if(this.reply == null) {
                this.reply = reply;
                this.latch.countDown();
            } else if(this.reply instanceof ErrorMessage) {
                this.reply = reply;
                this.secondChanceLatch.countDown();
            }
        }
    }
}

the configurations of SpringContext looks like this:
@Configuration
@ImportResource("gateway.xml")
public class Conf {

@Bean
@Autowired
@ServiceActivator(inputChannel = "clientOutChannel")
public NoSemaphoreTcpOutboundGateway noSemaphoreTcpOutboundGateway(ThreadAffinityClientConnectionFactory cf, DirectChannel clientInChannel){
    NoSemaphoreTcpOutboundGateway gw = new NoSemaphoreTcpOutboundGateway();
    gw.setConnectionFactory(cf);
    gw.setReplyChannel(clientInChannel);
    gw.setRequestTimeout(10000);
    return gw;
}

 <int-ip:tcp-connection-factory
        id="delegateCF"
        type="client"
        host="${remoteService.host}"
        port="${remoteService.port}"
        single-use="true"
        lookup-host="false"
        ssl-context-support="sslContext"
        deserializer="clientDeserializer"
        serializer="clientSerializer"
        interceptor-factory-chain="clientLoggingTcpConnectionInterceptorFactory"
        using-nio="false"/>

The delegateCF is passed to ThreadAffinityClientConnectionFactory constructor
So, the question is:

*

*Is it OK to use NoSemaphoreTcpOutboundGateway in conjunction with ThreadAffinityClientConnectionFactory in terms of concurrency?

A: Looks like you go right way, but at the same time I think you don't need custom TcpOutboundGateway. The semaphore logic is based on the:
if (!this.isSingleUse) {
            logger.debug("trying semaphore");
            if (!this.semaphore.tryAcquire(this.requestTimeout, TimeUnit.MILLISECONDS)) {
                throw new MessageTimeoutException(requestMessage, "Timed out waiting for connection");
            }

at the same time look at Gary's solution for the ThreadAffinityClientConnectionFactory:
@Bean
public TcpNetClientConnectionFactory delegateCF() {
    TcpNetClientConnectionFactory clientCF = new TcpNetClientConnectionFactory("localhost", 1234);
    clientCF.setSingleUse(true); // so each thread gets his own connection
    return clientCF;
}

@Bean
public ThreadAffinityClientConnectionFactory affinityCF() {
    return new ThreadAffinityClientConnectionFactory(delegateCF());
}

Pay attention to the comment. Only you need is delegate isSingleUse().


text:
Q: Passing dynamic array to ImageSlideshow ios Iam trying to use **ImageSlideshow
** library
and i followed the documentation step by step and it's working perfectly
but i  can  only pass static images and here's my code :
slideShow.setImageInputs([AFURLSource(urlString: "https://mylink.com/image.jpg")!, AFURLSource(urlString: "https://mylink.com/image2.jpg")!, AFURLSource(urlString: "https://mylink.com/image3.jpg")!])
But i need to get the images url from JSON array dynamically and pass it to slideshow like that :
var jsonArray:NSarray = [String]

slideShow.setImageInputs([jsonArray])

any idea how can i do that ?

A: try this :
let arr =  jsonArray.map { AFURLSource(urlString: $0 as! String)!}
slideShow.setImageInputs(arr)

hope it be helpful :-)


text:
Q: check the date format that is it correct or not i want to check the date format of the database value. I want to put a check in my code if the format of the date string is correct. If it is not correct then store the empty value.
$getTmpAfSite =   DB::table('tmp_af_site')->orderBy('id','DESC')->get(['id','name','email','number','origin','destination','estimated_rate','make','model','year','running_condition','carrier_type','avail_date','lead_source','request_params','bats_id','submitted_on']);

                    foreach ($getTmpAfSite as $key => $value) {

                        $avail_date = ($value->avail_date != '' && $value->avail_date == Carbon::parse($value->submitted_on)->format('m/d/Y')) ? Carbon::createFromFormat('m/d/Y', $value->avail_date)->format('Y-m-d') : '0000-00-00';
                        $submitted_on = ($value->submitted_on != '' && $value->submitted_on == Carbon::parse($value->submitted_on)->format('m/d/Y H:i')) ? Carbon::createFromFormat('m/d/Y H:i', $value->submitted_on)->format('Y-m-d H:i') : '0000-00-00 00:00:00';
                        DB::table('tmp_af_site')->where('id', $value->id)->update([
                            'avail_date'=>$avail_date,
                            'submitted_on'=>$submitted_on
                        ]);
                    }

i am trying this code to check the value but its not working for me. If i didn't put a check on it and the wrong format comes then the error happens. Here is the error
Unexpected data found. Data missing

A: try use this function, this function check valid or not valid string date with return true false
function validateDate($date, $format = 'd-M-Y')
{
  $d = DateTime::createFromFormat($format, $date);
  return $d && $d->format($format) === $date;
}

if you want more format date, you can add checking date like this
function validateDate($date)
{
  $valid = 0;
  $format1 = 'Y-m-d';
  $d = DateTime::createFromFormat($format1, $date);
  if($d && $d->format($format) === $date){
    $valid = 1;
  }
  $format2 = 'd-m-Y';
  $d = DateTime::createFromFormat($format2, $date);
  if($d && $d->format($format2) === $date){
    $valid = 1;
  }
  return $valid;
}

A: You can use :
checkdate(int $month, int $day, int $year): bool

Example :
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));

#bool(true)
#bool(false)

$valid = checkdate(12,31,2000);

if ($valid)
    echo "Date is valid.";
else
    echo "Date is not valid.";

?>

Regards,


text:
Q: does querying a list of entities from database loads the entities into managed context in jpa? for example:
1.I have 100 entities in a database
2.when i select all those 100 entities via select query,will those entities be loaded to managed context?
3.If yes , what happens if we dont change any attribute values of those entities,will it be committed again to the database after flush method gets called?


text:
Q: NSOperation on the iPhone I've been looking for some concrete scenarios for when NSOperation on the iPhone is an ideal tool to use in an application. To my understanding, this is a wrapper around writing your own threaded code. I haven't seen any Apple demo apps using it, and I'm wondering if I'm missing out on a great tool instead of using NSThread.
The ideal solution here would be to describe a use-case scenario for NSOperation and how you would use it to solve your problem(s).

A: You should also check out this URL:
http://developer.apple.com/cocoa/managingconcurrency.html
All these above answers are great, but make sure you read the article above and make liberal use of this line in your code:
if ( self.isCancelled ) return;

That line wasn't used in the samples provided by Coca is my Girlfriend, and it wasn't until I got crash logs in from the field that I realized this was an issue/concept.

A: Here is just a very simple implementation but take time to read the tutorials to fully understand everything:
NSOperationQueue *queue = [NSOperationQueue new];

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
    selector:@selector(methodToCall)
    object:objectToPassToMethod];

[queue addOperation:operation];

A: Cocoa Is My Girlfriend has a good tutorial on the use of NSOperation and NSOperationQueue. The tutorial makes use of NSOperation to download several webpages simultaneously in separate threads.
Also, see this article from Mac Research.

A: The way I use it in my iPhone apps is to basically create an NSOperationQueue member in my application delegate and make it available through a property. Then every time I need to run something in the background, e.g. download some XML I'll just create an NSInvocationOperation and send it to the queque.
NSInvocationOperation *operationToPerform = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateXML) object:nil];
[[(MyAppDelegate *)[[UIApplication sharedApplication] delegate] sharedOperationQueue] addOperation:operationToPerform];
[op release];

A: In a word: NSOperationQueue
NSOperationQueue is thread safe (you can add operations to it from different threads without the need for locks) and enables you to chain NSOp objects together.
My Flickr iPhone app, Reflections, uses NSOperation and NSOperationQueue extensively to manage downloading images and XML.
Caveat: Make sure you read, re-read, and understand what the docs mean when they talk about 'concurrency'.

A: I use it for asynchronous processing. It is the best way to get data from web services or to coordinate actions that take significant time to run. Because they are thread safe, asynchronous (doesn't tie up the main thread) and they support dependencies, they are a really great tool for your toolset.
Dependencies allow you to make several separate operations and make sure the execute and succeed or error out in a certain order.  This is really great when you need to synchronize a bunch of data but you need parent objects to sync before syncing child objects.

A: A sample that you can try using Swift
let operation : NSOperation = NSOperation()
operation.completionBlock = {
println("Completed")
}

let operationQueue = NSOperationQueue.mainQueue()
operationQueue.addOperation(operation)


text:
Q: Problem with installing thinkorswim I have Ubuntu on three computers, one 16.04 (this laptop) and two with 18.04. the same thing happens on all of them.
I download the thinkorswim installer file into Downloads, check the 'executable file' box in permissions, then, after cd Downloads and ls, I run "sh thinkorswim_installer.sh" as instructed in all the references I can find. In all cases the following messages come up:

gzip: sfx_archive.tar.gz: not in gzip format.
  I am sorry, but the installer file seems to be corrupted. If you downloaded that file, please try again. If you transfer that file with ftp, please make sure you are using binary mode.

Noone else seems to have this problem.
Can someone help with this?
Also, I have downloaded Google Chrome and it won't install.


text:
Q: Reload a React Native class component I have a class component directions in my project. I navigate to another component from it using this.props.navigation.navigate(). Now the problem is that I want to navigate back to the same directions component but with passing new values, ie I want it to reload from scratch, defining state variables once again. How can I do it?
Using navigation.navigate() simply takes me back to the previous state the screen has been.
 this.props.navigation.navigate('direction',{

            riderLocation:this.state.rideInfo.location,
            ride_id:this.state.ride_id,

          });

And this is the componentDidMount of directions.
componentDidMount(){

  alert('componentDidMount');
   const {navigation,route}=this.props;
        this.state.riderLocation = navigation.getParam('riderLocation');
        this.state.ride_id= navigation.getParam('ride_id');
}

A: In the "directions" component, use "componentDidMount" method.
Inside "componentDidMount" method, call a function which updates the state value as desired.
Once you are redirected back to the "directions" component, then "componentDidMount" will run and the state will be updated.
====
Edit:
Try using componentDidUpdate() method in "directions" component.

componentDidUpdate(prevProps, prevState) {
  if (prevProps.navigation.getParam('ride_id') !== this.props.navigation.getParam('ride_id')) {
    const {
      navigation,
      route
    } = this.props;
    this.setState({
      riderLocation: navigation.getParam('riderLocation'),
      ride_id: navigation.getParam('ride_id')
    })
  }
}

Also instead of "this.state.riderLocation" and "this.state.ride_id" use this.setState in componentDidMount(), just like I have written in componentDidUpdate().


text:
Q: SystemVerilog import statement outside module definition What does an import statement outside of a module (|class|package) definition mean?
Does it apply to entire file?
Is it even legal?  I don't see it in IEEE Std 1800™-2012.
It seems to be tolerated by ncsim (15.10-s008) - this compiles/runs w/o error:
package myPackage;
  integer  count  = 0;
endpackage//myPackage

import myPackage::*;

module a;
    initial begin
        myPackage::count++;
        #1;
        $display("%0d: %m: myPackage::count=%0d", $time, myPackage::count);
        $display("%0d: %m:            count=%0d", $time,            count);
    end//initial
endmodule//a

module b;
    import myPackage::*;
    initial begin
        count++;
        #1;
        $display("%0d: %m:            count=%0d", $time,            count);
        $display("%0d: %m: myPackage::count=%0d", $time, myPackage::count);
        myPackage::count++;
        #1;
        $display("%0d: %m:            count=%0d", $time,            count);
        $display("%0d: %m: myPackage::count=%0d", $time, myPackage::count);
    end//initial
endmodule//b

module test_package;
    a a();
    a b();
    b c();
    b d();
endmodule//test_package

A: It applies to the compilation unit, which is the scope outside a module / interface / package. That is normally a single file on your compilation command line ( and everything it includes, which is the same as C/C++) or it could be everything on the current compilation step. The default is tool dependent.
See section 3.12.1 Compilation units in the 1800-2012 LRM.


text:
Q: Question about gauge transformations of a Non-linear sigma model Consider a set of scalar fields $\phi^i$ ($i = 1, 2, \ldots, N$) which we now would to couple to a set of gauge vector fields $A_\mu^A$ where $A = 1, 2, \ldots \text{dim}(G)$ ($G$ is generically a non-Abelian gauge group). The (minimal coupling) prescription to do so is the usual replacement of the standard derivative by the gauge covariant derivative:
$$\partial_\mu \phi^i \longrightarrow D_\mu \phi^i \equiv  \partial_\mu\phi^i - A_\mu^A K_A{}^i$$
where $K_A^i$ are Killing vectors that satisfy the Killing condition $\mathcal{L}_{K_A}g_{ij} = 0$ and the algebra $\mathcal{L}_{K_A}K_{B} = [K_A, K_B] = f_{AB}{}^C K_C$ (here $f_{AB}{}^C$ are the structure constants of the Lie algebra of $G$, and $K_A \stackrel{\Delta}{=} K_A{}^i\partial_i$).
An infinitesimal gauge transformation is given by
$$\delta\phi^i = \Lambda^A K_A{}^i$$
$$\delta A_\mu^A = \partial_\mu \Lambda^A + f^A{}_{BC}A_\mu^B\Lambda^C$$
The parameters $\Lambda^A$ are arbitrary functions of spacetime. This is all from the book by Cecotti entitled "Supersymmetric Field Theories". For an excerpt click here.
Now, the author states
$$\label{eq:A}\delta D_\mu\phi^i = \Lambda^A(\partial_j K_A^i)D_\mu\phi^j + A_\mu^B\Lambda^C[K_B{}^j\partial_j K_C^i-K_C{}^i\partial_j K_B{}^i]-f_{BC}{}^A A_\mu^B \Lambda^C K_A^i = \Lambda^A(\partial_j K_A^i)D_\mu\phi^j \qquad \text{(#)}$$
I do not understand how this equation (the first equality) has been arrived at.
If spacetime is denoted by $\Sigma$ and labeled by coordinates $x^\mu$, and target space (the space where $\phi^i$'s live) is denoted by $\mathcal{M}$ (so the index $i$ labels coordinates of $\mathcal{M}$, i.e. the fields $\phi^i$), then my understanding is that $\delta\phi^i = \Lambda^A K_A^i$ is a diffeomorphism on target space, and I would expect
$$\delta K_A^i(\phi) \stackrel{?}{=} \Lambda^B \partial_B K^j \partial_j K_A^i - \partial_j(\Lambda^B K_B^i)K_A^j = \Lambda^B (f_{BA}{}^C K_C{}^i) - (\partial_j \Lambda^B)K_B^i K_A^j$$
where we can take $\partial_j \Lambda^B = 0$ because $\Lambda^B$ (as a Lie-algebra valued parameter) is not a function of $\phi^i$'s.
In the book by Cecotti, the transformation law for $K_A^i$ is not given. However, in a book by Tomás Ortín entitled "Gravity and Strings" (for an excerpt, click here), the transformation law for $K_A^i$ is (see Appendix J, equation J.8 if you wish to refer to the book)
$$\delta K_A{}^i = \Lambda^B K_B{}^j \partial_j K_A{}^i$$
which is just the first term (the ``transport term'') of what I wrote above.
My first question is: why doesn't the transformation law for $K_A{}^i$ contain a derivative of the transformation parameter, given that the transformation parameter is local (in target space) since $K_A{}^i$ depends in general on the fields $\phi^1, \ldots, \phi^N$?
My second question is is related to the actual derivation of equation (#): I did the naive thing of writing
$$\delta D_\mu\phi^i = \delta(\partial_\mu \phi^i - A_\mu^A K_A{}^i)$$
and then taking the $\delta$ in, using the transformation laws of $\phi^i$, $A_\mu^A$ and $K_A{}^i$. I expected to get (#) but I don't even get the first term this way. What am I doing wrong?

A: The key is to look at the transformation of $\partial_\mu\phi^i$ first:
$$\delta(\partial_\mu\phi^i) = (\partial_\mu\Lambda^A)K_A{}^i + \Lambda^A(\partial_\mu K_A{}^i) = (\partial_\mu\Lambda^A)K_A{}^i + \Lambda^A(\partial_j K_A{}^i)(\partial_\mu\phi^j) $$
where, in going from the first equality to the second, we have made use of the fact that $\phi^i: \Sigma \rightarrow \mathcal{M}$ is a map from $x^\mu$ to $\phi^i$ so one can write
$$\partial_\mu K_A{}^i(\phi) = \frac{\partial \phi^j}{\partial x^\mu}\partial_j K_A{}^i$$
since this is just like a "coordinate" transformation and this is just the chain rule to write spacetime derivatives in terms of target space derivatives.
The first term in $\delta(\partial_\mu\phi^i)$ has a $\partial_\mu \Lambda^A$ which is generically nonvanishing since the gauge parameter $\Lambda^A$ is local (i.e. a function of $x^\mu$). But if this term were not present, one would have the expected transformation of a target space vector (as this is just a target space diffeomorphism). So, we want a covariant derivative $D_\mu\phi^i$ with the property that
$$\delta(D_\mu\phi^i) = \Lambda^A(\partial_j K_A{}^i)D_\mu\phi^j$$
Now we can either accept this (as the definition of how a covariant derivative must transform) to figure out the transformation law that $K_A{}^i$ must obey. OR we can note that $K_A{}^i$ has a target space vector index $i$ so it must transform as a target space vector under a target space diffeomorphism, i.e. as
$$\delta K_A{}^i = \Lambda^B K_B{}^j\partial_j K_A{}^i$$
which has the form of derivative of the parameter times the vector. Note that the vector index in this setting is $j$.


text:
Q: Horizontal Pod Autoscale I install kubernetes on 4 CentOS node. 1 master and three worker.after that i want to autoscale my pod .as i know heapster is deprecated so i install metric server
git clone https://github.com/kubernetes-incubator/metrics-server.git
[root@ip-10-0-1-91 1.8+]# kubectl apply -f aggregated-metrics-reader.yaml
clusterrole.rbac.authorization.k8s.io/system:aggregated-metrics-reader created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f auth-reader.yaml
rolebinding.rbac.authorization.k8s.io/metrics-server-auth-reader created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f auth-delegator.yaml
clusterrolebinding.rbac.authorization.k8s.io/metrics-server:system:auth-delegator created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f metrics-apiservice.yaml
apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f resource-reader.yaml
clusterrole.rbac.authorization.k8s.io/system:metrics-server created
clusterrolebinding.rbac.authorization.k8s.io/system:metrics-server created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f metrics-server-deployment.yaml
serviceaccount/metrics-server created
deployment.extensions/metrics-server created
[root@ip-10-0-1-91 1.8+]# kubectl apply -f metrics-server-service.yaml
service/metrics-server created

but when i get log of metrics-server i get this
kubectl -n kube-system logs metrics-server-55d46868d4-9649g
I0327 07:53:03.900200       1 serving.go:273] Generated self-signed cert (apiserver.local.config/certificates/apiserver.crt, apiserver.local.config/certificates/apiserver.key)
W0327 07:53:34.327373       1 authentication.go:245] Unable to get configmap/extension-apiserver-authentication in kube-system.  Usually fixed by 'kubectl create rolebinding -n kube-system ROLE_NAME --role=extension-apiserver-authentication-reader --serviceaccount=YOUR_NS:YOUR_SA'
Error: Get https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication: dial tcp 10.96.0.1:443: i/o timeout
Usage:
   [flags]

and the kube-apiserver has this log
http: TLS handshake error from 192.168.122.29:41366: remote error: tls: bad certificate

A: The issue with your setup is it can't connect to kubelet. You need to change the metrics-server-deployment.yaml file in deploy/1.8+ folder
In containers section, you need to allow insecure-tls. Please add the following section:
containers:
   - command:
     - /metrics-server
     - --metric-resolution=30s
     - --kubelet-insecure-tls
     - --kubelet-preferred-address-types=InternalIP

Following is full metrics-server-deployment.yaml file, you can replace the full file with following:
apiVersion: v1
 kind: ServiceAccount
 metadata:
   name: metrics-server
   namespace: kube-system
 ---
 apiVersion: extensions/v1beta1
 kind: Deployment
 metadata:
   name: metrics-server
   namespace: kube-system
   labels:
     k8s-app: metrics-server
 spec:
   selector:
     matchLabels:
       k8s-app: metrics-server
   template:
     metadata:
       name: metrics-server
       labels:
         k8s-app: metrics-server
     spec:
       serviceAccountName: metrics-server
       volumes:
       # mount in tmp so we can safely use from-scratch images and/or read-only containers
       - name: tmp-dir
         emptyDir: {}
       containers:
       - command:
         - /metrics-server
         - --metric-resolution=30s
         - --kubelet-insecure-tls
         - --kubelet-preferred-address-types=InternalIP
         name: metrics-server
         image: k8s.gcr.io/metrics-server-amd64:v0.3.1
         imagePullPolicy: Always
         volumeMounts:
         - name: tmp-dir
           mountPath: /tmp

Now create the metrics-server-deployment again with the new file and it should work.


text:
Q: VB.net autofill form using webkit.net I've been trying to fill out web forms automatically using a custom made vb.net application, which has been working out perfectly fine for me.
When I went to try to do the same thing with a different website, which only supports IE9+, Chrome and Firefox, it suddenly became an issue. I then tried to download webkit.net, but was then struck by a new issue. The code that used to work using the default vb.net browser, doesn't work with the webkit.net browser.
VB.Net browser autofill form code
            Dim Elements As HtmlElementCollection = Browser.Document.All
            Browser.Document.GetElementById("user").SetAttribute("value", Username)
            Browser.Document.GetElementById("pass").SetAttribute("value", Password)
            Browser.Document.GetElementById("submit").InvokeMember("click")

I am hit by the following errors:
1. 'All' is not a member of 'WebKit.DOM.Document'.
2. 'InvokeMember' is not a member of 'WebKit.DOM.Element'.


text:
Q: How to unit test MVC classes? I'm new to unit testing in general, but wanted to implement it in MVC pattern (using PHP). Now I'm not sure how to approach this.
Should unit testing be built into the framework, or we just create a new folder called tests and include all necessary classes and unit test each one ?
In short, if there is a model M, it also has some coupling with the framework itself. So to test the model, should I include some portions of the framework in the unit tests ?
Are there some good code examples on how to go about accomplishing this.

A:
Should unit testing be built into the
  framework, or we just create a new
  folder called tests

If you're using a third party framework, it will usually include some unit testing helpers, but you'll want to put your own test classes into a separate folder so that (for example) you can roll a release of your software for distribution that does not include them.

include all necessary classes and unit test each one ?

You'll generally have one test class per application class. So, if you have a model class M, you'll have a test class M_Test (or whatever naming convention you adopt.)
If you're not already familiar with PHPUnit, you'll want to grab it and read their docs.

A:
Should unit testing be built into the framework, or we just create a new folder called tests and include all necessary classes and unit test each one ?

You should definitely create a separate folder for it. Cluttering up production code with tests is generally not a good idea for performance and debugging reasons.

So to test the model, should I include some portions of the framework in the unit tests ?

The least the better. Unit tests should require little to no dependencies. If class A depends on B, you should mock B to ensure that if B fails, it doesn't make A fail too.
The main advantage to unit tests (when done correctly) is that it allows you to easily pinpoint the problem. If A fails because of its B dependency, you will first look at A, then B. Again, if B depends on C and C fails, you will have to look into A, B and then C. This pretty much ruins one of the greatest advantage to unit testing. If all tests are done properly, a failure in C will not cause a failure anywhere else than in C, so you will have a single class to lookup to fix the problem.
To really make your code error-proof, you can use unit tests in conjunction with PHP assertions:
$return = $this->addOne($some_param);
assert('$return == $some_param + 1');

By the way, there is no difference between unit testing MVC as opposed to unit testing in general.

A: Unit testing should be part of the MVC framework. For example have a look at the Unit Testing Class chapter of the CodeIgniter user guide.


text:
Q: How to use on_message using discord.py in this way? I'm making a bot using discord.py. I want the bot to get triggered if a message from any user(on the server where the bot is present) is a mixture of Integers, Characters and Strings like this e.g 122-PG-CSAI-2022
How can I do so?

A: I'm not sure what you think the difference is between a char and string in this case, but this code will check if it contains at least one alphabetical letter and one int:
on_message(message):
    has_number = any(char.isdigit() for char in message.content)
    has_non_number = any(char.islapha() for char in message.content)

    if has_number and has_non_number:
        # do something

edit:
on_message(message):
    splits = message.content.split("-")

    # it's not in the wanted format
    if len(splits) != 4:
        # return or something else

    cont = True

    # check if first is a number within range <1, 999>
    try:
        if int(splits[0]) <= 0 and int(splits[0] >= 1000:
            cont = False
    except ValueError:
        cont = False

    # check if second is one of the options
    if splits[1] not in ["UG", "PG", "D"]:
        cont = False

    # check if third is one of the options
    if splits[2] not in ["some", "options", "here"]:
        cont = False

    # check if fourth is a number from range <2022 ...>
    try:
        if int(splits[3]) < 2022:
            cont = False
    except ValueError:
        cont = False

    # it fits all the criteria
    if cont:
        # do stuff

A: By Integers, Characters, and Strings, I assume you mean no special characters (i.e. @, !, *, &, etc.) If so, this works:
on_message(message):
    for char in message.content:
       if not char.isdigit() and not char.isalpha(): return False
    #trigger bot here


text:
Q: How exactly would you prove this? Would this just be the points on the boundaries between $U$ and $\mathbb{R}^n - U$? since any radius greater than $0$ would result in a ball including both $U$ and $\mathbb{R}^n - U$?

A: HINT: Show that $C=(\operatorname{cl}U)\cap\operatorname{cl}(\Bbb R^n\setminus U$), and use the fact that the intersection of two closed sets is closed. (And yes, this set is the boundary of both $U$ and $\Bbb R^n\setminus U$.)

A: Take $b$ in the closure of $C$; we want to see that $b\in C$.
Take an open neighborhood $V$ of $b$; then there exists $a\in C$ such that $a\in V$. Take an open neighborhood $W$ of $a$ such that $W\subseteq V$. Then $W$ intersects both $U$ and $\mathbb{R}^n\setminus U$, and therefore also $V$ does.
You can use open balls, if you prefer, but it just adds complications. This proof holds in every topological space.