text:
Q: Password no se resetea en Laravel 8 Estoy tratando de resetear contraseñas en un proyecto de Laravel y todo va bien menos el reseteo de la contraseña.
Pongo el correo, envía el email, abro el enlace y me sale el formulario para poder poner la nueva contraseña, pongo la nueva contraseña y entro loggeado a la aplicación. El problema es que cuando salgo e intento loggear con la nueva contraseña no me deja pero si con la anterior, en otras palabras no cambia la contraseña. Comparto el código que creo que es el que se encarga de eso y mi modelo de base de datos.
ResetPasswordController (no lo he cambiado)
 <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
}

ResetsPassword.php (tampoco lo he cambiado)
<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;

trait ResetsPasswords
{
    use RedirectsUsers;

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showResetForm(Request $request)
    {
        $token = $request->route()->parameter('token');

        return view('auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function reset(Request $request)
    {
        $request->validate($this->rules(), $this->validationErrorMessages());

        // Here we will attempt to reset the user's password. If it is successful we
        // will update the password on an actual user model and persist it to the
        // database. Otherwise we will parse the error and return the response.
        $response = $this->broker()->reset(
            $this->credentials($request), function ($user, $password) {
                $this->resetPassword($user, $password);
            }
        );

        // If the password was successfully reset, we will redirect the user back to
        // the application's home authenticated view. If there is an error we can
        // redirect them back to where they came from with their error message.
        return $response == Password::PASSWORD_RESET
                    ? $this->sendResetResponse($request, $response)
                    : $this->sendResetFailedResponse($request, $response);
    }

    /**
     * Get the password reset validation rules.
     *
     * @return array
     */
    protected function rules()
    {
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ];
    }

    /**
     * Get the password reset validation error messages.
     *
     * @return array
     */
    protected function validationErrorMessages()
    {
        return [];
    }

    /**
     * Get the password reset credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only(
            'email', 'password', 'password_confirmation', 'token'
        );
    }

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $this->setUserPassword($user, $password);

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));

        $this->guard()->login($user);

    }

    /**
     * Set the user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function setUserPassword($user, $password)
    {
        $user->password = Hash::make($password);
    }

    /**
     * Get the response for a successful password reset.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    protected function sendResetResponse(Request $request, $response)
    {
        if ($request->wantsJson()) {
            return new JsonResponse(['message' => trans($response)], 200);
        }

        return redirect($this->redirectPath())
                            ->with('status', trans($response));
    }

    /**
     * Get the response for a failed password reset.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    protected function sendResetFailedResponse(Request $request, $response)
    {
        if ($request->wantsJson()) {
            throw ValidationException::withMessages([
                'email' => [trans($response)],
            ]);
        }

        return redirect()->back()
                    ->withInput($request->only('email'))
                    ->withErrors(['email' => trans($response)]);
    }

    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker();
    }

    /**
     * Get the guard to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }
}

El código no lo he tocado pero el visual studio me marca como que si hubieran algunos errores, en la función ResetPassword muestro en una imagen.

Los métodos dicen que no están definidos y la variable $user dice esto
Expected type 'Illuminate\Contracts\Auth\Authenticatable'. Found 'Illuminate\Contracts\Auth\CanResetPassword'.intelephense(1006)

A continuación muestro mi modelo de base de datos.

Solo he usado migraciones para la tabla de users y la de password_resets y como pueden ver mi tabla Users es personalizada.
No sé a que se deba el error en especial porque el programa no muestra ningun error, aparentemente todo funciona perfectamente pero no me resetea la contraseña.
Disculpen si pongo código en imagen pero es para que se pueda ver que dice que está mal el Visual Studio Code.
Cómo fue solicitado pongo el código del modelo User
No se si algo puede estar mal en el modelo, cualquier ayuda así sea una pista de donde está la falla sería de ayuda porque como no me dá ningun error no tengo ni idea de donde podría estar la falla.
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'role',
        'name',
        'surname',
        'nick',
        'email',
        'password',
        'image',
        'idPersona',
        'estado'
    ];

    public function Persona(){
        return $this->belongsTo(Persona::class,'idPersona');
    }
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'remember_token'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


text:
Q: webform save data as new node is that possible? i use drupal 6 and i want to save webform data instad of sending to email to create a new node with fields ive set via new content type

A: Using CCK instead of webform is recommend to use.
But if you want, you should write custom module:
/**
 * Implementation of hook_form_alter()
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (substr($form_id, 0, 19) == 'webform_client_form') {
    $form['#submit'][] = '_YOURMODULE_webform_submit';
  }
}

/*
 * Submitting webform
 */
function _YOURMODULE_webform_submit($form, &$form_state) {
// Investigate here $form_state via print_r or dsm (if devel installed).
// How to save node: http://www.google.com/search?q=drupal+programmatically+save+node
}

A: You could modify this module, it's for drupal 7.
http://ichormedia.com.au/blog/webform-submissions-nodes/
It allows you to specify which content type you would like to submit Webform submissions to. The module will also create any missing fields for the chosen content type should the Webform be modified.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trim string after a certain character sql I have a list of places many of the  places not all  have their ID appended at the end of the name of the places they usually starts after the dash character (-). I only need to show the name of the place and not the ID. All the IDs have a length of 5  characters,
i.e :
132 rockaway blvd -12345 , 176-58 bayshore avenue -78952, 12-89 rosedale place but I need to only display:
    132 rockaway blvd
    176-58 bayshore avenue
    12-89 rosedale place

I have tried `select distinct right(rtrim(placeName),7) from places` but this only gives me the last characters  -12345

A: declare @table1 as table(column1 varchar(200))
insert into @table1(column1) values('132 rockaway blvd -12345')
insert into @table1(column1) values('176-58 bayshore avenue -78952')
insert into @table1(column1) values('12-89 rosedale place -9999999999')
select
column1,  left(column1,len(column1)-charindex('-',reverse(column1)))
from @table1

--if you can give me more example I can modify this query


text:
Q: Display header only when chlid is NOT NULL using Expandablelistview android studio -sqlite I'm trying to make an expendable list view with the header text being extratced from column "Organ features" and child text is extratced from the pharynx column, this is my database structure:
Database structure
I want organ features to be displayed as header only if their childlist(= instances from the pharynx colum) are NOT NULL.
This is what i got so far (as you see, the venous drainage is empty in pharynx column but still displayed as header, and i dont want that):
picture from the emulator
i Think i should add a statment " if(DATABASECHILD_1 != null)" or something like that ..
Thanks for the help!
Database.Java
package ma.ac.iav.learn;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class Database {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "URTdd.db";
    private static final String DATABASE_TABLE = "OrganAnatomy";
    public static final String DATABASE_ID = "_id";
    public static final String DATABASE_GROUP_1 = "Organ_features";
    public static final String DATABASE_CHILD_1 = "Pharynx";
    private final Context mContext;
    private DatabaseHelper mDatabaseHelper;
    private SQLiteDatabase mDB;

    public Database(Context context) {
        mContext = context;
    }

    public void open() {
        mDatabaseHelper = new DatabaseHelper(mContext, DATABASE_NAME, null, DATABASE_VERSION);
        mDB = mDatabaseHelper.getWritableDatabase();
    }

    public void close() {
        if (mDatabaseHelper != null) mDatabaseHelper.close();
    }

    public Cursor getDatabase() {
            return mDB.query(DATABASE_TABLE, null, null, null, null, null, DATABASE_GROUP_1);
    }

    public Cursor getID(long rowID) {
            return mDB.query(DATABASE_TABLE, null, "_id" + " = "
                + rowID, null, null, null, null);

    }

    public class DatabaseHelper extends SQLiteAssetHelper {

        public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);

        }
    }

}

MainActivity.java
package ma.ac.iav.learn;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;

public class MainActivity extends AppCompatActivity {
    ExpandableListView expandableListView;
    Database mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
             /*
        "Called when the database has been opened."
        https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onOpen(android.database.sqlite.SQLiteDatabase)
         */
        mDatabase = new Database(this);
        mDatabase.open();

        /*
        "This interface provides random read-write access to the result set returned by a database query."
        https://developer.android.com/reference/android/database/Cursor.html
         */

        Cursor cursor = mDatabase.getDatabase();
        startManagingCursor(cursor);

        /*
        "A list of column names that will be used to display the data for a group."
        "The group views (from the group layouts) that should display column in the "from" parameter."
        "A list of column names that will be used to display the data for a child."
        "The resource identifier of a layout file that defines the views for a child."
        https://developer.android.com/reference/android/widget/SimpleCursorTreeAdapter.html#SimpleCursorTreeAdapter(android.content.Context, android.database.Cursor, int, java.lang.String[], int[], int, java.lang.String[], int[])
         */

        String[] groupFrom = {
                Database.DATABASE_GROUP_1,
        };

        int[] groupTo = {
                R.id.group1,
        };
        String[] childFrom = new String[]{
                Database.DATABASE_CHILD_1,
        };
        int[] childTo = {
                R.id.child1,
        };

        /*
        "An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file."
        https://developer.android.com/reference/android/widget/SimpleCursorTreeAdapter.html
        */
        SimpleCursorTreeAdapter simplecursortreeAdapter = new ExpandableListViewAdapter(
                this,
                cursor,
                R.layout.list_group,
                groupFrom,
                groupTo,
                R.layout.list_child,
                childFrom,
                childTo
        );

        /*
        "Finds a view that was identified by the android:id XML attribute that was processed in onCreate(Bundle)."
        "Sets the adapter that provides data to this view."
        https://developer.android.com/reference/android/app/Activity.html#findViewById(int)
        https://developer.android.com/reference/android/widget/ExpandableListView.html#setAdapter(android.widget.ExpandableListAdapter)
         */
        expandableListView = findViewById(R.id.expandableListview);
        expandableListView.setAdapter(simplecursortreeAdapter);

    }

    /*
    "Closes the Cursor, releasing all of its resources and making it completely invalid."
    https://developer.android.com/reference/android/database/Cursor.html#close()
     */
    protected void onDestroy() {
        super.onDestroy();
        mDatabase.close();
    }

    private class ExpandableListViewAdapter extends SimpleCursorTreeAdapter {
        private ExpandableListViewAdapter(
                Context context,
                Cursor cursor,
                int groupLayout,
                String[] groupFrom,
                int[] groupTo,
                int childLayout,
                String[] childFrom,
                int[] childTo) {
            super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom, childTo);
        }

        /*
        "Gets the Cursor for the children at the given group."
        https://developer.android.com/reference/android/widget/CursorTreeAdapter.html#getChildrenCursor(android.database.Cursor)
         */
        protected Cursor getChildrenCursor(Cursor groupCursor) {
            return mDatabase.getID(groupCursor.getInt(groupCursor.getColumnIndex(Database.DATABASE_ID)));
        }

    }
}

