text:
Q: ListView does not show text from a text file I have a listview on an activity where I want to display information I read from a text file. This is the code for the said activity (class):
public class ViewData extends AppCompatActivity {

    //code to show strings from file
    private ArrayList<String>  readFromFile(Context context) {

        ArrayList<String> receiveString=new ArrayList<String>(  );

        try {
            InputStream inputStream = context.openFileInput(AddDataActivity.FileName);

            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
               String tempString="";
                while ((tempString=bufferedReader.readLine()) != null) {

                    receiveString.add(tempString);
                }

                inputStream.close();

            }
        } catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }

        return receiveString;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_data);
        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();
            }
        });

        ListView listView=(ListView)findViewById(R.id.listView);

        // Define a new Adapter
        // First parameter - Context
        // Second parameter - Layout for the row
        // Third parameter - ID of the TextView to which the data is written
        // Forth - the Array of data

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,readFromFile(getApplicationContext()));

        // Assign adapter to ListView
        listView.setAdapter(adapter);

        // ListView Item Click Listener
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                                    int position, long id) {
//
//                // ListView Clicked item index
//                int itemPosition     = position;
//
//                // ListView Clicked item value
//                String  itemValue    = (String) listView.getItemAtPosition(position);
//
//                // Show Alert
//                Toast.makeText(getApplicationContext(),
//                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
//                        .show();
//
//            }
//
//        });

    }

}

I have a menu button that is supposed to trigger this activity (start it) and in onCreate, I want to read from file and display the text contents I have saved to a file in another activity. However, I am currently seeing the following result, which seems always the same no matter what changes are saved to the text file mentioned:

This is the content view for my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="mhd.myupliftingmate.ViewData"
    tools:showIn="@layout/activity_view_data">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

And this is my Main Menu layout where the activity ViewData is called:
<menu 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"
    tools:context="mhd.myupliftingmate.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        android:icon="@drawable/settings"
        app:showAsAction="ifRoom"
        />
    <item app:showAsAction="ifRoom"
        android:orderInCategory="101"
        android:title="Add Data"
        android:id="@+id/action_addData"
        android:onClick="openAddActivity"
        android:icon="@drawable/input"
/>
    <item
        android:orderInCategory="102"
        android:title="View Data"
        android:id="@+id/action_viewData"
        android:onClick="openViewActivity"
        android:icon="@drawable/text"
        app:showAsAction="ifRoom"
/>

</menu>

I am also adding the file-writing code, in case there might be a problem with that.
public class AddDataActivity extends AppCompatActivity {

    public static final String FileName="data.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_data);
        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();
            }
        });
    }

    public void saveToFile(View view) {
//        private void writeToFile(String data,Context context) {
        Context context=getApplicationContext();
        View userText=(EditText) findViewById(R.id.userText);
        String inputString=userText.toString();
            try {
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(FileName, Context.MODE_PRIVATE));
                outputStreamWriter.write(inputString);
                outputStreamWriter.close();
            }
            catch (IOException e) {
                Log.e("Exception", "File write failed: " + e.toString());
            }
        }

}

I do not know if I need to implement my version of ArrayAdapter. I actually do not completely understand how it and its parameters work.

A: Change
       String inputString=userText.toString();

to
       String inputString=userText.getText().toString();


text:
Q: If $E$ is the Splitting Field for an Irreducible Separable Polynomial over $F$ then $[E:F]=\text{Aut}(E:F)$ $\DeclareMathOperator{\aut}{Aut}$ $\newcommand{\vp}{\varphi}$Let $p(x)$ be an irreducible and separable polynomial over a field $F$ and let $E$ be the splitting field for $p(x)$ over $F$.

Question. Is is true that $[E:F]=|\aut(E:F)|$?

I think the answer to this question is YES. Here is my argument for thinking so.
Say $\deg p=n$ and let $a_1, \ldots, a_n$ be all the roots of $p$ in $E$. Write $F_i$ to denote $F(a_1, \ldots, a_i)$. We claim that each $F$-embedding of $F_i$ in $E$ admits exactly $[F_{i+1}:F_i]$ extensions to an embedding of $F_{i+1}$ into $E$.
Suppose $\vp:F_i\to E$ be an $F$-embedding of $F_i$ in $E$ and let $d_i=[F_{i+1}:F_i]$. We need to show that there are exactly $d_i$ different extensions of $\vp$ to an embedding of $F_{i+1}$ into $E$. Let $p_i(x)\in F_i[x]$ be the minimal polynomial of $a_i$ over $F_i$. Since $p_i$ and $p$ both have $a_{i+1}$ has a root, we have $p_i|p$ and therefore $p_i$ has $d_i$ distinct roots in $E$. Now we may extend $\vp$ to $F_{i+1}$ by sending $a_{i+1}$ to any root of $p_i$ we wish. Further, all extensions of $\vp$ send $a_{i+1}$ to some root of $p_i$. Lastly, any extension of $\vp$ is determined completely by its action on $a_{i+1}$. Therefore there are precisely $d_i=[F_{i+1}:F_i]$ different extensions of $\vp$ to $F_{i+1}$. This proves our claim.
From the claim, we see that there are at least $[F_n:F_{n-1}]\cdots [F_1:F]=[E:F]$ distinct elements in $\aut(E:F)$. There cannot be any more and thus we are done.

A: I don't see anything wrong with your proof except for the last paragraph, for which I'm not sure what you mean. Prior to that you have already established that, at each step of adjoining a root of $p$, the number of extensions of an embedding is exactly the degree of the field extension. From this alone we can see that the total number of embeddings fixing $F$ is just the product of these degrees, because any embedding is in a 1-to-1 correspondence with the sequence of its restrictions to the chain of field extensions.
I may be mistaken but I do not see any other more obvious reason why $[E:F]$ is an upper bound on $\#(Aut(E:F))$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Joda Time subtracting 24 hours from an instance of MutableDateTime, I would like to know why I do not understand why MutableDateTime.setDate() is setting the time to "yesterday" (see the log timestamp hours - it is 20:28).  Is this timezone related?  Do I need to set something on the formatter?
I would expect that after calling setDate with "10/27/2010", the date would be the same as the parsed date 00:00 EDT 10/27/10, instead of 20:28 EDT 10/26/10.  This is 24 hours ago from "now".
What am I missing here, or how should I edit the code to get the desired result?  I am new to Joda Time, and would like to solve this mystery.
DateTimeFormatter dateFormatterJ = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTimeFormatter timestampFormatJ = DateTimeFormat.forPattern("HH:mm zzz MM/dd/yy");

MutableDateTime startDate = new MutableDateTime();

log.info("parsed date " +
    timestampFormatJ.print(dateFormatterJ.parseMutableDateTime(startDateString)));

startDate.setDate((dateFormatterJ.parseMutableDateTime(startDateString)));

log.info("startDate: " + timestampFormatJ.print(startDate));

In this case, startDateString is simply "10/27/2010".
here is the log output:
10-27 20:28:55 INFO parsed date: 00:00 EDT 10/27/10
10-27 20:28:55 INFO startDate: 20:28 EDT 10/26/10

Thanks

A: The simple answer would be, because the javadoc says so.

public void setDate(ReadableInstant
instant)
Set the date from another
instant. The time part of this object
will be unaffected.
Parameters:
instant - an instant to copy the date
from, time part ignored
Throws:
IllegalArgumentException - if the
object is invalidobject is invalid

When Joda says 'Date' it means the human meaning of the word Date. "The year-month-day portion of this value",  not the logical equivalent of a java.util.Date.  (the whole point of joda being to introduce some natural, sensible, semantics to handling date and time.)
EDIT:
To answer your 'how to fix' question, simply do:
MutableDateTime startDate = new MutableDateTime(dateFormatterJ.parseMutableDateTime(startDateString));

Or else manually zero out the time portions of course.
EDIT 2: Hmm, I apparently did not read carefully enough, this is only half of the answer.  Will check.
EDIT 3: well this bugged me so much that I took a minute to look for it.
public void setDate(final ReadableInstant instant) {
    long instantMillis = DateTimeUtils.getInstantMillis(instant);
    Chronology instantChrono = DateTimeUtils.getInstantChronology(instant);
    DateTimeZone zone = instantChrono.getZone();
    if (zone != null) {
        instantMillis = zone.getMillisKeepLocal(**DateTimeZone.UTC**, instantMillis);
    }
    setDate(instantMillis);
}

For some reason, it's rolling your absolute time forward into UTC before setting the date.  So you give it 10/27/2010 00:00 EDT and it sets the absolute magnitude of time to the number of milliseconds that represent 10/27/2010 00:00 UTC, which of course is only 6 or 7 PM the day before.  Then it finds the EDT date value of that to be 10/26.
Couldn't say if that's somehow intended or if it's a bug that's been there for 2 years or what.)

A: When parsing a string that does not contain a GMT offset or time-zone ID, you must do one of three things:

*

*do nothing, and accept that the string is parsed in the default time zone

*specify the time zone to parse in using withZone() on the formatter

*use parseLocalDate() instead of parseMutableDateTime()
The last is the preferred solution, as it correctly parses the data that was actually input, which was a date without time, offset or zone.
Using parseLocalDate() in the test code correctly parses the date.


text:
Q: jQuery construct dynamic html tags Can I not simply create a variable containing HTML constructed with variables?

I've also tried using templates with no luck.
var x = [
    "",
        "<asp:RadioButton ID='" + yesButton  +"' runat='server'>",
    ""
].join("\n");

Both attempts don't like the + yesButton + code.
I'm trying to attach dynamic html after a tag.


text:
Q: Sort array middle to low to high I have a list of points which I first sort ascending on the x value. Now I'd like to sort the list again based on the y-value but from middle to low to high (or middle to high to low, doesn't really matter).
This is my java code:
Collections.sort(list, Comparator.comparing((Integer[] p) -> p[0]).thenComparing(**"middle to low to high"**));

For example:
Initial list: {(10,9),(11,8),(10,5),(10,7),(8,9),(11,9)}
First sorting: {(8,9),(10,9),(10,5),(10,7),(11,8),(11,9)}
Second sorting:  {(8,9),(10,7),(10,5),(10,9),(11,8),(11,9)} this is where  I need help
Is there a way to write a comparator for this?
Thank you!

A: Rather than trying a new Comparator, change the numbers. Say your interval is (0..12), middle is 7, then the easiest way is to change all values >7 to v-13, sort the result and change back by adding 13 to all negative values.


text:
Q: How Collection copy function works in java I am trying to understand how Java Generic works. Here is the problems.
  public static void main(String args[]){

    List<Object> obj = Arrays.<Object>asList(23,"456",56.89);
    List<Integer> intb = new ArrayList<>();
    intb.add(234);
    intb.add(345);
    Collections.copy(obj,intb);
    for(Object d : obj){
        System.out.println(d);
    }

   }

