text:
Q: Rotate matrix rings first line is getting error In this code I had getting error the below error
Enter M:
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    M = int(input("Enter M: "))
ValueError: invalid literal for int() with base 10: '4 4'

The Question is below
Given a matrix of order M*N and a value K, write a program to rotate each ring of the matrix clockwise by K elements. If in any ring has less than or equal to K elements, then don't rotate that ring.
Input
The first line of input will be two space-separated integers, denoting the M and N.
The next M lines will contain N space-separated integers.
The next line will contain an integer, denoting K.
Output
The output should be M*N matrix by rotating the matrix by K elements.
Explanation
For example, if the given M and N are 4 and 4 respectively. If the matrix elements are
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
If the given K is 3. Rotate each ring of the matrix by 3 elements.
In the above matrix, the elements (1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5) is a ring, similarly, the elements (6, 7, 11, 10) will make a ring.
Therefore, by rotating each ring in clockwise direction by 3 elements will give (13, 9, 5, 1, 2, 3, 4, 8, 12, 16, 15, 14) and (10, 6, 7, 11). So the output should be
13 9 5 1
14 7 11 2
15 6 10 3
16 12 8 4
The code is below
M = int(input("Enter M: "))
N = int(input("Enter N: "))

A = [[0]*N for x in range(M)]
for i in range(0, M):
    for j in range(0, N):
        A[i][j] = int(input())

K = int(input("Enter K: "))
Ring = (min(M, N) + 1) // 2

count = 0
r = 0
d = 0
l = 0
u = 0

for i in range(Ring):
    size = 2*(M-2*i) + 2*(N-2*i) - 4
    if M-2*i == 1:
        size = N-2*i
    if N-2*i == 1:
        size = M-2*i
    if size == 0:
        size = 1
    if size <= K:
        continue
    B = [0] * size
    startX = i
    startY = i
    for r in range(i, N-i):
        B[count] = A[startX][r]
        count += 1
    for d in range(startY + 1, M-i):
        B[count] = A[d][r]
        count += 1
    l = r - 1
    if M-(2*i) > 1 and N-(2*i) > 1:
        while l >= i:
            B[count] = A[d][l]
            count += 1
            l -= 1
        u = d - 1
        while u >= i + 1:
            B[count] = A[u][l+1]
            count += 1
            u -= 1
    for t in range(K):
        temp = B[size - 1]
        j = size - 1
        while j != 0:
            B[j] = B[j-1]
            j -= 1
        B[0] = temp

    count = 0
    r = 0
    d = 0
    l = 0
    u = 0

    for r in range(i, N-i):
        A[startX][r] = B[count]
        count += 1
    for d in range(startY + 1, M-i):
        A[d][r] = B[count]
        count += 1
    l = r - 1
    if M-(2*i) > 1 and N-(2*i) > 1:
        while l >= i:
            A[d][l] = B[count]
            count += 1
            l -= 1
        u = d - 1
        while u >= i + 1:
            A[u][l+1] = B[count]
            count += 1
            u -= 1

    count = 0
    r = 0
    d = 0
    l = 0
    u = 0

print("")
for i in range(M):
    for j in range(N):
        print(A[i][j], end = "\t")
    print("")

And also not getting expected Test case output, the test cases are
Test case 1
Input
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
Output
13 9 5 1
14 7 11 2
15 6 10 3
16 12 8 4
Test case 2
Input
3 4
1 2 3 4
10 11 12 5
9 8 7 6
2
Output
9 10 1 2
8 11 12 3
7 6 5 4

Please help me anybody python expert.

A: Code for enter data (section Input of the question):
M, N = [int(x) for x in input("Enter M N: ").split(' ')]
nums = []
for i in range(0, M):
    nums.append([int(x) for x in input(f"Enter {i} row with {N} space-separated integers: ").split(' ')])
K = input("Enter integer K: ")

print(f"You entered:\nM={M},N={N}")
print(f"Lists of entered space-separated integers is:\n{nums}")
print(f"K={K}")

Output

Enter M N: 3 3
Enter 0 row with 3 space-separated integers: 1 2 3
Enter 1 row with 3 space-separated integers: 4 5 6
Enter 2 row with 3 space-separated integers: 7 8 9
Enter integer K: 10
You entered:
M=3,N=3
Lists of entered space-separated integers is:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
K=10


text:
Q: Android application Can't access database for insert and update I am developing notes application for Android, when I click the save button it is supposed to insert data to the db using the content provider method insert, after that the loader will automatically load the data, and the simplecursoradapter should populate that data. However, after clicking save nothing appears. It seems to me that the app can't access the database as I am getting this log when clicking the save button,
    02-27 12:31:31.112: E/SQLiteLog(13232): (257) Open fd: 74, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-27 12:31:31.112: E/SQLiteLog(13232): (257) Close fd: 74
02-27 12:31:31.112: E/SQLiteLog(13232): (257) Open fd: 74, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-27 12:31:31.186: E/SQLiteLog(13232): (257) Close fd: 74
02-27 12:31:31.271: E/SQLiteLog(13232): (257) Open fd: 80, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-27 12:31:31.271: E/SQLiteLog(13232): (257) Close fd: 80
02-27 12:31:31.907: E/MCA(13851): Here call up the service!
02-27 12:31:31.908: E/MCA(13851): LT passed!
02-27 12:31:34.392: E/(180): AudioCloseDumpPCMFile file== NULL
02-27 12:31:34.392: E/(180): AudioCloseDumpPCMFile file== NULL

Content provider code:
    public class NotesProvider extends ContentProvider{

    // database
    private static TodoDatabaseHelper mdatabaseHelper;

    // used for the UriMacher
    private static final int NOTES = 10; //in case an entire table were requested to be returned.
    private static final int NOTES_ID = 20; //in case a specific item with a specific uri needs to be returned.

    //Let's build the UriMatcher:
    static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); //sUriMatcher: s stands for static, it is just a name.
    //when we initialize the UriMatcher we first say that it still has no matches. Let's assign the matches:
    //we do that in a static block, that's once the class is created the matches are built.
    static {

        sUriMatcher.addURI(NotesContract.CONTENT_AUTHORITY, NotesContract.NOTES_PATH, NOTES); //match an entire table.
        sUriMatcher.addURI(NotesContract.CONTENT_AUTHORITY, NotesContract.NOTES_PATH +"/#", NOTES_ID);

    }//end matching static block.

    @Override
    public boolean onCreate() {
        //get a dbHelper obj,
         mdatabaseHelper = new TodoDatabaseHelper(getContext()); //why? Because this will help us retrieve a readable/writable db on which we can make operations like CRUD.
        return true; //we were successfully able to create an obj representation of the DB.
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        //here we should use the uri matcher to know how we can conduct the query.
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables(NotesContract.NotesTable.TABLE_TODO); //could be used for joins also.

        verifyColumns (projection); //verify if the columns are valid.
        int match= sUriMatcher.match(uri); //save the int associated with this uri in a var to be able to use it in the switch.
        Cursor cursor=null; //initialize cursor, it will be used to return the result of the query.
        SQLiteDatabase  db= mdatabaseHelper.getReadableDatabase(); //we need this because we use an SQLiteQueryBuilder.
        switch (match) //start the switch
        {
            case NOTES:
                // call method query and send the params.
                cursor= queryBuilder.query(db,  projection, selection,
                       selectionArgs, null, null, sortOrder);
                break; //don't go to next case.
            case NOTES_ID:
                //first initialize the where clause in the query builder:
                queryBuilder.appendWhere(NotesContract.NotesTable._ID + "=" + ContentUris.parseId(uri));
                //invoke the query method:
                cursor= queryBuilder.query(db,  projection, selection,
                        selectionArgs, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);

        }//end switch
        /*the queries above could be built using mSQLiteHelper.getReadableDatabase.query(..)*/
        cursor.setNotificationUri(getContext().getContentResolver(), uri); //very important and required, to update the ui when the data change.
        return cursor; //return the query result.
    }//end query.

    @Override
    public String getType(Uri uri) {

        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        int match = sUriMatcher.match(uri);
        SQLiteDatabase db = mdatabaseHelper.getWritableDatabase();
        long id = 0;
        switch (match) {
            case NOTES:
                id = db.insert(NotesContract.NotesTable.TABLE_TODO, null, contentValues);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null); //notify observers about any update.
        return Uri.parse(NotesContract.NOTES_PATH + "/" + id);

}

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int match = sUriMatcher.match(uri);
        SQLiteDatabase db = mdatabaseHelper.getWritableDatabase();
        int rowsDeleted = 0;

        switch (match) {
            case NOTES:
                rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_TODO, selection, selectionArgs);
                break;
            case NOTES_ID:
                if (selection.isEmpty()){
                String whereClause= NotesContract.NotesTable._ID +  "=" + ContentUris.parseId(uri);
                rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_TODO, whereClause, null);}

                else{
                    rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_TODO,
                            NotesContract.NotesTable._ID + "=" + ContentUris.parseId(uri)
                                    + " and " + selection,
                            selectionArgs);
                }//end else
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }//end switch
        getContext().getContentResolver().notifyChange(uri, null); //if any delete happens notify the observers.
        return rowsDeleted;
    }//end delete

    @Override
    public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mdatabaseHelper.getWritableDatabase(); //return a writable obj from the db.
        int rowsUpdated = 0;
        int match= sUriMatcher.match(uri);
        switch (match) {
            case NOTES:
                rowsUpdated = db.update(NotesContract.NotesTable.TABLE_TODO,
                        contentValues,
                        selection,
                        selectionArgs);
                break;
            case NOTES_ID:
                long id = ContentUris.parseId(uri);
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = db.update(NotesContract.NotesTable.TABLE_TODO,
                            contentValues,
                            NotesContract.NotesTable._ID + "=" + id,
                            null);
                } else {
                    rowsUpdated = db.update(NotesContract.NotesTable.TABLE_TODO,
                            contentValues,
                            NotesContract.NotesTable._ID + "=" + id
                                    + " and "
                                    + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    private void verifyColumns (String [] cols) {
        //lets get the columns in the Db and compare.
        String[] existed = {NotesContract.NotesTable._ID, NotesContract.NotesTable.COLUMN_CATEGORY,
                NotesContract.NotesTable.COLUMN_DESCRIPTION,
                NotesContract.NotesTable.COLUMN_SUMMARY};
        if (cols != null) {
            ArrayList<String> existedCols = new ArrayList<String>(Arrays.asList(existed)); //this is how we convert an array to an arraylist.
            ArrayList<String> requestedCols = new ArrayList<String>(Arrays.asList(cols));
            // check if all columns which are requested are available
            if (!existedCols.containsAll(requestedCols)) {
                throw new IllegalArgumentException("Some columns don't exist in the database");
            }//end if.
        }//end outer if.
    }//end verification.

    public static Cursor searchDescription (String key)
    {
        String desc []= {"%"+key +"%"};
        SQLiteDatabase db = mdatabaseHelper.getReadableDatabase();
        Cursor rtCursor= db.rawQuery("select * from " + NotesContract.NotesTable.TABLE_TODO+ " where " +
                NotesContract.NotesTable.COLUMN_DESCRIPTION + " like ?", desc);

        return rtCursor;
    }//end searchDescription

}//end Provider.

Details activity code where the note is edited and saved:
 public class NotesDetails extends ActionBarActivity {

    private EditText noteSummary;
    private EditText noteDescription;
    private Spinner noteCategory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final ContentResolver resolver = getApplicationContext().getContentResolver();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notes_edit);

        Button saveButton = (Button) findViewById(R.id.todo_edit_button);
         noteSummary = (EditText) findViewById(R.id.todo_edit_summary);
         noteDescription = (EditText) findViewById(R.id.todo_edit_description);
         noteCategory= (Spinner) findViewById(R.id.category);

        if (getIntent().getStringArrayExtra(Intent.EXTRA_TEXT)!=null){
        String [] receivedData=getIntent().getStringArrayExtra(Intent.EXTRA_TEXT);

            if (receivedData [0].equalsIgnoreCase("important")){
                noteCategory.setSelection(0);}//end if
            else {
                noteCategory.setSelection(1);} //end else
            noteSummary.setText(receivedData[1]);
            noteDescription.setText(receivedData[2]);

        }//end if (feasible only if the received intent contains an array of string, which happens if the user clicks onm one of the items in the simplecursoradapter view)

        saveButton.setOnClickListener(new View.OnClickListener() {

             String summary= null;
             String description= null;
             String category= null;

            @Override
            public void onClick(View view) { //this will happen every time you click the button.
               summary= noteSummary.getText().toString();
               description= noteDescription.getText().toString();
               category = noteCategory.getSelectedItem().toString();
                Toast toast ;
               if (summary.isEmpty()) {
                   toast = Toast.makeText(NotesDetails.this, "Summary cannot be empty", Toast.LENGTH_SHORT);
                   toast.show();
               }
               else {
                   ContentValues values = new ContentValues();

                   values.put(NotesTable.COLUMN_CATEGORY, category);
                   values.put(NotesTable.COLUMN_SUMMARY, summary);
                   values.put(NotesTable.COLUMN_DESCRIPTION, description);

                   //start inserting into the db via provider.
                   Uri uri =getContentResolver().insert(NotesTable.NOTES_URI, values);
                   Intent intent = new Intent(NotesDetails.this, NotesList.class);
                   startActivity(intent);
               }
            }//end onClick

        }); //end onClickListener

    }

}