A: I believe that you want a query based upon :-
SELECT * FROM OrganAnatomy WHERE Pharynx IS NOT NULL ORDER BY Organ_features;

This would result in :-

To convert this for use by the SQLiteDatabase query method, the code instead of being :-
    public Cursor getDatabase() {
        return mDB.query(DATABASE_TABLE, null, null, null, null, null, DATABASE_GROUP_1);
    }

could be :-
    public Cursor getDatabase() {
        String whereclause = DATABASE_CHILD_1 + " IS NOT NULL";
        return mDB.query(DATABASE_TABLE, null, whereclause, null, null, null, DATABASE_GROUP_1);
    }

*

*Note the above code is in-principle code and has not been tested, so may contain some errors.

*Note no attempt has been made to apply this to the ExpanableListView, it has been assumed that the adapter handles the Cursor appropriately.

*There is no IF statement as such (IF ??? EXISTS/ NOT EXISTS is where you you see IF used), rather a WHERE clause, which determines what rows are to be included (so in this case only include rows WHERE the Pharynx column IS NOT NULL).

*

*The real equivalent to IF is the CASE WHEN .... ELSE .... END AS construct, although this isn't needed and also isn't suitable for this scenario.

*There is also the HAVING clause but this expects a GROUP BY clause and acts upon the result rather than the input rows and is really used for post processing, e.g. you could have SELECT * FROM OrganAnatomy GROUP BY _id HAVING Pharynx IS NOT NULL ORDER BY Organ_features; (works as _id will be unique so every row will be in it's own group).

*Using the HAVING clause is overkill/over-complicated in this scenario.


text:
Q: Extracting TLS session keys from lighttpd Is it possible to extract the TLS session keys from Lighttpd so we are able to decrypt traffic captured by tcpdump?
Alternatively, we could disable PFS but we prefer not to do that.

A: you can find private key in the file referenced by entry ssl.pemfile in the file /etc/lighttpd/lighttpd.conf
The key is at the beginning before the certificate.
decrypt question was already answered here:
how-to-decrypt-ssl-traffic-with-a-packet-sniffer-when-i-have-the-private-key

Ssldump is supposed to be able to do that, but it appears to be unmaintained (in the source archive of the latest version, the date of last modification of all files are in 2002 or before) so it is quite possible that it won't support newer SSL/TLS; actually, it is highly implausible that a software from 2002 could process the new encryption formats defined in TLS 1.2 (AES/GCM). TLS 1.1 was published in 2006, and TLS 1.2 in 2008.
OpenSSL is a library that implements the protocol, but is not meant for analysing a recorded session.
You may have better chance with Wireshark, which has ample documentation on how to use it to decrypt recorded sessions.
There is an important parameter to mind: decryption of a passively recorded session (with a copy of the server private key) works only if the key exchange was of type RSA or static DH; with "DHE" and "ECDHE" cipher suites, you won't be able to decrypt such a session, even with knowledge of the server private key. In that case, you will need either the negotiated "master secret", or to use the server private key to actively intercept the connection (in a Man-in-the-Middle setup).

A: Lighttpd does not support this out-of-the box.
Stefan, a developer of lighttpd, suggested checking out the following answer:
Extract pre-master keys from an openssl application


text:
Q: Why is my legend in my seaborn countplot not showing all the labels? I have a Seaborn countplot showing seven different animal classes:
g = sns.countplot(data=df, x="class_type")
plt.legend(title="Animal Type", loc="upper right", labels=["Mammal", "Bird", "Reptile", "Fish",
                                                           "Amphibian", "Bug", "Invertebrate"])
plt.show(g)

which gives me this image.

as you can see, only the first label is displayed. How do I show the label for each bar, please?
this is the top (first 20 rows) of my dataframe:
   animal_name  hair  feathers  eggs  milk  airborne  aquatic  predator  \
0     aardvark     1         0     0     1         0        0         1
1     antelope     1         0     0     1         0        0         0
2         bass     0         0     1     0         0        1         1
3         bear     1         0     0     1         0        0         1
4         boar     1         0     0     1         0        0         1
5      buffalo     1         0     0     1         0        0         0
6         calf     1         0     0     1         0        0         0
7         carp     0         0     1     0         0        1         0
8      catfish     0         0     1     0         0        1         1
9         cavy     1         0     0     1         0        0         0
10     cheetah     1         0     0     1         0        0         1
11     chicken     0         1     1     0         1        0         0
12        chub     0         0     1     0         0        1         1
13        clam     0         0     1     0         0        0         1
14        crab     0         0     1     0         0        1         1
15    crayfish     0         0     1     0         0        1         1
16        crow     0         1     1     0         1        0         1
17        deer     1         0     0     1         0        0         0
18     dogfish     0         0     1     0         0        1         1
19     dolphin     0         0     0     1         0        1         1

    toothed  backbone  breathes  venomous  fins  legs  tail  domestic  \
0         1         1         1         0     0     4     0         0
1         1         1         1         0     0     4     1         0
2         1         1         0         0     1     0     1         0
3         1         1         1         0     0     4     0         0
4         1         1         1         0     0     4     1         0
5         1         1         1         0     0     4     1         0
6         1         1         1         0     0     4     1         1
7         1         1         0         0     1     0     1         1
8         1         1         0         0     1     0     1         0
9         1         1         1         0     0     4     0         1
10        1         1         1         0     0     4     1         0
11        0         1         1         0     0     2     1         1
12        1         1         0         0     1     0     1         0
13        0         0         0         0     0     0     0         0
14        0         0         0         0     0     4     0         0
15        0         0         0         0     0     6     0         0
16        0         1         1         0     0     2     1         0
17        1         1         1         0     0     4     1         0
18        1         1         0         0     1     0     1         0
19        1         1         1         0     1     0     1         0

    catsize  class_type
0         1           1
1         1           1
2         0           4
3         1           1
4         1           1
5         1           1
6         1           1
7         0           4
8         0           4
9         0           1
10        1           1
11        0           2
12        0           4
13        0           7
14        0           7
15        0           7
16        0           2
17        1           1
18        1           4
19        1           1

as you can see, it's a mix of numeric, string and one hot encoded data.

A: Thank you for including the sample data.
One issue seems to be that the plt.legend() command isn't operating on your current axis.
You can do this instead:
import seaborn as sns, pandas as pd, matplotlib.pyplot as plt

ax = sns.countplot(data=df, x="class_type", hue='class_type', dodge=False)
h,l = ax.get_legend_handles_labels()
labels=["Mammal", "Bird", "Reptile", "Fish", "Amphibian", "Bug", "Invertebrate"]
ax.legend(h,labels,title="Animal Type", loc="upper right")
plt.show()

Result:

The dodge=False kwarg tip was found here: https://github.com/mwaskom/seaborn/issues/871


text:
Q: Holding an array of T within a template class I'm trying to develop a template class for a queue and getting the error error C3265: cannot declare a managed 'items' in an unmanaged 'TQueue<T>'. From what I understand I can't have managed types within an unmanaged "class". My code is as follows:
#pragma once

template<class T> class TQueue
{
private:
    array<T>^ items;
    int currentIndex;
    int count;
public:
    TQueue();
    void Enqueue(T toAdd);
    T Dequeue();

    GetCount() {return currentIndex;}
};

How would I go about holding an array of type <T> in my Queue?
Thanks in advance,
J

A: Simply included the 'ref' in the class prototype. I accidentally deleted it causing the class to become 'unmanaged'.
The class prototype ended up as: template<class T> ref class TQueue


text:
Q: Extract elements x from array for which aI'm trying to do a rather simple operation, which I somehow fail to successfully perform. What I have is an array (array0) of values, say 1000 of them, all between 0 and 10. Now what I want to do is create three separate arrays:
array1 = all elements of array0 that are equal to 3 or smaller
array 2 = all elements from array0 that are larger than 3 but equal to or smaller than 7
array 3 = all elements from array0 that are larger than 7
Now, array1 and array3 work just fine. I use
array1= array0(array0<=3);
array3= array0(array0>7);

But array 2 is a problem. The 'logical' thing for me is to try
array2= array0(3<array0<=7);

But this doesn't work, it just gives me an empty array. It doesn't give an error though. Could anyone help me find the flaw in my code?

A: You need to use a logical "and" operator like this:
array2= array0(array0>3 & array0<=7);

similar to how you might say it in English, A is greater than 3 AND less than or equal to 7.


text:
Q: Will a clustered index improve performance of updates performed sequentially on that clustered index? I know indexes reduce data modification performance, but I have a task where (almost) all updates are done on items in a sequential order. Would a clustered index improve or reduce performance in updating these rows?
The clustered index would be on column id where id is an IDENTITY column. id is thus never changed and will be sequential (in addition rows should never be deleted).
This is the format of my update statements:
UPDATE [table] SET value = 1
WHERE  id IN (1,2,3,4...)

The values are not necessarily continous however. A sequence of IN (1,2,4,5) is also possible if id=3 is not set to be updated, but they will always be in order.
When all updates are in sequential order, will a clustered index improve or reduce performance?

A: The IN like this is a set of discrete values. SQL Server won't bother working out it is a range or checking ascending values.
That is, x IN (1,2,4,5) is parsed out to x=1 OR x=2 OR x=4 OR x=5. OR is non-SARGable in most cases and result in scans rather than seeks.
If you put the data into a temp table with an index and did x IN (SELECT foo FROM #bar) then it becomes a semi-join and will more likely use an index


text:
Q: how to give format in NSDate while converting it into timestamp using Swift I have two different values of timestamp on same day in different time. So I want to provide format 'yymmdd' to the NSDate to covert date into timestamp since the value changes acc. to time. If anyone could help me in this or suggest me since i am new to Swift.

A: I was a bit confused about what you were asking for but after reading your own comments/answers to the original post I understand that you are looking for "the epoch unix timestamp". You can easily get this from any NSDate object as follows:
NSDate *yourDate = [NSDate date];//now in this example

NSTimeInterval epochTimestamp = [yourDate timeIntervalSince1970];

NSString *epochTimestampString = [@(epochTimestamp) stringValue];

NSLog(@"%@",epochTimestampString);

This way you will get the epoch timestamp defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.


text:
Q: Typecasting Error in Python pop=x.nextSibling()[0]  # pop="Population: 1,414,204"
pre_result=pop.text.split(" ") #pre_result=['Population:','1,414,204']
a=pre_result[1] # a='1,414,204'
result=int(a) #Error pops over here.Tried int(a,2) by searching answers in internet still got an error.
print(result)
print(type(result))

The following is the error message.I thought typecasting from str to int would be simple but still i came across this error.I am a beginner in python so sorry if there has been any silly mistake in my code.
File "C:\Users\Latheesh\AppData\Local\Programs\Python\Python36\Population Graph.py", line 14, in getPopulation
    result=int(a)
ValueError: invalid literal for int() with base 10: '1,373,541,278'

A: The error is self explaining, a contains the string '1,373,541,278', and that is not a format Python can handle.
We can however remove the comma's from the string, with:
result=int(a.replace(',', ''))

But it is possible that for some elements, you will have to do additional processing.


text:
Q: re How to change HP boot logo on Ubuntu 20.04? Each time I power on my HP Probook 440 G2, it will show a customize photo before booting into Ubuntu - at that time, it would be prompted in the bottom left corner of the screen:
"Press ESC for Setup Menu"
I found that it could be changed on Windows, and changing it related to BIOS multiplication - https://support.hp.com/us-en/document/c01646879.
And it was said somewhere, on Linux, it involves "EFI" folder, but my "EFI" folder was empty.
Is anyone here know how to do this?
These were the output of "sudo blkid":
/dev/sdb5: UUID="4076ff65-4166-480b-9d65-27642c523b78" TYPE="ext4" PARTUUID="96f2f010-05"
/dev/loop0: TYPE="squashfs"
/dev/loop1: TYPE="squashfs"
/dev/loop2: TYPE="squashfs"
/dev/loop3: TYPE="squashfs"
/dev/loop4: TYPE="squashfs"
/dev/loop5: TYPE="squashfs"
/dev/loop6: TYPE="squashfs"
/dev/loop7: TYPE="squashfs"
/dev/sda1: LABEL="Products" UUID="9e148580-9ad0-4070-9364-3e37f3254c4e" TYPE="ext4" PARTUUID="9e62b9bd-01"
/dev/sda2: LABEL="Projects" UUID="27124deb-e165-4b7f-847e-0a2dfbd268ea" TYPE="ext4" PARTUUID="9e62b9bd-02"
/dev/sda3: LABEL="Goods" UUID="13f2ed7d-fc42-4e41-ac28-be6605fb21f5" TYPE="ext4" PARTUUID="9e62b9bd-03"
/dev/sda4: LABEL="Archives" UUID="3dbd2523-74c0-49de-8bd6-e248d089cbea" TYPE="ext4" PARTUUID="9e62b9bd-04"
/dev/sdb1: UUID="6671-F0DE" TYPE="vfat" PARTUUID="96f2f010-01"
/dev/sdb2: UUID="F976-5B53" TYPE="vfat" PARTUUID="96f2f010-02"
/dev/loop8: TYPE="squashfs"
/dev/loop9: TYPE="squashfs"
/dev/loop10: TYPE="squashfs"
/dev/loop11: TYPE="squashfs"
/dev/loop12: TYPE="squashfs"
/dev/loop13: TYPE="squashfs"
/dev/loop14: TYPE="squashfs"


text:
Q: Is it possibile Add a default function (constructor) to JS Object This is my Code
var obj={a:1,b:2}

I don't want to change the code above (it's from somewhere else)
I am searching for a way to add a function (constructor maybe) to the object.
So users will be able to run obj()
I thought about

*

*obj=function () {} // It is deleting all the keys above

*obj.contructor=function () {} // Not Working

Do you have other idea?

A: Since functions are also objects in JavaScript, you can do this:

var x = function() {
  return 0;
};
x.a = 1;
x.b = 2;

document.body.textContent = x() + ' ' + x.a + ' ' + x.b;

A: In the middle of asking the question I found an answer:
Use the extend function
new_obj=function () {alert('the new function')}
obj=jQuery.extend(new_obj,obj)

//New I can run:

obj.a // 1
obj.b // 2
obj() // will show an alert


text:
Q: how to detect screen mirroring I have been wondering if there is any way in the android API (or any other lib/framework) that can help me to detect if my device screen is mirrored using WiDi,Miracast or MHL or basically any other technique for mirroring your screen.
Br,
Inx

A: You may navigate through the list of all device display and get flags on each for finding one with, maybe, VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR ? Not sure but a few trys should allow you to figure out which ones will do it.
cf: DisplayManager and VirtualDisplay documentation

A: Since API level 16 (Android 4.1, released in 2012 so rather new when the question was asked) Android has had MediaRouter API. Adding callback for ROUTE_TYPE_LIVE_VIDEO subscribes MediaRouter.Callback.onRoutePresentationDisplayChanged to be called when external display is connected or disconnected. If the app has sound, other option is to track routed output. The output types TYPE_HDMI and TYPE_REMOTE_SUBMIX are used for external display.

A: I'm not sure what you are trying to achieve, but if you simply want to disable screenshots and such, you can use FLAG_SECURE.

*

*https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SECURE

*http://www.vogella.com/code/ApiDemos/src/com/example/android/apis/app/SecureWindowActivity.html

A: You can't detect but you can remove functionality which mirrors.
No software can mirror if developer option is disabled.
This code will tell whether android can mirror or not.
int CanMirror = Settings.Secure.getInt(this.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0);
//returns 1 if can mirror
//returns 0 if can't mirror

Reference : https://stackoverflow.com/a/63971764/11390822


text:
Q: PLC - get absolute value of number when the CPU has no "ABS" instruction I am working with a "CLICK" PLC from automationdirect.  I am trying to set up a deadband for a specific process value X.  When X changes by more than a specified amount, something should happen.
The simple way to do this is to simply subtract the previous value of X from the current value.  Then if the absolute value of this result is greater than the allowable deadband, "do something".
However, the "CLICK" PLC doesn't have an ABS operator, that I can find.  The only way I can think of to simulate this is by doing SQRT(value ^ 2), which will always yield a positive number.  But this seems like huge overkill plus wasted CPU cycles, and the likelihood of overflow when larger numbers are in play.
I suppose I could AND the result with 0x7fff but that forces me to work with 16-bit numbers (the PLC doesn't allow AND operations on 32-bit INTs).
"CLICK" instruction set: https://cdn.automationdirect.com/static/specs/clickinstr.pdf
I'd appreciate any advice.

A: If you still want to avoid sign comparison and multiplication by -1, then you can use the following procedure adapted from http://www.geeksforgeeks.org. Initially a 31-bit arithmetic right shift is performed (I am assuming here, 32-bit signed integers) to retrieve the sign bit - with extension. The central idea is to undo the complement of 2 if the number is negative (subtract 1 and invert with an or-exclusive, in that order). If the number is positive, a sum and an or-exclusive are performed with the value zero - with no effect at all. The code is in C, but can be adapted to your needs.
#include <stdio.h>

#define BAND    15

int main() {
  int n = -20, mask;

  mask = n >> 0x1F;
  if (((n + mask) ^ mask) > BAND)
      printf("OUT OF BAND");

  return 0;
}

A: If you are missing an AND bitwise instruction, you can still perform the operation on a range of bits  repeating the following rung for all bits,

|  A_bit_0  B_bit_0        R_bit_0  |
|---[ ]------[ ]--------------( ) --|
|                                   |

And for bitwise OR,

|  A_bit_0                 R_bit_0  |
|--+-[ ]--+-------------------( ) --|
|  |      |                         |
|  | B_0  |                         |
|  +-[ ]--+                         |

Using this method for OR and XOR, even shift, you can transform the C code to PLC ladder logic.


text:
Q: Is is possible to tunnel a port over SSH for the current user only? I'd like to establish an SSH tunnel, but I'm on a shared system. I'd rather not share access to the tunnel with the rest of the users. Is there any way to restrict the local port for my use only, as a standard user?

A: No, you can't restrict TCP/UDP socket access by user like that; you want to use a unix socket for this, because they show up as a file in the filesystem and can have permissions applied to them. The problem here is that I don't think there are any SSH clients that support creating unix socket tunnels (and the OpenSSHd server does not either, so you'd need to run a customized SSH client on your shared system and SSH to back to where you want the other SSH tunnel endpoint to be). Furthermore, you'd have to make sure that the application(s) that you want to tunnel support unix sockets, which it might not.
If the application you want to tunnel does support filesystem pipes or unix sockets, then you might be in luck, but it'll still require a good bit of work. You can try creating a program which opens a unix socket and connects it to STDIN/STDOUT, and then use SSH in non-interactive mode to tunnel that data over the default PTY channels instead of a socket tunnel. Use the same program on the other end of the SSH connection to connect it to a local unix socket.
Voilà! A socket tunnel, secured over SSH, with additional permissions and ACLs on both ends. Creating the program (aka, the hard part) left as an exercise for the reader.


text:
Q: algorithm for merging polygons by across certain edges I have a list of lists of edges of XY points that I would like to merge on certain edges,
A slightly simplified version is this:
class XY{
    double X;
    double Y;
    public XY(double x, double y){
       this.X=x;
       this.Y=y;
    }
}

Edge {
    XY p1;
    XY p2;
    bool mergeOn;
}

Now I would like to merge these lists/polygons such that all edges that have the mergeOn property disapear. For example:

Would be merged on the redline.
However when doing this I need to retain the order of the points in such a way that a complete polygon can be made out of following each line.
The obvious sollution for this is to loop over the edges that make up a polygon and when you meet a mergeOn edge you switch to the other side however this does not work for a case such as the following:
[where merging the two polgons in this manner would result in the lose of the edge in the hole, which should instead become it's own list.
List l1= new List<edge>();
l1.add(new Edge(new XY(0,0) , new XY(10,0),false));
l1.add(new Edge(new XY(10,0) , new XY(10,3),true));
l1.add(new Edge(new XY(10,3) , new XY(10,7),false));
l1.add(new Edge(new XY(10,7) , new XY(10,10),true));
l1.add(new Edge(new XY(10,10) , new XY(0,10),false));
l1.add(new Edge(new XY(0,10) , new XY(0,0),false));

l2.add(new Edge(new XY(20,0) , new XY(20,10),false));
l2.add(new Edge(new XY(20,10) , new XY(10,10),false));
l2.add(new Edge(new XY(10,10) , new XY(10,7),true));
l2.add(new Edge(new XY(10,7) , new XY(12,7),false));
l2.add(new Edge(new XY(12,7) , new XY(12,3),false));
l2.add(new Edge(new XY(12,3) , new XY(10,3),false));
l2.add(new Edge(new XY(10,3) , new XY(10,0),true));
l2.add(new Edge(new XY(10,0) , new XY(20,0),true));

merge(new list{l1,l2});

which should result in something like this
list{l3,l4}
with l3 being
new Edge(new XY(0,0) , new XY(20,0),false)
new Edge(new XY(20,0) , new XY(20,10),false)
new Edge(new XY(20,10) , new XY(0,10),false)
new Edge(new XY(0,10) , new XY(0,0),false)

and l4 being
new Edge(new XY(10,3) , new XY(12,3),false)
new Edge(new XY(12,3) , new XY(12,7),false)
new Edge(new XY(12,7) , new XY(10,7),false)
new Edge(new XY(10,7) , new XY(10,3),false)

Some notes it's possible that there is more then one  and it's also possible for the same point to occur in more then two edges (even with these edges not being mergeOn).
Any idea what type of algoritm might work here?
Note that right now due to some underlying double point precision problems sometimes the edges don't quite match up, while I can solve that myself it does make tools such as the clipperlib less usefull.
After some discussion in chat here are some clarifications: no two lines in the initial data can ever intersect, they can share points though (one point can be in many different lines). The final goal of this method is to use it in a pathfinding solution, the redlines are obstacle lines that this agent can move through while the black lines cannot be moved through (for example the red lines might be a river while the black lines are a large rock, an amphibious vehicle can cross the river but not the rock).


text:
Q: Electronic fuse I teach electrochemistry to students in chemistry. During each class, there is at least one student that manages to burn the 200mA fuse of our $15 multimeters.
It's quite annoying. I am thinking of replacing the wire fuses by electronic ones. The kind that resets itself automatically after a short time.
I know I won't find any electronic fuse that will fit the multimeter, but I am prepared to solder & add wires to fit everything in place.
However, I don't know how to select the fuse. The original piece is rated 500 V ; 200 mA.
Is there anything I need to consider prior to replacing 40+ multimeter fises with electronic ones ?
Do you have any part number / manufacturer to recommend ?

A: If they are only working with voltages up to ~ 3 V, you could replace the fuse with a resistor. Say you want to limit current to 200 mA @ 3 V -- that gives about 15 ohm resistance. At the 20 mA, that will increase the DMM burden by about 0.3 V which may or may not be a problem.
3 V & 200 mA == 0.6 W -- use a 1 W resistor if you can find it.
Note that this won't protect if the meter is plugged into the mains (110 V or 220 VAC), and in fact would be dangerous.
Alternatively you could use a polyfuse polyfuse-- these are low R when cold and increase to higher values when hot -- however neither are these robust to protect against plugging into the mains.


text:
Q: What is the precise definition of a rigid shape? Wikipedia's section on rigid shapes does not appear to actually define what a rigid shape is. Rather it defines 'same shape' and 'rigid transformations' without giving any definitions of what is necessary and sufficient for a shape to be considered rigid.
For instance, I've seen the following image:

I understand intuitively why the triangle is rigid and quadrilateral is non-rigid. It is also my understanding that inserting a single diagonal connection into the quadrilateral would make the shape rigid? However, given the following image (labeling the shapes $S_1$, $S_2$ and $S_3$ in sequence left to right):

If $S_1$ had a single diagonal connection AB, it would be possible to flip ADB over axis q to obtain a shape similar to $S_2$ with the addition of connection AB (my explanation may not be the greatest). This shape is clearly not the same as $S_1$, so how can we say $S_1$ with a single diagonal connection CD is rigid? I feel I am unclear on what the definition of rigidity actually is.

A: Although the accepted answer by rschwieb is an excellent one, I think there is a connection between the mathematical notion of "rigid motion" and the physical notion of "structural rigidity" that has not  been mentioned yet.
Let us define a diagram to refer to any finite collection of line segments with labeled endpoints in the plane.  Suppose we have two kinds of data about a given diagram:  its incidence relations (i.e. knowing which points are the endpoints of which which line segments) and its linear measurements (i.e. knowing how long the segments are).  We ask the question:

Is a diagram completely specified by its incidence relations and its linear measurements?

Another (slightly less formal) way to put this is:  If you know how long all the segments in a diagram are, can you draw the diagram?
First, let's notice that at best we might be able to say that a diagram is completely specified up to a rigid motion.  That is, even if could reconstruct a diagram from its incidence relations and linear measurements, we would not know where to position it in the plane or how to orient it, because a rigid motion of the plane preserves all incidence and metric properties while possibly changing position and orientation.
But a more significant observation is that knowing the incidence relations and linear measurements of a diagram does not, in general, completely specify a diagram.  To see this, just look at the example in the OP of a "nonrigid" shape:  A square that deforms into a rhombus.  The original diagram (the square) and the deformed diagram (the rhombus) have exactly the same incidence relationships and linear measurements, but the angles in them are different.
We can take this as a mathematical characterization of the physical notion of "structural rigidity":  If a diagram is completely determined (up to a rigid motion) by its incidence relations and its linear measurements, we can call it a rigid diagram.
Now consider a triangle.  Suppose we know the three side-lengths of a given triangle $\Delta ABC$.  Is it possible to reconstruct everything else about the triangle?
The answer is Yes.  This is known as the Side-Side-Side property.  In high school geometry it is usually formulated as a criterion for proving that two triangles are congruent:

If $\Delta ABC$ and $\Delta PQR$ are two triangles with $AB=PQ,BC=QR,$ and $AC=PR$, then $\Delta ABC \cong \Delta PQR$.

The Side-Side-Side property tells you that if the sides of a triangle are non-deformable then its angles are completely "locked in", i.e. the entire triangle is rigid.
Note that this is not true for any polygon other than a triangle:  There is no such thing as a "Side-Side-Side-Side" congruence criterion for quadrilaterals.
Now let's consider the examples in the OP.  The diagram $S_1$, without the dotted diagonals, is a quadrilateral $ADBC$.  Such a quadrilateral is not rigid, because one can draw another quadrilateral $A'D'B'C'$ with all corresponding lengths exactly the same but with different interior angles.
However, if you add even one of the dotted segments (for example, $\overline{DC}$) into the diagram, then the diagram would be rigid, because the triangles $\Delta ADC$ and $\Delta BDC$ are rigid.
Exactly the same remarks apply to $S_2$.
For $S_3$, the question of whether or not the diagram is rigid depends on whether the line that appears to join $A$ to $C$ and the line that appears to join $B$ to $D$ is actually a segment, and if so whether the point that appears to be at the intersection of those segments (call it $P$) is explicitly part of the diagram or not, and whether $\overline{AP}$, $\overline{PC}$, etc. are all part of the diagram.  (Notice that this is all contained in the "incidence relations" specification of a diagram.)  If they are, then the diagram is rigid; otherwise, it is just a non-rigid quadrilateral.

A: The reason you are finding these ideas hard to reconcile is because the diagram is referring to a physical notion of rigidity, while the wiki page you're reading is centered around a geometrical notion of rigidity. (I don't find the article you linked to be particularly clearly written either.)
Geometry
In geometry, we don't talk about rigid shapes really, we talk about rigid transformations. Shapes in geometry are just sets of points, not physical objects with resistance to bending and stretching. They are at the mercy of transformations applied to them.
Assuming we are working in a geometry that has notions of how to measure angles and distances:

A rigid transformation preserves all distances and angle measures (and depending on your taste, orientation too)

The idea is that no matter what shape we start out with, any shape you draw in the plane at all will look the same after a rigid transformation is applied, except that its location and situation might be different from what it used to be. (It might also be its mirror image, if you have allowed transformations to flip the orientation of the plane.)
Many of those shapes would be changed if we picked a nonrigid transformation, for example, the transformation given by $x\mapsto x$ and $y\mapsto 2y$ in the Cartesian plane. This would change a circle at the origin into an ellipse.
If you are interested in geometry that is not founded upon distance, then you can adopt some geometry axioms that assume notions of congruence of segments and angles. Rigid transformations of the plane would then be ones which do not disturb segment congruence nor angle congruence.
Physics
Now, there is a notion of rigidity in reality that has more to do with its resistance to changing shape. This is called structural rigidity. This is really not the same animal as rigidity of shape in geometry, although it's obviously related.
In the diagram you supplied, the point seems to be that we are assuming the segments do not change length, but that the joints are on hinges. You are able to apply physical forces to both, and see how they behave. One would classify the triangle as a rigid shape because none of its edgelengths or angles would change because of the intrinsic shape of the object. The square on the other hand isn't geometrically limited to having 90 degree angles when you apply pressure to it, so it can change into a rhombus rather quickly.
Moreover, you could easily imagine building an object with length changing segments and rigid hinges, so that a square could be pulled into a rectangle, but not pushed over into a rhombus. I don't think that object would be considered "rigid" either.
Conclusion
Hopefully I've expressed a bit about the difference between these two studies.
I don't mean to say that the physics notion is totally disjoint from mathematics: for sure physical rigidity can be analyzed with mathematics. It's just that the wiki page on geometry was not where you wanted be if you're interested in structural rigidity.

A: I believe that rigidity is used in a relatively intuitive way here. However, if I wanted to ignore any pretense of geometric purity and just try to define the concept in a way that works, I would do it like this: it seems like one needs to have a notion of a ''bottom'' edge, which we consider to be fixed. The others should be free to move, and in particular we want the preserved properties to be perimeter and area.  Therefore:

A shape is called rigid along an edge $e$ if any continuous function $f$ that fixes that edge and preserves geodesic distances, in fact preserves Euclidean distances as well (and area?).

Here, the concept of geodesic distances is difficult to formalize but easy to understand; it is simply the shortest distance between two points if one is restricted to traveling along the shape's edges. The Euclidean distance is a distance is just the length of the line in the plane connecting two points.
Under this definition $S_1$ is rigid along $AB$: the proposal of flipping across $AB$ is not allowed because although the geodesic distances have stayed the same, the distance between $C$ and $D$ has decreased
More thoughts:

*

*I doubt the continuous restriction is necessary, but non-continuous functions are scary and I didn't really want to think about them :)

*I'm also not entirely convinced about area-preserving; this may actually be a strictly weaker condition than geodesic-preserving and Euclidean-preserving.

*It's possible that rigidity along any $e$ implies rigidity along every $e$. If not, you might want to define rigid shapes as those having rigidity along every $e$, depending on your motivations.

A: In two planar linkages, if j is the number of joints, L number of links,
L = 2 j - 3. These lead to frames as rigid as a triangle. And in three dimensions, L = 3 j - 6.
If more than these many links are provided, parts of designed frame start moving as a mechanism with extra degrees of freedom.


text:
Q: Javafx : TableCell focus lost I have  TableView and I want to do something when the cell loses the focus.
I have cell selection enabled on this TableView and it doesn't listens to cell focus lost. I tried this way:
table.getFocusModel().focusedCellProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue != null) {
            //doSomething
        }
        // else doSomethingElse doesn't work
});