This will work fine.But I implemented my own copy function like this
   public static <T> void copy(List<? super T> des,List<? extends T> scr){
    for(T f : scr){
        des.add(f);
    }
  }

Then I used copy(obj,intb) instead of Collections.copy(obj,intb). Then I am getting errors. I don't understand why,But I know "? extends T" means  any type that is a subtype of T and "? super T" means any type that is a supertype of T.

A: You cannot add anything to this fixed-length list:
List<Object> obj = Arrays.<Object>asList(23,"456",56.89);

You can only set new values to its elements (which is what Collections.copy() does). See also the Javadoc:

Returns a fixed-size list backed by the specified array.

What you probably intended to do was this:
List<Object> obj = new ArrayList<>(Arrays.asList(23,"456",56.89));

A: Well, a little bit late, but why your compiler complained about your code is not only because you used a fixed-size (immutable) List as a parameter in your copy method.
List<Object> obj = Arrays.<Object>asList(23, "456", 56.89);
Collections.copy(obj, intb);

It is also because of your (copy) method declaration.
public static <T> void copy(List<? super T> des,List<? extends T> scr) {

The declaration above has two lists with wildcards. When you use wildcard type <?>, you give message to the compiler that you are ignoring the type information. Whenever you pass arguments to a generic type, the java compiler tries to infer the type of the passed argument as well as the type of the generics and to justify the type safety. Now,(in your copy method) you are trying to use the add() method to insert an element in the list. Since des(your destination list) doesn't know the exact type of object it holds, it is risky to add elements to it. Generics was introduced in the language to ensure type safety in the first place. So you can not use methods like add that modifies the object. I hope the default implementation of the copy method in the java.util.Collections will help clarify it.
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
        int srcSize = src.size();
        if (srcSize > dest.size())
            throw new IndexOutOfBoundsException("Source does not fit in dest");

        if (srcSize < COPY_THRESHOLD ||
            (src instanceof RandomAccess && dest instanceof RandomAccess)) {
            for (int i=0; i<srcSize; i++)
                dest.set(i, src.get(i));
        } else {
            ListIterator<? super T> di=dest.listIterator();
            ListIterator<? extends T> si=src.listIterator();
            for (int i=0; i<srcSize; i++) {
                di.next();
                di.set(si.next());
            }
        }
    }

I know there already exists the same code block, but there was no explanation for what is the reason behind why we can't use methods like add on Lists with wildcards, and that is mainly to protect type safety.

A: In copy method
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
        int srcSize = src.size();
        if (srcSize > dest.size())
            throw new IndexOutOfBoundsException("Source does not fit in dest");

        if (srcSize < COPY_THRESHOLD ||
            (src instanceof RandomAccess && dest instanceof RandomAccess)) {
            for (int i=0; i<srcSize; i++)
                dest.set(i, src.get(i));
        } else {
            ListIterator<? super T> di=dest.listIterator();
            ListIterator<? extends T> si=src.listIterator();
            for (int i=0; i<srcSize; i++) {
                di.next();
                di.set(si.next());
            }
        }
    }

copy replace the value with index from index 0.
 public static <T> void copy(List<? super T> des,List<? extends T> scr){
    for(T f : scr){
        des.add(f);
    }
  }

in this approach add into tail.


text:
Q: issues with accessing the additional options from an {{action}} In pre4, I should be able to access additional parameters provided in {{action}}. Such as the value for field in this example:
{{action doSomething field="value" on="someEvent"}}

If I try and retrieve hash.field, nothing is returned. None of the variables that should contain information, do (options, contexts, hash, view).
Am I missing something?

A:
In pre4, I should be able to access additional parameters provided in {{action}}

True in pre4 you may specify additional parameters to the {{action}} helper. The action helper is not expecting these parameters to be in it's options hash. Key-value pairs like field="value and on="someEvent" are interpreted as options for the action helper itself and not passed along to the target.

If I try and retrieve hash.field, nothing is returned. None of the variables that should contain information, do (options, contexts, hash, view)

In your example above you are calling the action helper with event doSomething and no parameters, so it makes sense that nothing would be set. Try something like this instead:
{{action doSomething value on="someEvent"}}


text:
Q: Meaning of ordering of existential and universal quantifiers Consider the predicate L, such that L(x,y) = "x loves y"
I'm not sure about how the meaning of the predicates change by swapping the order of variables and quantifiers. I've done my best to interpret the following statements. Can someone please let me know if my interpretation is correct?

*

*∀x$\exists$y L(x,y) = For all people x, the following is true: There exists some person y where x loves y. In plain English, this means that "every person has some person out there that they love." (They do not have to be the same person).

*$\exists$x∀y L(x,y) = There exists some person x, such that for all y, x loves y. In plain English, this means that "some single person loves each and every person in some group of people".

*∀y$\exists$x L(x,y) = For all people y, the following is true: There exists some person x, where x loves all y. In plain English, this means that "each and every person in a group of people is loved by some single person".

*$\exists$y∀x L(x,y) = There exists some person y, such that all people x love y. In plain English, this means that "some single person is loved by each and every person in a group of people".
If my interpretation is correct, the I'm noticing a few things. Can someone also let me know if these statements are correct?

*

*The key difference between statements 1 and 4 is that in statement 1, all the people in x each love a potentially different person y. However, in statement 4, a single person that exists, person y, is loved by all the people in x.

*The key difference between statements 2 and 3 is the subject and the "phrasing", although they are essentially saying the same thing. In statement 2, the subject is a single person x, who loves all the people in y. In statement 3, the subject is a group of people y, who are all loved by a single person x.
Thanks for the help. This concept is quite confusing to me, and I want to make sure that I am understanding it correctly.

A: One by one:

*

*Yes: Everyone loves somebody (not the same somebody for everyone!)

*Yes: This is "there's someone (x) who loves everybody (y)".

*No: Everyone (y) is loved by somebody (x).

*Yes: This is "somebody (y) is loved by everyone (x)", or "there is somebody (y) whom everybody (x) loves".


text:
Q: How to do bulk insertion in square sqldelight? Thanks square for SQLDelight and providing  typesafe api's for sqlite db interactions. I am doing single insert row as below:
      MyTable.Insert_row insert_row =
    new MyTableModel.Insert_row(
      mOpenHelper.getWritableDatabase(),
      MyTable.FACTORY
    );
  MyTable.bind(insert_row, data);
  insert_row.program.executeInsert();

Is there a way to perform bulk insertion for list of data at once ?

A: Kind of. Theres two approaches. Since SQLite 3.7.11 (included in Android API 16 and above) you can insert multiple values at once from the sqlite side:
INSERT INTO myTable
VALUES (?, ?), (?, ?), (?, ?);

which is probably not what you want. As long as you are only creating the insert statement once, binding and executing multiple rows is actually really fast:
MyTable.Insert_row insert_row =
    new MyTableModel.Insert_row(
      mOpenHelper.getWritableDatabase(),
      MyTable.FACTORY
    );
for (Row row : rows) {
  MyTable.bind(insert_row, row);
  insert_row.program.executeInsert();
}

which is probably closer to what you want. At the moment there's no planned support of arbitrary-sized bulk inserts from the .sq file side.


text:
Q: Using SetParent to steal the main window of another process but keeping the message loops separate Background: My coworker and I are maintaining a million-line legacy application we inherited.  Its frontend is written in VB6, and as we're devoting almost all of our resources to converting it to C#, we are looking for quick & dirty solutions to our specific problem.
The application behaves in a plugin-ish manner.  There are up to 20ish separate ActiveX controls that can be loaded at once in a grid-style layout.  The problem is that the ActiveX controls do all of their processing on their own UI thread, and as a lot of it is blocking waiting on network access, the UI gets very soupy.  When our hosting C# app loads these controls, it becomes unresponsive because of how many controls are chewing up UI resources doing nothing.  To top it off, the controls are fragile and will crash at the slightest provocation.  When they are hosted in the main C# app, it creates serious instability.
The best my coworker and I have come up with so far is starting a process per ActiveX control.  This process, which we call the proxy, is another winforms app.  It uses named pipes to communicate with the hosting process.  The hosting process creates a window, loads an ActiveX control of our choice (via some reflections & AxHost magic), and tells the main process what its window handle is via the named pipe.  The main process uses a combination of SetParent, and SetWindowPos to move the proxy application into itself to emulate a plugin.  Size updates are sent via the named pipe.
This works well enough until the ActiveX application does some sort of lengthy process and we click around on the main window while it's working.  For awhile the main window is responsive, but eventually it becomes unresponsive as the child window waits for its UI thread.  How can we keep the child windows on their own complete thread while still getting the benefits of SetParent?
(please let me know if anything isn't clear!)

A: I've done this before. It gets messy.
We were running every plugin in its own AppDomain, which started up its own UI thread. We did this after running into lots of really nasty issues when we didn't use different UI threads.
It does mean that you have all the pain of communicating across AppDomains, but it's feasible. The main thing is that you'll need to run Application.Run in each AppDomain/plugin. Communicate between them with a huge amount of care - even shutting down is tricky.
Good luck :)


text:
Q: What is the best estimate known for the upper bound for the difference between consecutive primes? Bertrand's Postulate gives us that:
$$p_n < p_{n+1} < 2p_n$$
So that:
$$p_{n+1} - p_n < p_n$$
In this answer, this paper is cited which says in Prop 6.8 that:

For $x \ge 396738$ there is always a prime in the interval $[x, x + x/(25\ln^2 x)]$

Is this the best upper bound known for consecutive primes?
If I understand it correctly, does it mean that:
$$p_{n+1} - p_n < \frac{p_n}{25\ln^2 p_n}$$

A: The best result is a result of Baker, Harman and Pintz (Baker, R. C.; Harman, G.; Pintz, J. (2001) "The difference between consecutive primes, II". Proceedings of the London Mathematical Society 83 (3): 532–562) which states that $$p_{n+1}-p_{n}<p_{n}^{\theta}$$
 with $\theta=0.525$
  and a sufficiently large $n.$


text:
Q: Is it possible to convert a .so compiled for Android into an .so for ubuntu without having the source code? I've got an library compiled for android, and I would like to use some of its functions on ubuntu.
Is this possible, and if it is, how can I do this?
I don't have the source code.

A: Cannot do.... unless you are running Ubuntu and Android on the same platform (same processor architecture at the bare minimum)

A: The answer is no since ARM binaries are different to x86 binaries in terms of instruction sets. And thusly incompatible with each other.


text:
Q: ID3DX11Texture2D pixel data I'm trying to get the back buffer pixel data in DX11 in order to save it to a file.
Is there any way to get the pixel data of a ID3D11Texture2D without having to create a view for it and then get the resource from the view ?
Thanks.

A: You can lock the texture and then copy from it.  However, the bits coming back may be implementation-dependent.  Also, not every GPU allows you to mess with the back buffers, especially if things like FSAA is on...
In these cases, for dynamic screen-shots, you usually create a RenderTarget surface and then render into it.