Can anyone please tell me why this is happening and how to fix the problem?
Thanks

A: Use this for insert
 public void onClickAddName(View view) {
        ContentValues values = new ContentValues();
        values.put(MyProvider.name, ((EditText) findViewById(R.id.txtName))
                .getText().toString());
        Uri uri = getContentResolver().insert(MyProvider.CONTENT_URI, values);
        Toast.makeText(getBaseContext(), "New record inserted", Toast.LENGTH_LONG).show();
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Raspi I2C communication with Arduino issues with wiringPi I'm experiencing unexpected results using wiringPi's wiringPiI2CWriteReg16() function, and I'm not sure if it's due to incorrect usage, or something else. This is the declaration for the function:
extern int wiringPiI2CWriteReg16 (int fd, int reg, int data);

There are notes within the wiringPiI2C.c file that state it resembles Linux's SMBus code, if that helps.
On my Arduino (both an Uno R3 and a Trinket Pro), I am running this pared-down sketch:
#include <Wire.h>

#define SLAVE_ADDR 0x04

void receive_data (int num_bytes){
  Serial.print("bytes in: ");
  Serial.println(num_bytes);

  while(Wire.available()){
    int data = Wire.read(); // tried char, uint8_t etc
    Serial.println(data);
  }
  Serial.print("\n");
}

void setup() {
  Serial.begin(9600);
  Wire.begin(SLAVE_ADDR);
  Wire.onReceive(receive_data);
}

void loop() {
  delay(500);
}

I would think that Wire.read() would break things apart at the byte boundary, but that's not occurring in my case. Perhaps this is my issue... a misunderstanding.
Nonetheless, I have this C code (requires wiringPi v2.36+ to be installed):
// word.c

#include <wiringPiI2C.h>

void main (){
    int fd = wiringPiI2CSetup(0x04);
    wiringPiI2CWriteReg16(fd, 0x00, 255);
    wiringPiI2CWriteReg16(fd, 0x01, 256);
}

Compiled like this:
gcc -o word word.c -lwiringPi

When run, ./word, I receive the following on my Arduino's serial output:
bytes in: 3
0
255
0

bytes in: 3
1
0
1

In the first call to wiringPiI2CWriteReg16(), I expect the first byte in the output to be zero (0x00) as that's the register address I'm requesting. The second byte (255) is also correct. The third byte (0) is meaningless from what I can tell (as I'm only sending in one byte as data).
However, in the second call to that function, I do get the correct output for the register (first byte as 0x01 == 1), but the second byte is zero, and the third byte has what appears to be the correct remainder (255 == one byte, + 1). The problem is, is that the second byte is 0.
The exact same effect happens if I pass in 511 or for that matter, any number as the data in the call.
My question is whether I'm missing something glaringly obvious (I'm relatively new to C and Arduino), and/or if I can get some pointers on how to troubleshoot this more thoroughly.

A: I found that the problem was in my Arduino code. In the official Raspi forums, Gordon tipped me off that the bytes are read in separately, LSB first. Throughout all of my searching, I hadn't come across that, and really didn't quite understand what was happening. After changing my I2C read loop code in my Arduino sketch to this:
while(Wire.available()){
    Wire.read(); // throw away register byte

    int16_t data = Wire.read(); // LSB
    data += Wire.read() << 8;   // MSB

    Serial.print("data: ");
    Serial.println(data);
}

...everything works. In effect, that's at least one way to read two-byte values over I2C on the Arduino and put the bytes back together.


text:
Q: Difference between get instance() and get reference() in android studio..? What is Difference between get instance() and get reference() in android studio which we use while saving or retrieving data from fire base..??

A:
The entry point for accessing a Firebase Database. You can get an
  instance by calling getInstance().
To access a location in the database and read or write data, use
  getReference().

check doc here
https://firebase.google.com/docs/reference/android/com/google/firebase/database/FirebaseDatabase


text:
Q: What is wrong with my model of aerodynamic drag? I am creating a JavaScript program which simulates fireworks in a 2-dimentional context launching from the ground and exploding somewhere in mid-air.
The program takes into account gravity and drag, but something is wrong with the way I am calculating acceleration due to drag.
Observe these animations:

*

*Without drag

*With drag

My implementation of drag physics is producing an undesired, physically inaccurate "square" effect, where particles seem to have a different drag depending on the direction in which they are traveling (the more parallel they are to either the x or y axis, the greater the drag — with the least drag at a 45° angle from either axis). If I turn the drag "off", the firework particles explode evenly in all directions, as they should.
My calculations of acceleration due to drag are based on the following equations:

*

*D = ½ρCAv² (Nasa)

*a = D/m (Newton's Second Law of Motion)

And these are the snippets of code in the program that I believe are relevant to the problem (However, please feel free to audit the entire source code on GitHub: github.com/foxyjacob/vulcan):
function calculateAccelerationDueToDrag(fluidDensity, dragCoefficient, crossSectionalArea, speed, mass) {

    let acceleration = -(0.5 * fluidDensity * dragCoefficient * crossSectionalArea * (speed * speed)) / mass;

    if (speed < 0) {
        acceleration = -acceleration;
    }

    return acceleration;

}

...
let accelerationDueToDrag = [
    calculateAccelerationDueToDrag(
        AIR_DENSITY,
        this.dragCoefficient,
        this.crossSectionalArea,
        lastVelocity[0],
        this.mass
    ),

    calculateAccelerationDueToDrag(
        AIR_DENSITY,
        this.dragCoefficient,
        this.crossSectionalArea,
        lastVelocity[1],
        this.mass
    )
];

Essentially, I am calculating each particle's acceleration, velocity, and position on the x and y axes independently.
Why is my model of drag producing this strange "square" effect?

A: With a drag force proportional to velocity$^2$, you can't do the calculations for the $x$ and $y$ directions separately.
$$\vec{D} = -k|\vec{v}|^2\hat{v} = -k|\vec{v}|\vec{v}$$
Therefore,
$$D_{x} = -k\sqrt{v_x^2 + v_y^2}\ v_x$$
You can't just send the $x$-component of the velocity of the projectile to to the function to get the $x$-component of the drag force. Your calculateAccelerationDueToDrag() function needs to have inputs for both velocity components for both drag components.
Related:

*

*Why the does drag force in the $x$-direction depend on the drag force in the $y$-direction?

*Splitting up a force into horizontal and vertical components?


text:
Q: ExtJs 3.4 : Get all records from a grid and pass them into a servlet I have a grid store and I want to get all the records from that grid and push them into an array. And also I want to pass this array of data to a servlet to save them in a database. Here is my attempt.
var tourData = plannedGridStore.getRange();
var gridData = new Array();
tourData.each(function (record) {
    gridData.push(record.data);
});

But my firebug console says
.each(function (record) { is not a function

I am using ExtJs 3.4. What's wrong with my code ?
And also I need to know how should I pass my gridData array to a servlet.
Please help me
Cheers

A: Ext.data.Store getRange method returns array of records. For iterates this array you can use Ext.each() method:
Ext.each(tourData, function (record) {
    gridData.push(record.data);
});

For sending your array data to server you can use Ext.Ajax.request method. You can not pass array as request parameter so firstly you have to encoced it to JSON with Ext.util.JSON.encode() method.
Ext.Ajax.request({
    url: 'YOUR_URL',
    params: {
       gridData: Ext.util.JSON.encode(gridData)
    }
});

A: If you are using a POST you can do something pretty succinct like:
Ext.Ajax.request({
    url: 'url',
    jsonData: Ext.pluck(store.getRange(), 'data')
});


text:
Q: doing check internet connection on another thread? When I press login button, the app freezes for a while because it checks internet connection on the main thread. how to do it in the background thread or new thread and what is the difference between them (Background thread and another new Thread).
my internet check function :
public Boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

A: You are basically trying to execute a PING command to check if you have a real internet connection and not just network connection. In that case, its using a Network and so you will end up with a NetworkOnMainThreadException.
One of the way you can implement this is by creating a callback method that returns the result of the PING from the background thread.
Below pseudo code reiterates what I mean:
interface ResultCallback {
   void onComplete(boolean result);
}

class checkInternet extend AsyncTask<., ., Boolean> {
  ResultCallback callback;
  public static checkInternet(ResultCallback callback) {
    this.callback = callback;
  }

  void doInBackGround() {
     return isOnline();
  }

  onPostExecute(Boolean result) {
    callback.onComplete(result);
  }
}

Have a function
void performCheckOnInternet(ResultCallback callback) {
    new checkInternet(callback).execute();
  }

Now, you can call this async task like:
performCheckOnInternet(new ResultCallback {
    void onComplete(boolean result) {
       //do your stuff here
    }
});

A: Do you really need to check if data is actually flowing? If not, you can use this (simpler) apporach:
public static boolean hasInternetConnection(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}


text:
Q: Shape operator of pseudo-spheres In the following, I will refer by O'Neil to Barrett O'Neil's book Semi-Riemannian Geometry With Applications to Relativiy.

Consider the $M=\{ x \in \mathbb{R}^n_s | f(x)=r^2\}$ with $f(x)=g_s(x,x)$ and $g_s(x,y)=-\sum_{i=1}^{s}x_iy_i+\sum_{i=s+1}^{n}x_iy_i$. It is a hypersurface of the pseudo-Euclidean space $\mathbb{R}^n_s=(\mathbb{R}^n,g_s)$.
I would like to compute its shape operator (or Weingarten map). Here are my steps:

*

*The gradient of $f$ is grad$f(x)=\frac{2}{r}(-x_1,...,-x_s,x_{s+1},...,x_n)^t$

*By O'Neil (Proposition 4.17, p.106) $n(x)=\frac{1}{r}(-x_1,...,-x_s,x_{s+1},...,x_n)^t$ defines a unit normal vector field of $M$.

*The shape operator is then given by $-\widetilde{\nabla}_vn(x)$ with $\widetilde{\nabla}$ being the Levi-Civita connection of $\mathbb{R}^n_s$.

*Using the formula $\widetilde{\nabla}_VZ=\sum_iV[Z^i]\partial_i$ (with a local frame), I obtain the following for the shape operator: $S_x(v)=\frac{1}{r}\sum_{i=1}^sv_i\partial_i-\frac{1}{r}\sum_{i=s+1}^nv_i\partial_i$
However, O'Neil states $S=-I/r$. (Lemma 4.27, p.111)
What am I missing?
Addendum
I believe I made a silly mistake when computing the covariant derivative:
$\widetilde{\nabla}_vn\neq\frac{1}{r}(-\sum_{i=1}^sv_i\partial_i+\sum_{i=s+1}^nv_i\partial_i)$
Instead it should read
$\widetilde{\nabla}_vn=\frac{1}{r}(\sum_{i=1}^sv_i\partial_i+\sum_{i=s+1}^nv_i\partial_i)$.
Derivating $-x_i$ flips the sign again.


text:
Q: Do I need to embed a LinearLayout into another for inclusion into a ListView? In order to create an XML resource file to be included via tools:listitem="@layout/row", I was told to create an XML structure like so:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/reminder_row">

        <android.support.v4.widget.Space
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:id="@+id/view"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/textView"/>
   </LinearLayout>
</LinearLayout>

Now... is it important to have the second LinearLayout nested into the first one? Are there good reasons why I can't do this instead?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="50dp">

    <android.support.v4.widget.Space
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:id="@+id/view"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"/>
</LinearLayout>

A: I'm wondering you are told by whom to do the first xml? The second one should totally work. Just don't forget to include the orientation.
And tools:xxx is just for IDE preview purposes, it doesn't really matter.


text:
Q: Востановить бекап MySQL базы Пытаюсь востановить дамп базы из файла.
код:
 $dbhost=$host;
 $dblogin=$user;
 $dbpass=$password;
 $dbname=$database;

 $q=file_get_contents("http://".$_SERVER['SERVER_NAME']."/install/dump.sql");

 //Подключаемся к серверу баз данных
    $db = mysql_connect ($dbhost, $dblogin, $dbpass);
             mysql_select_db ($dbname, $db);

    if(!mysql_query($q,$db)) die('Ошибка запроса: '.mysql_error($db).'<br>');
        else echo 'Запрос успешно выполнен';
}

Получаю вот такой ответ:

Ошибка запроса: You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'INSERT INTO admin (login,
password) VALUES ('admin',
'21232f297a57a5a74389' at line 14

Вот фрагрмент базы:
CREATE TABLE IF NOT EXISTS `admin` (
  `login` varchar(16) NOT NULL DEFAULT '',
  `password` varchar(32) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=cp1251;

--
-- Дамп даних таблиці `admin`
--

INSERT INTO `admin` (`login`, `password`) VALUES
('admin', '21232f297a57a5a743894a0e4a801fc3');

-- --------------------------------------------------------

--
-- Структура таблиці `comments`
--

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_article` varchar(11) NOT NULL,
  `name` varchar(60) NOT NULL,
  `mail` varchar(60) NOT NULL,
  `text` varchar(500) NOT NULL,
  `date_add` varchar(18) NOT NULL,
  `public` int(1) NOT NULL,
  `st` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=cp1251 AUTO_INCREMENT=93 ;

14 строка на котороую ругается это INSERT INTO admin (login, password) VALUES
Не могу понять в чем проблема, бекам был сделан на этом же хостинге по средству Експорта из myadmin
A: Если вам не принципиально, залейте дамп через консоль. Например так:
cat my_dump.sql | mysql -v -u -h127.0.0.1 -p

UPDATE
читайте мануалы на оф сайте:
mysql_query() посылает один запрос (посылка нескольких запросов не поддерживается) активной базе данных сервера, на который ссылается переданный дескриптор link_identifier.
UPDATE 2
И вообще переходите на pdo


text:
Q: substitute word separators with space I just want to replace some word separators with a space.  Any hints on this? Doesn't work after converting to character either.
df <- data.frame(m = 1:3, n = c("one.one", "one.two", "one.three"))

> gsub(".", "\\1 \\2", df$n)
[1] "       "   "       "   "         "
> gsub(".", " ", df$n)
[1] "       "   "       "   "         "

A: You don't need to use regex for one-to-one character translation. You can use chartr().
df$n <- chartr(".", " ", df$n)
df
#   m         n
# 1 1   one one
# 2 2   one two
# 3 3 one three

A: You can try
gsub("[.]", " ", df$n)
#[1] "one one"   "one two"   "one three"

A: Set fixed = TRUE if you are looking for an exact match and don't need a regular expression.
gsub(".", " ", df$n, fixed = TRUE)
#[1] "one one"   "one two"   "one three"

That's also faster than using an appropriate regex for such a case.

A: I suggest you to do like this,
gsub("\\.", " ", df$n)

OR
gsub("\\W", " ", df$n)

\\W matches any non-word character. \\W+ matches one or more non-word characters. Use \\W+ if necessary.


text:
Q: Storing a object with localStorage I can't seem to find a way for localStorage to record the clicks variable when I refresh the browser.
I've tried using JSON.stringify and JSON.parse, but then found out about parseInt, which seems a better alternative (I'm just trying to store a number).
I'm brand new to programming and all the examples I checked were pure javascript, too complicated/poorly explained or outdated. Hope you can help me out. I've been trying to solve this issue for over a week.
Some more info: I'm using Phaser 2.5.0 with MAMP. Google Chrome v49.0.2623.112 (64-bit), OS X 10.8.5.

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });

var scoreText;
var clicks = 0;

function preload() {

    game.load.image('clickBox', 'assets/ClickMe.png');
    game.stage.backgroundColor = '#182d3b';
    game.stage.disableVisibilityChange = true;
}

function create() {

    localStorage.setItem('clicks', parseInt('clicks'));
    localStorage.getItem('clicks');

    button = game.add.button(game.width/2, game.height/2, 'clickBox', upScoreText);

    scoreText = game.add.text(30, 30, "CLICKS: " + clicks, {font: "20px Arial", fill: "#ffffff", align: "left"});

    button.scale.x = 0.5;
    button.scale.y = 0.5;
    button.anchor.setTo(0.5);
    button.inputEnabled = true;
}

function update () {

            scoreText.setText("CLICKS: " + clicks);
}

function upScoreText () {

     clicks++;
}

A: You should not store the literal clicks, but the variable with that name. Also there is no sense in calling parseInt on clicks, since it already is a number. Moreover, localStorage stores everything as a string, so whatever you do, it will end up being stored as a string anyway.
Storing:
localStorage.setItem('clicks', clicks); // is always stored as string

Reading:
clicks = +localStorage.getItem('clicks'); // `+` makes it a number

Now you have to put the above statements at the right place. It makes no sense to first write the value to storage and then read it out again: obviously the value will be the same after as before, and no advantage was taken from whatever was stored before you did this. You might as well skip those two lines then...
Instead you will want to read the value once, in the create function, and write the value whenever you change the it, i.e. in upScoreText:
function create() {
    // Load. If not exists in localStorage, use 0.
    // If it does, cast to number with `+`:
    clicks = +localStorage.getItem('clicks') || 0;
    // etc...
}

function upScoreText () {
    clicks++;
    // Save:
    localStorage.setItem('clicks', clicks);
}

Now you'll have an ever incrementing clicks variable that survives a page reload, but you'll probably need to add a way to reset the value back to 0.

A: Your using parseInt wrong i.e instead of
localStorage.setItem('clicks', parseInt('clicks'));

You should use
localStorage.setItem('clicks', parseInt(clicks));/*removed the quotes for the clicks*/

And i think ypu should check first whether the clicks variable exists in localStorage and then assign the variable clicks,but this is just a suggestion.you can implement it like this:-
var clicks=localStorage.getItem("clicks")||0;

not sure if you wanted this though :/


text:
Q: MVC 4 MEF View cannot find the @Model from another assembly I'm working on my custom CMS. I have the main application and modules. My problem is that whenever I load the view from my Module, the view cannot find the model assigned to that view.

CS0246: The type or namespace name 'EAccounting' could not be found (are you missing a using directive or an assembly reference?)

The view of that module is located in ~/Modules/EAccounting/Views/. I can call the module controller with no problem, also I can locate call the view from the controller with no problem, but the view itself cannot find the model from the loaded assemblies:
@model EAccounting.Models.Transaction
This is the code that loads the assemblies:
public class SafeDirectoryCatalog : ComposablePartCatalog
{
    private readonly AggregateCatalog _catalog;

    public SafeDirectoryCatalog(string directory)
    {
        var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);

        _catalog = new AggregateCatalog();

        foreach (var file in files)
        {
            try
            {
                var asmCat = new AssemblyCatalog(file);

                //Force MEF to load the plugin and figure out if there are any exports
                // good assemblies will not throw the RTLE exception and can be added to the catalog
                if (asmCat.Parts.ToList().Count > 0)
                {
                    _catalog.Catalogs.Add(asmCat);
                }
            }
            catch (ReflectionTypeLoadException)
            {
            }
            catch (BadImageFormatException)
            {
            }
        }
    }
    public override IQueryable<ComposablePartDefinition> Parts
    {
        get { return _catalog.Parts; }
    }
}

I'm sure that is nothing wrong with the assembly loading. Also if I move my module assembly .dll to my main bin folder (~/bin/) it works fine, so the problem must be that the view only able to search for the assembly in the main/bin folder.
How can I configure my system so that the view can search the assembly from another folder? Note: The assembly is loaded at runtime tho.

A: Also your post is a few month old, I think following link could perhaps answer your question :
http://shazwazza.com/post/Developing-a-plugin-framework-in-ASPNET-with-medium-trust
I hope this will help you.


text:
Q: On Digts of Cubes and Squares This is a pretty nice site I found, which contains special properties of all numbers between $1$ and $9999$, with the exception of few.
The number I noticed was $69$. All digits appear exactly once in  $69^2=4761$, and $69^3=328509$.
However, is the following true?

Are there an infinite number of $i$ for which there exists such an interger $n$ that $n^2$ and $n^3$ contain all digits exactly $i$ times?

Since a square or cube does not normally have a lot of same numbers, it would seem that the answer is false. However, I was not able to prove or disprove the above.
It is clear that if such a $n$ existed for $i$, $n \equiv 0 \pmod 3$ or $n \equiv 8 \pmod 9$ through modular inspection.
Any help would be appreciated.

A: Here is an extremely handwavy argument suggesting that there should be many examples.  To have a chance this works we need $n^2$ and $n^3$ to have exactly $10i$ digits between them.  This requires that $4.64 \cdot 10^{2i-1} \lt n \lt 10^{2i}$, where the $4.64$ is the cube root of $100$.  This forces $n^2$ to have $4i$ digits and $n^3$ to have $6i$ digits.  We now make the wild assumption that for large $i$ the digits are randomly selected and ask the probability that we get exactly $i$ of each digit.  As there are $10i$ digits, we can choose the places for zeros in $10i \choose i$ ways.  Having done that, we can choose the places for ones in $9i \choose i$ ways.  The chance we get exactly the same number of each digit is then $$p(i)=\frac {{10i \choose i}{9i \choose i}{8i \choose i}\dots {2i \choose i}}{10^{10i}}=\frac {(10i)!}{(i!)^{10}10^{10i}}$$  If we use Stirling's approximation we get $$p=\frac{(10i)^{10i}e^{10i}\sqrt{2\pi (10i)}}{i^{10i}10^{10i}e^{10i}(\sqrt{2\pi i})^{10}}=\frac{\sqrt{10}}{(2\pi i)^{9/2}}$$  For $i=4$ this is about $1.6 \cdot 10^{-6}$ while the exact answer is about $1.3 \cdot 10^{-6}$.  As there are over $5 \cdot 10^7$ numbers in our range we should expect tens of examples.  This is a number that would be easy to search by computer.  As $i$ gets larger the expected number of examples per decade will grow rapidly.  The $i^{9/2}$ divisor gets swamped by the $10^{2i}$ multiplier from the range of $n$.


text:
Q: Convert Unix TimeStamp into "x seconds ago" so I have a table which lists chat messages in my game server (chat messages are stored in a database) and I have a UNIX timestap like this (for example) 1455749769
Does anyone know how I can use php to convert the timestamp so it echos how long ago the chat message was for example: "5 Seconds Ago"
Here is my table

$name=$row['client_name'];
$time=$row['msg_time'];
$name=htmlentities($name);
        echo "
";
 echo " $time 	";
 echo " $name 	";
 echo " $msg 	";
 echo "
";
    }
    echo "
";
} else {
    echo "0 results";
echo "
";
}
$conn->close();
?>

Any help greatly appreciated :)

A: The timestamp is seconds since the Epoch, so just get the current timestamp and subtract:
$seconds = time() - $time

A: Just get the current time and substract:
$now = time();
//results into an unix like 1455750460
//then just substract:

$diff = $now - $time
// gives you the passed seconds

//readable
echo date('H:i:s', $diff);


text:
Q: Make hover resize element only affect the element I have a list of elements that have a bit of information, and I want the user to be able to hover over an element to see more information.
However, doing something like:
$('a.song').each(function() {
  var origwidth = $(this).width();
  var origheight = $(this).height();
  $(this).hover(
    function() {
      $(this).stop().animate({width: origwidth * 2, height: origheight * 2});
    }, function() {
      $(this).stop().animate({width: origwidth, height: origheight});
  });
});

causes the element to affect the position of other elements (instead of simply overlapping), and the width expansion is limited by the column-count: 5; in the ol css rules.
How can we make it so when the element expands it simply covers over any overlapping elements instead of pushing them, and properly expand the width even with column-count: 5;?

A: http://jsfiddle.net/Yk2du/1/
You could use position:absolute on the element and set the width of the container.
In the jsfiddle I also used z-index to make sure the hovered element shows over the top of the others.
ol li {
  display: inline-block;
  margin: 5px 10px;
  position:relative;
  width: 200px;
  height: 40px;
}

ol li a {
  background-color: #EEE;
  display: block;
  width: 200px;
  height: 40px;
  cursor: pointer;
  text-overflow:ellipsis;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
    position:absolute;
}

P.S. You can do this with CSS3 and no javascript.


text:
Q: Вопрос по file_get_contents() Есть страница, которая показывает echo file_get_contents('url'), можно ли узнать этот url?

A: Если вы знаете что на каком то сайте используется запрос на получение документа с другого сайта серверными методами, и у вас нет ни доступа ни возможности перехвата сигнала, то думаю что у вас нет возможности с точностью сказать куда идет запрос.
Может быть в теле документа есть какой то намек? посмотрите где лежат статические файлы (картинки, js, css)


text:
Q: Как обозначить такой формат даты? использую "vue good table". Для анализа дат "vue good table" использует "date-fns" Есть столбец "дата", который имеет свойство:
"dateInputFormat" - указывает формат даты, который должен быть у данных прилетающих с сервера,
и
"dateOutputFormat" - указывает формат даты, который будет выведен пользователю.
С сервера прилетает запись в которой дата указана как - "2021-06-01 22:55:20.913".
В коде я указываю формат 'yyyy-MM-dd hh:mm:ss', однако данные в таблице не отображаются, а в консоли появляется ошибка
Какой формат тогда надо указывать?

            {
              label: 'Дата',
              field: 'createdAt',
              type: 'date',
              dateInputFormat: 'yyyy-MM-dd hh:mm:ss',
              dateOutputFormat: 'yyyy-MM-dd hh:mm:ss',
            }

Мне прилетает запись, в которой дата записана как - "2021-06-01 22:55:20.913".

A: Попробуйте это
yyyy-MM-dd HH:mm:ss.SSS

Вместо этого
yyyy-MM-dd hh:mm:ss

Вы забыли добавить милисекунды в формат))


text:
Q: How to loop all properties in a Class I have a class in my Delphi app where I would like an easy and dynamic way of resetting all the string properties to '' and all the boolean properties to False
As far as I can see on the web it should be possible to make a loop of some sort, but how to do it isn't clear to me.

A: if you are an Delphi 2010 (and higher) user then there is a new RTTI unit (rtti.pas). you can use it to get runtime information about your class and its properties (public properties by default, but you can use {$RTTI} compiler directive to include protected and private fields information).
For example we have next test class with 3 public fields (1 boolean and 2 string fields (one of them is readonly)).
    TTest = class(TObject)
      strict private
        FString1 : string;
        FString2 : string;
        FBool : boolean;
      public
        constructor Create();
        procedure PrintValues();

        property String1 : string read FString1 write FString1;
        property String2 : string read FString2;
        property BoolProp : boolean read FBool write FBool;
    end;

constructor TTest.Create();
begin
    FBool := true;
    FString1 := 'test1';
    FString2 := 'test2';
end;

procedure TTest.PrintValues();
begin
    writeln('string1 : ', FString1);
    writeln('string2 : ', FString2);
    writeln('bool: ', BoolToStr(FBool, true));
end;

to enumerate all properties of object and set it values to default you can use something like code below.
First at all you have to init TRttiContext structure (it is not neccesary, because it is a record). Then you should get rtti information about your obejct, after that you can loop your properties and filter it (skip readonly properties and other than boolean and stirng). Take into account that there are few kind of strings : tkUString, tkString and others (take a look at TTypeKind in typinfo.pas)
    TObjectReset = record
      strict private
      public
        class procedure ResetObject(obj : TObject);  static;
    end;

{ TObjectReset }

class procedure TObjectReset.ResetObject(obj: TObject);
var ctx : TRttiContext;
    rt : TRttiType;
    prop : TRttiProperty;
    value : TValue;
begin
    ctx := TRttiContext.Create();
    try
        rt := ctx.GetType(obj.ClassType);

        for prop in rt.GetProperties() do begin
            if not prop.IsWritable then continue;

            case prop.PropertyType.TypeKind of
                tkEnumeration : value := false;
                tkUString :      value := '';
                else continue;
            end;
            prop.SetValue(obj, value);
        end;
    finally
        ctx.Free();
    end;
end;

simple code to test:
var t : TTest;
begin
    t := TTest.Create();
    try
        t.PrintValues();
        writeln('reset values'#13#10);
        TObjectReset.ResetObject(t);
        t.PrintValues();
    finally
        readln;
        t.Free();
    end;
end.

and result is
string1 : test1
string2 : test2
bool: True
reset values

string1 :
string2 : test2
bool: False

also take a look at Attributes, imo it is good idea to mark properties (wich you need to reset) with some attribute, and may be with default value like:
[ResetTo('my initial value')]
property MyValue : string read FValue write FValue;

then you can filter only properties wich are marked with ResetToAttribute

A: Please note, the following code works only for published properties of a class! Also, the instance of a class passed to the function below must have at least published section defined!
Here is how to set the published string property values to an empty string and boolean values to False by using the old style RTTI.
If you have Delphi older than Delphi 2009 you might be missing the tkUString type. If so, simply removeit from the following code:
uses
  TypInfo;

procedure ResetPropertyValues(const AObject: TObject);
var
  PropIndex: Integer;
  PropCount: Integer;
  PropList: PPropList;
  PropInfo: PPropInfo;
const
  TypeKinds: TTypeKinds = [tkEnumeration, tkString, tkLString, tkWString,
    tkUString];
begin
  PropCount := GetPropList(AObject.ClassInfo, TypeKinds, nil);
  GetMem(PropList, PropCount * SizeOf(PPropInfo));
  try
    GetPropList(AObject.ClassInfo, TypeKinds, PropList);
    for PropIndex := 0 to PropCount - 1 do
    begin
      PropInfo := PropList^[PropIndex];
      if Assigned(PropInfo^.SetProc) then
      case PropInfo^.PropType^.Kind of
        tkString, tkLString, tkUString, tkWString:
          SetStrProp(AObject, PropInfo, '');
        tkEnumeration:
          if GetTypeData(PropInfo^.PropType^)^.BaseType^ = TypeInfo(Boolean) then
            SetOrdProp(AObject, PropInfo, 0);
      end;
    end;
  finally
    FreeMem(PropList);
  end;
end;

Here is a simple test code (note the properties must be published; if there are no published properties in the class, at least empty published section must be there):
type
  TSampleClass = class(TObject)
  private
    FStringProp: string;
    FBooleanProp: Boolean;
  published
    property StringProp: string read FStringProp write FStringProp;
    property BooleanProp: Boolean read FBooleanProp write FBooleanProp;
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  SampleClass: TSampleClass;
begin
  SampleClass := TSampleClass.Create;
  try
    SampleClass.StringProp := 'This must be cleared';
    SampleClass.BooleanProp := True;
    ResetPropertyValues(SampleClass);
    ShowMessage('StringProp = ' + SampleClass.StringProp + sLineBreak +
      'BooleanProp = ' + BoolToStr(SampleClass.BooleanProp));
  finally
    SampleClass.Free;
  end;
end;


text:
Q: Calculating the number of processor cores in linux How can one deduce the amount of processors a linux os has by using elapsed time(time it takes to execute any section of code).I have the clock ticks it took to perform a particular section of code .How do i measure the amount of cores on the machine from that

A: You can get the information about CPU(No of processors & no of cores,etc) using
cat /proc/cpuinfo.
but if you are trying to calculate the clock ticks taken in executing particular code inside linux-kernel you can try.
#include <sys/time.h>

unsigned long ini,end;
preempt_disable();
rdtscl(ini);
...your code....
rdtscl(end);
preempt_enable();
printk("time lapse in cpu clics: %lu\n",(end-ini));

for more details http://www.xml.com/ldd/chapter/book/ch06.html or download.intel.com/embedded/software/IA/324264.pdf and if your code is taking more time then you can also use jiffies effectively.
And for user-space application you can use various timing functions which give the time in nanosecond resolution or oprofile(http://oprofile.sourceforge.net/about/) & refer Timer function to provide time in nano seconds using C++

A: I guess we could do something like this:
Write some code that does some heavy math work, that can be run in parallel - such as a naive method for finding primes. Then run that in multiple threads, starting with one, then going up. At some point, the time it takes to figure out the N first primes will be, the number of threads will be the same as the number of (available) processor cores.
But it's a very clumsy method to find the number of processors, and it almost certainly won't work on a system with high load, or a system that is running on a virtual machine, etc, etc.


text:
Q: Flutter - Format Exception : Unexpected end of input (at character 1) I'm facing this Exception while loading json from a .json file. complete Exception is :
E/flutter ( 4062): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
FormatException: Unexpected end of input (at character 1)
E/flutter ( 4062):
E/flutter ( 4062): ^
E/flutter ( 4062):
E/flutter ( 4062): #0      _ChunkedJsonParser.fail (dart:convert-  patch/convert_patch.dart:1405:5)
E/flutter ( 4062): #1      _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
E/flutter ( 4062): #2      _parseJson (dart:convert-patch/convert_patch.dart:41:10)
E/flutter ( 4062): #3      JsonDecoder.convert (dart:convert/json.dart:506:36)
E/flutter ( 4062): #4      JsonCodec.decode (dart:convert/json.dart:157:41)
E/flutter ( 4062): #5      _HomePageState.loadJsonData.<anonymous closure>.<anonymous closure> (package:audio_player/presentation/pages/home_page.dart:22:35)
E/flutter ( 4062): #6      State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter ( 4062): #7      _HomePageState.loadJsonData.<anonymous closure> (package:audio_player/presentation/pages/home_page.dart:20:27)
E/flutter ( 4062): #8      _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter ( 4062): #9      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 4062): <asynchronous suspension>
E/flutter ( 4062): #10     _HomePageState.loadJsonData (package:audio_player/presentation/pages /home_page.dart:19:5)
E/flutter ( 4062): <asynchronous suspension>

My Json file path (lib/utils/json/popular_books.json) and code look like this:
[
  {
   "rating":"4.5",
   "title":"sometitle",
   "text":"sometext",
   "img":"lib/utils/assets/image_1",
  }
   ...
]

My images are in the same folder utils/assets. I'm loading json
  List? popularBooks;

  loadJsonData() async {
    await DefaultAssetBundle.of(context).loadString("lib/utils/json/popular_books.json").then(
          (loadedJson) => setState(
            () {
              popularBooks = json.decode(loadedJson);
            },
          ),
        );
      }

  @override
  void initState() {
  loadJsonData();
  super.initState();
 }

And I'm trying to load only the images in the page view :
PageView.builder(
              itemCount: popularBooks==null?0:popularBooks!.length,
              controller: _controller,
              itemBuilder: (context, index) {
                return Container(
                  margin: EdgeInsets.only(right: 10),
                  height: 150,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                   ),
                   child: Image.asset("${popularBooks![index]["img"]}"),
                 );
               },
             ),

And then this Format Exception If you have any fix please share it I'd me very thankful. <3

A: Your JSON is invalid. With a json validator you can spot the problem. In your JSON it is the following syntax error:
[
  {
   "rating":"4.5",
   "title":"sometitle",
   "text":"sometext",
   "img":"lib/utils/assets/image_1", <-- This comma is the problem
  }
]


text:
Q: Package pgfkeys Error: I do not know the key '/tikz/box' and I am going to ignore it When I am compiling this code using xelatex 2018:
\begin{tikzpicture}[sibling distance=80pt]
   \node[box] {TeX}
   child {node[box] {Plain\TeX}} child {node[box] {\LaTeX}
   child {node[box] {amsmath}} child {node[box] {graphicx}} child {node[box] {hyperref}}
}; \end{tikzpicture}

Throw this error:
Package pgfkeys Error: I do not know the key '/tikz/box' and I am going to ignore it. Perhaps you misspelled it. ...icture}[sibling distance=80pt] \node[box]

this is my reference:
\usepackage{pgf}
\usepackage{tikz} % Required for drawing custom shapes
\usetikzlibrary{shapes,arrows,automata}

What package missing?

A: box is not a predefined style so you may want to define it in your code. One possible definition could be
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{automata}
\begin{document}
\begin{tikzpicture}[sibling distance=80pt,box/.style={rectangle,draw}]
   \node[box] {TeX}
   child {node[box] {Plain\TeX}} child {node[box] {\LaTeX}
   child {node[box] {amsmath}} child {node[box] {graphicx}} child {node[box] {hyperref}}
}; \end{tikzpicture}
\end{document}

A: I am also facing error

Extra }, or forgotten \endgroup. }

Kindly guide, what is missing in it.
I have copied the code from below URL, and only modify the box items
How to draw a figure of taxonomy in tikz or similars
\documentclass[border=10pt]{standalone}
\usepackage[edges]{forest}
\usetikzlibrary{shadows.blur}
\begin{document}
% addaswyd o ateb marmot: https://tex.stackexchange.com/a/436172/
% starting point: https://tex.stackexchange.com/a/341454/121799
\begin{forest}
  forked edges,
  for tree={font=\sffamily, rounded corners, top color=gray!5, bottom color=gray!10, edge+={darkgray, line width=1pt}, draw=darkgray, align=center, anchor=children},
  before packing={where n children=3{calign child=2, calign=child edge}{}},
  before typesetting nodes={where content={}{coordinate}{}},
  where level<=1{line width=2pt}{line width=1pt},
  [SDA, blur shadow
    [Symetric
      [310131432]
    ]
    [Asymetric
     [Homomorphic
        [Fog-Based
            [PHE
                [61 79 80]
            ]
        ]
        [Non-Fog-Based
            [PHE
                [Paillier
                    [6,11,23,30,31,34,37,39,40,44,53,54,56,69,70,72,73,74,75,76]
                ]
                [Elgamal
                    [4,5,38,71]
                ]
            ]
            [SWHE
                [7,84]
            ]
            [FHE Schemes
                [57,58,71]
            ]
        ]

     ]
     [Non Homomorphic
        [No-Fog-Based
            [SMPC
                    [678283]
            ]
            [Others
                [89212645]
            ]
        ]
        [Fog-Based
            [62]
        ]
     ]
    ]
  ]
\end{forest}
\end{document}


text:
Q: DBD::MySQL: LongReadLen and LongTruncOk Have the attributes LongReadLen and LongTruncOk when using DBD::mysql as driver for the Perl5 Database Interface (DBI) any meaning? I didn't found these attributes in the DBD::mysql documentation but I found some example on the internet which uses these attributes with DBD::mysql.

A: That is a DBI attribute which applies to all handles.  Its documented in the DBI library.  AFAIK it applies to DBD::mysql and every DBI driver.

A: If you search dbdimp.c I find:
 *
 *  Name:    dbd_st_blob_read
 *
 *  Purpose: Used for blob reads if the statement handles "LongTruncOk"
 *           attribute (currently not supported by DBD::mysql)

I could not find any reference to longreadlen. Note, I don't use DBD::mysql myself and this was just a quick search in the code.


text:
Q: $f_1:\left(0, \frac{\pi}{2}\right), f_1(x)=\left(\frac{\ln\left(\cos^2(x)\right)}{\ln\left(x^3\right)}\right)$ let $f_1:\left(0, \frac{\pi}{2}\right),  f_1(x)=\left(\frac{\ln\left(\cos^2(x)\right)}{\ln\left(x^3\right)}\right)$
$\rightarrow$ The ln function is only used for an interval with positive values so I assume it is continuous.
$$|f(x) - f(x_0)|$$
$$\left|\frac{\ln\left(\cos^2(x)\right)}{\ln\left(x^3\right)}- \frac{\ln\left(\cos^2(x_0)\right)}{\ln\left(x_0^3\right)}\right|$$
Question: How can I go on to get $|x-x_0|$ to have my $\delta$ and finally to define the $\epsilon$.
I appreciate every hint.


text:
Q: Finding the partial intraclass correlation How do I calculate the partial correlation with an intraclass correlation? I tried asking earlier, but provided too much detail because it's not easy to explain what I mean in a short or simple way. I'll try to ask again in a more simple way but perhaps in a way that's more interpretable. I want to know how to find/calculate the partial correlation between 2 groups of people using intraclass correlation. The issue that arises here is the following: if we call the value X group 1 and Y group 2 and Z the value we need to adjust for when trying to find the partial intraclass correlation - and we know the correlation between the values in group 1 and 2 is 0.5, (let's say group 1 is the bmi values in mothers and group 2 the bmi values in their brothers), how do I find out what the correlation between the bmi values in mothers and their brothers is when adjusting for the third variable (let's call this third variable soft drink consumption? The mother-her brother correlation in terms of bmi is already 0.5, (xy) and if the correlation between mothers bmi and her soft drink consumption is 0.4 (XZ) and the correlation between mothers brother's soft drink consumption and bmi is 0.45 (YZ), how do I then find the partial correlation after soft drink consumption has been controlled for, when there isn't anything provided in the partial correlation coefficient that takes into consideration what the correlation between mothers soft drink comsumtpions and her brothers soft drink consumption is? When referring to the adjusted xy,z correlation, and x is mothers bmi and y is her brothers bmi and z is soft drink comsumption, the only things taken into consideration by the partial correlation coefficient is the xy correlation (which is the correlation between mothers bmi and her brothers bmi, xz (which is mothers bmi and her soft drink comsumption and yz (which is mothers brothers bmi and his soft drink comsumption). I feel like the correlation between mothers soft drink consumption and her brothers soft drink comsumption is missing here in order to find out the partial correlation between mother-her brothers bmi after adjusting for soft drink comsumption.

A: The intraclass correlation (ICC) is an estimate of how consistent a measurement is when it is taken multiple times (e.g., across time). The example you've provided is not a situation where ICC would be appropriate. It sounds like you may be tripped-up by the fact that you are considering associations between family members (i.e., observations are grouped), which in some contexts should be analyzed with a mixed effect model (which can be used to compute the ICC sometimes). However, in your example, the unit of observation would be the family. It would be appropriate the run the analysis as a simple regression. Alternatively, if you really do want the partial correlation, residualize each person's BMI with respect to their own soft drink consumption (i.e., run BMI ~ SoftDrink, then take the residuals, once for mothers-only, then for brothers-only), and then compute the correlation using the residuals.


text:
Q: d3 svg rect height becomes NaN I am unable to debug the reason why the rect height becomes NaN , with the embedded code below.
Instead , if I just have .attr("height",yScale.bandwidth()) , then I would see proper height in HTML elements.
The csv file is loaded properly , as I'm able to access the country and year properly.
If needed , I can upload the full code.

var rHeight       = function(d) { return d.ratio;};

//// data is of CSV format :
//country,ratio,year
//United States,0.33,1924
//United States,0.33,1928
//United States,0.33,1932
//United States,0.0,1936
//United States,0.17,1948
//United States,0.2,1952
//::
//::
//

        // draw rectangles
        svg.selectAll(".bar")
            .data(rpc_data)
            .enter()
            .append("rect")
            .attr("class","bar")
            .attr("x",xMap)
            .attr("y",yMap)
            .attr("width",xScale.bandwidth())
            .attr("height",Math.floor((yScale.bandwidth())*rHeight) );

A: As we can see from your snippet rHeight it is a function, so when you run:
Math.floor((yScale.bandwidth())*rHeight

it is the same as number * function and you get NaN as result (check demo).

console.log(1 * function() {});

You should calculate the height this way:
...
.attr("height", function(d){
  return Math.floor((yScale.bandwidth()) * rHeight(d)
}));


text:
Q: Listing huge amount files and directories include subdirectories in Adobe AIR I am trying to list files and directories and copy all files existing into any other folder.
By the way, there are many files and directories more than 1000 000+.
Here is a part of code.
private function getFileList(sourceDir:String):void{
    var file:File = File.userDirectory.resolvePath(sourceDir);
    file.addEventListener(FileListEvent.DIRECTORY_LISTING, directory_listing);
    file.getDirectoryListingAsync();
}
private function directory_listing(e:FileListEvent):void{
    var getfiles:Array = e.files;

    for each(var item:File in e.files){

        if(checkDir(item.nativePath)){
            // It is a directory, more logic!
            totalDirNum++;
            item.addEventListener(FileListEvent.DIRECTORY_LISTING, directory_listing);
            item.getDirectoryListingAsync();
        }
        else{
        // It is a file, more logic!
            totalFileNum++;
                if(analyzeFile(item) === true){
                if(overwriteChk.selected === false){ // Don't overwrite same file
                            if(checkFile(destinationDir.nativePath + "\\" + item.name) === false){
                            copyInto(item, destinationDir.resolvePath(destinationDir.nativePath + "\\" + item.name));
                            copiedNum++;
                        }
                        else uncopiedNum++;
                    }
                    else{ // Overwrite same file
                        copyInto(item,destinationDir.resolvePath(destinationDir.nativePath + "\\" + item.name));
                        copiedNum++;
                    }

                }
                else{
                    skippedNum++;
                    }
            }
    }

As you see, it executes recursive directory_listing().
In case of little files and directories, it works clearly.
But, for example, in the following case it not works clearly(appear not responding.)
Root Directory : A!
A includes 500 000+ subdirectories.
Each subdirectories include 4 or 5 files and one or two subdirectories.
And also the subdirectoy include a 4 or 5 files.
So, I need to copy all files of "A" folder to the specific folder (B!).
Program is stopped in first before loop. i.e. Named "A" folder include huge subfolders, so when program run to select a "A" folder, then it is stopped just in "A" folder listing(stopped at getDirectoryListingAsyc()). So, actually it is not called recursive.
Here is my full source code.
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       width="800" height="600"
                       title="eveningCopier - Niao Jina"
                       creationComplete="initApp()">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;

            public var sourceDir:File;
            public var destinationDir:File;

            public var totalDirNum:uint;
            public var totalFileNum:uint;
            public var copiedNum:uint;
            public var skippedNum:uint;
            public var uncopiedNum:uint;

            public var startTime:String;
            public var finishTime:String;

            /**
             * Boot Function
             **/
            public function initApp():void{
                sourceBtn.addEventListener(MouseEvent.CLICK, click_sourceBtn);
                destinationBtn.addEventListener(MouseEvent.CLICK, click_destinationBtn);
                startBtn.addEventListener(MouseEvent.CLICK, click_startBtn);

                totalDirNum     = 0;
                totalFileNum    = 0;
                copiedNum       = 0;
                skippedNum      = 0;
                uncopiedNum     = 0;
            }

            /**
             * Event Listener when click "Source" button
             **/
            protected function click_sourceBtn(e:MouseEvent):void{
                sourceDir = new File();
                sourceDir.addEventListener(Event.SELECT, select_source);
                sourceDir.browseForDirectory("Please select a source directory...");
            }
            private function select_source(evt:Event):void {
                sourceTxt.text = sourceDir.nativePath;
            }

            /**
             * Event Listener when click "Destination" button
             **/
            protected function click_destinationBtn(e:MouseEvent):void{
                destinationDir = new File();
                destinationDir.addEventListener(Event.SELECT, destination_select);
                destinationDir.browseForDirectory("Please select a source directory...");
            }
            private function destination_select(evt:Event):void {
                destinationTxt.text = destinationDir.nativePath;
            }

            /**
             * Event Listener when click "Start" button
             **/
            protected function click_startBtn(e:MouseEvent):void{
                if(sourceTxt.text == "") Alert.show("Please select a source directory", "Warning");
                else if(destinationTxt.text == "") Alert.show("Please select a destination directory", "Warning");

                if(checkDir(sourceTxt.text) === false) Alert.show("A selected Source folder:\n" + sourceTxt.text + "\n is not exist. Please check!", "Warning");
                else if(checkDir(destinationTxt.text) === false) Alert.show("A selected Destination folder:\n" + destinationTxt.text + "\n is not exist. Please check!", "Warning");

                //Alert.show(checkFile("D:\\New Folder\\f.txt").toString());
                //Alert.show(checkDir("D:\\New Folder\\f.txt").toString());

                workedTextArea.text = "";
                currentLabel.text   = "";
                timeLabel.text  = "";
                totalDirLabel.text  = "";
                totalFileLabel.text = "";
                copiedLabel.text    = "";
                skippedLabel.text   = "";
                uncopiedLabel.text  = "";

                totalDirNum     = 0;
                totalFileNum    = 0;
                copiedNum       = 0;
                skippedNum      = 0;
                uncopiedNum     = 0;

                startTime = getNow() + "\n";

                getFileList(sourceTxt.text);
            }

            /**
             * Get a current date and time as format - YYYY-MM-DD HH:II:SS
             *
             * @return String
             **/
            public function getNow():String{
                var now:Date = new Date();
                return now.getFullYear() + "-" + now.getMonth() + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
            }

            /**
             * Check if the directory is exist.
             * @param dirName:String Path of the directory
             * @return Boolean true or false
             **/
            private function checkDir(dirName:String):Boolean{
                var dir:File = File.userDirectory.resolvePath(dirName);
                return dir.isDirectory;
            }

            /**
             * Check if the file is exist.
             * @param fileName:String Path of the file
             * @return Boolean true or false
             **/
            private function checkFile(fileName:String):Boolean{
                var file:File = File.userDirectory.resolvePath(fileName);
                return file.exists;
            }

            /**
             * Ananlyze a structure of files and directory
             * If is a folder, loop in its subfolder.
             * If is a file, copy to the destination folder
             *
             * @param sourceDir:String
             **/
            private function getFileList(sourceDir:String):void{
                var file:File = File.userDirectory.resolvePath(sourceDir);
                file.addEventListener(FileListEvent.DIRECTORY_LISTING, directory_listing);
                file.getDirectoryListingAsync();
            }

            private function directory_listing(e:FileListEvent):void{
                var getfiles:Array = e.files;

                for each(var item:File in e.files){
                    trace(item.nativePath);
                    currentLabel.text = "Latest In : " + item.nativePath;

                    if(checkDir(item.nativePath)){
                        // It is a directory, more logic!
                        totalDirNum++;
                        item.addEventListener(FileListEvent.DIRECTORY_LISTING, directory_listing);
                        item.getDirectoryListingAsync();
                    }
                    else{
                        // It is a file, more logic!
                        totalFileNum++;
                        if(analyzeFile(item) === true){
                            if(overwriteChk.selected === false){ // Don't overwrite same file
                                if(checkFile(destinationDir.nativePath + "\\" + item.name) === false){
                                    copyInto(item, destinationDir.resolvePath(destinationDir.nativePath + "\\" + item.name));
                                    copiedNum++;
                                }
                                else uncopiedNum++;
                            }
                            else{ // Overwrite same file
                                copyInto(item, destinationDir.resolvePath(destinationDir.nativePath + "\\" + item.name));
                                copiedNum++;
                            }

                        }
                        else{
                            skippedNum++;
                        }
                    }
                }

                finishTime  = getNow();
                timeLabel.text = startTime + finishTime;

                totalDirLabel.text  = "Total Dir : " + totalDirNum;
                totalFileLabel.text = "Total Files : " + totalFileNum;
                copiedLabel.text    = "Copied Files : " + copiedNum;
                skippedLabel.text   = "Skipped Files : " + skippedNum;
                uncopiedLabel.text  = "Uncopied Files : " + uncopiedNum;
            }

            /**
             * Copy files
             * @param sourceFilePointer:File
             * @param destinationDirPointer:File
             * @return void
             **/
            private function copyInto(sourceFilePointer:File, destinationDirPointer:File):void{
                sourceFilePointer.copyTo(destinationDirPointer, true);

                if(logsChk.selected === true)
                    workedTextArea.text += sourceFilePointer.nativePath + "\n";
            }

            private function analyzeFile(filePointer:File):Boolean{
                //Alert.show(filePointer.extension + "\n" + filePointer.size + "\n" + filePointer.name.indexOf("@"));
                if((filePointer.extension) == null && (filePointer.size/1024 > 2) && (filePointer.name.indexOf("@") == -1))
                    return true;
                else
                    return false;
            }
        ]]>
    </fx:Script>

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <s:BorderContainer width="100%" height="100%">
        <s:VGroup width="90%" height="5%" left="0">
            <s:HGroup width="100%">
                <s:Button id="sourceBtn" label="Source"/>
                <s:TextInput id="sourceTxt" width="90%" fontSize="11"/>
            </s:HGroup>
            <s:HGroup width="100%">
                <s:Button id="destinationBtn" label="Destination"/>
                <s:TextInput id="destinationTxt" width="90%" fontSize="11"/>
            </s:HGroup>
        </s:VGroup>

        <s:Button id="startBtn" label="Start" height="48" top="0" right="0"/>

        <s:HGroup top="50" width="100%">
            <s:Label id="currentLabel" width="90%" height="19" text="Latest In : "
                     textAlign="left" verticalAlign="middle"/>
            <s:CheckBox id="overwriteChk" label="Overwrite" selected="false"/>
            <s:CheckBox id="logsChk" label="Logs" selected="false"/>
        </s:HGroup>

        <s:TextArea id="workedTextArea" x="0" top="77" width="100%" height="90%" editable="false"/>

        <s:HGroup width="100%" height="5%" bottom="0">
            <s:Label id="timeLabel" width="20%" height="100%" textAlign="center" verticalAlign="middle" fontSize="11"/>
            <s:Label id="totalDirLabel" width="16%" height="100%" textAlign="center" verticalAlign="middle"/>
            <s:Label id="totalFileLabel" width="16%" height="100%" textAlign="center" verticalAlign="middle"/>
            <s:Label id="copiedLabel" width="16%" height="100%" textAlign="center" verticalAlign="middle"/>
            <s:Label id="skippedLabel" width="16%" height="100%" textAlign="center" verticalAlign="middle"/>
            <s:Label id="uncopiedLabel" width="16%" height="100%" textAlign="center" verticalAlign="middle"/>
        </s:HGroup>
    </s:BorderContainer>

</s:WindowedApplication>

A: Your problem lies within the execution time. If you're trying to perform everything in one go it will use all the CPU it can get. If one thread is being executed for longer than X seconds (usually 15), flash will abort it saying it takes too much.
Before starting your loop, take a timestamp with getTimer() and in the loop, in the beginning of your loop check if the startTimestamp - currentTimestamp is less than 5000 (5 seconds). If it is, break the array and start it over (with or without delay, flash will allow it) from the place you've left.
For this type of operations it would make sense to use workers, check this.
Here's an abstract example:
var counter:int = 0; // our progress
var startTime:int;

function increaseCounter():void
{
    startTime = getTimer();
    while(true) // infinite loop
    {
        if (getTimer() - startTime  > 5000)
        {
           increaseCounter();
           break;
        }

        counter++;

        if (counter >= int.MAX_VALUE) // our custom loop exit
        {
           trace(counter);
           break;
        }
    }
}

A: Though this thread seems to be quite old but I am posting a working code here which I wrote for searching files with given search string. It goes through all subfolders and pretty fast to respond in comparison to File.getDirectoryListing()
Here is my code
        protected function performSearch(event:MouseEvent):void
        {
            searchResults = new Array(); // instance variable
            foldersToBeSearched = new Array(); // instance variable

            // keep file search list empty at start
            fileSearchList.dataProvider = searchResults;

            // instance level variable to store search string
            searchString = searchText.text.toLowerCase();

            // add root folder to array
                    foldersToBeSearched.push(File.applicationStorageDirectory);
            findoutFolderNames(File.applicationStorageDirectory);

            // keep and eye on folder search counter
            setTimeout(checkAsyncFolderCounter, 500);

            // show controls if search is on
            showHideControlsAsPerSearchNeed();

        }

        // Because folder search is async hence use timeout to confirm if all folders are listed
        private function checkAsyncFolderCounter():void
        {
            if(foldersToBeSearched.length === counterCapturedLast)
            {
                // I am done searching all folders and subfolder
                // show this data now
                fileSearchList.dataProvider = searchResults;
                trace(searchResults.length);
            }
            else
            {
                // I am not yet done with folders...keep finding
                counterCapturedLast = foldersToBeSearched.length;
                setTimeout(checkAsyncFolderCounter, 500);
            }
        }

        // Find out all folders in this folder
        private function findoutFolderNames(folder:File):void
        {
            folder.addEventListener(FileListEvent.DIRECTORY_LISTING, directoryListingHandler);
            folder.getDirectoryListingAsync();
        }

        // CHECK ALL FILES AND FOLDER AND FIND FOR SEARCH STRING OTHERWISE ADD FOLDER TO SEARCH FOLDERS LIST
        private function directoryListingHandler(event:FileListEvent):void
        {
            event.target.removeEventListener(FileListEvent.DIRECTORY_LISTING, directoryListingHandler);
            var list:Array = event.files;

            for (var i:uint = 0; i < list.length; i++)
            {
                var file:File = list[i];
                if(file.isDirectory)
                {
                    foldersToBeSearched.push(file);
                    findoutFolderNames(file);
                }
                else
                {
                    if(file.extension === "drl" && file.name.toLowerCase().indexOf(searchString) !== -1)
                    {
                        searchResults.push({label: file.name, creationDate: file.creationDate, nativePath: file.nativePath});
                    }
                }
            }

            trace("Folder Count " + foldersToBeSearched.length);
        }


text:
Q: How can I fix this Python script? I'm trying to convert a CVS repository to Git using cvs2svn and am following the directions on this page. I got to step 7 but am getting an error running git-move-refs.py:
Traceback (most recent call last):
  File "../../cvs2svn-trunk/contrib/git-move-refs.py", line 23, in ?
    from subprocess import Popen, PIPE, call
ImportError: No module named subprocess

For reference, this is what the script shows:
usage = 'USAGE: %prog [options]'

import sys
import optparse
from subprocess import Popen, PIPE, call

I'm not a Python expert but from browsing the web it looks like subprocess is a standard module, right? I'm using a Python installation built from source for version 2.6.3. What am I missing for this script to work?

A: I'm guessing that you have an old version (pre-2.4) of Python at /usr/bin/python, from your distribution, and the Python 2.6 you compiled is somewhere else (like /usr/local/bin/python). You have the Python 2.6 executable on your path before /usr/bin, so when you execute python from the command-line you get Python 2.6.
However, looking at the cvs2svn source code, git-move-refs.py's interpreter line is hard-coded to
#!/usr/bin/python

instead of #!/usr/bin/env python, which means when you run the script it uses the old Python.
As a workaround, run the script by passing it to your Python 2.6 interpreter:
user@host$ python /path/to/cvs2svn/contrib/git-move-refs.py


text:
Q: How to use 2 different change_list.html for 2 applications in the same django project I have 2 applications in the django project. I want to add different widgets in the change_list.html for the 2 different applications. In settings.py, after adding the change_list.html in the admin directory of the templates in both the applications respectively as,
TEMPLATE_DIRS = (
"/home/path/project/application1/templates",
"/home/path/project/application2/templates",
)
I notice that the change_list.html template considered is from the application1. Only if I comment it, the template from application2 is considered. How to go about? I want both of them to be considered for the 2 different applications. Please suggest.

A: Read the section on overriding admin templates: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates (more specifically https://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model)
Place your change_list.html in admin/application1 in one of the folders parsed by TEMPLATE_DIRS or one of the template loaders and that template will be served only for application1.
Your current code is always telling django to prioritize matches on the first path over the second.


text:
Q: UICollectionViewCell Shake I have created a UICollectionView and would like to have all the cells shake like the edit mode of the springboard on the iPhone. I have created my shake code but don't know how to implement it. I have custom cells so I assume it goes in there but don't know how it gets implemented. Thank You.
#define degreesToRadians(x) (M_PI * (x) / 180.0)
#define kAnimationRotateDeg 0.5
#define kAnimationTranslateX 1.0
#define kAnimationTranslateY 1.0

//startJiggling

int count = 1;
CGAffineTransform leftWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? +1 : -1 ) ));
CGAffineTransform rightWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? -1 : +1 ) ));
CGAffineTransform moveTransform = CGAffineTransformTranslate(rightWobble, -kAnimationTranslateX, -kAnimationTranslateY);
CGAffineTransform conCatTransform = CGAffineTransformConcat(rightWobble, moveTransform);

    self.transform = leftWobble;  // starting point

    [UIView animateWithDuration:0.1
                          delay:(count * 0.08)
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
                     animations:^{ self.transform = conCatTransform; }
                     completion:nil];

A: Swift 5 Easy like this
Enter this 2 functions to your UICollectionViewCell and call it when ever you want to animate/stop, ex: cell render
func shake() {
    let shakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shakeAnimation.duration = 0.05
    shakeAnimation.repeatCount = 2
    shakeAnimation.autoreverses = true
    let startAngle: Float = (-2) * 3.14159/180
    let stopAngle = -startAngle
    shakeAnimation.fromValue = NSNumber(value: startAngle as Float)
    shakeAnimation.toValue = NSNumber(value: 3 * stopAngle as Float)
    shakeAnimation.autoreverses = true
    shakeAnimation.duration = 0.15
    shakeAnimation.repeatCount = 10000
    shakeAnimation.timeOffset = 290 * drand48()

    let layer: CALayer = self.layer
    layer.add(shakeAnimation, forKey:"shaking")
}

func stopShaking() {
    let layer: CALayer = self.layer
    layer.removeAnimation(forKey: "shaking")
}

Help Source from Git

A: If anyone is curious on how to do this in Swift 2.0 the below should be a good starting point.
let animationRotateDegres: CGFloat = 0.5
let animationTranslateX: CGFloat = 1.0
let animationTranslateY: CGFloat = 1.0
let count: Int = 1

func wobble() {
    let leftOrRight: CGFloat = (count % 2 == 0 ? 1 : -1)
    let rightOrLeft: CGFloat = (count % 2 == 0 ? -1 : 1)
    let leftWobble: CGAffineTransform = CGAffineTransformMakeRotation(degreesToRadians(animationRotateDegres * leftOrRight))
    let rightWobble: CGAffineTransform = CGAffineTransformMakeRotation(degreesToRadians(animationRotateDegres * rightOrLeft))
    let moveTransform: CGAffineTransform = CGAffineTransformTranslate(leftWobble, -animationTranslateX, -animationTranslateY)
    let conCatTransform: CGAffineTransform = CGAffineTransformConcat(leftWobble, moveTransform)

    transform = rightWobble // starting point

    UIView.animateWithDuration(0.1, delay: 0.08, options: [.AllowUserInteraction, .Repeat, .Autoreverse], animations: { () -> Void in
        self.transform = conCatTransform
        }, completion: nil)
}

func degreesToRadians(x: CGFloat) -> CGFloat {
    return CGFloat(M_PI) * x / 180.0
}

When I want to make my cells wobble I do so like this:
for cell in collectionView.visibleCells() {
        let customCell: MyCustomCell = cell as! MyCustomCell
        customCell.wobble()
    }

A: Updated to swift 3 syntax:
let animationRotateDegres: CGFloat = 0.5
let animationTranslateX: CGFloat = 1.0
let animationTranslateY: CGFloat = 1.0
let count: Int = 1

func wobble() {
    let leftOrRight: CGFloat = (count % 2 == 0 ? 1 : -1)
    let rightOrLeft: CGFloat = (count % 2 == 0 ? -1 : 1)
    let leftWobble: CGAffineTransform = CGAffineTransform(rotationAngle: degreesToRadians(x: animationRotateDegres * leftOrRight))
    let rightWobble: CGAffineTransform = CGAffineTransform(rotationAngle: degreesToRadians(x: animationRotateDegres * rightOrLeft))
    let moveTransform: CGAffineTransform = leftWobble.translatedBy(x: -animationTranslateX, y: -animationTranslateY)
    let conCatTransform: CGAffineTransform = leftWobble.concatenating(moveTransform)

    transform = rightWobble // starting point

    UIView.animate(withDuration: 0.1, delay: 0.08, options: [.allowUserInteraction, .autoreverse], animations: { () -> Void in
        self.transform = conCatTransform
    }, completion: nil)
}

func degreesToRadians(x: CGFloat) -> CGFloat {
    return CGFloat(M_PI) * x / 180.0
}

A: If you put you're code in a method called startJiggling in your custom cell, then you could call this method in your controller:
[self.collectionView.visibleCells  makeObjectsPerformSelector:@selector(startJiggling)];
That ensures that all visible cells will start jiggling.
Then I'd also set some flag indicating that your cells should jiggle and test for that in collectionView:cellForItemAtIndexPath:. If YES, then call your method.

A: Place this line of code at two places:
[self.collectionView.visibleCells makeObjectsPerformSelector:@selector(startJiggling)];

*

*-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath

*-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView


text:
Q: How to make a php script run a specific command I have a command line that I run from a specific directory to resize images, but I now need it to run from a php script so I can put it into a cron job to automate.  The command is mogrify -resize 800x800\> *.jpg.  I'm only looking for help to set up the php script, as I'm novice to doing this.  Thanks in advance.

A: Cron has nothing to do with php. Have you tried putting
cd "$whatever_directory" && mogrify -resize 800x800\> *.jpg

in cron?
That said, you can get php to execute shell commands with exec and shell_exec, but I would urge you to consider if that's what you want.


text:
Q: Change CSS "display: none;" to shown I want an element on my website hidden when the website loads, but when a user submits a form, then it changes to show. I have tried for hours now, can't get it to work.
Code:
HTML
<form onsubmit="show();">

Message was sent.

CSS
.hidden {
  display: none;
}

JavaScript
function show () {
  document.getElementById("mymessage").style.display = 'block';
}

Disclaimer: I only included relevant code.
Hope somebody is able to help me/spot the error!

A: You have to return false to prevent the browser from refreshing the page so that you can hide the element on submit:

function show () {
  document.getElementById("mymessage").style.display = 'block';
  return false;
}
.hidden {
  display: none;
}
<form onsubmit="return show();">

<button>enviar</button>
</form>

Message was sent.

A: I would remove the hidden class:
function show () {
  document.getElementById("mymessage").classList.remove("hidden");
}

(classList has very broad support, and can be polyfilled on obsolete browsers if necessary.)
Live Example (using a button click instead of a form submit):

function show () {
  document.getElementById("mymessage").classList.remove("hidden");
  return false;
}
.hidden {
  display: none;
}
<form>

Message was sent.

<input type="button" onclick="show();" value="Click Me">

A: i think this is a solution
document.getElementById("mymessage").classList.remove("hidden");

A: What about if you use jQuery instead?
</script>

Remember to add the library above the code.


text:
Q: Hyper-V VM Lab + RRAS + RDP My background is primarily .NET Development with some System Administration skills.  I'm trying to set up a VM Lab for me to test System Applications I'm developing but I've only ever done System Administration in already set up environments; I've never set up my own.
My current setup:
Server 2008 R2 Hyper-V Host on physical machine (only role enabled) with two NICs.
First NIC dedicated for Management w/ DHCP address from company's network.
Second NIC dedicated to RRAS VM w/ DHCP address from company's network.
RRAS VM has two NICS, one is virtual private internal only NIC w/ static entry.
The other is the physical NIC mentioned above.
I've joined it to my VMLab.net internal domain.
My Active Directory Domain Controller server (ADCT) also runs DNS, DHCP, and Certificate Services which I'm familiar with but don't understand completely.
RRAS is already set up with NAT to provide the private internal network with Internet access.  What I would like to do is be able to RDP into the servers/computers on the VMLab.net domain from my computer.  Do I need to add the Remote Desktop Services role and enable the Remote Desktop Gateway service on RRAS in order to do this or is there a way to set up port forwarding on RRAS to just allow a direct connection to the internal servers...or both?  What would the best practices be here?
Network Diagram
(no longer available)

A: Assuming you're pc is behind 10.50.190.0/24 network and the default gateway of that network is 10.50.190.254/24 you just need to add a static route to this gateway like 10.0.0.0/24 -> 10.50.190.37 and make sure that the default gateway of every machine on the 10.0.0.0/24 network points to 10.0.0.1 (RAS Server). With this configuration everybody on the 10.50.190.0/24 network will reach 10.0.0.0/24 network. If you just need for your PC or for start testing you can make this local route, in windows: "route add 10.0.0.0 mask 255.255.255.0 10.50.190.37" (cmd). Regards.


text:
Q: How to scroll the page smoothly? I need to scroll the page on load to a certain position on the page in an animated manner.  And it works fine (using jQuery's animate):
$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "linear");
});

However, one thing that it is not is smooth.  Particularly on a mobile device it feels very jerky.
I've seen some CSS animations (using transition and transform) that are very smooth but can't figure out how to apply it to page scrolling.  Is it possible to do what I want using CSS?

A: Try setting the following css:

You could also try using vanilla JavaScript instead of jQuery:
function showIt(el_id) {
    var el = document.getElementById(el_id);
    el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')

Also consider adding an itermediary element in the middle of the page, example:

function showIt(el_id) {
    var middle_el = document.getElementById('middle');
    var el = document.getElementById(el_id);
    middle_el.scrollIntoView(true, {behavior: "instant"});  // Go to middle directly and then scroll slowly to #today.
    el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')

More info on scrollIntoView: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Also you might be interest in: Scrolling slow on mobile/ios when using overflow:Scroll if you are on iOS

A: The best solution for cross-browser/cross-device decent smooth scrollTop I found is using velocity.js. It's faster than jQuery's animate, quite light and supports multiple syntaxes, one of them being the one used by jQuery.animate(), so all you need to do is to replace .animate() with .velocity() (and loading the thing, of course).
I know there might be other solutions out there, but this one has been solid for years, they are always keeping it up to date, I'd say it's a keeper in any serious frontend web developer's tools. You'll find some very fancy names on velocity's libscore page. And no, I'm not affiliated. I'm just thankful for being able to use it for free.

A: Try using easeOutCubic or another easing function (choose one here):
$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "easeOutCubic");
});


text:
Q: libraries needed for python multiprocessing manager list? My code works good on my machine, but on another:
Process child:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 749, in _callmethod
AttributeError: 'ForkAwareLocal' object has no attribute 'connection'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
  File "/usr/local/lib/python3.6/multiprocessing/process.py", line 93, in run
  File "/home/eri/Projects/server/child.py", line 215, in setup_loop
  File "/home/eri/Projects/server/child.py", line 164, in setup_clients
  File "<string>", line 2, in append
  File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 753, in _callmethod
  File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 740, in _connect
  File "/usr/local/lib/python3.6/multiprocessing/connection.py", line 487, in Client
  File "/usr/local/lib/python3.6/multiprocessing/connection.py", line 614, in SocketClient
FileNotFoundError: [Errno 2] No such file or directory

Python was built from source. Maybe some libs not configured?
Python build finished successfully!
The necessary bits to build these optional modules were not found:
_bz2                  _curses               _curses_panel
_dbm                  _gdbm                 _lzma
_sqlite3              _ssl                  _tkinter
readline
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

The following modules found by detect_modules() in setup.py, have been
built by the Makefile instead, as configured by the Setup files:
atexit                pwd                   time

Main process joins child.

A: Manager() class was in local context. Making it global solves my issue.