Simply it doesn't listen when I deselect (Ctrl + click) the cell. What did I wrong or how can I listen to focus lost on a TableCell?

A: I'm using this:
TABLEVIEW.focusedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) {
        if (newPropertyValue) {
            System.out.println("on focus");
        } else {
            System.out.println("out focus");
        }
     }
});

It works only if you select another selectable element (doesn't work e.g clicking on a pane).


text:
Q: Java Script - Convert Object to XML and XML to Object while using custom names of attributes I need to convert XML to Object and Object to XML in java script. (I can use a Json conversion in the middle of the conversion process)
But, I want to use my custom tag name and custom attribute name while converting, for example:
Person Object:
function PersonObject(firstName, lastName) {
   this.FirstName = firstName;
   this.LastName = lastName
}

Convert to XML like this:
<person f_name="First Name" l_name="Last Name" />

Something like saving metadata for every property in the object (in C# I did it with writing attribute: [XmlAttribute("f_name")] above the property).
I want to do it dynamically and not to give the objects properties those names because I want the continuing code to be readable.
So, How can I do it - Convert easily object to XML and vice versa while using custom names of attributes?


text:
Q: RestTemplate (Spring Boot Starter Parent 2.1.9.RELEASE) and jackson-dataformat-xml 2.10.0 is not parsing yyyy-MM-ddTHH:mm:ss.sss I have a maven project with spring-boot-starter-parent 2.1.9.RELEASE,
jackson-dataformat-xml, jackson-core,
and jackson-databind v2.10.0.
I am using RestTemplate to get XML data and convert it to a POJO,
but the following exception is thrown:
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of ... (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('2019-05-29T16:49:00.583')
The xml has: <dtAlteracao>2019-05-29T16:49:00.583</dtAlteracao>
How to solve this issue,
please?


text:
Q: React-Native unable to call function In my app i have  a function outside 'export' which return a view, on click event of a button inside view another function is invoked which defined inside 'export'.
While clicking button error is received -
this4.myFunc is not a function.
screenshot attached below - error screen shot
below is my code -
export default class RosterView extends Component{
   constructor(props){
   super(props)
   this.state={
    ....
   }

  render () {
    mContext = this;
    return (
       <List dataArray={mContext.state.rosterList}
       renderRow={(item) =>
        <View style = {MainView.PlayerSelected}>
         <AddPlayersToRosterList
          data={item}/>
      </View>
    }>
</List>
     );
    }
   isExist = (item) =>{
     //My Code
     return flag;
   }
   addRemovePlayer = (data) =>  {
    //My Code
   }

}

 const AddPlayersToRosterList= ({data}) => (
          (!mContext.isExist(data))?
          <View style = {MainView.PlayerSelected}>
             <Ripple style={MainView.PlayerAddRemoveContainer} onPress={()=> this.addRemovePlayer(data)}>
             </Ripple>
          </View>
 )

when press button inside AddPlayersToList, this.addRemovePlayer() shows error.
please provide your help how to fix this problem.
Thanks in advance.

A: Hi you have many errors here. i tried to rewrite your code. try this here. and let me know if that helps. delete the whole AddPlayersToRosterList functional component that you wrote at the end. and rewrite it inside the component RosterView as a function.
The problem is, if you try to use functions that were not declared inside functional components, those components dont know the functions you are trying to call. In the case of const AddPlayersToRosterList you call the functions isExist(data) and this.addRemovePlayer(data), that were declared inside RosterView, but not inside AddPlayersToRosterList.
       // add this function inside RosterView
       AddPlayersToRosterList = (data) => {
              (!this.isExist(data))?
              <View style = {MainView.PlayerSelected}>
                 <Ripple
                  style={MainView.PlayerAddRemoveContainer}
                  onPress={() => this.addRemovePlayer(data)}>
                 </Ripple>
              </View>
     }

       render (){
        var mContext = this;
        return (
           <List dataArray={mContext.state.rosterList}
             renderRow={(item) =>
              <View style = {MainView.PlayerSelected}>
                {this.AddPlayersToRosterList(item)// make sure you call the function here}
              </View>
           }>
           </List>
         );
       }

you could just pass as props the functions you need to your functional component without delete anything. but it would be cost more memory and compution power that you probably need depending of how many props you want to pass.
const AddPlayersToRosterList= ({data, isExist, mContext, addRemovePlayer}) => (
          (!mContext.isExist(data))?
          <View style = {MainView.PlayerSelected}>
             <Ripple
               style={MainView.PlayerAddRemoveContainer}
               onPress={()=> this.addRemovePlayer(data)}
             >
             </Ripple>
          </View>
 )

and in your render method
 render () {
    mContext = this;
    return (
       <List dataArray={mContext.state.rosterList}
         renderRow={(item) =>
          <View style = {MainView.PlayerSelected}>
            <AddPlayersToRosterList
              data={item}
              isExist={this.isExist}
              mContext={mContext}
              addRemovePlayer={this.addRemovePlayer}
            />
          </View>
       }>
       </List>
     );
  }


text:
Q: Launch Android App using AlarmManager I am very new to Android and I am planning to make an app that will launch at a specific time. I have read about AlarmManager, intents and Broadcast receivers.
I have seen and run some sample codes from the other threads and was able to run them. Those sample are sending out notifications and text (through Toast).
But my question is, is it possible to launch my app i.e show my app's main screen on the time that I have set using the AlarmManager ? If yes, how can I do this?
I would really appreciate your help.
Thanks in advance..

A: Yes, this is possible. The following code is working for me.
Intent intent = new Intent(this, YOUR_MAIN_ACTIVITY.class);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, ID,
                        intent, 0);

final long DELAY_IN_MILLIS = DELAY_IN_MILLI_SECONDS+ System.currentTimeMillis();
AlarmManager alarmManager = (AlarmManager)
getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, DELAY_IN_MILLIS,pendingIntent);


text:
Q: Select rows with multiple occurrences over multiple tables DB: SQL Server 2008
I want to select id, title and userid from a table if that userid occurs more than once across 2 tables.
So if a user has 2 records in locations table, and 1 in artists table, i want to return the id, title and userid of all 3 records.
This is what I have now, but it returns 0 records.
When I leave out the "having count(userid)>1" part, I get ALL 400 records in all tables.
select userid,id,title from (
select id,title,userid from locations l
union
select id,title,userid from artists a
) as info
group by userid,id,title
having count(userid)>1

A: Something like this should work:
select userid,id,title
from
( select id,title,userid from locations l union select id,title,userid from artists a )
as grabfromthis
where userid in (
select userid
( select id,title,userid from locations l union select id,title,userid from artists a )
as info
group by userid having count(userid)>1)

A: I modified the above slightly to make it just a bit more slick:
WITH combined AS
(
SELECT id from t1
UNION ALL
SELECT id FROM t2
etc...
)
SELECT id, count(id) as numOccurrences
FROM combined
GROUP BY id
HAVING count(id) > 1

The difference being that this will show you just how many times your number is repeated.
You could also add
ORDER BY numOccurrences to chop down your worst offenders first

A: ;WITH combined AS (
  SELECT id, title, userid FROM locations
  UNION ALL
  SELECT id, title, userid FROM artists
)
SELECT *
FROM combined c
  INNER JOIN (
    SELECT userid
    FROM combined
    GROUP BY userid
    HAVING COUNT(*) > 1
  ) g ON c.userid = g.userid

Get the non-unique userid list from the UNION sub-query and join it back to the subquery on userid. The sub-query is implemented only once, as a CTE.


text:
Q: T-SQL UDF vs full expression run-time I'm trying to make my query readable by using UDF in SQL SERVER but the run time increasing dramatically when using the function.
Following is the function I'm using:
create function DL.trim_all(@input varchar(max))
returns varchar(max)
as begin
    set @input=replace(replace(replace(@input,' ',''),')',''),'(','')
    return @input
end

Instead of writing:
SELECT
CASE WHEN replace(replace(replace([FULL_NAME_1],' ',''),')',''),'(','')=replace(replace(replace([FULL_NAME_2],' ',''),')',''),'(','') THEN 1 ELSE 0 END AS [name_match],
CASE WHEN replace(replace(replace([ADDRESS_1],' ',''),')',''),'(','')=replace(replace(replace([ADDRESS_2],' ',''),')',''),'(','') THEN 1 ELSE 0 END AS [adrs_match]
.
.
.
FROM
TABLE_1

for 20 different fields.
When using the function I'm getting run-time of 12.5 minutes while run-time of 45 seconds when not using the function.
Any ideas?

A: Taking John's idea one step further, converting the scalar function into an inline table function and using cross apply to activate it for each pair of columns - you might get an even better performance, for the price of a more cumbersome query:
CREATE function DL.DoesItMatch(@s1 varchar(500),@s2 varchar(500))
returns table -- returns a table with a single row and a single column
as return
  SELECT
    CASE WHEN replace(replace(replace(@s1,' ',''),')',''),'(','') =
              replace(replace(replace(@s2,' ',''),')',''),'(','') THEN 1 ELSE 0 END As IsMatch;

and the query:
SELECT NameMatch.IsMatch AS [name_match],
       AddressMatch.IsMatch AS adrs_match
.
.
.
FROM TABLE_1
CROSS APPLY DL.DoesItMatch(FULL_NAME_1, FULL_NAME_2) As NameMatch
CROSS APPLY DL.DoesItMatch(ADDRESS_1, ADDRESS_2) As AddressMatch

A: Can't imagine a huge boost, but how about an alternate approach
create function DL.DoesItMatch(@s1 varchar(500),@s2 varchar(500))
returns bit
as begin
    return CASE WHEN replace(replace(replace(@s1,' ',''),')',''),'(','')=replace(replace(replace(@s2,' ',''),')',''),'(','') THEN 1 ELSE 0 END
end

Then call the function as:
SELECT
      DL.DoesItMatch([FULL_NAME_1],[FULL_NAME_2])  AS [name_match],
      ...
FROM
TABLE_1

A: Inlining is always the way to go. Period. Even without considering the parallelism inhibiting aspects of T-SQL scalar UDFs - ITVFs are faster, require less resources (CPU, Memory and IO), easier to maintain and easier troubleshoot/analyze/profile/trace. For fun I put together a performance test comparing Zohar's ITVF to John's scalar UDF. I created 250K rows, tested a basic select against both, then another test with an ORDER BY against the heap to force a sort.
Sample data:
-- Sample Data
BEGIN
  SET NOCOUNT ON;
  IF OBJECT_ID('tempdb..#tmp','U') IS NOT NULL DROP TABLE #tmp;
  SELECT TOP (250000) col1 = '('+LEFT(NEWID(),10)+')', col2 = '('+LEFT(NEWID(),10)+')'
  INTO    #tmp
  FROM   sys.all_columns a, sys.all_columns;

  UPDATE #tmp SET col1 = col2 WHERE LEFT(col1,2) = LEFT(col2,2)
END

Performance Test:
PRINT 'scalar, no sort'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @isMatch BIT;
  SELECT @isMatch = DL.DoesItMatch(t.col1,t.col2)
  FROM   #tmp AS t;
PRINT DATEDIFF(MS,@st,GETDATE())
GO 3

PRINT CHAR(10)+'ITVF, no sort'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @isMatch BIT;
  SELECT      @isMatch = f.isMatch
  FROM        #tmp AS t
  CROSS APPLY DL.DoesItMatch_ITVF(t.col1,t.col2) AS f;
PRINT DATEDIFF(MS,@st,GETDATE())
GO 3

PRINT CHAR(10)+'scalar, sorted set'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @isMatch BIT;
  SELECT @isMatch = DL.DoesItMatch(t.col1,t.col2)
  FROM   #tmp AS t
  ORDER BY DL.DoesItMatch(t.col1,t.col2);
PRINT DATEDIFF(MS,@st,GETDATE())
GO 3

PRINT CHAR(10)+'ITVF, sorted set'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @isMatch BIT;
  SELECT      @isMatch = f.isMatch
  FROM        #tmp AS t
  CROSS APPLY DL.DoesItMatch_ITVF(t.col1,t.col2) AS f
  ORDER BY    f.isMatch;
PRINT DATEDIFF(MS,@st,GETDATE())
GO 3

Test Results:
scalar, no sort
------------------------------------------------------------
Beginning execution loop
844
843
840
Batch execution completed 3 times.

ITVF, no sort
------------------------------------------------------------
Beginning execution loop
270
270
270
Batch execution completed 3 times.

scalar, sorted set
------------------------------------------------------------
Beginning execution loop
937
930
936
Batch execution completed 3 times.

ITVF, sorted set
------------------------------------------------------------
Beginning execution loop
196
190
190
Batch execution completed 3 times.

So, when no parallel plan is needed, the ITVF is 3X faster, when a parallel plan is required it's 5X faster. Here's a few other links where I have tested ITVF vs (scalar and Multistatement Table Valued UDFs).
Set based plan runs slower than scalar valued function with many conditions
SQL Server user defined function to calculate age bracket
Function is slow but query runs fast
Why does SQL Server say this function is nondeterministic?
Grouping based on the match percentage
SQL Server 2008 user defined function to add spaces between each digit
Sql table comma separated values contain any of variable values checking
SQL String manipulation, find all permutations

A: You could use Scalar UDF inlining in SQL Server 2019. With that, you will be able to retain the same UDF that you have written, and automatically get the performance identical to the query without the UDF.
The UDF you have given fits the criteria for inlineability so you are in good shape. Documentation about the UDF inlining feature is here: https://learn.microsoft.com/en-us/sql/relational-databases/user-defined-functions/scalar-udf-inlining?view=azuresqldb-current
Pro tip: I'd suggest that you make a make a minor modification to your UDF before using Scalar UDF inlining. Make it into a single statement scalar UDF by avoiding the local variable. With this, you should be better off than using an inline TVF with cross apply.


text:
Q: Are all sets with finite measure measurable? In my textbook, it says:
"Let E be any set with m*(E) < $\infty$. Then E is measurable if and only if there exists a measurable set B with m(B) = m*(E)."
There always exists a measurable set of any given measure implying that there always exists a measurable set with measure m*(E). Thus this would imply that all sets with finite measure are measurable. I'm not sure if I'm thinking correctly. Is this true? Are all sets with finite measure measurable?
Proof: Let $E$ be measurable. Then take $B = E$. Conversely, let there exist a measurable set $B \supset E$ with $m(B) = m$*$(E)$. Then, by Theroem 3.4.10 (b), we have $m$ * $(E-B) = m$ * $(E) - m$ * $(B) = 0$ Now, $E - B$ being a set of measure zero, is measurable and hence $ E = (E - B) \cup B $ is measurable


text:
Q: Using Both Elasticsearch and Sphinx I have currently sphinx integrated in my website.
Now i thought of integrating Elastic Search for some other Search features which i haven't yet built with sphinx.
I thought to migrate to Elastic Search. But I do not want to change my previous integration from sphinx to elastic search (right now).
Is there any major issue if i use both search engines ?

A: Use more resources. Like more RAM, more diskspace, and increased CPU. Also more contention on database if both index at the same time. Need powerful enough server
And more maintenance as would need to maintain two packages, updates etc likely to be on different schedules


text:
Q: How can I to manipulate dynamically created controls? Lets say I have a form where someone can catalog a multiple people's Name and their State and City?
Assume I already have all the State/Cities in database. (a table for each state, with cities listed in each table)
The Name field will be a TextBox.  And the State & City fields will be ComboBox (DropDownLists).
One row (for the entry of one person) already exists in the form.  But I want the user to be able to dynamically add rows of entries by pressing an "Add Person" button.
The next step is where I'm struggling.  In each dynamically added row of fields, I would like the second ComboBox (Cities) to be populated depending on which State is chosen in the first Combo Box.  Also, the Cities ComboBox will remain disabled until the State ComboBox is chosen.
My code looks something like this:
    public ComboBox cbState;
    public ComboBox cbCities;
    public static int NumberOfPeople = 1;

    private void btnAddNewPerson_Click(object sender, EventArgs e)
    {

        NumberOfPeople++;

        TextBox txtPerson = new TextBox();
        txtPerson.Name = "Person" + NumberOfPeople;
        Panel.Controls.Add(txtPerson);

        //  ADD State ComboBox
        cbState = new ComboBox();
        cbState.Name = "State" + NumberOfPeople;
        cbState.Enabled = true;
        cbState.DropDownStyle = ComboBoxStyle.DropDownList;
        Panel.Controls.Add(cbState);

        //  ADD City ComboBox
        cbCity = new ComboBox();
        cbCity.Name = "City" + NumberOfPeople;
        cbCity.DropDownStyle = ComboBoxStyle.DropDownList;
        cbCity.Enabled = false;
        cbCity.SelectedValueChanged += new System.EventHandler(this.ChangeState);
        Panel.Controls.Add(cbCity);

    }

    private void ChangeState(object sender, EventArgs e)
    {

       ..... Don't know how to properly identify the City ComboBox that is in the same row as the State ComboBox that was just changed, and manipulate/populate it.....

    }

Anyone able to help me solve this issue??
I'd greatly appreciate it!!

A: You could use a dictionary
Dictionary<ComboBox,ComboBox> CityToStateMap = new Dictionary<ComboBox,ComboBox>();

then when you add a row
CityToStateMap[cbState] = cbCity;

then when you changestate
ComboBox city = CityToStateMap[(ComboBox)sender];

A: First of all I would create an additional class (e.g. with name Row) that contains all controls of one row. So you can encapsulate controls of one person in one object.
Your Form class gets a list member of such row objects like
List<Row> _rows = new List<Row>();.
In constructor of that class Row you create the controls of one row and assign the event handlers to the SelectedValueChanged event of the combobox controls.

A: You could use the Control.Tag in order to attach a data object to your controls. See how the controls are introduced to each other in the example.
private void btnAddNewPerson_Click( object sender, EventArgs e )
{
    AddPersonRow();
}

private void AddPersonRow()
{
    // Create combo boxes
    ComboBox cbCity = new ComboBox();
    ComboBox cbState = new ComboBox();

    // Introduce them to each other
    cbCity.Tag = cbState;
    cbState.Tag = cbCity;

    //  ADD State ComboBox
    cbState.Name = "State" + NumberOfPeople;
    cbState.Enabled = true;
    cbState.DropDownStyle = ComboBoxStyle.DropDownList;
    cbState.SelectedValueChanged += new EventHandler( cbState_SelectedValueChanged );
    panel.Controls.Add( cbState );

    // Populate the states sombo
    PopulateStateCombo( cbState );

    //  ADD City ComboBox
    cbCity.Name = "City" + NumberOfPeople;
    cbCity.DropDownStyle = ComboBoxStyle.DropDownList;
    cbCity.Enabled = false;
    cbCity.SelectedValueChanged += new EventHandler(cbCity_SelectedValueChanged);
    panel.Controls.Add( cbCity );
}

void cbState_SelectedValueChanged( object sender, EventArgs e )
{
    ComboBox cbState = sender as ComboBox;
    ComboBox cbCity = cbState.Tag as ComboBox;

    cbCity.Enabled = true;

    // .. Go ahead and populate cbCity by cbState's selected value ..
}

void cbCity_SelectedValueChanged( object sender, EventArgs e )
{
    // Up to you...
}

Note that instead of shaking hands with each other ComboBox, you could create a class that will hold both ComboBoxes, your TextBox control, the row number, etc. and then set the Tag of all these controls to the class itself.
public class PersonRow
{
    public int RowNum { get; private set; }
    public TextBox NameTextBox { get; private set; }
    public ComboBox CityCombo { get; private set; }
    public ComboBox StateCombo { get; private set; }

    public PersonRow( int rowNum )
    {
        RowNum = rowNum;

        // Create the controls
        NameTextBox = new TextBox();
        CityCombo = new ComboBox();
        StateCombo = new ComboBox();

        // Bind them to this instance
        NameTextBox.Tag = this;
        CityCombo.Tag = this;
        StateCombo.Tag = this;

        //.. continue as in the prev. example..
    }
}

A: First of all you should find the name of the comboBox you want to manipulate.
then you can search a control in the panel which has the name we just found, then you can do what ever you want.
here is the code for that
    private void ChangeState(object sender,EventArgs e){
        ComboBox stateComboBox= (ComboBox)sender;
        //find the name of target City ComboBox
        string cityComboName = "City"+stateComboBox.Name.Substring(5); // 5 is the Length of 'State'
        ComboBox cityComboBox=null;
        foreach(Control cntrl in panel1.Controls){
            if (cntrl.Name == cityComboName) {
                cityComboBox= (ComboBox)cntrl;
                break;
            }
        }
        if (cityComboBox!= null) {
            cityComboBox.Enabled = true;
            // now you have the both cityComboBox and stateComboBox Of the same Row
        }
    }


text:
Q: FCM not loading Properties for configured Hyper-V shares Have 3 nodes 2 of which are part of a hyper-v cluster. Many moons ago I configured network shares within FCM, for the last few days when attempting to select properties for specific shares it displays the below:

I have restarted all nodes.
I have confirmed i can PSSession to the server my PC.
I have confirmed WinRM can communicate to the remote Nodes with:
winrm id -r:ComputerName

I can confirm i do not have a loopback ip configured:
netsh http show ip listen

I have confirmed i do not have any proxy configured:
netsh winhttp show proxy

I have confirmed that WMI is also working as to be expected.
The issue is happening on certain pc's in the network, other PC's in the network can still access it, when using my credentials on the working PC's i am able to view the properties.
Can anyone help me out with this?

A: All - I raised an issue with Microsoft and after hours of troubleshooting got no where.
The good news is I found the problem myself, I have found the solution to the issue myself.
It turns out the version of RSAT being offered by Microsoft for windows 10 (WindowsTH-RSAT_WS2016-x64.msu) appears to be have the issue, do not use FCM from the new version of RSAT from the URL: https://www.microsoft.com/en-au/download/details.aspx?id=45520
After getting a package output from my working colleges PC I noticed a difference with the RSAT versions, see below:
Non-Working:
Package Identity : Microsoft-Windows-RemoteServerAdministrationTools-Client-Package-TopLevel~31bf3856ad364e35~amd64~~10.0.14393.347
State : Installed
Release Type : Update
Install Time : 5/12/2016 1:50 AM
Working:
Package Identity : Microsoft-Windows-RemoteServerAdministrationTools-Client-Package-TopLevel~31bf3856ad364e35~amd64~~10.0.14300.1041
State : Installed
Release Type : Update
Install Time : 3/02/2017 12:43 AM
I removed the .347 version from my PC and installed the .1041 RSAT version from my colleges PC, after doing this all is working perfectly. Thanks Microsoft for the great undocumented feature!


text:
Q: How Can I hide an info button from a subview? I have a mainViewController and inside its nib file I added an info button, in which action is to flip between two subviews, subview A and subview B.
From mainViewController, under viewDidLoad, I'm inserting subview A. Here I notice that the info button is in front of the subview A, which is fine.
The problem comes that when pressing any buttons that are located within subview A's nib file, in which they add new subviews, the info button remains on front.
So, how can I add these later subviews on front of all parent view stacks, so the info button does not appear? or how can I hide the info button?

A: If I understand correctly, your mainViewController's view has two superviews: subView A and infoButton.  You'd like to add subviews to subviewA that appear over the infoButton view?
The simple answer is that you can't make subviews of subviewA appear over the infoButton view.  If you think of the view hierarchy as a tree, the renderer draws the views in a depth-first way.  This means it draws subviewA, and all of subviewA's subviews (and so on) before it considers the infoButton view.  If you want a view to appear over the infoButton view you need to add it as a sibling of infoButton after infoButton in the main view's subview list.
If you'd like to hide the infoButton, you can simply set the hidden property to YES, and then set it to NO when you want the infoButton view to reappear, of course.
Depending on what you're doing with subviewA, you might consider using a modal view controller or a navigation controller to manage the views that you add when the user interacts with subviewA.


text:
Q: HTTP End point to service the request I am designing a small component for an application. The role of this component is to provide a HTTP Endpoint for the user requests and also return back the response.
My question is, do I have to have serve the requests/response through a servlet?? In case if it happens to be Servlet, Am I compelled to deploy it on a full stack Application Server. The reason being I do not have large volume of data to handle.
I am looking for simple solution in this regard, I would request if anyone could help me on this.

A: Well if you want to stay in Java world, I would recommend you Spring Boot which provides embedded HTTP server (Tomcat, Jetty...) in your application. So you don't depend on any external application server. It is very simple (main-method like) implementation and will give you everything you possibly need (with Spring included).
If you don't want to have Spring included, you can use plain Tomcat/Jetty. That is also valid but Spring Boot may be useful for you as it gives you utilities you may need/like (now or in future).
There is also option to go with HttpServer implementation from com.sun package but I would use this only if I would be sure that Oracle Java will be used.
Just to note, I feel that days of "external" application servers are coming to an end. Even ThoughtWorks in their Technology radar put Application Servers to Hold (Hold = We don't have an "avoid" ring, but we do throw things in the hold ring that we wish our clients wouldn't use).


text:
Q: Jenkins job getting failed on getpass.py file raise EOF error Jenkins Pipeline job is getting failed with these logs in the deployment stage of my code:
  Logs:
  File "/usr/lib/python2.7/site-packages/fabric/network.py", line 642, in prompt_for_password
    new_password = _password_prompt(password_prompt, stream)
  File "/usr/lib/python2.7/site-packages/fabric/network.py", line 614, in _password_prompt
    return getpass.getpass(prompt.encode('ascii', 'ignore'), stream)
  File "/usr/lib64/python2.7/getpass.py", line 83, in unix_getpass
    passwd = fallback_getpass(prompt, stream)
  File "/usr/lib64/python2.7/getpass.py", line 118, in fallback_getpass
    return _raw_input(prompt, stream)
  File "/usr/lib64/python2.7/getpass.py", line 135, in _raw_input
    raise EOFError
EOFError
[Pipeline] load

Please help in resolving the error at the earliest, what is the reason behind EOF error.


text:
Q: Python XML parser - break down to class and functions I've created recently python script parsing multiple xml files matching given pattern and writing the results into the .csv file (see code below).
I would like to break the code below into the class and functions, something like this:
Class:
Function 1 -> loads filepaths into the list;
Function 2 -> writes the results into the .csv file
Any suggestions how to do it? Many thanks in advance for your help.
#
# Import Python modules
#
import os
import fnmatch
import sys
import datetime
import xml.etree.ElementTree as ET
#
# Define rootpath and pattern
#
rootpath = '/Users/USER_ONE/XML_Test_Data'
pattern = 'data-*'
#
# Search for files in directory and add the selection into list
#
List = []
for root, dors, files in os.walk(rootpath):
    for filename in fnmatch.filter(files, pattern):
        List.append(os.path.join(root, filename))

print('')
print('=====================================')
print('List of files matching the criteria')
print('=====================================')
print('')
#
# Print files matching the criteria one by one
#
count = 0
for item in List:
    print(item)
    count += 1
print('')
print(str(count) +' files retrieved')
#
print('')
print('=====================================')
print('System now extracts data from XML files above into .CSV file')
print('=====================================')
##
## Get current Time
curr_time = str(datetime.datetime.now())
##
## Open a file - file gets created in CWD
outfile = "XML-Output-"+curr_time+".CSV"
fo = open(outfile, "a")
#
# Write field names
fo.write('UID;TITLE;ACTOR;DIRECTOR;COUNTRY;FORMAT;BITRATE;FPS;ASPECT RATIO;PATH'+'\n')
#
for item in List:
    ## Set Variables for XML parsing
    tree = ET.parse(item)
    root = tree.getroot()
    #print(root)
    product = root.find('uid')

    ##
    ## Set Node variables
    ##
    ## get UID
    if 'uid' in root.attrib:
        uid = root.attrib.get('uid')
    else:
        uid = ""
    ##
    ## Get title
    title = root[0].text
    ##
    ## Get actor
    actor = root[1].text
    ##
    ## Get director
    director = root[2].text
    ##
    ## Get country
    country = root[3].text
    ##
    ## Get elements inside ASSET node
    ##
    ## Get Format
    format = root[4][0].text
    ##
    ## Get Bitrate
    bitrate = root[4][1].text
    ##
    ## Get fps
    fps = root[4][2].text
    ##
    ## Get Aspect ratio
    aspect_r = root[4][3].text
    ##
    ## Path = merge of Filepath + uid + format
    filepath = item
    #
    # Define extract + ignore ascii encoding
    line_extr = (uid + ';' + title + ';' + actor + ';' + director + ';' + country + ';' + format + ';' + bitrate + ';' + fps + ';' + aspect_r+ ';' + filepath + '-' + uid + '-' + format).encode('ascii', 'ignore').decode('ascii')
    ##
    ## Write output with line end character
    fo.write(line_extr + '\n')
    ##
fo.close()
print('')
print('*** Data extracted successfully! ***')
print('*** Check results in: '+ outfile + ' ***')


text:
Q: How to set mariadb on jhipster I need use MariaDB and I want to start a project with JHipster.
How Can I configure to use MariaDB DataBase?
I try to configure application-prod.yml and pom.xml files but it doesn't work for me.

A: Here's what's worked for me:
 1. Configure JHipster to use MySql.
 2. Make sure mariadb is running (depends on you platform, on linux i verified by running the mysql command and making sure it can connect to my db)
 3. Create a database named like your app (i think that should happen somewhere in the generate/build process but for me it didn't, so i created it with 'CREATE DATABASE myappname' from the same mysql command line tool.
 4. Build and run your app with 'mvn' or 'gradle' in the apps root directory.


text:
Q: VTK: Put Label/Text near points in the 3d plot I have written a code which plots multiple 3d points as spheres. I want to add some text near each sphere in 3D to mention some info about each point. But I have vtkPoints to store points positions which doesn't have GetOutputPort which I need in labelMApper (and also used glyph3d to make spheres)
vtkSmartPointer<vtkLabeledDataMapper> labelMapper = vtkSmartPointer<vtkLabeledDataMapper>::New();
labelMapper->SetInputConnection( vtkpoints->GetOutputPort() ); // No GetOutputPort()
vtkSmartPointer<vtkActor2D> labelActor = vtkSmartPointer<vtkActor2D>::New();
labelActor->SetMapper(labelMapper);
renderer->AddActor(labelActor);

A: You should construct a vtkPolyData from the points and set it as Input to the label mapper.
Something like this:
vtkNew<vtkPolyData> labelPolyData;
labelPolyData->SetPoints(labelPoints);
labelMapper->SetInput(labelPolyData);  // Note: If you're using VTK from master (6.x), this is SetInputData(...)
renderer->AddActor2D(labelActor);


text:
Q: Setting priority/niceness within a jupyter/ipython notebook Is there any way to set the CPU priority of a jupyter notebook lower within the notebook? E.g. when running a days long parameter search on a compute server, setting priority within that notebook behind notebooks that others are working on in real-time.

A: Maybe setting the priority of your python process would be enough for you? As possible startet processes inherit the priority.
If yes, the following code my help:
import psutil
psutil.Process().nice(19)# if on *ux
psutil.Process().nice(psutil.IDLE_PRIORITY_CLASS)# if on win

A: I guess you can renice the whole server (not aware of any way to renice a particular notebook). If the other notebooks are running on distinct notebook server process, you can do it from a subshell:
---------------------------------------------------------------
  !for pid in `pgrep -f jupyter`; do { renice -20 $pid; }; done
---------------------------------------------------------------

9721 (process ID) old priority 19, new priority -20
12449 (process ID) old priority 19, new priority -20
25502 (process ID) old priority 19, new priority -20

Or, if you want to do it in Python, first get the list of running servers:
>>> from notebook import notebookapp
>>> servers = list(notebookapp.list_running_servers())
>>> servers
[{'url': 'http://localhost:8888/',
  'base_url': '/',
  'token': '5ea29b3...7e1fba5331ae',
  'secure': False,
  'pid': 9721,
  'hostname': 'localhost',
  'password': False,
  'port': 8888,
  'notebook_dir': '/home/paulos/work'
}]

Filter the list for the ones you want if needed.
pids = [_['pid'] for _ in servers if meets_condition(_)]

Then call setpriority:
>>> from ctypes import cdll
>>> libc = cdll.LoadLibrary("libc.so.6")
>>> pids = [_['pid'] for _ in servers]
>>> for pid in pids:
        print("old priority for PID", pid, "is", libc.getpriority(0, pid))
        libc.setpriority(0, pid, 20)
        print("new priority for PID", pid, "is", libc.getpriority(0, pid))

old priority for PID 9721 is 0
new priority for PID 9721 is 19


text:
Q: Javascript regex to catch either '%20' or whitespace Can't get my head around regex. Want to turn this string:
 var str = "Hello my%20name is%20Jascination"

into
 str2 = "Hello&my&name&is&Jascination"

I've tried:
 var str2 = str.replace(/[20%]/w/s/g, '&')
 var str2 = str.replace(/[20%/w/s]/g, '&')

but these don't work. With Regex how do I capture both specific characters and specific groups of characters?

A: It's easy. Just use or (x|y)
var str2 = str.replace(/%20| /g, '&');

Debuggex Demo

A: Try this:
var str2 = str.replace(/(?:%20|\s)+/g, '&');


text:
Q: ViewModel with generic type How can i create a viewModel with a generic type? Let me show you an example:
ViewModel
public class MyViewModel<T> extends ViewModel
{
    private Repository<T> repository;

    ...

    @Override
    public LiveData<Model<T>> getModel()
    {
        return repository.getModel();
    }
}

Fragment
        private MyViewModel<T> viewModel;

        ...

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState)
        {
            super.onActivityCreated(savedInstanceState);

            // this is where i need my viewModel with the generic type
            viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        }

As you can see, i am unable to get the sepecified viewModel i initialized as a variable in my fragment Maybe someone can lead me in the right direction, thanks.

A: I know this question asked a long time ago but for anyone else who has same problem you should use a factory class to send your own constructor to a view model class ( in Kotlin Code):
//Your view model
class BaseViewModel<K1, K2> : ViewModel() {
}

a factory class that extend ViewModelProvider.Factory:
    class BaseViewModelFactory<K1,K2>:ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return BaseViewModel<K1,K2>() as T
    }
}

and declare your view model in activity or fragment as below:
val viewmodel=ViewModelProvider(this, BaseViewModelFactory<K1, K2>())
            .get(BaseViewModel::class.java) as BaseViewModel<K1, K2>


text:
Q: OnClick listener - one function for all clicks In my layout xml file I have set the android:onClick attribute for a Button element to a function in my activity.  So when I click the button the function is called with a View as its argument.  Are there any information in that View argument that has the id of the button being clicked?  I'm trying to figure out if I have to have one onClick function for every element or if I can use one function and switch depending on the id of the element being clicked.

A: switch (v.getID) {
case R.id.A:
 .....
}

A: ohh Apps has the answer all right... just for throughness I have something like so...
case sensitive stuff.... funny how a getID won't work while a getId will be golden...  funny how a compiler couldn't do a "sloppy check" and correct such case issues.
like so
View myButton = findViewById(R.id.mybutton);
     myButton.setOnClickListener(this);
  View myOtherButton = findViewById(R.id.myotherbutton);
       myOtherButton.setOnClickListener(this);
public void onClick(View v) {
             switch (v.getId()) {
           case R.id.mybutton:
                              //Do something related to the mybutton click

            break;
        case R.id.myotherbutton:
                              //Do something related to the myotherbutton click

            break;
       //chain all Resource ID's here like above....
                                   }
}

you must also not to forget to setup a Onclick listener for every click event before the switch or the case will never get resolved....
//whoo hoo.  8cupsaday android app coming soon!


text:
Q: Letter O considered harmful? Back in the day, the FORTRAN standards committee reviewed a technical proposal called "Letter O considered harmful". I used to be able to find a link to the text of this proposal on the net, but it seems to have disappeared since the last time I looked for it -- the link disappeared off the relevant Wikipedia page and the only Google hits for the term are references back to Wikipedia. Does anyone happen to know a good repository of information about FORTRAN so that I could track it down, or even better, have a link to the proposal itself?

A: You are indeed correct!
Yes, there was such a proposal (entitled "Letter 'O' Considered Harmful")
in the official set of documents supplied to voting members at the November 1976 meeting of X3J3 that was held at Brookhaven National Laboratory.  (At this same meeting, committee chose "Fortran 77", with six lower-case letters, as the name for this revision of the language.)
I am able to verify this because I was not only the host for this meeting but also the actual author of this anonymous "proposal".  As such, I enlisted the typist (my boss' secretary, Bette) to type up this phony "proposal" in the proper format and slip it into the official distribution provided at the meetingplace (Conference Room B of Berkner Hall).
Loren Meissner was so amused by it that he wrote a little item in a Fortran publication for which he was editor.  Walt Brainerd also mentioned it in his publication. I had sworn both of them to secrecy regarding my little prank, so those articles did not identify me. (Sorry, I don't recall the names of these two publications.)
The lists of pro and con arguments (as was typical of X3J3 proposals in those days) included:

*

*Restoring the number of Fortran characters to 48 (by omitting 'O'to counterbalance the addition of the colon ':')

*Solving ambiguities caused by nested DO loops.

*Eliminating problems with (deprecated) Hollerith specifications in FORMAT statements.

*Preventing misuse of GO TO statements.

while the "con" list contained only one objection (with a disclaimer):

*

*This proposal may invalidate some existing FORTRAN programs, but most of these are probably "standard-conforming" anyway.

A: I think this is the guy to ask: Bruce A. Martin. He seems* to be the one who originally posted it on Wikipedia, and he puts himself as working at Brookhaven (where the article was circulated) at the same time.
The citation he gives on Wikipedia for the article is:

X3J3 post-meeting distribution for meeting held at Brookhaven National Laboratory in November 1976.

(* the user page for the user that posted it links to the website as being their material)

A: Mentioned on Wikipedia, referred to as a joke / folklore.  Doesn't surprise me TBH.


text:
Q: How to edit the list of files to download in a .torrent file? I have a torrent that contains many files in it, but I don't want to download all of them because I need only few files among them. I am not downloading from a torrent client, but I am actually using put.io service that converts torrents into direct downloads for me.
I want to edit the .torrent file (or magnet link) in such a way that I get only those files which I need from the torrent. I tried by editing with text editors, but I am getting some crazy hash errors when I did that.
I have seen people editing trackers in a torrent file (using online editors and other editors), but none of them edited the list of files in the torrent file.
So, the question is:
How to edit a .torrent file (and save it back as another .torrent file) such that when you run that torrent file, it only downloads only those files you need?

A: It may not be possible - from some preliminary googling
"The torrent file format makes adding or removing files impossible without access to the original files. " from Faq - Torrent Editor
This might need client support to only download the needed files, however put.io doesnt seem to support it yet

A: Use BEncode Editor which can edit torrents and their file lists.

A: Delete download from the software. Then again double click .torrent file and again add it. Then again it will ask what to download. You can tick them. Things now download will append to the previously downloaded content. Unticked content will not be downloaded.


text:
Q: Does the following inequality hold under Zygmund condition? Let $f:R\rightarrow R$ be a continuous function which satisfies the Zygmund condition
$$
|f(x+\delta)+f(x-\delta)-2f(x)|\leq \text{const} \frac{|\delta|}{(\log\frac{1}{|\delta|})^{\alpha}}, \,\, \text{for any}\,\,|\delta|<1,
$$
where $\alpha >1/2.$ According to the Weiss and Zygmund Theorem,
$f$ is absolute continuous and $f'\in L_{p}$ for every $p>1.$
Q: For any interval $[a, c]$ such that $|[a,c]|<1$, does the following inequality hold?:
$$
\int_{a}^{c}\Big|\int_{a}^{x}\frac{f'(y)(y-a)dy}{(x-a)^{2}}-\int_{x}^{c}\frac{f'(y)(c-y)dy}{(c-x)^{2}}\Big|dx\leq \text{const}\frac{|[a,c]|}{(\log\frac{1}{|[a,c]|})^{\alpha}}
$$


text:
Q: does android.media.SoundPool cause memory leak? I found these code may case memory leak on android 2.1

    SoundPool soundPool = new SoundPool(10, 7, 0);
    ...
    ...
    soundPool = null;

every time after the execution, the MAT pluging tells that two String objects of "android:unnamed_thread" are added to the heap of the process. is that an issue?

A: did you try to run soundPool.release() instead of soundPool = null?

A: I see two possibilities (there may well be more).
The first (most likely) is true of all Java objects: just because you set the reference to null doesn't automatically mean that the object behind it will be garbage-collected.
If a SoundPool object itself contains a reference to the two thread objects, none of the three will necessarily be GC'ed until space is required (although that depends, of course, on how aggressive your collector is).
The second (less likely) is that Android may be smart enough to cache thread (or even SoundPool) objects in case they need to be used again. They may nave done this as a performance optimisation if object creation is more expensive than object re-cycling.
In that case, they would still have a reference to the objects somewhere in a cache and they wouldn't be considered eligible for garbage collection.