A: I found what I need: ID3D11DeviceContext::CopyResource.


text:
Q: Resizing label in Windows Forms application I have a Windows Forms application which contains a couple of labels, a button and a combobox all wrapper inside a Panel.
this.pnlSuboptions.Controls.Add(this.label1);
this.pnlSuboptions.Controls.Add(this.cboPtSize);
this.pnlSuboptions.Controls.Add(this.label2);
this.pnlSuboptions.Controls.Add(this.btnSelect);

I facing an issue with my labels when I try loading localized strings for my labels. The localized strings for some languages are larger than the English strings. In such cases, a part of the label gets hidden under the combo box or the button.
I want the label to increase in size towards the left instead of right. I've set my labels' AutoSize property to true and also played around with the Anchor property but nothing seems to work.
I found an SO link which contains a solution to this problem when the label text changes but I'm sure how I can apply this in my scenario where the label is read only once during the form load.
Any suggestions?

A: You could put them into a TableLayoutPanel with 2 columns and two rows. Each label goes in left side of each row and both combo box/buttons goes in the others cells (right side of each row).
Then you must dock both elements (Dock Fill) and set the columns to AutoSize. (As you can see in the image)

You also may want to dock the TablePanelLayout to your common panel.
As you can see in the image below, both TablePanelLayout have the same components. But in the secoend I just changed the label3's text.

Hope it helps. (Also sorry for my bad english, it isn't my native language. Please feel free to correct any wrong spelling, thanks!)

A: First suggestion from me would be:

*

*set the AutoSize property to False

*Make sure that the width is alot larger than it needs to be by resizing the label.

*The label should now fit nicely regardless of what content it receive.

Second suggestion, you can use the GDI+ to determine the size of the text and then resize the label accordingly See http://msdn.microsoft.com/en-us/library/6xe5hazb(v=vs.110).aspx
Graphics gfx = this.label1.CreateGraphics(); // I think its called that, cant remember :)

Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = gfx.MeasureString(this.label1.Text, stringFont);
this.label1.Size = new Size((int)stringSize.Width, (int)stringSize.Height);

Oh yeah I almost forgot. Make sure that you're panel is not the cause of the clipping. I mean, check if the panel is large enough for the labels to fit :-)
Hope this helps!
Best regards,
Zerratar


text:
Q: why does system send RST flag when try - TCP 3 way handshake in python i wanna create a TCP-3 way handshake in my ubuntu.
i used a kali linux in a virtual machine. and in terminal of kali linux(IP- 172.16.28.130) i opened a port in "LISTEN " mode to get a connection with that machine.
nc -l -p 1025

my python code which ran in ubuntu host machine,
#!/usr/bin/python
from scapy.all import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

#if i send to broadcast address : 192.168.1.255 what will happen?
def sendPacket(src, dst):
   ip = IP(dst = dst)
   port = RandNum(1024, 65535)
   SYN = ip / TCP(sport=port, dport=1025, flags="S", seq = 42)
   SYNACK = sr1(SYN, verbose=0)

   ACK = ip / TCP(sport = SYNACK.dport, dport=80, flags="A", seq = SYNACK.ack, ack = SYNACK.seq + 1)
   send(ACK)

   print "Done!!\n"

src = '1.2.3.4'
dst = '172.16.28.130'
sendPacket(src, dst)

the packets capture using wireshark,
3      172.16.28.1   172.16.28.130   TCP   54   64865 > blackjack [SYN] Seq=0 Win=8192 Len=0

4      172.16.28.130   172.16.28.1   TCP   60   blackjack > 64865 [SYN, ACK] Seq=0 Ack=1 Win=29200 Len=0 MSS=1460

7      172.16.28.1   172.16.28.130   TCP   54   64865 > blackjack [RST] Seq=1 Win=0 Len=0

8      172.16.28.1   172.16.28.130   TCP   54   64865 > http [ACK] Seq=1 Ack=1 Win=8192 Len=0

9      172.16.28.130   172.16.28.1   TCP   60   http > 64865 [RST] Seq=1 Win=0 Len=0

before ran the code, i changed IPtable,
iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 192.168.1.20 -j DROP

when i changed the destination to , dst = "www.google.com" and destination port to, dport=80 it was working fine.
but now,
1) i could send SYN packet
2) the destination respond with SYN, ACK packets
3) my system sends RST
4) i sent ACK
5) destination system reply with RST
So i can't establish a connection!!
Questions:
1) how can i success full establish a connection
2) my source ip = "1.2.3.4",
* but when i sent to virtual machine it shows 172.16.28.1(Broadcast ip). why?

A:

1) how can i success full establish a connection

Here's a guess. Change your iptables command to:
iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 172.16.28.1 -j DROP

When you connect to google.com, you are connecting through your physical Ethernet device, which has IP 192.168.x.y, so the -s argument matches.
When you connect to Kali, you are connecting through a virtual Ethernet device which has address 172.16.x.y, so the -s doesn't match.
You need to drop the RST packets from the correct output queue.

2) my source ip = "1.2.3.4", * but when i sent to virtual machine it shows 172.16.28.1(Broadcast ip). why?

First, 172.16.28.1 is not your broadcast IP. It is the IP of your host computer's virtual Ethernet device.
The reasons why your source IP isn't appearing is that you aren't using it:
ip = IP(dst = dst)

You specify a destination address, but no source address. Some entity (scapy or the host OS IP stack, I'm not sure) is choosing a reasonable source address for you. You might try:
ip = IP(dst = dst, src = src)

and see what happens there.


text:
Q: Django - Most efficent display of list values (ForeignKey or ChoiceField) I am designing a Django model, but found myself using many ForeignKey relations, and consequently started to have slow loading times (specially inside the Admin panel).
However most of these ForeignKey relations are just to display a name field.
class Field1(models.Model):
    name = models.CharField(max_length=250)

class Field2(models.Model):
    name = models.CharField(max_length=250)

class Field3(models.Model):
    name = models.CharField(max_length=250)

...

class Main(models.Model):
    ...
    field1 = models.ForeignKey(Field1, on_delete=models.CASCADE)
    field2 = models.ForeignKey(Field2, on_delete=models.CASCADE)
    field3 = models.ForeignKey(Field3, on_delete=models.CASCADE)

I could change these fields to ChoiceField but I would hard-code the choices inside models.py (not ideal)
I imagine it would be possible to do something like this, but would it be faster/more efficient?:
class Fields(models.Model):
     name = models.CharField(max_length=250)

class ListValues(models.Model):
    type = models.ForeignKey('Fields', on_delete=models.CASCADE)
    name = models.CharField(max_length=250)

class Main(models.Model):
    ...
    field1 = models.CharField(choices=ListValues.objects.get(type__name='Field1'), on_delete=models.CASCADE)
    field2 = models.CharField(choices=ListValues.objects.get(type__name='Field2'), on_delete=models.CASCADE)
    field3 = models.CharField(choices=ListValues.objects.get(type__name='Field3'), on_delete=models.CASCADE)

Any insights would be helpful.
Thank you.

A: The select2 package can provide you with select inputs that will not render all options on page load, they provide a search like widget that perform AJAX requests to get matching options.
Specifically the ModelSelect2Widget should do what you need
class NameSearchWidget(ModelSelect2Widget):
    search_fields = [
        'name__icontains',
    ]

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('field1', 'field1', 'field1')
        widgets = {
            'field1': NameSearchWidget,
            'field2': NameSearchWidget,
            'field3': NameSearchWidget,
        }


text:
Q: UIView animation being held up on main thread I have some nested UIView animations like so:
[UIView animateWithDuration:1.0 animations:^{
    //Animation
}completion:^(BOOL success){
    [UIView animateWithDuration:1.0 animations:^{
        //More animation
    }completion:^(BOOL success){

    }];
}];

The inside animation occasionally has a delay before starting when there's other activity on the thread.
I was wondering if there was a way around this, and if GCD can be used here to run this on a background thread? It's UI code, so perhaps not.

A: If it's not too obvious an answer, a way around your problem would be:
[UIView
    animateWithDuration:1.0
    animations:^{
         //Animation
    }];
[UIView
    animateWithDuration:1.0
    delay:1.0
    options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionTransitionNone
    animations:^{
        //More animation
    }
    completion:^(BOOL success) {}];

i.e. just schedule the second animation at the same time as you schedule the first, but tell it not to start until you know the first will be finished.
Once things are scheduled, Core Animation isn't blocked by main queue activity so you can be busy a second later and the second thing will still start immediately after the first has finished.


text:
Q: Find the interior points of the following set: I can identify each element of the set $\mathbb{Q}$ $\cap$ $[0,1[$; however, I must confess that it is pretty hard for me to use the proper open ball for it. I would really appreciate your help. Have a nice day and blessings. :)

A: Let $x\in\mathbb Q\cap [0,1)$. Suppose there exists $r>0$ with $B_r(x)\subseteq\mathbb Q\cap [0,1)$. Then $y=x+r/2\in B_r(x)$. If $y$ is irrational, this is a contradiction. If $y$ is rational, there exists an irrational $z$ such that $x<z<y$ and $z\in B_r(x)$. This is also a contradiction, so $r=0$ is the only number such that $B_r(x)\subseteq\mathbb Q\cap[0,1).$ But in this case, $B_r(x)=\emptyset$. Since the interior of a set is the union of all balls which are subsets, the interior is also empty.


text:
Q: How do I generate regex for repeating pattern Good day! I am working on an interpreter of LOLCODE and I'm having a trouble in this line:
SMOOSH "A" AN "B" AN "C" AN "D"

I need to get the string literals A,B,C,D but I only got the first and the last two literals.
Here's my code:
 r = new Regex(@"(\s+)?(?<smoosh>SMOOSH)\s+(\""(?<yarn1>[^\""]+).*)\s+(\""(?<yarn2>[^\""]+).*)(\s+)?((\s+)(AN)?(\""(?<yarn3>[^\""]+).*))+(\s+)?(?<comment>BTW\s*.*\s*)?$");

I need to hold all the string literals so that i could concatenate it later.
Thanks in advance.

A: Try this:
Regex re = new Regex(@"""(.*?)""");
MatchCollection mc = re.Matches(sourcestring);
      int mIdx=0;
      foreach (Match m in mc)
       {
        for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
          {
            Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
          }
        mIdx++;
      }

You will get all literals in array.

A: You could use capturing groups.
@"""([^""]*)"""

And get the string you want from group index 1.
Regex rgx = new Regex(@"""([^""]*)""");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

OR
Use \G anchor.\G assert position at the end of the previous match or the start of the string for the first match. It grabs the values inside double quotes only on the lines which contains the string SMOOSH
@"(?:(?:\s+)?(?<smoosh>SMOOSH)\s+|(?<!^)\G) *(?:AN)* *""?([^""\n]*)""?"

Code:
String input = @"SMOOSH ""A"" AN ""B"" AN ""C"" AN ""D""";
Regex rgx = new Regex(@"(?:(?:\s+)?(?<smoosh>SMOOSH)\s+|(?<!^)\G) *(?:AN)* *""?([^""\n]*)""?");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

IDEONE


text:
Q: Why doesn't cURL work with Windows Authentication on IIS7? I am trying to access a service that is behind Windows Authentication. I thought I could pass the credentials the way HTTP Basic Authentication credentials are passed, but it's not working. When I do the following, I get a 401 error, and I am absolutely sure the password is correct.
curl --user username:password http://example.com

Why doesn't this work?

A: If you are using Windows Authentication, you need to use NTLM:
curl --ntlm --user username:password http://example.com

A: I just want to add that authorization might include several redirects and the NTLM authentication might be required for the second or subsequent requests, but not the first one. In this case the answers here won't work.
The thing is, CURL sends credentials with the first request only, while you might need them for the second one for example. To pass credentials with all the requests, use the --location-trusted option.
From CURL documentation (-L option):

When authentication is used, curl only sends its credentials to the initial host. If a redirect takes curl to a different host, it won't be able to intercept the user+password. See also --location-trusted on how to change this.

This important note helped me authorize on my company website. Hope that helps somebody else.

A: You can also leave the username and password fields empty (-u :) and curl will use your current credentials from your environment:
curl --ntlm -u : http://example.com

Per the docs (under -u, --user)

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5,
  Negotiate, NTLM or Digest authentication then you can tell curl to
  select the user name and password from your environment by specifying
  a single colon with this option: "-u :".
Kerberos-Enabled Binaries

A: I had the same issue with you, but I through adjust iis server configuration to authenticate, to enable HTTP basic or digest authentication, after done, you could use simplest authenticate, sorry for my bad English


text:
Q: User specific views MVC I've some action buttons on a page. Then in my CI controller i've functions for each
  of them like view, edit, new.   Now all these functions have this if else block. Is this how
  you do it? Other patterns?
I'm using CI with mod. extension and have many controllers under several modules with
  this kind of functions.
if(hasPermission('view_all'))
{
   $this->model->queryAll()
   $this->load->view('all_layout')
}
else if(hasPermission('view_group'))
{
   $this->model->queryGroup()
   $this->load->view('group_layout');
}
else {
   $this->model->querySingle()
   $this->load->view('single_layout');
}

A: I would have written the same code using Switch Case & little tweak in hasPermission class
  $permission = getPermission() // It wud return 1 for view_all, 2 for view_group, 3 for single layout

  switch($permission){
     case 1:
       $this->model->queryAll();
       $this->load->view('all_layout');
       break;
     case 2:
       $this->model->queryGroup();
       $this->load->view('group_layout');
       break;
     default:
       $this->model->querySingle()
       $this->load->view('single_layout');
       break;
 }

I know this code doesn't decrease number of lines, but sometimes readability is more important then LOC :) I would like to see more improvisations


text:
Q: Problem splitting a linked list into two other linked lists in c My code is supposed stores 10 int numbers in a linked list, divide these 10 numbers equally into two other linked lists. But my two lists are returning empty
My struct:
typedef struct no
{
    int value;
    struct no *next;
} no;

The variable size comes from a function that loops through my main list and returns its size.
Then created two "almost equal" functions to take the value from the main list and store it in the ListB and ListC.
My functions:
no* copylist(no *list, no *listReceive,int size)
{
    no *aux = list;
    no *receive=listReceive;

    int count=0;

    while(aux!=NULL&&count<size/2)
    {
        insert(receive, aux->value);

        aux=aux->next;
    }
    count = size/2;

    return receive;
}
no* copylist1(no *list, no *listReceive,int size)
{
    no *aux = list;
    no *receive=listReceive;

    int count=0;

    while(aux!=NULL&&count<size/2)
    {
        aux=aux->next;
        count++;
    }

    count = size/2;
    aux=aux->next;

    while(aux!=NULL&&count<size)
    {
        insert(receive, aux->value);

        aux=aux->next;
    }

    return receive;
}

Obs: for me linked lists is a very confusing content

A: The split can be done in a single pass if we use two pointers. One that traverses via cur1 = cur1->next and another that traverses twice as fast (e.g. cur2 = cur2->next->next);
When cur2 reaches the end, cur1 will be at the midpoint.
When we pass a "single star" pointer that is the list start to a function that must adjust and return the head of the list, the adjustment will not be reflected back to the caller.
Rather than pass down "double star" pointers for this lists, it's easier/better to use a separate list struct in addition to the node struct.
Note that we could co-opt/reuse a [dummy] node as the list pointer, but it's more clear if we use the separate struct.
Below is some annotated code. Unfortunately, I had to refactor a good deal of it to get it to work.

Here is a version that does [depending on the program argument]:

*

*A simple two pass version. One to compute the count and a second pass to do the split based on that count

*An improved version that does the split in a single pass by using the "two pointer" technique mentioned above

#include <stdio.h>
#include <stdlib.h>

int passno;

// node
typedef struct no {
    int value;
    struct no *next;
} no;

// list
typedef struct li {
    no *head;
} li;

// show -- show a list
void
show(li *lst,const char *sym)
{

    printf("%s:",sym);

    for (no *cur = lst->head;  cur != NULL;  cur = cur->next)
        printf(" %2d",cur->value);

    printf("\n");
}

// newlist -- create a new list with N elements
li *
newlist(int count)
{
    li *lst = malloc(sizeof(*lst));
    no *cur;
    no *prev;

    lst->head = NULL;

    prev = NULL;
    for (int idx = 0;  idx < count;  ++idx) {
        cur = malloc(sizeof(*cur));
        cur->next = NULL;

        cur->value = idx + 1;

        if (prev != NULL)
            prev->next = cur;
        else
            lst->head = cur;

        prev = cur;
    }

    return lst;
}

// lstcount -- count number of elements in the list
int
lstcount(li *lst)
{
    no *cur;
    int count = 0;

    for (cur = lst->head;  cur != NULL;  cur = cur->next)
        ++count;

    return count;
}

// splitA -- split a list into two halves (single pointer, two pass version)
void
splitA(li *lstleft,li *lstright,li *lstfrom)
{
    int count;
    int idx;
    no *cur;
    no *left;

    count = lstcount(lstfrom);
    count = (count + 1) / 2;

    left = NULL;
    lstleft->head = NULL;

    idx = 0;
    for (cur = lstfrom->head;  cur != NULL;  cur = cur->next) {
        if (++idx > count)
            break;

        // append to left list
        if (left == NULL)
            lstleft->head = cur;

        left = cur;
    }

    // disconnect/cut the tail of the left list from the right list
    if (left != NULL)
        left->next = NULL;

    // start the right list
    lstright->head = cur;

    // zap the original list
    lstfrom->head = NULL;
}

// splitB -- split a list into two halves (two pointer, one pass version)
void
splitB(li *lstleft,li *lstright,li *lstfrom)
{
    no *cur1;
    no *cur2;
    no *left;

    left = NULL;
    lstleft->head = NULL;

    cur2 = lstfrom->head;
    for (cur1 = lstfrom->head;  cur1 != NULL;  cur1 = cur1->next) {
        // wait for double speed pointer to end
        if (cur2 == NULL)
            break;
        cur2 = cur2->next;

        // append to left list
        if (left == NULL)
            lstleft->head = cur1;
        left = cur1;

        // advance at twice the rate
        if (cur2 != NULL)
            cur2 = cur2->next;
    }

    // disconnect/cut the tail of the left list from the right list
    if (left != NULL)
        left->next = NULL;

    // start the right list
    lstright->head = cur1;

    // zap the original list
    lstfrom->head = NULL;
}

// clean -- free up list elements and list descriptor
void
clean(li *lst)
{
    no *cur;
    no *next;

    for (cur = lst->head;  cur != NULL;  cur = next) {
        next = cur->next;
        free(cur);
    }

    free(lst);
}

// dotest -- test the split for a given number of nodes
void
dotest(int count)
{
    li *big;
    li *left;
    li *right;

    printf("\n");
    printf("dotest: count=%d\n",count);

    big = newlist(count);
    show(big,"big");

    left = newlist(0);
    right = newlist(0);

    switch (passno) {
    case 1:
        splitA(left,right,big);
        break;
    case 2:
        splitB(left,right,big);
        break;
    }

    show(left,"lhs");
    show(right,"rhs");

    clean(left);
    clean(right);
    clean(big);
}

int
main(int argc,char **argv)
{

    --argc;
    ++argv;

    if (argc > 0)
        passno = atoi(*argv);
    if (passno <= 0)
        passno = 1;
    if (passno > 2)
        passno = 2;
    printf("passno=%d\n",passno);

    for (int count = 0;  count <= 12;  ++count)
        dotest(count);
}

Here is the program output:
passno=1

dotest: count=0
big:
lhs:
rhs:

dotest: count=1
big:  1
lhs:  1
rhs:

dotest: count=2
big:  1  2
lhs:  1
rhs:  2

dotest: count=3
big:  1  2  3
lhs:  1  2
rhs:  3

dotest: count=4
big:  1  2  3  4
lhs:  1  2
rhs:  3  4

dotest: count=5
big:  1  2  3  4  5
lhs:  1  2  3
rhs:  4  5

dotest: count=6
big:  1  2  3  4  5  6
lhs:  1  2  3
rhs:  4  5  6

dotest: count=7
big:  1  2  3  4  5  6  7
lhs:  1  2  3  4
rhs:  5  6  7

dotest: count=8
big:  1  2  3  4  5  6  7  8
lhs:  1  2  3  4
rhs:  5  6  7  8

dotest: count=9
big:  1  2  3  4  5  6  7  8  9
lhs:  1  2  3  4  5
rhs:  6  7  8  9

dotest: count=10
big:  1  2  3  4  5  6  7  8  9 10
lhs:  1  2  3  4  5
rhs:  6  7  8  9 10

dotest: count=11
big:  1  2  3  4  5  6  7  8  9 10 11
lhs:  1  2  3  4  5  6
rhs:  7  8  9 10 11

dotest: count=12
big:  1  2  3  4  5  6  7  8  9 10 11 12
lhs:  1  2  3  4  5  6
rhs:  7  8  9 10 11 12


text:
Q: How to append an element in the end of list structure in java? I'm trying to write a function to append a new element in the end of my list. But i dont know how my method always append new element in the first index of the list.
I have 2 class named Waypoint and TourElement. Waypoint contains method to handle points in linked list. TourElment contains waypoint and next.
Waypoint.java
public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

TourElement.java
 public class TourElement {
     private Waypoint points;
     private TourElement next;
     public void setWaypoint( Waypoint points)
     {
         this.points = points;
     }
     public void setTourElement(TourElement next)
     {
         this.next = next;
     }
     Waypoint getWaypoint()
     {
         return this.points;
     }

     TourElement getNext()
     {
         return this.next;
     }

     //+ method below
}

method add new TourElement in the list, Why is alway append TourElement in the first index of the list?
public TourElement append(Waypoint waypoint)
{
    TourElement newTourElement = new TourElement();
    TourElement current = this;
    while(current.next != null)
    {
        current = current.next;
    }
    newTourElement.setWaypoint(waypoint);
    current.next = newTourElement;
    return newTourElement;
}

Here is my test case:
//create an element list:
private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

//create an waypoint:
private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

//add Start
public   TourElement addStart(Waypoint wp) {
     TourElement newTourElement = new TourElement();
     newTourElement.setWaypoint(wp);
     newTourElement.setTourElement(this);
     return newTourElement;
    }

 public void testAppend() {
        TourElement elem = createElementList(new int[][] {{2, 2}});
        elem = elem.append(createWaypoint(3, 3));
        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }

public void testAppend_AfterTwo() {
    TourElement elem = createElementList(new int[][] {{1, 1}, {2, 2}});
    elem = elem.append(createWaypoint(3, 3));
    assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
    assertArrayEquals(new int[] {2, 2}, elem.getNext().getWaypoint().toArray());
    assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
    assertNull(elem.getNext().getNext().getNext());
}

I expect that the output will look like this:
Test case 1: {2,2} => {3,3}
Test case 2:  {1,1} => {2,2} =>{3,3}
But my actual output is:
Test case 1: {3, 3} => {2,2}
Test case 2:  {3,3} =>{1,1} =>{2,2}

A: You're updating your "elem" in the line elem = elem.append(createWaypoint(3, 3));.
So I wonder, how your test cases return the complete list anyway? I'd expect the "actual output" would be "{3,3}" only.
To solve the issue, the test should NOT change the elem variable at all, after it's initialized in first place:
 public void testAppend() {
        // add "final" to prevent accidentially changes of references
        final TourElement elem = createElementList(new int[][] {{2, 2}});

        // DO NOT CHANGE "elem"!
        // elem = elem.append(createWaypoint(3, 3));
        // instead keep the reference to the first elem:
        elem.append(createWaypoint(3, 3));

        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }

BTW: your code could be MUCH clearer, if you give the "Waypoint" a constructor "Waypoint(x, y)", make the x and y fields final, remove setXY() and add a toString().
public class Waypoint {
    final int x;
    final int y;
    public WayPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() { ... }
    public int getY() { ... }

    @Override
    public String toString() {
        return String.format("{%d,%d}", x, y);
    }
}

Your TourElement could need a Collection<Waypoint> waypoints() method, which returns subsequent Waypoint objects (makes testing easier).
public Collection<Waypoint> waypoints() {
    Collection<Waypoint> res = new java.util.ArrayList<>();
    TourElement currTE = this;
    while (currTE.next()!=null) {
        res.add(currTE.getWaypoint());
        currTE = currTE.next();
    }
    return res;
}

To then print the list of Waypoint, you simply do
    org.apache.commons.lang.StringUtils.join(elem.waypoints(), ", ");


text:
Q: Permitted bound states in extended QCD color group $SU(4)$ I'm very much curious about the possible quark combinations to form bound states in $SU(4)$ QCD.
We already know Wilson has proven that only colorless combinations can arise in $SU(3)$ of these formats: $q\bar{q}$, $qqq$, tetra quarks and penta quarks.
I guess in $SU(4)$ one can only find $q\bar{q}$ and $qqqq$ and combinations of these two.
Am I right?

A: In fact yes, a simple way to get all possible states is by the following argument: quarks belong to the fundamental representation of the color group, and to them one can assign the upper index $q^{i}$, the antiquarks belong to the antifundamental representation, and to them we assign the lower index $\bar{q}_i$. Also there is a Levi-Civita symbol $\varepsilon^{i_1 \ldots i_N}$  ($N$ being the number of colors). The asymptotic states in QCD are color singlets $-$ so to get all possible states, you should contract all indices with each other in some way.
As for quark-antiquark pair you form a singlet by:
$$
\bar{q}_i q^{i} \,,
$$Which means taking the trace in color space. And baryons (antibaryons) correspond to:
$$
\varepsilon_{i_1 \ldots i_N} q^{i_1} \ldots q^{i_N} \,,\qquad
\varepsilon^{i_1 \ldots i_N} \bar{q}_{i_1} \ldots \bar{q}_{i_N}
\,.$$

A: The argument is still the same: A hadron has to be a color singlet ${\bf 1}$ under the $SU(N)_C$ color gauge group, due to color confinement.

*

*A single quark $q$ transforms in the fundamental representation ${\bf N}$ of $SU(N)_C$, and is hence not allowed since $N>1$.

*In a meson, the quark-antiquark-pair $q\bar{q}$ belongs to ${\bf N}\otimes\bar{\bf N}\cong{\bf 1}\oplus({\bf N^2\!-\!1})_{\rm Adj}$, which contains a singlet ${\bf 1}$, and is hence allowed.

*In a baryon, the $N$ quarks $\overbrace{qq\ldots q}^{N\text{ times}}$ form a totally antisymmetric representation $\wedge^N {\bf N}\cong {\bf 1}$ of $SU(N)_C$, which is isomorphic to a singlet ${\bf 1}$, and is hence allowed.
As one can see the number of quarks minus the number of anti-quarks should be divisible by $N$. For $N=3$, see also my related Phys.SE answer here.


text:
Q: itext image field in fillable form in itext 2 the below code worked well, in itext 5 it fail.
does anyone have a sample of how to add an image to an image field on a PDF?
This is my code...
public static void atsSetFieldImage(AcroFields form, PdfStamper stamper, String fieldName, Image img)
{
    try
    {
        float[] photograph = form.getFieldPositions(fieldName);
        Rectangle rect = new Rectangle(photograph[1]
                           , photograph[2]
                           , photograph[3]
                           , photograph[4]);

        //Image img = Image.getInstance(imageName);
              image1.scaleToFit(rect.getWidth(), rect.getHeight());
              image1.setAbsolutePosition(
                                    photograph[1] + (rect.getWidth() - image1.getScaledWidth()) / 2
                                  , photograph[2] + (rect.getHeight() - image1.getScaledHeight()) / 2);

        PdfContentByte cb = stamper.getOverContent((int)photograph[0]);
                       cb.addImage(image1);

    }
    catch(Exception e)
    {
        //e.printStackTrace();
    }
}

A: How to add an image to an acroForm field:
Rectangle rect = form.getFieldPositions(fieldName)[0].position;
int page = form.getFieldPositions(fieldName)[0].page;
//Scale it
image1.scaleAbsolute(rect.getWidth(), rect.getHeight());
//Position it
img.setAbsolutePosition(rect.getLeft(), rect.getBottom());
//Add it to the correct page
stamper.getOverContent(page).addImage(img);


text:
Q: element not appends in body on window onload I have been created the function which detects the screen zoom-in or zoom-out function. I am trying if window zoom == 100 or is in normal size the notification will remove else it append instantly.
In my code, it's working perfectly but it not working on window load, for showing the demo and result I have to click ctrl+ or ctrl-.
I am trying as window load it auto decide and append if window zoom, not 100 or normal.
Please help me with how I fix this?

function informationbar(percentage, zoomstatus) {
  $("body").append('
You are using the window screen on ' + percentage + '% ' + zoomstatus + ' resolution, might some options are not visible properly on this current resolution please fit the screen on 100% as this our highly recommendation.
');
}

$(window).resize(function() {
  var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
  if (browserZoomLevel !== '100') {
    if (browserZoomLevel > "100") {
      var status = "ZoomIn";
    } else {
      var status = "ZoomOut";
    }

    informationbar(browserZoomLevel, status);
  } else {
    $("div#informationbar").remove();
  }
});

var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
if (browserZoomLevel == '100') {
  $("div#informationbar").remove();
} else {
  if (browserZoomLevel > "100") {
    var status = "ZoomIn";
  } else {
    var status = "ZoomOut";
  }

  informationbar(browserZoomLevel, status);
}
#informationbar {
  position: fixed;
  left: 0;
  width: 100 %;
  text - indent: 5 px;
  padding: 5 px 0;
  background - color: lightyellow;
  border - bottom: 1 px solid black;
  font: bold 12 px Verdana;
}

* html# informationbar {
  /*IE6 hack*/
  position: absolute;
  width: expression(document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth + "px": body.clientWidth + "px");
}

A: You seem to be using !== to compare numbers and strings, e.g. browserZoomLeveL !== '100' where browserZoomLevel = Math.round(...).
That will always give false, since the a string isn't a number, and === is strict about types. You should replace === '100' with just === 100.


text:
Q: How to Retrieve an image when inserted from backend using php I've used the below code to store and get the images from the backend. The images are getting stored but it is not getting converted to base64 format...
$fruit_img = addslashes($_FILES['fruit_img']['tmp_name']);
$name = addslashes($_FILES['fruit_img']['name']);
$fruit_img = file_get_contents($fruit_img);
$fruit_img = base64_encode($image);

while($row = mysqli_fetch_array($res))
{
    echo ' ';
    echo $row[0];
}

A: I presume your code represents storing the data here:
$fruit_img = addslashes($_FILES['fruit_img']['tmp_name']);
$name = addslashes($_FILES['fruit_img']['name']);
$fruit_img = file_get_contents($fruit_img);
$fruit_img = base64_encode($image);

And retrieving the data here:
while($row = mysqli_fetch_array($res))
{
    echo ' ';
    echo $row[0];
}

If that is the case, you have simply mislabeled a variable in this line:
$fruit_img = base64_encode($image);

$image has not been assigned any value previously.
$fruit_img = base64_encode($fruit_img);

If that is not the case, please post additional (complete insert and read) code.


text:
Q: How to extract last directory in path in Zsh? Say I have a variable containing path to a directory (with a trailing slash):
dir="path/to/dir/"

How can I extract the last directory (i.e. "dir") using Zsh's parameter expansion? I would like to avoid calling external programs (like sed).

A: Parameter expansions in zsh can use csh-style history modifiers; in this case, you can use :t

   t      Remove  all leading pathname components, leaving the tail.  This
          works like `basename'.

% dir="path/to/dir/"
% print $dir
path/to/dir/
% print $dir:t
dir

A: In Zsh, you can nest expansions. So this works:
$ dir="path/to/dir/"
$ echo "${${dir%/}##*/}"
dir


text:
Q: C rand(). Issue with generating random strings Encountered issue with generating random strings.
Example below generates repeated blocks of random strings. Amount of random string in block depends on 'WORD_LENGTH'. For 1M 'COUNT' and 'WORD_LENGTH' of 20 chars each block contains 262144 (2^18) random strings and then block repeats.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define WORD_LENGTH 20

//const char charset[62] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const char charset[16] = "0123456789abcdef";

int main(int argc, char** argv) {
    srand(time(NULL));
    if (argc != 2) {
        printf("Usage: program COUNT'\n\n");
        return 0;
    }
    unsigned int count = atoi(argv[1]);
    char buf[WORD_LENGTH];
    for (int c = 0; c < count; c++ ) {
        for (int i = 0; i < WORD_LENGTH; ++i) {
            buf[i] = charset[ rand() % sizeof charset];
        }
        buf[WORD_LENGTH] = '\0';
        printf("%s\n", buf);
    }
    return 0;
}

Important thing. I could not reproduce "issue" when "..charset[62]..." are used with 'COUNT' up to 100M.
Question: Could someone please explain why it works that way ?

A: C uses Pseudorandom number generator in rand() function. Thus they are repeating sequence.

A: What about try this one:
char buf[WORD_LENGTH];
for (int c = 0; c < count; c++ ) {
    for (int i = 0; i < WORD_LENGTH; ++i) {
        buf[i] = charset[ rand() / (RAND_MAX + 1u) * sizeof charset];
    }
    buf[WORD_LENGTH - 1] = '\0';
    printf("%s\n", buf);
}

It is said in the C reference, codes like rand() % sizeof charset is biased. This answer may give some ideas.

A: To sum up comments from @WhozCraig and @LightVillet.
Problem discovered in :
buf[i] = charset[ rand() % sizeof charset]

Being precise with 'rand() % X' and connected with 'X' and not connected with charset array.
Issue reproduced when
X = 4,8,16,32,64.

But not reproduced with values between. Made short tests with COUNT up to 1M.
Be careful with rand() and use
(int)(rand()/(RAND_MAX+1.0) * (sizeof charset))

Which was mentioned by @Mr.Chip and @rici


text:
Q: failed to load csv file using csv-loader I am learning webpack-loader, and using csv-loader to load a csv file.

I have already install the csv-loader and add the rule. However, webpack log an

error:  Cannot find module 'papaparse'.

How do this error happened?

A: Indeed, it looks like papaparse is declared as a dependency within csv-loader which does not install by default after npm 3. You can just install it yourself using the following:
npm install --save-dev papaparse


text:
Q: Sending JSON data to a method within my custom class I am trying to send JSON data that's been loaded via dojo/request/xhr to a method within my custom class.
when I receive the data inside the .then() function I do not have access to my class instance methods since the data is only contained inside the .then() function call.
require([
  "dojo/_base/declare",
  "dojo/request/xhr"
], function(declare, xhr) {

  declare("rpg.game",null, {

    /**
     *
     * @param {type} domNode
     * @returns {undefined}
     */
    constructor: function(domNode) {
      domNode.innerHTML = "hello world";
    },

    /**
     *
     * @param {type} _url
     * @returns {undefined}
     *
     */
    loadData: function(_url) {

      xhr(_url, {
        handleAs: "json"
      }).then(function(data){
        // Do something with the handled data

        console.log(data); // <-- How can I send this data to my class?
        this.saveData(data); // <-- this does not work

      }, function(err){
        // Handle the error condition

      }, function(evt){
        // Handle a progress event from the request if the
        // browser supports XHR2

      });
    },

    saveData: function(data) {
      this.data = data;
    }
  });
});

I want to send the data to the method saveData but when I call the method, it is "undefined" within the .then() call.

A: this doesn't reference your class since xhr call is asynchronous, your situation is similar to this issue with Promises.
You can bind proper context using lang.hitch from dojo/_base/lang (this will ensure that also this.data will use correct this):
require([
  "dojo/_base/declare",
  "dojo/_base/lang",
  "dojo/request/xhr"
], function(declare, lang, xhr) {

/*...*/

    loadData: function(_url) {

      xhr(_url, {
        handleAs: "json"
      }).then(lang.hitch(this, function(data){
        // Do something with the handled data

        console.log(data);
        this.saveData(data); // <-- `this` should refer to your class

      }),

Using var self = this; you'll have to set data directly in .then callback (or call saveData with context set to self)
loadData: function(_url) {

  var self = this;
  xhr(_url, {
    handleAs: "json"
  }).then(function(data) {
    // Do something with the handled data

    console.log(data);
    self.data = data; // set `data` property of your class
//  self.saveData(data); // <-- this does not work because of `this.data` in `saveData`

  }, /**/);
},

saveData: function(data) {
  this.data = data;
}


text:
Q: How to get rows from Google Sheets filtered by a column's value? I have a spreadsheet that looks like this : (this is just a snippet of my sheet, it might have 10,000 rows in the future)

What I want to do is, Get every row whose For Class (column) value = 7 - In above sample case, rows #3, #5, #8, #10 have the For Class value of 7, so I should get them.
Using this reference - https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get, I tried to get some data : (range is just Sheet3 because I want all the rows available)

But as you can see, since I haven't applied any filters, it just gives me everything - (I require that the majorDimension should be ROWS)

What should I do, in order to get all rows containing For Class = 7, keeping the majorDimension to ROWS?

A: Issue:
There's no way to filter rows based on a column value during the Sheets API request. There's batchGetByDataFilter, but it only allows you to filter according to a specified range or according to DeveloperMetadata.
Workaround:
That said, you can easily filter that data after receiving the response from the API. I don't know what language you are using, but for example, if you were using Node, it could be something like:
const filteredRows = response["values"].filter(row => row[0] == "7");
console.log(filteredRows);

Where response corresponds to the API response from spreadsheets.values.get.


text:
Q: Finding the centre of a circle I am trying to find the centre of the equation mentioned in part c), but I can only really understand the "long way" of doing it (i.e., finding the intersection of the prependicular bisectors of $PT$ and $QT$). In the marking scheme, the quickest way of doing it is to find the midpoint of $QT$. This implies that $QT$ is a diameter but I simply cannot undretsand this since it seems to me that it certainly can be a chord. My question  is whether we can, with the information given,  detail why exactly $PQ$ is a diameter.

Thanks
(Note: By part "c" I mean "A second circle...")


text:
Q: Parse.com cloud code dirty relation I am using Parse Cloud code hooks (beforeSave).
My object has a relation and I need to know which objects where added to this relation.
My problem is exactly the same than here.
I want to be able to do this :
var op = myObject.op('toto');

//Get all add op in relation toto
var added = op.added();

//Get all remove op in relation toto
var deleted = op.removed();

added.forEach(function(pointer) {
     //Do something with pointer

     //If you need value on pointer
     pointer.fetch(function(objectFetched) {
         //Do something with object
     });
});
}

But that is not working anymore because

Result: TypeError: Object [object Object] has no method 'added'

How can I do now to know which objects was added to the relation ?

A: Unfortunately there is no information on this in Parse documentation. I had to poke through their source code to figure out how to do the exact thing for my Cloud Code. Anyway, you can get an Array of objectIds that are being added to a Relation like this:
var added = request.object.op("toto").relationsToAdd;

If you want to find the ones being removed, just replace relationsToAdd with relationsToRemove


text:
Q: Delete Multiple Rows from local json string in JQGrid I want to delete multiple rows using row ids from local json data in Jqgrid.
Example:
I have ids in Array as below
rowids="1,2";
I want to delete these two rows, 1 and 2, from json string with out using loop.
I am currently using
$.each(rowids,function(){
$grid.delRowData(this);
});

Can anyone suggest a solution to delete multiple rows with out using looping statements ?

A: First of all the string "1,2" is not correct JSON string. Either you have an object [1,2] or [1,2] or you have a string like "1,2". If you have the string "1,2" then you can use .split(",") to convert it to array of items which you can enumerate with using $.each for example. If you do have a JSON string like "[1,2]" then you can use $.parseJSON to convert such JSON string to array of items. I would recommend you to use http://jsonlint.org/ to validate which strings as in JSON format and so there can be converted using $.parseJSON.


text:
Q: Text processing on data frame in r I have a text file in which data is stored is stored as given below
{{2,3,4},{1,3},{4},{1,2} .....}

I want to remove the brackets and convert it to two column format where first column is bracket number and followed by the term
1 2
1 3
1 4
2 1
2 3
3 4
4 1
4 2

so far i have read the file
tab <- read.table("test.txt",header=FALSE,sep="}")

This gives a dataframe
      V1      V2   V3    V4
1 {{2,3,4  {1,3   {4   {1,2  .....

How to proceed ?

A: We read it with readLines and then remove the {} with strsplit and convert it to two column dataframe with index and reshape to 'long' format with separate_rows
library(tidyverse)
v1 <- setdiff(unlist(strsplit(lines, "[{}]")), c("", ","))
tibble(index = seq_along(v1), Col = v1) %>%
       separate_rows(Col, convert = TRUE)
# A tibble: 8 x 2
#  index   Col
#  <int> <int>
#1     1     2
#2     1     3
#3     1     4
#4     2     1
#5     2     3
#6     3     4
#7     4     1
#8     4     2

Or a base R method would be replace the , after the } with another delimiter, split by , into a list and stack it to a two column data.frame
v1 <- scan(text=gsub("[{}]", "", gsub("},", ";", lines)), what = "", sep=";", quiet = TRUE)
stack(setNames(lapply(strsplit(v1, ","), as.integer), seq_along(v1)))[2:1]

data
lines <- readLines(textConnection("{{2,3,4},{1,3},{4},{1,2}}"))
#reading from file
lines <- readLines("yourfile.txt")

A: Data:
tab <- read.table(text='     V1      V2   V3    V4
1 {{2,3,4  {1,3   {4   {1,2
2 {{2,3,4  {1,3   {4   {1,2 ')

Code:  using gsub, remove { and split the string by ,, then make a data frame. The column names are removed. Finally the list of dataframes in df1 are combined together using rbindlist
df1 <- lapply( seq_along(tab), function(x)  {
  temp <- data.frame( x, strsplit( gsub( "{", "", tab[[x]], fixed = TRUE ), split = "," ),
                      stringsAsFactors = FALSE)
  colnames(temp) <- NULL
  temp
} )

Output:
data.table::rbindlist(df1)
#    V1 V2 V3
# 1:  1  2  2
# 2:  1  3  3
# 3:  1  4  4
# 4:  2  1  1
# 5:  2  3  3
# 6:  3  4  4
# 7:  4  1  1
# 8:  4  2  2


text:
Q: Convert decimal to date format in r I have the data frame which has column of Date&time in the decimal format Date time is current format and expected format are like this
   Date Time      Expected format
1  43824.838  2019-12-27 20:06:43
2  43824.842  2019-12-27 20:12:28
3  43824.846  2019-12-27 20:18:14
4  43824.850  2019-12-27 20:24:00
5  43824.854  2019-12-27 20:29:45
6  43824.858  2019-12-27 20:35:31
7  43824.863  2019-12-27 20:42:43
8  43824.867  2019-12-27 20:48:28

With the following decimal date times:
c(43824.838, 43824.842, 43824.846, 43824.85, 43824.854, 43824.858, 43824.863, 43824.867)

A: In base R you can do
as_datetime <- function(x) as.POSIXct("1900-01-01") + as.difftime(x, units = "days")

dates <- c(43824.838, 43824.842, 43824.846, 43824.85,
           43824.854, 43824.858, 43824.863, 43824.867)

as_datetime(dates)
#> [1] "2019-12-27 20:06:43 GMT" "2019-12-27 20:12:28 GMT" "2019-12-27 20:18:14 GMT"
#> [4] "2019-12-27 20:24:00 GMT" "2019-12-27 20:29:45 GMT" "2019-12-27 20:35:31 GMT"
#> [7] "2019-12-27 20:42:43 GMT" "2019-12-27 20:48:28 GMT"


text:
Q: Free malloc when its value is returned by a function I have the following function:
char *lsl(){
    chdir("/Users/some/directory");
     FILE *fp;
    if ((fp = popen("ls -l", "r")) == NULL) {
        perror("popen failed");
        return (char *)EXIT_FAILURE;
    }

    size_t str_size = 1024;
    char *stringts = malloc(str_size);
    if (!stringts) {
        perror("stringts allocation failed");
        return (char *)EXIT_FAILURE;
    }
    stringts[0] = '\0';

    char buf[128];
    size_t n;
    while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) {
        buf[n] = '\0';
        size_t capacity = str_size - strlen(stringts) - 1;
        while (n > capacity) {
            str_size *= 2;
            stringts = realloc(stringts, str_size);
            if (!stringts) {
                perror("stringts realloation failed");
                return (char *)EXIT_FAILURE;
            }
            capacity = str_size - strlen(stringts) - 1;
        }
        strcat(stringts, buf);
    }

    if (pclose(fp) != 0) {
       perror("pclose failed");
       return (char *)EXIT_FAILURE;
    }

    return stringts;
}

Related part in main:
 char *out=lsl();
    if(send(new_socket, out, 200, 0)<0){. //sending the string to the client to print it there
       printf("Error in send! %s\n", strerror(errno));
        return -1;
    }

It returns a string to the main function, problem is I use malloc() to allocate memory for this function, if I use free(stringts) before return then obviously nothing will get returned, so how I my supposed to use free() while still returning it?
Note:
I found this link here: How do I free() after malloc() when the result of malloc() is returned by the function?
It is not in the same programming language hence why I am asking again.

A: If you want to return it, you must not free() stringts.  You must later free() it in the calling function.
char *out=lsl();
int r = send(new_socket, out, 200, 0);
free(out);
    if(r <0){. //sending the string to the client to print it there
       printf("Error in send! %s\n", strerror(errno));
        return -1;
    }


text:
Q: Multithreading for convolution calculation I am trying to calculate the convolution product the two pictures from two cameras as fast as possible. The cameras output ~ 17 fps, each frame is ~3MB. The camera manufacturer provides some c/c++ libraries to capture the images, all I need to do is to fourier transform each image, multiply the corresponding fourier transforms and make an inverse transform. What I currently do is I create a buffer and fill it with the frames in one thread, and there are three more threads, two for fourier transforming images from each camera and one for multiplication and calculation of the inverse fourier transforms.
At certain moment it becomes hard to pair the corresponding frames. I assign unique IDs to each frame when it is created. And when a new frame arrives I check if there are any frames with the same ID from the other camera. At certain moment it becomes hard to tell if it is a new frame in sequence and I need to put it to buffer and wait for the pair, or I've lost too many frames from the other camera and I need to discard this to catch it up.
What data types is it better to use and how to organize the data flow?


text:
Q: 'ExponentImagePicker.launchCameraAsync' has been rejected On a specific device (Samsung Galaxy S9 with Android 9), when I try to open the camera through ExponentImagePicker, I get the following error:
Error: Call to function 'ExponentImagePicker.launchCameraAsync' has been rejected.
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property cameraLauncher has not been initialized

On an Android 9 emulator it works, and also for newer API version emulators.
This was working previously, but seems to have stopped working after updating react native and other libraries.
Anything I can do about it?
Code:
import * as ImagePicker from 'expo-image-picker';

const MediaSelector: React.FC<Props> = (props) => {
    const open = async () => {
        const permissions = await ImagePicker.requestCameraPermissionsAsync();
        if (!permissions.granted) return Alert.alert("permission denied!"))

        const config: ImagePicker.ImagePickerOptions = {
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            allowsMultipleSelection: false,
            exif: false,
            aspect: [1, 1],
        }
        try {
            const result = await ImagePicker.launchCameraAsync(config);
        } catch (error) {
            console.log(error)
            Alert.alert("error!")
            return
        }
    }

    return <Pressable style={styles.container} onPress={open}>
        <ImageView img={props.image}/>
    </Pressable/>
}

versions:
"react": "18.0.0",
"expo-image-picker": "~13.3.1",
"react-native": "0.69.6",

A: I had the same issue, and for some reason using getCameraPermissionsAsync() fixed the issue - whereas requestCameraPermissionsAsync() on its own would cause launchCameraAsync() to be rejected on Android devices.
See the following:
let permissionResult = await ImagePicker.getCameraPermissionsAsync();
        if(permissionResult.status !== 'granted') {
            permissionResult = await ImagePicker.requestCameraPermissionsAsync();
        }
        if(permissionResult.status !== 'granted') {
            alert("You must turn on camera permissions to record a video.");
        }
        else {
            let result = await ImagePicker.launchCameraAsync({
                mediaTypes: ImagePicker.MediaTypeOptions.Videos,
                allowsEditing: true,
                aspect: [3, 4],
            });


text:
Q: Differential form equation conversion to derivative equation Suppose $x=x(t)$. Let $dx$ and $dt$ be 1-forms.
Does there exist a rigorous theorem for converting $dx=f(t)dt$ into the derivative ("fraction") expression $\frac{dx}{dt}=f(t)$?
Is this possible in general for other possibly multivariate functions (or does it require that $x$ is only a function of $t$). Or is this just false?
My guess is that by the linear independence of the basis differential form dt, it is possible to expand in the following manner and simply equate coefficients of $dt$.
$dx=\frac{dx}{dt}dt$
Therefore, $\frac{dx}{dt}=f(t)$.

A: As I commented, you want to think of a mapping $x\colon\Bbb R\to\Bbb R$. Using $t$ as a coordinate on the domain and $u$ on the range, you pull back $du$ by the mapping $u=x(t)$. Then you get $dx = x^*du = x'(t)\,dt$. Setting this equal to $f(t)\,dt$, you have $x'(t)\,dt = f(t)\,dt$, whence $x'(t)=f(t)$.
You asked about the multivariate situation. Consider, for example, $$dx = P(u,v)\,du + Q(u,v)\,dv.$$ Then this reduces likewise to the equations
$$\frac{\partial x}{\partial u} = P(u,v) \quad\text{and}\quad \frac{\partial x}{\partial v} = Q(u,v).$$
Can you make the analogous argument?


text:
Q: VHDL code not compiling I'm new to VHDL and I cannot seem to get my code to compile. I've looked over the code to the best of my ability, but I do not see anything wrong with it from my current basic understanding of how it works and I am wondering if anybody could help. The code is supposed to model a NLX1G99 configurable multi-function gate (minus the enable bit)
library ieee;
use ieee.std_logic_1164.all;

entity multifun_gate is
port(
        d,c,b,a: in std_logic;
        y: out std_logic
    );
end multifun_gate;

architecture dataflow of multifun_gate is
begin
    y <= (a and not b and not c and not d) or
         (a and b and not c and not d) or
         (not a and b and c and not d) or
         (a and b and c and not d) or
         (not a and not b and not c and d) or
         (not a and b and not c and d) or
         (not a and not b and c and d) or
         (and and not b and c and d);
end dataflow;

A: In the second last line:

(and and not b and c and d);

you have and repeated.

A: Judging from the picture in the datasheet, I'd write:
sig1 <= a and not c;
sig2 <= b and c;
sig3 <= sig1 or sig2;
y <= d xor sig3;

Much easier to check I reckon.


text:
Q: typescript interface for specific json I wonder, how to create ts interface for this kind of JSON:
  "Cities": {

        "NY": ["New York", [8000, 134]],

        "LA": ["Los Angeles", [4000, 97]],

    }

I dont knot how to create this nested arrays and unique label.

A: You can declare the elements an array will contains:
interface IData {
  [key: string]: [
    string,
    [number, number]
  ];
}

[number, number] indicates the array contains exactly 2 elements of type number. The notation differs from number[] which indicates an array of number.


text:
Q: # edges = # of vertices implies unique simple cycle I received a review of one of my papers in which the reviewer made an objection:
"...from the equations e(G) = v(G) you derive that there is a unique simple cycle of G. This is false for non-simple graphs (with loops)."
Here e(G) and v(G) are the number of edges and vertices of the graph, respectively. G is assumed to be connected.
I think the definition of a simple cycle is a path that begins and ends at the same vertex and does not repeat any vertices or edges (and uniqueness is up to cyclic permutation, i.e., the starting point doesn't matter).
I can't think of any counterexample even when I allow multiple edges between vertices, or loops (an edge from a vertex to itself). In fact, I feel like this should be easy to prove. Am I missing something?

A: Note that we cannot have a simple graph where $e (G)=v (G) $ is one or two.  However it is possible to have non-simple graphs which are connected and satisfy $e (G)=v (G) $ without being simple cycles.
Consider a tree with four vertices and three edges.  Now add one more edge that either duplicates an existing edge or puts a loop (self-edge) on a leaf vertex.
The result remains connected but is no longer a simple graph, and in particular is neither a simple cycle nor contains a simple cycle except a loop or double-edge between two vertices.

If these are allowed (and the OP has not spoken up to say not so), then we can prove the uniqueness of the simple cycle contained in the connected (undirected) graph $G$.
If $G$ did not contain a cycle, even of the loop or double-edge variety, yet was connected, then it would be tree and $e(G)$ would be $v(G)-1$ (a proof of this by induction is easy and has been discussed previously at Math.SE).  On the other hand if $G$ were a connected simple graph with $e(G)=v(G)$, then $G$ itself would be a single cycle of length $e(G)=v(G)$.
Finally if $G$ is connected with $e(G)=v(G)$, then it differs from a spanning tree $T$ contained in $G$ by a single edge.  So if $G$ is not itself a cycle, then the extra edge in $G$ but not in $T$ must be a loop (self-edge) or a duplicate (parallel) of an edge in $T$.  As any cycle in $G$ must use the edge which doesn't belong to $T$, we see in either of those cases that the "simple cycle" of $G$ is unique, a loop or a pair of parallel edges.


text:
Q: Checking Database Names and Create Database at run time I have one JTextfield for getting the database name to be created and JButton for performing database creation action in my swing form. The problem is when I give the value to the textfield and click the button it needs to check the entire database if the database exists with the same name that we gave to the new database. This means the existing database need to be deleted and the given name to be accepted for the new database. Here is my code.
package db1;

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

  public class Main implements ActionListener
    {
        JTextField txt;
        JButton create;
        JFrame frame;
        JPanel panel;
        JOptionPane jop;
        //Font font = UIManager.getFont("txt.font");
        public Main()
        {
           frame=new JFrame();
           panel=new JPanel();
           txt=new JTextField(10);
           create=new JButton("create");
           create.setBounds(20, 200, 50, 40);

        panel.add(txt);
        panel.add(create);
        create.addActionListener(this);
        frame.add(panel);

           // n.getContentPane().add(new textf());
            frame.setSize(440,310);
            frame.setVisible(true);

        }
        public void actionPerformed(ActionEvent e)
        {
        Connection con = null;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay","root","root");
                try{

                                     String database=txt.getText();
                                     Statement st = con.createStatement();
                                     String check=null;
                                    ResultSet rs = con.getMetaData().getCatalogs();
                                    while (rs.next()) {
                                   // System.out.println("" + rs.getString("TABLE_CAT") );
                                     check=rs.getString("TABLE_CAT");
                                     System.out.println(check);

                                    if(database.equals(check))  {I NEED CODE HERE}
                                    {
                                        String query = "DROP DATABASE"+check;
                                        st.executeUpdate(query);
                                    }
                                    else{
                                    st.executeUpdate("CREATE DATABASE "+database);
                    JOptionPane.showMessageDialog(frame,"DATA BASE IS CREATED");

                                        }

                                }
                        }

                catch (SQLException s)
                            {
                    System.out.println(s);
                                //JOptionPane.showMessageDialog(frame,"DATA BASE IS already exist");
                }
            }
            catch (Exception ea){
                       ea.printStackTrace();
            }
        }

        public static void main(String[] args)
        {
            new Main();

        }

    }

A: Before create database just use:
DROP DATABASE IF EXISTS db_name;

and don't bother checking whether it exists or not. Check MySQL DROP DATABASE Syntax.


text:
Q: Is it okey using WebSocket to get JSON on Android? I am developing client application on Android, which uses REST API to get JSON.
App sends a lot of requests to different URLs. This way is somehow slow - takes 30~60 seconds. This article says that WebSocket works faster. Now I am wondering  whether I can use WebSockets for this purpose. So I have several questions about this:

*

*Is it a good practice to use WebSocket to get JSON data from server?
If not, what can be better(faster/more secure) than regular HTTP?

*Can I send request to regular HTTP REST API using WebSocket?(this question may seem strange, but I really do not know)? Or guys on
backend should change/modify something to make this enable?

*What can be disadvantage(eg. battery drain) for using WebSocket?

A: *

*You can use WebSocket to get JSON data from a server.  However both the client and server must "talk" WebSocket.  If the server only understands REST calls, you will not be able to directly connect with WS from a browser to that REST server.

*No, you cannot use WebSocket to directly connect to an HTTP REST API.  Your browser must use the same protocol as the server.  That's why protocols were invented. right?  :)

*WebSocket is a persistent connection between a client and a server.  Its like a TCP socket connection in that way.  HTTP is fundamentally not persistent (although there are tricks to keep the connection for a long time).  An HTTP client usually calls an HTTP server, gets the data, returns and then the connection is terminated.  There are advantages and disadvantages to both (like anything else).  A WebSocket connection by itself will not drain your smartphone battery quickly.  If you are constantly sending data over that WebSocket that has to be rendered by the GPU on your screen, then your battery will drain.  An HTTP connection by itself will not drain your smartphone battery either.  But if your phone is polling some REST server and is in a low bandwidth area, your battery will drain from constantly going from low-power mode to high-power mode.  So its not the connection that is affecting the battery; its what's happening with that connection that affects the battery.

A: *

*You still send HTTP requests. It is a good practice if you have a bunch of them that you want to send in a burst or want to have two-way interaction with the server. You simply avoid rebuilding a fresh Session everytime and multiple handshake protocols. If you want to visit a webpage with lots of resources (e.g. images) it is a good idea. Also the server can send request to you without being polled.

*WebSockets need to be enabled on the server side (they are by default), but to keep the connection alive the webserver stores some references which need to be managed. So you allocate resources even if there is no messaging. When you have lots of clients, it can become challenging to handle the resource allocations.

*Battery drain is not an issue since you are not sending lots of data, but for you as a developer you need to add extra logic to handle the cases when the network or wifi are no longer available. This is when the Websocket is terminated and you need to reconnect with the server.

As a personal comment: Use it if you need server to interact with you (if something happens e.g. a new message has arrived for you at the server, the server can use the websocket to let you know) or if you are expecting lots of requests being send to the server in a short time from your client.
Hope it helps! I am not an expert.


text:
Q: Wireless connection keeps dropping randomly on Dell Inspiron N5110 I have Ubuntu 14.04.1 installed on a Dell Inspiron N5110 laptop.
I'm connecting to the internet through a wireless adapter, but when I'm connected I suddenly lose internet connection while I am still connected to the LAN and I have to disconnect and reconnect to regain internet connection.
My wireless adapter is  BCM4313 802.11b/g/n Wireless LAN Controller
How can I fix this problem?

A: https://help.ubuntu.com/community/WifiDocs/Driver/bcm43xx
Apparently the b43 series has some problems with Ubuntu.
The link explains how to update your drivers for the WiFi card.
I am writing from my phone so can't copy and paste all the details, but take care to use the commands specific for your version.
I hope it helps


text:
Q: Подскажите пожалуйста как переписать на useState Подскажите пожалуйста как переписать на useState
errs.inner.forEach((err: any) => {
  this.setState((state: any) => ({
    fieldsError: {
      ...state.fieldsError,
      [err.path]: err.message,
    },
  }));
});

пробовал вот так, но понимаю что это неправильно
const [fieldsErrorState, setFieldsErrors] = useState({type: undefined, model: undefined, number: undefined,})

errs.inner.forEach((err: any) => {
  setFieldsErrors({
   ...fieldsErrorState,
   [err.path]: err.message,
   })
});

A: Вот так попробуйте
errs.inner.forEach((err: any) => {
  setFieldsErrors((prev: any) => ({
    ...prev,
    [err.path]: err.message
  }))
});


text:
Q: Voltage divider, need help simplifying fractions
I have no clue on how $V_o$ ends up looking like $\frac{V_{in}}{10}\frac{(iw)}{1 + iw(\frac{1}{2})}$ and would like to know how.
My attempt:
I plug in $Z_{iw} = \frac{1}{10}\frac{1}{1 + iw\frac{2}{5}}$ and get $$V_o = V_{in}\frac{\frac{1}{10}\frac{1}{1 + iw\frac{2}{5}}}{\frac{1}{iw}+\frac{1}{10}\frac{1}{1 + iw\frac{2}{5}}}$$ Multiply $\frac{1}{iw}$ in the denominator by $\frac{10}{10}$ to get $$V_o = V_{in}\frac{\frac{1}{10}\frac{1}{1 + iw\frac{2}{5}}}{\frac{10}{10iw}+\frac{1}{10}\frac{1}{1 + iw\frac{2}{5}}}$$ Factor out $\frac{1}{10}$ to get $$V_o = \frac{V_{in}}{10}\frac{\frac{1}{1 + iw\frac{2}{5}}}{\frac{10}{iw}+\frac{1}{1 + iw\frac{2}{5}}}$$ and from there I have no clue what the next step would be to get $$V_o = \frac{V_{in}}{10}\frac{(iw)}{1 + iw(\frac{1}{2})}$$ a step in the right direction would be greatly appreciated

A: The impedance seen from the output is
$$Z_{out}=\frac1{10+i4\omega}$$
and that from the input
$$Z_{in}=\frac1{i\omega}+Z_{out}.$$
Then the transmittance
$$\frac{Z_{out}}{Z_{in}}=\frac{\dfrac1{10+i4\omega}}{\dfrac1{i\omega}+\dfrac1{10+i4\omega}}=\frac{i\omega}{10+i4\omega+i\omega}=\frac1{10}\frac{i\omega}{1+i\dfrac\omega2}.$$


text:
Q: Google maps API marker - mouseover instead of click - using kml I wanna simply get markers from a kml file and show them on a map, but add "mouseover" for tooltip, not click
using this code, but it don't work (works if i use click)
function initialize() {
    var latlng = new google.maps.LatLng(53.477876, -2.471289);
    var myOptions = {
      zoom: 5,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    //kml begin
    var nyLayer = new google.maps.KmlLayer('http://code.nebtron.com/kml2.kml', {suppressInfoWindows: false});
    nyLayer.setMap(map);
    google.maps.event.addListener(nyLayer, "mouseover", function(kmlEvent) {
      var text = kmlEvent.featureData.description;
      showInDiv(text);
    });

    function showInDiv(text) {
      var sidediv = document.getElementById('contentWindow');
      sidediv.innerHTML = text;
    }//kml end

  }

Demo: http://code.nebtron.com/map3.php

A: As pointed out here, there is no mouseover event for KMLLayers. But maybe you could use a polygon. Here's a link.
Hope this helps!


text:
Q: C program compilation with VC++ [2005] I can see that my VC++ 2005 express edition compiles following code perfectly
/*Following Code compiles fine*/
#include <stdio.h>

main()
{
    int i;
    int;
    5;

    printf("\n\r Whats up??");
    getchar();
    return 0;
}

However I have observed that it gives compilation error for same code with slightly different order.
/*Following code gives error*/

#include <stdio.h>
main()
{
    int;
    5;

    int i;
    printf("\n\r Whats up??");
    getchar();
    return 0;
}

Position of "int i" is different in both the cases.
I get error as "Error   2   error C2143: syntax error : missing ';' before 'type'   on line 6.
Why is this happening?
Thanks,

A: This is happening because it seems the compiler has a bug. Neither the first program nor the second program shall be compiled.
I can guess that the second program is not compiled because declarations in old C must be placed in the beginning of a code block.
I have no at hand the old C Standard but according to the current C Standard (6.7 Declarations)

2 A declaration other than a static_assert declaration shall declare
  at least a declarator (other than the parameters of a function or
  the members of a structure or union), a tag, or the members of an
  enumeration.

It seems that the old C allowed empty declarations. At least in the Rationale for International Standard— Programming Languages— C Revision 2 20 October 1999 there is written:

6.7 Declarations 25
  The C89 Committee decided that empty declarations are invalid, except for a special case with tags (see §6.7.2.3) and the case of
  enumerations such as enum {zero,one}; (see §6.7.2.2). While many
  seemingly silly constructs are tolerated in other parts of the
  language in the interest of facilitating the machine generation of C,
  empty declarations were considered sufficiently easy to 30 avoid.

Take into account that some compiler implementations call such bugs as their own language extensions.:)