text:
Q: Need to flush the Java EDT ( event dispatch queue ) I have a Java app where many threads are writing to a StyledTextBox rapidly. At some point all the threads are terminated. However, the TextBox continues to receive text for a bit presumably because the dispatch queue was a bit backed up. Is it possible to somehow force the EDT to be flushed so that when the threads are terminated the updates to the TextBox end immediately?
Thank you,
Jim

A: You can push() your own EventQueue subclass, as shown here, and add your own flush() method to empty the queue. Note that getNextEvent() blocks if the queue is empty, so check peekEvent() first.

A: Use a queue for your changed text to apply, schedule events an the EDT that work the queue empty before returning. This would lead to "empty" events, once the threads finished and one further scheduled event on the EDT ran.

A: Ok I found the solution. The idea is to install a "verify" listener which gets called whenever text is about to be added to the StyledText. So when text is about to be added ( from the backed up dispatch queue ) the code looks for a flag to be set indicating whether or not the threads have been terminated. If the threads have been terminated then ignore the text update. This allows the control to stop being updated while allowing the event queue to be drained. The following code snippet solves the problem.
txtOutput is the StyledText control.
endingThreads is a boolean set to true when the threads have been terminated.
This appears to be the easiest way to handle the issue in an SWT application.
        txtOutput.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent e)
        {
            if( !endingThreads )
            {
                e.doit = true;
            }
            else
            {
                e.doit = false;
            }
        }
    });


text:
Q: incorrect encoding of rsyslog output I'm running a rsyslog service in a docker container.
Its configuration(rsyslog.conf) looks like below,

module(load="imuxsock")    # local system logging support (e.g. via
logger command)
module(load="imudp")       # UDP listener support module(load="imtcp")
module(load="mmutf8fix")
action(type="mmutf8fix")
LOCAL1.*                                                  action(type="omfile" file="/var/log/my.log")

The client program is Java program that is using logback to write the log to both local file and remote rsyslog service.
The local log file looks like for non-ascii characters, whose encoding is UTF-8.
However the output file of rsyslog is NOT UTF-8. Of course the non-ascii characters can not be shown properly.

➜  rsyslog git:(master) ✗ file /volume/disk/logs/svt/my.log
/volume/disk/logs/svt/my.log: ASCII text, with very long lines

I'm wondering how to configure rsyslog to write output as UTF-8, there is no obvious solution after searching Google.

A: I solved it.
The problem is that the default locale of the container is not UTF-8. I'm using alpine linux as the OS of rsyslog container. Finally adding below environment declarations in Dockerfile to fix the encoding issue.
ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8

redpajama_set_name: RedPajamaStackExchange


text:
Q: How could I use arrays in this? For my assignment, I am supposed to, "Write the code for your parent class(es) and the child classes and write a driver class to demonstrate the methods and variables of your application. In your driver, include an array to store objects of all your child classes. Use a loop to print out the relevant values of each object and/or use its methods."
Well, this is what I have made so far:
Dog (Abstract Class):
    package objectsofaffection;

    public abstract class Dog extends Test {

        static String name;
        static String age;
        static String coatColor;

        public abstract void name();
        public abstract void age();
        public abstract void coatColor();
}

DogBetty:
package objectsofaffection;

public class DogBetty extends Dog {

    public DogBetty() {
        name();
        age();
        coatColor();
    }

    @Override
    public void name() {
        System.out.println("Dog Name: Betty");
        }
    @Override
    public void age() {
        System.out.println("Age: 11 years");
        }
    @Override
    public void coatColor() {
        System.out.println("Coat Color: Brown");

        }
    }

DogCarl:
package objectsofaffection;

public class DogCarl extends Dog {

    public DogCarl() {
        name();
        age();
        coatColor();
    }

    @Override
    public void name() {
        System.out.println("Dog Name: Carl");
        }

    public void age() {
        System.out.println("Age: 2 months");
        }

    public void coatColor() {
        System.out.println("Coat Color: Black");

        }
    }

DogJoe:
package objectsofaffection;

public class DogJoe extends Dog {

    public DogJoe() {
        name();
        age();
        coatColor();
    }

    @Override
    public void name() {
        System.out.println("Dog Name: Joe");
        }

    public void age() {
        System.out.println("Age: 6 years");
        }

    public void coatColor() {
        System.out.println("Coat Color: Spotted Black and White");

        }
    }

DogMollie:
package objectsofaffection;

public class DogMollie extends Dog {

    public DogMollie() {
        name();
        age();
        coatColor();
    }

    @Override
    public void name() {
        System.out.println("Dog Name: Mollie");
        }

    public void age() {
        System.out.println("Age: 3 years");
        }

    public void coatColor() {
        System.out.println("Coat Color: Black, Brown, White mix.");

        }
    }

Test (Driver Class):
package objectsofaffection;

public class Test {

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        DogBetty betty = new DogBetty();
            System.out.println(); //space

        DogJoe joe = new DogJoe();
            System.out.println(); //space

        DogCarl carl = new DogCarl();
            System.out.println(); //space

        DogMollie mollie = new DogMollie();
            System.out.println(); //space

    }
}

So, how could I possibly use arrays? Help please.

A: In addition to the accepted answer from Salman, I must point out that your parent class declared 3 static variables.  Static variables are shared across all instances of the class, so when those are set, every instance of dog will have the same name, age, color.  Fortunately, those variables are never set, so they just illustrate you're confused about their purpose and the use of 'static'.   Also, note that everyone of your child classes do the same thing.  This is a hint you should move that logic into the parent class.   Each child class constructor should call super(),  and the super class constructor would call those same 3 methods.

A: First of all, you don't have make child class for each dog, an abstract class represents a type, and child class represents a sub-type. so in your if Dog is parent class, your child class can be breeds and for each dog you make an object.
Dog-> germanShepard extends Dog ->  germanShepard dogMollie = new germanShepard();
Then you can use ArrayList of type germanShepard: ArrayList<germanShepard> dogs = new ArrayList<germanShepard>();
dogs.add(dogMollie); ArrayList is dynamic data structure so it grows according to your need
but if you want to use array,
germanShepard[] dogs;
dogs =new germanShepard[10];
dogs[0] = new germanShepard(name,age,coatColor);


text:
Q: Which is the default provider for LocationSource? LocationSource is just an Interface to help me with location-data.
It makes use of the onLocationChanged(Location location) method which takes a Location object as parameter ( lat, long and other info ).
So if I understand well what is says here :
A GoogleMap object has a built-in location provider for its my-location layer, but it can be replaced with another one that implements this interface.

...there is a new ( a built-in location provider ) location provider for my GoogleMap object, although I can make use of the LocationManager and choose from there
My code is below ( as you can see I don't make any use of the LocationManager ) and I get a very accurate location when I click for my location ( mMap.setMyLocationEnabled(true);  )
If I have the GPS on I can get my location so do I when I have only the wifi.
So my question is : this new provider is something "different" from GPS/network ? If I don't use locationManager there will be a problem? ( yes I know for an official app I better make use of the LocationManager to check every case but it still works  ).
My guess is it uses either  GPS or network but if I have both enabled which one is the default? Which provider the app makes use first ?
Code :
public class MainActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener, LocationSource, LocationListener {

private GoogleMap mMap;
private OnLocationChangedListener mapLocationListener=null;

private static final LatLng SKG_VIEW = new LatLng(40.6402778, 22.9438889);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setUpMapIfNeeded();

//   mMap = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)  ).getMap();

}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

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

/**  **************** SetUp Map if needed *****************
 *
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 *

 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView
 * MapView}) will show a prompt for the user to install/update the Google Play services APK on
 * their device.
 *

 * A user can return to this Activity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the Activity may not have been
 * completely destroyed during this process (it is likely that it would only be stopped or
 * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
 * {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setMyLocationEnabled(true);
        mMap.setOnMapClickListener(this);

             /***
              *         *****   CAMERA *****
              ***/

     // Construct a CameraPosition focusing on Mountain View and animate the camera to that position.
        CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(SKG_VIEW)      // Sets the center of the map to SKG_VIEW point
            .zoom(7)                   // Sets the zoom
            .build();                   // Creates a CameraPosition from the builder

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}
/** ******************   Add Markers ***************************
 *
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 *
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(10, 10)).title("Marker 2"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(40, 40)).title("Marker 2"));

}

/**
 *
 * *****************  onMapClick *******************************
 *
 */

@Override
public void onMapClick(LatLng point) {
        mMap.animateCamera(CameraUpdateFactory.newLatLng(point));

}

@Override
public void onMapLongClick(LatLng point) {
    //dont need it right now
}

@Override
public void activate(OnLocationChangedListener listener) {
    // LocationSource
    this.mapLocationListener=listener;
}

@Override
public void deactivate() {
    // LocationSource
    this.mapLocationListener=null;
}

public void OnLocationChanged(Location location)    {                               //LocationListener
        if( mapLocationListener != null )   {
            mapLocationListener.onLocationChanged(location);

            double lat = location.getLatitude();
            double lon = location.getLongitude();

            Log.v("TAG", "i was here");
        }
}

@Override
public void onProviderDisabled(String provider) {                                   //LocationListener
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {                                    //LocationListener
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

A:
this new provider is something "different" from GPS/network ?

No. LocationSource is an interface, not a provider.

If I don't use locationManager there will be a problem?

You are welcome to have your locations come from a random number generator via your own custom LocationSource, if you so choose. Note that this may confuse the user. :-)

My guess is it uses either GPS or network but if I have both enabled which one is the default?

As Maps V2 is closed source, we have no way to know for certain, and AFAIK the behavior is undocumented. I would assume it will use more accurate locations as available, and it probably uses both providers while the GPS provider is awaiting its first fix.


text:
Q: Converting IEEE 754 float to hex string I have this code that converts hex to float i basically need the reverse of this operation
byte[] bytes = BitConverter.GetBytes(0x445F4002);
float myFloat = BitConverter.ToSingle(bytes, 0);
MessageBox.Show(myFloat.ToString());

I want to enter the float and turn it to hex string.

A: *

*Call BitConverter.GetBytes to get a byte array representing your float.

*Convert the byte array to hex string: How do you convert Byte Array to Hexadecimal String, and vice versa?
FWIW, the code in your question does not do the reverse of this. In fact the code in your question does not receive a hex string. It receives an int literal that you expressed as hex. If you wish to convert from a hex string to a float then you use the code in the link above to convert from hex string to byte array. And then you pass that byte array to BitConverter.ToSingle.

It seems you are having problems putting this together. This function, taken from the question I link to above, converts from byte array to hex string:
public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

Call it like this:
string hex = ByteArrayToString(BitConverter.GetBytes(myfloat));

And in comments you state that you wish to reverse the bytes. You can find out how to do that here: How to reverse the order of a byte array in c#?


text:
Q: Problema validando img_perfil de la tabla users (me valida la imagen aún sin seleccionar ninguna) estoy personalizando los templates y controladores que te  crea automaticamente laravel con el comando :

php artisan make:auth

Y pues bien, ya lo tengo casi terminado en una primera version de lo que yo quiero. Pero me he topado con el siguiente problema:

Le he añadido a la tabla users que crea por defecto laravel varios campos, para personalizarla, entre ellos el campo img_perfil. El tema de las migraciones y el añadido de nuevos campos a la tabla users no me han causado ningun tipo de problemas.

Pero el tema del campo img_perfil si que me pone impedimentos:

A la hora de validarlo en la parte frontend esta puesto con un input de tipo file:

                    Imagen de perfil

                        <input id="img_perfil" type="file" class="form-control @error('img_perfil') is-invalid @enderror" name="img_perfil" value="{{ old('img_perfil') }}" autocomplete="img_perfil">
                        @error('img_perfil')

                                {{ $message }}

                        @enderror

En mi validacion backend (fichero Controllers\Auth\RegisterController.php) lo tengo de la siguiente manera:
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],

            'apel_1'=>['string','max:255'],
            'apel_2'=>['string','max:255'],
            'user_name'=>['string','required','max:20','unique:users'],
            'img_perfil'=>['max:100000','mimes:jpg,png,jpeg,gif'],

        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),

            'apel_1' => $data['apel_1'],
            'apel_2' => $data['apel_2'],
            'user_name' => $data['user_name'],
            'img_perfil' => $data['img_perfil']

        ]);
    }
}

Como se puede observar, en la validacion del campo img_perfil esta puesto de la siguiente manera:
'img_perfil'=>['max:100000','mimes:jpg,png,jpeg,gif'],

Se entiende que la valdiacion que le hago es : tamaño imagen|extensiones permitidas no le estoy indicando que sea required, pues cuando hago una prueba de insertar usuario sin seleccionar ninguna foto me dice :

The img perfil must be a file of type: jpg, png, jpeg, gif.

Pero eso me lo deberia de decir si he seleccionado una foto. Si no hay pues que no valide nada.

A: Dependiendo de como estés enviando el formulario, puedes usar:
'img_perfil'=>['nullable|max:100000|mimes:jpg,png,jpeg,gif'],

si el campo va a estar siempre presente, aunque tenga null como valor.
O puedes usar:
'img_perfil'=>['sometimes|max:100000|mimes:jpg,png,jpeg,gif'],

si el campo sólo va a estar presente cuando tenga un valor.
nullable:
no considera los valores null como no validos.
sometimes:
ejecuta verificaciones de validación en un campo solo si ese campo está presente.


text:
Q: Why this scanned book image has no background? If you save this image on your desktop, you see it's background color as your desktop color. If you open it with Adobe Photoshop, its background id checkered which means it has no background. It's transparent.
The background data is removed and I think this image has this size without any compression because no lag in zooming compared to the same image with white background (you can find it through trial and error and converting it to different formats with different compressions) which leads to faster scrolling speed when converted to PDF. How we can do it?
How to produce a 1-bit transparent gif?
By the way, in archive.org it's recognized as animated gif.

A:
Why this scanned book image has no background?

Whoever produced it set it's background to be transparent.
This is a feature of several image file formats. sometimes it is referred to as an alpha channel (which provides degrees of transparency) some tools/formats simply allow for one color to be selected and marked as fully transparent.
GIF supports index transparency, which is the latter type.

How we can do it?

For simple index transparency,iIn many tools you can choose a transparency option when you save a file.

Example of save options in IrfanView


text:
Q: Samba credentials changing when attempting to mount I'm trying to mount Samba shares automatically using fstab.
Right now my fstab entry for the network share is
//bistack/matt  /mnt/Network_Shares/Matt  cifs  user=matt,pass=*****,auto,nouser,exec,rw,async,atime,vers=3.0  0  0

Although when I try to mount the shares using sudo mount -av it errors out with error 13 permission denied. I thought this was simply because the password or the username I had was wrong, although the verbose output has the credentials as user=root,pass=******** which is of course not the same as the fstab file has.


text:
Q: Cannot "Build All" subreports in Jaspersoft Studio 6.3.1 I am using TIBCO Jaspersoft® Studio 6.3.1.final and I have a report with 15 subreports embeded in the main report in this way:
<subreport>
<reportElement x="0" y="320" width="1000" height="20" uuid="504fbc60-0036-46a1-9a04-d42bda10a85f"/>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
<subreportExpression><![CDATA["BSR015_17_eu_roamed_text.jasper"]]>
</subreportExpression>
</subreport>

When I open the main report and click "Project -> Build All" (or press Ctrl+B) it compiles only the main report and does not compile subreports (it does not create *.jasper files).
When I open each of them and compile individualy then it works well.
Is there any way to compile all subreports at the same time?
Thank you and kind regards
Pawel


text:
Q: How can I select data rows by id in a database query? I have a database query that needs filtering further. The id needs to match a number in an array I have. For some reason, I can select where using every column except id. Even something as simple as $query->where('users.id', 1); doesn't work. How can I perform a database query by id?
$portfolio_query_array = UserPortfolio::all()->pluck('user_id')

$query = DB::table('users');
        $query->select('users.id as user_id','users.user_slug', 'users.social_id', 'users.social_img_update_status', 'users.avatar', 'users.first_name', 'users.last_name', 'users.bio', 'comments.rating', 'user_portfolios.title', 'user_portfolios.description', 'user_portfolios.filepath');

        $query->leftjoin('comments', 'comments.comment_to', '=', 'users.id');
        $query->leftjoin('user_portfolios', 'user_portfolios.user_id', '=', 'users.id');

        $query->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', '=', 'users.id');

        $query->where('users.status', 1);
        $query->where('users.user_type', 3);

        // The below simple query line doesn't work
        $query->where('users.id', 1);

        // The lines I do want to work also fail.
        foreach ($portfolio_query_array as $user_id){
            $query = $query + $query->where('users.id', $user_id);
        }

Thank you for your help!

A: First of all, you should take advantage of Eloquent ORM, there is no need to use raw queries unless you have some performance issues or really complex queries.
Assuming you have 3 models User, UserPortfolio, Comment, and all relationships defined, you could do something as simple as this:
$users = User::with('comments', 'portfolio')
   ->where('status', 1)
   ->where('user_type', 3)
   ->whereHas('portfolio')
   ->get();

In this way, you are getting all users with portfolios which is what I assume you want.
Anyway, if you insist to use a raw query, there whereIn() method is what you need
$portfolio_query_array = UserPortfolio::pluck('user_id')->toArray();

$query = DB::table('users')
    ->select(
         'users.id as user_id',
         'users.user_slug',
         'users.social_id',
         'users.social_img_update_status',
         'users.avatar',
         'users.first_name',
         'users.last_name',
         'users.bio',
         'comments.rating',
         'user_portfolios.title',
         'user_portfolios.description',
         'user_portfolios.filepath'
     )
     ->leftjoin('comments', 'comments.comment_to', 'users.id')
     ->leftjoin('user_portfolios', 'user_portfolios.user_id', 'users.id')
     ->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
     ->where('users.status', 1)
     ->where('users.user_type', 3)
     ->whereIn('users.id', $portfolio_query_array)
     ->get();

BTW, why are you doing a leftJoin to user_profile_category_selects if no fields are selected from that table?
In addition, if you are looking for all users that have a portfolio, starting from the whole list of portfolios, wouldn't be better to do a join to portfolios and get only those users having portfolios?
$query = DB::table('users')
    ->select(
         'users.id as user_id',
         'users.user_slug',
         'users.social_id',
         'users.social_img_update_status',
         'users.avatar',
         'users.first_name',
         'users.last_name',
         'users.bio',
         'comments.rating',
         'user_portfolios.title',
         'user_portfolios.description',
         'user_portfolios.filepath'
     )
     ->leftjoin('comments', 'comments.comment_to', 'users.id')
     ->join('user_portfolios', 'user_portfolios.user_id', 'users.id')
     ->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
     ->where('users.status', 1)
     ->where('users.user_type', 3)
     ->get();


text:
Q: Light house not working in latest chrome version 95.0.4638.69 Light house not generating report in latest chrome browser.My browser was auto enabled for update.After updating the latest version, chrome not generating light house report.Its failed to generate the report only for performance.
chrome version 95.0.4638.69
Thanks

A: If it's PWA you're trying to generate a report on, probably caused by the service worker. Uncheck clear storage option under lighthouse. Linking an answer for reference.


text:
Q: Proxy sub domains without redirect in .htaccess Need to redirect requests sent to, for instance, sub domain auto.domain.int to www.domain.int/doc/sample-rates. It is a Zend application so MVC is used. I have the following in my .htaccess conf:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^auto\.domain\.int$
RewriteRule ^.*$ /doc/sample-rates [PT,L]

The thing is, when I put a name of a real file on filesystem as the RewriteRule substitution, lets say 'script.php', it all works well. The content of the script.php file served under the auto.domain.int hostname.
On the other hand when I put an MVC route as the RewriteRule substitution I got 500 error from apache for '/doc/sample-rates' path and 400 error for 'http://www.domain.int/doc/sample-rates' path and several lines in apache log:

127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d75058/initial] (3) [perdir /var/www/domain/base/www.domain.com/htdocs/] strip per-dir prefix: /var/www/domain/base/www.domain.com/htdocs/ ->
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d75058/initial] (3) [perdir /var/www/domain/base/www.domain.com/htdocs/] applying pattern '^.*$' to uri ''
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d75058/initial] (2) [perdir /var/www/domain/base/www.domain.com/htdocs/] rewrite '' -> '/doc/sample-rates'
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d75058/initial] (2) [perdir /var/www/domain/base/www.domain.com/htdocs/] forcing '/doc/sample-rates' to get passed through to next API URI-to-filename handler
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d75058/initial] (1) [perdir /var/www/domain/base/www.domain.com/htdocs/] internal redirect with /doc/sample-rates [INTERNAL REDIRECT]
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (3) [perdir /var/www/domain/base/www.domain.com/htdocs/] add path info postfix: /var/www/domain/base/www.domain.com/htdocs/doc -> /var/www/domain/base/www.domain.com/htdocs/doc/sample-rates
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (3) [perdir /var/www/domain/base/www.domain.com/htdocs/] strip per-dir prefix: /var/www/domain/base/www.domain.com/htdocs/doc/sample-rates -> doc/sample-rates
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (3) [perdir /var/www/domain/base/www.domain.com/htdocs/] applying pattern '^.*$' to uri 'doc/sample-rates'
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (2) [perdir /var/www/domain/base/www.domain.com/htdocs/] rewrite 'doc/sample-rates' -> '/doc/sample-rates'
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (2) [perdir /var/www/domain/base/www.domain.com/htdocs/] forcing '/doc/sample-rates' to get passed through to next API URI-to-filename handler
127.0.0.1 - - [04/Mar/2013:10:50:19 --0500] [auto.domain.int/sid#b73cd9d8][rid#b6d67018/initial/redir#1] (1) [perdir /var/www/domain/base/www.domain.com/htdocs/] internal redirect with /doc/sample-rates [INTERNAL REDIRECT]

Updated: auto.domain.int is an alias for the "main" www.domain.int using ServerAlias.

Thanks,
Eugene

A: You must add an additional RewriteCond to prevent an endless rewrite
RewriteCond %{HTTP_HOST} ^auto\.domain\.int$
RewriteCond %{REQUEST_URI} !^/doc/sample-rates$
RewriteRule ^.*$ /doc/sample-rates [PT,L]


text:
Q: Identificar de varios botones, cuál se ha presionado, para agregar ese producto al carrito en Javascript Estoy haciendo un carrito de compras. Tengo varios productos, pero no sé cómo puedo identificar qué botón se presionó para agregar ese producto al carrito. Lo primero que hago es hacer una clase, llamada Producto, que va a contener todos los productos.
class Producto {
    constructor(id, descripcion) {
        this.id = id;
        this.descripcion = descripcion;
    }
}
let productos = [];
let carrito = [];

productos.push(new Producto("751100", "Manija"));
productos.push(new Producto("851100", "Manija"));
productos.push(new Producto("751200", "Manija"));
productos.push(new Producto("753100", "Manija"));

Luego de eso, obtengo con el método getqueryselector() el elemento que quiero sumarle el innerHTML. Luego, por cada producto que definí arriba, se hará una card. (No adjunto los estilos porque quedaría muy largo)
El código es:
let section = document.querySelector('.tiendaOnline.row.separar.container-fluid');

for (const producto of productos) {
    let article = document.createElement("article");
    article.className = "col col-12 col-md-6 col-lg-4 carta"
    article.innerHTML = `

${producto.id}

${producto.descripcion}

Precio

                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                class="bi bi-cart" viewBox="0 0 16 16">
                                <path
                                    d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                            </svg>
                                    Agregar al Carrito

                                    Ver detalles

`;
    // Agregar a sección y no al documento
    section.appendChild(article);
}

El problema es que tengo que buscar una forma de saber qué botón está siendo apretado, para poder obtener el ID o la clase de ese producto (El ID del elemento va a ser el mismo que el ID del producto), para, con un push, poder agregarlo al array. No sé, o no conozco otra forma de hacerlo, pero si hay alguna más fácil, es bienvenida. Lo que yo traté de hacer es esto, pero no funcionó, sólo con el primero.
let producto = document.getElementsByClassName("producto");
producto.onclick = function (event){
    event.preventDefault();
    carrito.push(event.target)
}
console.log(carrito);

Mi HTML es:

Muchas Gracias!

A: Cuando se busca por getElementsByClassName para añadirle un evento hay que recorrer todos los elementos que tiene. Sería algo así en tu caso:
let producto = document.getElementsByClassName("producto");

for (var i=0; i < producto.length; i++) {
  producto[i].onclick = function (event){
    event.preventDefault();
    carrito.push(event.target)
  }
}

Por otro lado, ahora mismo tienes puesto el ID de producto como una clase en "Agregar al Carrito". Es más fácil que lo pongas como ID y no repitas en todos los productos el id="carrito". Cambia por algo así:
Agregar al Carrito

Con esto podrás conseguir de manera fácil el botón que se ha pulsado ya que, en event.target, existe una propiedad id que tendrá el ID de tu producto:
carrito.push(event.target.id)

Nota: También lo podrías obtener dejando el código como está, pero tendrías que buscar entre las clases del botón y es algo menos natural.
Nota 2: Si en vez de usar un elemento  usas uno <button> no haría falta usar el event.preventDefault();
Espero te sirva de ayuda


text:
Q: Username alias with Spring Security Is it possible to provide a user with an ability to login using either his ordinary username or it's alternative?
The reason I need the feature is following. We use emails as usernames (customer's requirement), which are both valid as user@mail.domain.com and user@domain.com for the same user. Some of them used to utilize the first notation, others the second.
Users are being authenticated via LDAP, which is read-only for me, so I can't just add a second mail atrribute to the user record. Any ideas please?

A: The solution I ended up with is based on this answer: https://stackoverflow.com/a/1422202/711031. I use the following FilteredRequest implementation:
public class LoginDomainCutFilter implements Filter {
    public void init(FilterConfig arg0) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new FilteredRequest(request), response);
    }

    private static class FilteredRequest extends HttpServletRequestWrapper {
        public FilteredRequest(ServletRequest request) {
            super((HttpServletRequest) request);
        }

        public String getParameter(String paramName) {
            String value = super.getParameter(paramName);
            if ("j_username".equals(paramName)) {
                value = cutSuffix(value, "@mail.domain.com");
                value = cutSuffix(value, "@domain.com");
            }
            return value;
        }

        private String cutSuffix(String value, String suffix) {
            if (value.endsWith(suffix)) value = value.substring(0, value.length() - suffix.length());
            return value;
        }
    }
}

In this case we should register our filter at web.xml before the Spring Security filter:
<filter>
    <filter-name>loginDomainCutFilter</filter-name>
    <filter-class>org.mydomain.myapp.LoginDomainCutFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loginDomainCutFilter</filter-name>
    <url-pattern>/j_spring_security_check</url-pattern>
</filter-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Finishing touch is to change (mail={0}) to (mail={0}@*) in your LDAP search filter:
<beans:bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
    <beans:constructor-arg index="0" value="ou=users,ou=myorgunit"/>
    <beans:constructor-arg index="1" value="(mail={0}@*)"/>
    <beans:constructor-arg index="2" ref="contextSource"/>
    <beans:property name="searchSubtree" value="true"/>
</beans:bean>

Please note that side-effect of the solution is that Spring Security username will no longer contain @domain suffix, so you should add it manually when you need to display the email. You should decide which one is primary, however.
You should also note that the filter doesn't affect usernames that contain another domain suffix, or doesn't have suffix at all. This is done for purpose, and you can add a simple check for that.
Now user could login as user@mail.domain.com, user@domain.com or even user. If you don't like the latter "bonus behaviour", you can also add a check.


text:
Q: Decrypting portions of AES encrypted file For my C++ application, I have looked at Crypto++. Seems simple enough to encrypt some content and save it in a file. It also seems simple enough to decrypt the whole file. However, our requirement is that we cannot decrypt the whole file at once. I need to decrypt portions of the file on the fly as requested by the caller. Essentially, I need to implement the following pseudo methods:
  int openFile(const char* aesFile); // returns a handle
  long read(int handle, long pos, int size, byte* buffer);

How can I achieve this? Is there something in Crypto++ or some other library that is readily available to do this? Regards.

A:
How can I achieve this? Is there something in Crypto++ ...

I think you need two things. First, you need a seekable cipher mode of operation. Counter mode (CTR) will probably work for that. You can check if a cipher is seekable using IsRandomAccess(). Its inherited from StreamTransfoormation Class.
In counter mode (and other seekable modes), be careful to ensure you still have authenticity assurances. This can be tricky. Also see Authenticated Encryption on the Crypto++ wiki.
Second, probably you need to avoid the streaming interface, and you need to use Put and Get. Put and Get are just C-like class functions present on every Crypto++ BufferedTransformation class.
Most examples of Put and Get are rather trivial. However, a more substantial one recently made an appearance on the Crypto++ wiki at Init-Update-Final. Though its more substantial, its not more complex because its a simple concept.

... or some other library that is readily available to do this?

Well, that's a choice you have to make. If C++ and security libraries are your only library requirements, then you can also check out Jack Lloyd's Botan.


text:
Q: SQL - illegal character in XML parsing trying to add replace How do I add a replace function to this code :
cast (convert(varchar(max), Convert(varbinary(max), c_xml)) as xml) c_xml

I get an xml parsing error. I believe I would need to conver & to &amp. I found one of the cell in sql where the problem lies to have two box like characters.
<SyncShipment xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" releaseID="9.2" versionID="2.6.3" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/trunk/InforOAGIS/BODs/Developer/SyncShipment.xsd"><ApplicationArea><Sender><LogicalID>infor.syteline.tangent</LogicalID><ComponentID>erp</ComponentID></Sender><CreationDateTime>2018-09-13T19:02:40Z</CreationDateTime><BODID>infor-nid:infor:Tangent:Tangent:5222898:?Shipment&verb=Sync</BODID></ApplicationArea><DataArea><Sync><TenantID>infor</TenantID><AccountingEntityID>Tangent</AccountingEntityID><LocationID>Tangent~MAIN</LocationID><ActionCriteria><ActionExpression actionCode="Add" /></ActionCriteria></Sync><Shipment><ShipmentHeader><DocumentID><ID accountingEntity="Tangent" lid="infor.syteline.tangent" location="Tangent~MAIN" variationID="2745613608842789">5222898</ID></DocumentID><DisplayID>5222898</DisplayID><LastModificationDateTime>2018-09-13T19:02:28Z</LastModificationDateTime><DocumentDateTime>2018-09-13T19:02:28Z</DocumentDateTime><Status>Shipped<EffectiveDateTime>2018-09-13T19:02:28Z</EffectiveDateTime></Status><WarehouseLocation><ID accountingEntity="Tangent" location="Tangent">Tangent~MAIN</ID><Name languageID="en-US">Tangent Technologies</Name><Address><AddressLine sequence="1">1001 Sullivan Road</AddressLine><AddressLine sequence="2" /><AddressLine sequence="3" /><AddressLine sequence="4" /><CityName>Aurora</CityName><CountrySubDivisionCode listID="State-Province">IL</CountrySubDivisionCode><CountryCode listID="Countries">US</CountryCode><PostalCode listID="Postal/ZIP Codes">60506</PostalCode></Address></WarehouseLocation><ActualShipDateTime>2018-09-13T19:02:28Z</ActualShipDateTime><ActualDeliveryDateTime>2018-09-13T19:02:28Z</ActualDeliveryDateTime><ShipFromParty><PartyIDs><ID accountingEntity="Tangent">Tangent</ID></PartyIDs><Name>Tangent Technologies</Name><Location><ID accountingEntity="Tangent" location="Tangent">Tangent~MAIN</ID><Name languageID="en-US">Tangent Technologies</Name><Address><AddressLine sequence="1">1001 Sullivan Road</AddressLine><AddressLine sequence="2" /><AddressLine sequence="3" /><AddressLine sequence="4" /><CityName>Aurora</CityName><CountrySubDivisionCode listID="State-Province">IL</CountrySubDivisionCode><CountryCode listID="Countries">US</CountryCode><PostalCode listID="Postal/ZIP Codes">60506</PostalCode></Address></Location></ShipFromParty><CarrierParty><PartyIDs><ID accountingEntity="Tangent" /></PartyIDs><Location><ID /></Location></CarrierParty><ShipToParty><PartyIDs><ID accountingEntity="Tangent">Tangent~MAIN</ID></PartyIDs><Name>Tangent Technologies</Name><Location><ID accountingEntity="Tangent" location="Tangent">Tangent~MAIN</ID><Name languageID="en-US">Tangent Technologies</Name><Address><AddressLine sequence="1">1001 Sullivan Road</AddressLine><AddressLine sequence="2" /><AddressLine sequence="3" /><AddressLine sequence="4" /><CityName>Aurora</CityName><CountrySubDivisionCode listID="State-Province">IL</CountrySubDivisionCode><CountryCode listID="Countries">US</CountryCode><PostalCode listID="Postal/ZIP Codes">60506</PostalCode></Address></Location><Contact><Communication><UseCode listID="Communication Use Codes">Phone</UseCode><DialNumber>630-264-1110</DialNumber></Communication></Contact></ShipToParty><CustomerParty><Name languageID="en-US">Tangent Technologies</Name><Location><Name languageID="en-US">Tangent Technologies</Name><Address><AddressLine sequence="1">1001 Sullivan Road</AddressLine><CityName>Aurora</CityName><CountrySubDivisionCode listID="State-Province">IL</CountrySubDivisionCode><CountryCode listID="Countries">US</CountryCode><PostalCode listID="Postal/ZIP Codes">60506</PostalCode></Address></Location><Contact><Communication><UseCode listID="Communication Use Codes">phone</UseCode></Communication></Contact></CustomerParty></ShipmentHeader><ShipmentItem><ItemID><ID accountingEntity="Tangent">.75X2.625X144XMCHXR187X2E2</ID></ItemID><Description>3/4 x 2 5/8 x 144 Mocha DEM 2PAT</Description><OrderQuantity unitCode="">240.00000000</OrderQuantity><ShippedQuantity unitCode="">240.00000000</ShippedQuantity><ShippedBaseUOMQuantity unitCode="">240.00000000</ShippedBaseUOMQuantity><EstimatedWeightMeasure unitCode="">1756.8000000000000</EstimatedWeightMeasure><LoadingWeightMeasure unitCode="">1756.8000000000000</LoadingWeightMeasure><PlannedShipQuantity unitCode="">240.00000000</PlannedShipQuantity><SerializedLot><Lot sequence="1"><LotIDs><ID accountingEntity="Tangent">.75X2.625X144XMCHXR187X2E2~33191-02-01</ID></LotIDs></Lot></SerializedLot><LineNumber>10</LineNumber><CountSequence>1</CountSequence></ShipmentItem></Shipment></DataArea></SyncShipment>

This is one of the parsing that went through. Every few minutes batches like these go through.
This has to be converted to XML : [encoded data, 7578 characters]

A: At this position your XML includes bad characters (shortend with ...):
<ID lid="..." schemeAgencyID="..." schemeName="...">1124-8TURFGR</ID>

Taking the  away resolves the problem.
But: These two characters are part of the <ID>s value. I do not know, why these characters are there, neither do I know if they have any meaning.
'#x4' is known as end-of-transmission, while '#x1' is known as start-of-heading. I'm pretty sure, that these invisible characters are some kind of residue...
Try it out:
SELECT CAST(REPLACE(CAST(@xmlBin AS VARCHAR(MAX)),'','') AS XML)


text:
Q: 3D coordinates to pixel coordinates in Matlab I'm writing code to simulate stereo vision and found some troubles with the 3D to 2D mapping. The object I'm looking at is built around the axes origin and the camera target is set to [0 0 0].
Camera up-vector is [0 0 1] so that the camera reference system and world (object) reference system are the same. To map 3D points into 2D points I have:
[x/z y/z 1]' = K * P * [X Y Z 1]'

where [x/z y/z] are the pixel coordinates of the 3D point located at [X Y Z 1] using homogeneous notation. K is the 3 x 4 calibration matrix (last column made of zeros) and P is the 4 x 4 projection matrix.
Since I also need to simulate calibration process I've obtained K using the Matlab Calibration Toolbox from Caltech with a typical chess pattern (this one built in Matlab too). K is found to be:
K = [521 0   409 0;
     0   521 288 0;
     0   0   1   0]

where the focal lenght is set by the camera view angle and i'm using 800 x 600 pictures taken with command print.

Here's my problem: if in 3D view I put a marker at the origin of the axes and take a picture of the scene with camera placed at [0 -50 -50] (for example) looking at [0 0 0] as said before I found the pixel coordinates of the origin at [415 290] in the picture.
But trying to calculate the projection through K * P * [0 0 0 1]' I'm getting wrong results such as [409 811 1] where X is almost the same but Y is completely wrong (even outside the picture boundaries).
K is defined by calibration toolbox, P is defined by rotation just on X-axis (45° in this case) and translation at [0 -50 -50].
What am i doing wrong?
Here's the P matrix (if it helps):
 P = [1  0      0     0;
      0  0.707 -0.707 -50;
      0  0.707  0.707 -50;
      0  0      0     1]


text:
Q: How to trigger canvas drawing line animation without actual mouse move? I am currently figuring out how to draw lines on page load without even having to actually moving the mouse to draw
Here is my code which draws line only when mouse is moved.
https://codepen.io/arvi/pen/RgYZqB
I added a "load" event listener and tied it to documentMouseMoveHandler but it seems not the solution for this scenario.
window.addEventListener('load', documentMouseMoveHandler, false);

Is it possible?

A: Ok do something like this until you get a mouse event , take random moue point in a interval if mouse event came, then remove it;
var intervalId;
function documentMouseMoveHandler(event) {
  if (!event) {
    intervalId = setInterval(function () {
       mouseX = Math.floor(Math.random() * (window.innerWidth - 1));
       mouseY = Math.floor(Math.random() * (window.innerHeight + 1));
      }, 3000);
    return;
  }
  if (event && intervalId) {
    clearInterval(intervalId);
  }

  mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
  mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}`


text:
Q: C# string to long pointer I am working with an application in C# that need to send a message to a C++ application.
I imported
[DllImport("user32.dll")]
        public static extern IntPtr SendMessage(
              int hWnd,      // handle to destination window
              uint Msg,       // message
              IntPtr wParam,  // first message parameter
              IntPtr lParam   // second message parameter
              );

but now, my problem is that I need to passe string to wParam and lParam. I tried unsafe code, but it seems string just doesnt work like the rest of variables. How can I achieve that? Thanks.

A: The declaration is wrong, the wParam and lParam arguments are IntPtr, not long.
There is a complication because you are trying to send strings.  What matters if the target window is Unicode enabled or not.  There are two versions of SendMessage, SendMessageA() and SendMessageW().  The former needs to be used if the program is dated and uses 8-bit character strings rather than UTF-16 encoded strings.
You can find out by using Spy++.  Use the finder tool to select the window of the application.  In the General property tab, you'll see "Window proc".  It will say (Unicode) if the window is Unicode enabled.  If you don't see it then the strings have to be translated to 8-bit characters.
To generate the string pointers you need to pass, you can use Marshal.StringToHGlobalAnsi or StringToHGlobalUni (respectively 8-bit and Unicode).  You can however play a trick to let the P/Invoke marshaller translate the string for you.  Saves you the hassle of having to free the strings after the call.  For the Ansi version, you can declare the API function like this:
    [DllImport("user32.dll", CharSet = CharSet.Ansi, EntryPoint = "SendMessageA", ExactSpelling = true)]
    private static extern IntPtr SendMessageStrings(IntPtr hWnd, int msg, string wParam, string lParam);

And the Unicode version like this:
    [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW", ExactSpelling = true)]
    private static extern IntPtr SendMessageStrings(IntPtr hWnd, int msg, string wParam, string lParam);

One final note: this will not work as-is if the window belongs to another application, you'll crash it.  The pointer values you pass are only valid in your own process, not in the C++ process.  To work around that, you have to allocate memory in the target process so that the pointer is valid.  That requires OpenProcess to get a handle to the process, VirtualAllocEx() to allocate memory in the target process, big enough to store the string, WriteProcessMemory to write the string.  Now you can call SendMessage(), use a version that is declared with IntPtr for the wParam and lParam arguments, pass the value you got from VirtualAllocEx.  Next use VirtualFreeEx() to release the memory and CloseHandle to clean up.  Or keep the memory around for the next time if you do this often.
Quite a lot of P/Invoke to get wrong there.  Not to mention security issues, WriteProcessMemory requires admin privileges, UAC elevation is required.

A: Passing the address of the string would involve unsafe code,
since Win32 API calls expect addresses (in a C/C++ native envrion).  What windows message are you sending that requires a string in wParam or lParam?

A: We ended up using "WmCpyDta_d.dll" to deal with all that.


text:
Q: How to keep form always selected I am creating a program where I can increase / decrease my volume control using buttons on my keyboard. I have created the codes to increase / decrease the volume with my specified buttons however when I am active on another program, If I press the buttons on my keyboard they will not increase or decrease the volume. Now I need a code to keep my form always selected even if another form has been activated , I tried using Me.Topmost = true however it didn't work since the form is not selected with that code. I have spent hours trying to search for any hints but to no avail, however someone must know how to do this so any help is appreciated.
- I am using Visual Basic 2012

A: What you need is a keyboard intercept.  http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx has a working sample.

A: I think what you actually want is a "global keyboard hook".  You'll need to add some code from the link below, but using it is simple...
To create the hook:
Private WithEvents kbHook As New KeyboardHook

Then each event can be handled:
Private Sub kbHook_KeyDown(ByVal Key As System.Windows.Forms.Keys) Handles kbHook.KeyDown
    Debug.WriteLine(Key.ToString)
End Sub
Private Sub kbHook_KeyUp(ByVal Key As System.Windows.Forms.Keys) Handles kbHook.KeyUp
    Debug.WriteLine(Key)
End Sub

Stolen from here:
How to listen keyboard in background and fire keystrokes on demand?


text:
Q: Could not install module (runpy issue) When trying to install a Python module on the Qualcomm® QCS610, some error messages occur. Python3 is used and the following commands are tried:
Python3 -m pip install tensorflow
**python3 -m pip install tflite **
The same error message comes up no matter what module is tried to install:
"Could not import runpy module
ImportError: No module named 'runpy'"
I thought ,I don't have access to the internet with myboard and assume Python wants to download the module over the internet. So I have found a way to download a module from My PC and then transfer it to the board using WinSCP and then install it from there as well.
I download the module "tflite-runtime" and keep it in Root .
By using " python3 -m pip install tflite_runtime-2.7.0-cp39-cp39-manylinux2014_x86_64.whl -f ./ --no-index"
By using this command , "tflite-runtime" module should have be installed ,however still showing same errros.
" Could not import runpy module
ImportError: No module named 'runpy'"
If anyone has an idea to solve this problem I appreciate it.
Thanks.
Deniz


text:
Q: Are eddy currents produced by a coil of copper wire? if I were too drop a magnet down a length of coiled copper wire would the motion of the magnet be opposed by eddy currents?

A:
if I were too drop a magnet down a length of coiled copper wire would the motion of the magnet be opposed by eddy currents?

Yes, but the eddy currents would be much smaller than if you had either a solid copper tube, or a series of rings.
The fact that an insulator (the air or wire insulation) is present where the current would "prefer" to flow will break up the eddy currents in a manner very similar to what happens in the laminated core of a laminated core transformer. Eddy currents exist, but at reduced amplitude.
You could increase the eddy currents by connecting the two ends of the coil together.

A: The magnet's motion would be opposed by electrical currents induced in the wire. I wouldn't call these "eddy currents" since they flow in the same direction along the entire wire, but that's just a point about names. You can connect a light bulb to the coil and it will light up as the magnet passes through.
Here's a video of a magnet moving past various arrangements of copper. The coil demonstration starts at 1:49.


text:
Q: Setting Authorization to specific parts of a component I have an events component, it displays a list of all the events in the database.
I am fairly new to authorization and react/redux in general
and I can't figure out how to do the authorization properly.
I want everybody to see all the events all the time
as well as when you click on it you see the tickets available for that specific event(now it displays all tickets of all events, I'll have to fix that later)
but the main thing I want have happen now
is that either
the 'CREATE EVENT' button is not displayed when a visitor isn't logged in
or that it is displayed, but when the visitor clicks on it
and they aren't logged in
they are redirected to the /login page
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { getAllEvents, getEvent, addEvent } from "../../actions/events";
import { getUsers } from '../../actions/users'
import Paper from "@material-ui/core/Paper";
import Moment from "moment";
import { Redirect } from "react-router-dom";

class EventsList extends PureComponent {

  componentWillMount() {
    this.props.getAllEvents();
  }

  getEvent(eventId) {
    this.props.getEvent(eventId);
  }

  addEvent = event => {
    this.props.addEvent(event);
  };

  render() {
    const { events, authenticated } = this.props;
    const eventsList = events.sort((a, b) =>{
     return a.id - b.id;
   });

    if (!authenticated) return <Redirect to="/login" />;

    return (

        <Paper className="styles" elevation={4}>

Coming Events

                Event Name
                Starts
                Ends

              {eventsList.map(event => (

                    {" "}
                    <Link
                      className="link"
                      to={`/events/${event.id}`}
                      onClick={() => this.getEvent(event.id)}
                    >
                      {event.name}
                    </Link>

                                 {Moment(event.startDate).format('ll')}

                                  {Moment(event.endDate).format('ll')}

              ))}

          <Link className="link" to={`/createEvent`}>
            CREATE EVENT
          </Link>
        </Paper>

    );
  }
}

const mapStateToProps = function(state) {
  console.log('users', state.users)
  return {
    events: state.events,
    event: state.event,
    authenticated: state.currentUser !== null,
    users: state.users === null ? null : state.users
  };
};

export default connect(
  mapStateToProps,
  {
    getAllEvents,
    getEvent,
    addEvent,
    getUsers
  }
)(EventsList);

Any suggestion

A: Well, to hide the button you could just do smth like
{ if(this.props.authenticated) {
    <Link className="link" to={`/createEvent`}>
      CREATE EVENT
    </Link>
}}

To handle the redirect depending on which the user is authenticated or not you could use the onClick event of Link (I'm not sure the Link component exposes the onClick event, if not, just changed it to a regular button).
<Link className="link" onClick={this.onCreateEvent}> // maybe use a <button /> instead
  CREATE EVENT
</Link>

// ...

onCreateEvent() {
  if(this.props.authorized) this.props.history.push("/createEvent"); // this dependes on which version of React-Router you are using.
  else this.props.history.push("/login");
}


text:
Q: How do I set values for NSDictionary object in Xamarin? I need to interface with a function that receives an object of type NSDictionary<NSString, NSObject> in Xamarin.
First, I don't understand the syntax.
What exactly is a NSDictionary<NSString, NSObject> type object?
I know there is NSDictionary type and I know how to create one and set keys and values, but what is NSDictionary<?,?> ? Is it suppose to be some sort of a special tuple?
Second, how do I create such an object and define the key and associated object?

A: On Xamarin.Mac, and following Sven-Michael Stübe, it can be:
var dictionary = new NSDictionary(
    new NSString("key1"), new NSString("object1"),
    new NSString("key2"), new NSString("object2")
);

Probably Xamarin.iOS too but I didn't tested.

A: NSDictionary<TKey, TValue> is just a generic version of NSDictionary. This means that the keys are all of the type TKey (in your case NSString) and the values are all of type TValue (in your case NSObject.). This provides more type safety, because e.g. you can't add integers as keys. The underlying iOS object is still a NSDictionary. This class is kind of "syntactic sugar", because we are used to strict typing in C# and want to use it where ever possible.
You can create it with a constructor. It has multiple constructors. E.g. NSDictionary(TKey[] keys, TValue[] values) is taking the keys and values as parameters and creates NSDictionary of it.
var keys = new[]
{
    new NSString("key1"),
    new NSString("key2"),
    new NSString("key3"),
    new NSString("key4")
};

var objects = new NSObject[]
{
    // don't have to be strings... can be any NSObject.
    new NSString("object1"),
    new NSString("object1"),
    new NSString("object1"),
    new NSString("object1")
};

var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);


text:
Q: Resample points in a Geodataframe so they stay equally spaced but inside area I have a geopandas dataframe that contains a complex area and some Point objects representing latitude and longitue inside that same area, both reading from .kml and .xlsx files, not defined by me. Thing is that those points are really close to each other, and when ploting the whole map they overlap, making it really difficult to spot each one individually, specially when using geoplot.kdeplot()
So what I would like to do is to find some way to equally space them, respecting the boundaries of my area. For sake of simplicity, consder the Polygon object as the area and the Point objects as the ones to resample:
import random
import matplotlib.pyplot as plt

y = np.array([[100,100], [200,100], [200,200], [100,200], [50.0,150]])
p = Polygon(y)

points = []
for i in range(100):
    pt = Point(random.randint(50,199),random.randint(100,199))
    if p.contains(pt):
        points.append(pt)

xs = [point.x for point in points]
ys = [point.y for point in points]

fig = plt.figure()
ax1=fig.add_subplot(111)
x,y = p.exterior.xy
plt.plot(x,y)
ax1.scatter(xs, ys)
plt.show()

That gives something like this:

Any ideas on how to do it witout crossing the area? Thank you in advance!
EDIT:
Important to mention that the resample should not be arbitrary, meaning that a point in coordinates (100,100), for example, should be somewhere near its original location.

A: This kind of problems can be handled in various ways such as force based method or geometrical method; Here, geometrical one is used.
I have considered the points to be as circles, so an arbitrary diameter can be specified for them, and also the area size for plotting with matplotlib. So we have the following codes for the beginning:
import numpy as np
from scipy.spatial import cKDTree
from shapely.geometry.polygon import Polygon
import matplotlib.pyplot as plt

np.random.seed(85)

# Points' coordinates and the specified diameter
coords = np.array([[3, 4], [7, 8], [3, 3], [1, 8], [5, 4], [3, 5], [7, 7]], dtype=np.float64)
points_dia = 1.1             # can be chosen arbitrary based on the problem

# Polygon creation
polygon_verts = np.array([[0, 0], [8.1, 0], [8.1, 8.1], [0, 8.1]])
p = Polygon(polygon_verts)

# Plotting
x, y = coords.T
colors = np.random.rand(coords.shape[0])
area = 700                   # can be chosen arbitrary based on the problem
min_ = coords.min() - 2*points_dia
max_ = coords.max() + 2*points_dia
plt.xlim(min_, max_)
plt.ylim(min_, max_)
xc, yc = p.exterior.xy
plt.plot(xc, yc)
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

I separate the total answer to two steps:

*

*dispersing (moving away) the suspected points from average position coordinates

*curing the point-polygon overlaps

First step
For the first part, based on the number of points and neighbors, we can choose between Scipy and other libraries e.g. Scikit learn (my last explanations on this topic 1 (4th-5th paragraphs) and 2 can be helpful for such selections). Based on the (not large) sizes that the OP is mentioned in the comment, I will suggest using scipy.spatial.cKDTree, which has the best performance in this regard based on my experiences, to query the points. Using cKDTree.query_pairs we specify groups of points that are in the distance range of the diameter value from each other. Then by looping on the groups and averaging each group's points' coordinates, we can again use cKDTree.query to find the nearest point (k=1) of that group to the specified averaged coordinate. Now, it is easy to calculate distance of other points of that group to the nearest one and move them outward by a specified distance (here just as much as the overlaps):
nears = cKDTree(coords).query_pairs(points_dia, output_type='ndarray')
near_ids = np.unique(nears)
col1_ids = np.unique(nears[:, 0])

for i in range(col1_ids.size):

    pts_ids = np.unique(nears[nears[:, 0] == i].ravel())
    center_coord = np.average(coords[pts_ids], axis=0)
    nearest_center_id = pts_ids[cKDTree(coords[pts_ids]).query(center_coord, k=1)[1]]
    furthest_center_ids = pts_ids[pts_ids != nearest_center_id]

    vecs = coords[furthest_center_ids] - coords[nearest_center_id]
    dists = np.linalg.norm(vecs, axis=1) - points_dia
    coords[furthest_center_ids] = coords[furthest_center_ids] + vecs / np.linalg.norm(vecs, axis=1) * np.abs(dists)

Second step
For this part, we can loop on the modified coordinates (in the previous step) and find the two nearest coordinates (k=2) of the polygon's edges and project the point to that edge to find the closest coordinate on that line. So, again as step 1, we calculate overlaps and move the points to placing them inside the polygon. The points that where single (not in groups) will be moved shorter distances. This distances can be specified as desired and I have set them as a default value:
for i, j in enumerate(coords):
    for k in range(polygon_verts.shape[0]-1):
        nearest_poly_ids = cKDTree(polygon_verts).query(j, k=2)[1]

        vec_line = polygon_verts[nearest_poly_ids][1] - polygon_verts[nearest_poly_ids][0]
        vec_proj = j - polygon_verts[nearest_poly_ids][0]
        line_pnt = polygon_verts[nearest_poly_ids][0] + np.dot(vec_line, vec_proj) / np.dot(vec_line, vec_line) * vec_line

        vec = j - line_pnt
        dist = np.linalg.norm(vec)

        if dist < points_dia / 2:
            if i in near_ids:
                coords[i] = coords[i] + vec / dist * 2 * points_dia
            else:
                coords[i] = coords[i] + vec / dist

These codes, perhaps, could be optimized to get better performances, but it is not of importance for this question. I have checked it on my small example and need to be checked by larger cases. In all conditions, I think this will be one of the best ways to achieve the goal (may some changes based on the need) and can be a template which can be modified to satisfy any other needs or any shortcomings.

A: so this is not particularly fast due to the loop checking for "point in polygon", but as long as you don't intend to ave a very fine grid-spacing something like this would do the job:
from scipy.interpolate import NearestNDInterpolator

# define a regular grid
gx, gy = np.meshgrid(np.linspace(50, 200, 100),
                     np.linspace(100, 200, 100))

# get a interpolation function
# (just used "xs" as values in here...)
i = NearestNDInterpolator(np.column_stack((xs, ys)), xs)

# crop your grid to the shape
newp = []
for x, y in zip(gx.flat, gy.flat):
    pt = Point(x, y)
    if p.contains(pt):
        newp.append(pt.xy)

newp = np.array(newp).squeeze()

# evaluate values on the grid
vals = i(*newp.T)

ax1.scatter(*newp.T, c=vals, zorder=0)


text:
Q: Aggregate and sum json data in python I am new to python, using python3. I have json data like:
{
    "message": {
        "count": 46,
        "limit": 1000,
        "schools": [
            {
                "class": "1",
                "class_id": "1c8***",
                "charges": [
                    {
                        "cost": 10,
                        "breakdown": [
                            {
                                "books": "1",
                                "unitQuantity": "10"
                            }
                        ]
                    }
                ],
                "area": "maccau"
            },
            {
                "class": "2",
                "class_id": "1c3***",
                "charges": [
                    {
                        "cost": 100,
                        "breakdown": [
                            {
                                "books": "1",
                                "unitQuantity": "100"
                            }
                        ]
                    }
                ],
                "area": "maccau"
            },
            {
                "class": "1",
                "class_id": "1c3***",
                "charges": [
                    {
                        "cost": 10,
                        "breakdown": [
                            {
                                "books": "1",
                                "unitQuantity": "10"
                            }
                        ]
                    }
                ],
                "area": "maccau"
            },
            {
                "class": "2",
                "class_id": "1c8***",
                "charges": [
                    {
                        "cost": 50,
                        "breakdown": [
                            {
                                "books": "1",
                                "unitQuantity": "50"
                            }
                        ]
                    }
                ],
                "area": "maccau"
            }
        ],
        "url": {
            "link": "/"
        }
    }
}

I was able to use json.loads to load data and I am trying to get results like:
class   Cost
1       20
2       150

I tried converting json to a dictionary:
item_dict = json.load(json_data)

Tried to get data out using for loop and checking if class = 1 and then summing up the cost. But I feel like that is not the best approach. Can someone please tell me what would be the best way of doing this?


text:
Q: How to test spring cloud stream kafka binder This is my code and I am looking to test it. Been looking at a few things (TopologyTestDriver, etc.) but could not get any to work. This example is directly from https://docs.spring.io/spring-cloud-stream/docs/current/reference/html/spring-cloud-stream-binder-kafka.html#_programming_model
Is there a simple, example unit test? Do I even need the kafka stuff or can I just directly test this function
  @Bean
  public Function<KStream<Object, String>, KStream<?, WordCount>> process() {

    return input -> input
                .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
                .map((key, value) -> new KeyValue<>(value, value))
                .groupByKey(Serialized.with(Serdes.String(), Serdes.String()))
                .windowedBy(TimeWindows.of(5000))
                .count(Materialized.as("word-counts-state-store"))
                .toStream()
                .map((key, value) -> new KeyValue<>(key.key(), new WordCount(key.key(), value,
                        new Date(key.window().start()), new Date(key.window().end()))));
  }


text:
Q: What is the best way to deal with Ansible's import_tasks/import_role and "notify"? Here is a very simple code fragment taken from my "kafka" role:
- import_role:
    name: java
  notify:
    - restart kafka
    - restart zookeeper

Basically I want to install Java running "java" role and when there are changes performed by that role (e.g. Java has been updated), then restart "kafka" and "zookeeper" services. It turns out, Ansible doesn't throw any error as well as not running these handlers specified in "notify" field.
What would be my options to workaround this?
P.S. Java is being installed manually, not from repositories.

A: I am answering my own question.

Problem
I have 3 roles in total:

*

*kafka - installs kafka and zookeeper apps, configures, enables/starts services etc.

*ssl - copies certificates to the server specific dir and that's it. When certificate is changed, I need to restart only kafka service.

*java - installs java and that is it. When java is updated, I need to restart both kafka and zookeeper services.

Then intention was to run only kafka role and include other ssl and java roles inside kafka role. Like this:
- import_role:
    name: java
  notify:
    - restart kafka
    - restart zookeeper

- import_role:
    name: ssl
  notify:
    - restart kafka

I've been expecting above code to work, because why not? Ansible did not throw any error regarding this, but silently did not run any handlers...
Note: both ssl and java are being re-usable roles, used by few other roles/playbooks.

Workaround
I've changed my handlers in kafka role into like this:
- name: restart kafka
  service:
    name: kafka
    state: restarted
  when: "'kafka_all' in group_names"
  listen:
    - restart SSL dependent services
    - restart java dependent services
    - restart kafka & zookeeper services

- name: restart zookeeper
  service:
    name: zookeeper
    state: restarted
  when: "'kafka_all' in group_names"
  listen:
    - restart java dependent services
    - restart kafka & zookeeper services

Then changed code in kafka role tasks like this:
- import_role:
    name: java

- import_role:
    name: ssl

And in both java and ssl role tasks I've added handlers accordingly. Like this for ssl role:
- name: upload SSL files
  copy:
    src: <hidden>
    dest: <hidden>
  notify: restart SSL dependent services

All above code might not make any sense yet, but familiarize yourself with below key points:

*

*In kafka role I import and not include other roles. It means that imported roles (kafka and ssl) are able to "see" handlers of kafka role. Upstream note.

*I am using Ansible's 2.8 new feature called listen. It means tasks can call a specified "listener" and it will automatically calls all listening handlers. If there are no handlers bound to the listener, it will not run anything (and that's expected behavior).

*Not so important, but I am using when: "'kafka_all' in group_names" just because I am storing kafka installation tasks in task file install.yml and I specified there notify: restart kafka & zookeeper services and the thing is - I want to install Kafka on server where I want Kafka as a service as well as on server where I want to have Kafka CLI tools only (so no services are started). Such server won't be part of kafka_all and eventually these handlers won't be executed.

A: In case anyone else stumbles on this post and wishes for something aside from workarounds. I have found through some testing and research that one should be able to now have notify: work in import_role:. As of Ansible v2.11 it appears that notify: is no longer ignored in the case of import_role:, meaning, the handlers specified as part of the import_role: task will run in the event said role does happen to make a change.
This seems to be an indirect benefit of now (at least as of Ansible v2.11) being able to add notify: to block: and notify: also not being ignored by import_tasks: (see https://github.com/ansible/ansible/blame/stable-2.11/changelogs/CHANGELOG-v2.11.rst#L879 and https://github.com/ansible/ansible/pull/73572/commits).


text:
Q: Example of an adiabatically perturbed integrable 2 d.o.f. Hamiltonian? Consider the following (classical) Hamiltonian system: $H(u,v,p,q, \tau)$, where $(u,v)$ and $(p,q)$ are conjugated variables and $\tau = \epsilon t$ is a slowly varying parameter, $0 < \epsilon << 1$, and $t$ is time.
Assume that:

*

*For each fixed $\tau$, Hamiltonian is integrable, and decouples into a product of a rotor + pendulum.

*Mathematically, this means that in terms of $(u,v)$ the phase space consists of closed periodic orbits only and hence action angle variables $I, \varphi$ can be introduced for each fixed $\tau$;

*In terms of $(p,q)$ variables, the phase space resembles that of a pendulum, with a hyperbolic fixed point and a homoclinic to it, i.e. $\frac{p^{2}}{2} + \cos q - 1 $, for each fixed $\tau$.

The slow perturbation couples the system and it becomes no longer integrable. The fixed point in $(p,q)$ persists and gives rise to a Normally Hyperbolic Invariant Manifold, with associated local stable / unstable manifolds.
I have two questions:

*

*What would be an explicit example of such Hamiltonian?

*I want to introduce A-A variables for the "totally elliptic" part of the Hamiltonian, so that I'd have $H(I, \varphi, p,q, \tau)$. When I transfer to action-angle variables would they depend on $(u,v, \tau)$ only, or also on $(p,q)$? In other words, do we seek the transformation as $I(u,v,p,q, \tau)$ or $I(u,v, \tau)$?


text:
Q: Group data based on specific conditions and find duration in R or Python I have a dataset, df, that looks like the following:
 subject    recipient                  length   folder    message  date                       edit
                                        80      out                1/2/2020 1:00:01 AM        T
                                        80      out                1/2/2020 1:00:05 AM        T
hey        sarah@mail.com,g@mail.com    80      out                1/2/2020 1:00:10 AM        T
hey        sarah@mail.com,g@mail.com    80      out                1/2/2020 1:00:15 AM        T
hey        sarah@mail.com,g@mail.com    80      out                1/2/2020 1:00:30 AM        T
some       k                           900      in       jjjjj     1/2/2020 1:00:35 AM        F
some       k                           900      in       jjjjj     1/2/2020 1:00:36 AM        F
some       k                           900      in       jjjjj     1/2/2020 1:00:37 AM        F
hey        sarah@mail.com,g@mail.com    80    draft                1/2/2020 1:02:00 AM        T
hey        sarah@mail.com,g@mail.com    80    draft                1/2/2020 1:02:05 AM        T
no         a                          900       in        iii      1/2/2020 1:02:10 AM        F
no         a                          900       in        iii      1/2/2020 1:02:15 AM        F
no         a                          900       in        iii      1/2/2020 1:02:20 AM        F
no         a                          900       in        iii      1/2/2020 1:02:25 AM        F
hey        sarah@mail.com,g@mail.com   80    draft                 1/2/2020 1:03:00 AM        T
hey        sarah@mail.com,g@mail.com   80    draft                 1/2/2020 1:03:20 AM        T

Background and Ojective
The dataset represents when a user is editing a message, steps away, and resumes to that same exact message. I am trying to capture the total duration of the message at hand. I know that I must first group the message. I wish to group the message based on these conditions:
If the Folder column is == "out" OR "draft", if the Message column is == "", and if the Edit == "T", the Length column should also be consecutively identical. So once I have these groups, I wish to find the duration (start and end) of these groups. For example the first group duration would be 29 seconds, because it starts at 1/2/2020 1:00:01 AM and ends at 1/2/2020 1:00:30 AM. The second group would start at 1/2/2020 1:02:00 and ends at 1:02:05 AM. Lastly the third group starts at 1/2/2020 1:03:00 AM and ends at 1:03:20 AM. Furthermore, since these groups all belong to the SAME message, I'd like to link these altogether by using the logic if: The Subject, Recipient, and Length contents in the last row of a group match the first row of the next groups Subject, Recipient and Length, then these all belong to the same group.
I'd like the output to look like this:
Desired Output
 Start                  End                        Duration          Group  Subject  Length
 1/2/2020 1:00:10 AM    1/2/2020 1:00:30 AM        20                A      hey       80
 1/2/2020 1:02:00 AM    1/2/2020 1:02:05 AM        5                 A      hey       80
 1/2/2020 1:03:10 AM    1/2/2020 1:03:20 AM        20                A      hey       80

Here is my dput
  structure(list(Subject = structure(c(1L, 1L, 2L, 2L, 2L, 4L,
  4L, 4L, 2L, 2L, 3L, 3L, 3L, 3L, 2L, 2L, 1L, 1L), .Label = c("",
 "hey", "no", "some"), class = "factor"), Recipient = structure(c(1L,
 1L, 5L, 5L, 5L, 4L, 4L, 4L, 5L, 5L, 3L, 3L, 3L, 3L, 5L, 5L, 1L,
 2L), .Label = c("", " ", "a", "k", "sarah@mail.com,gee@mail.com"
  ), class = "factor"), Length = c(80L, 80L, 80L, 80L, 80L, 900L,
 900L, 900L, 80L, 80L, 900L, 900L, 900L, 900L, 80L, 80L, NA, NA
 ), Folder = structure(c(4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 2L, 2L,
 3L, 3L, 3L, 3L, 2L, 2L, 1L, 1L), .Label = c("", "draft", "in",
 "out"), class = "factor"), Message = structure(c(1L, 1L, 1L,
 1L, 1L, 2L, 2L, 2L, 1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L), .Label = c("",
 "jjjjjjj", "llll"), class = "factor"), Date = structure(c(2L,
 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
17L, 1L, 1L), .Label = c("", "1/2/2020 1:00:01 AM", "1/2/2020 1:00:05 AM",
"1/2/2020 1:00:10 AM", "1/2/2020 1:00:15 AM", "1/2/2020 1:00:30 AM",
"1/2/2020 1:00:35 AM", "1/2/2020 1:00:36 AM", "1/2/2020 1:00:37 AM",
"1/2/2020 1:02:00 AM", "1/2/2020 1:02:05 AM", "1/2/2020 1:02:10 AM",
"1/2/2020 1:02:15 AM", "1/2/2020 1:02:20 AM", "1/2/2020 1:02:25 AM",
"1/2/2020 1:03:00 AM", "1/2/2020 1:03:20 AM"), class = "factor"),
Edit = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE,
TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, NA, NA
)), class = "data.frame", row.names = c(NA, -18L))

This is what I am working on:
   df <- df %>%
    mutate(Message = ifelse(is.na(Message), '', Message)) %>%
    mutate(
    cond = Edit & Folder %in% c('out', 'draft') & Message == ''
       ) %>%
    mutate(grp = cumsum(!cond)) %>%
   filter(cond, Subject = '')

   df$Date <- as.POSIXct(as.character(df$Date), format = '%m/%d/%Y %H:%M:%OS')

   get_group_number = function(){
   i = 0
   function(){
   i <<- i+1
     i
       }
   }
  group_number = get_group_number()
  df <- df %>% group_by(Subject, Recipient, Length) %>% mutate(Group = group_number())

  df %>% group_by(grp) %>%
  summarise(Start = min(Date), End = max(Date),
         Duration = End - Start, Group = unique(Group)[1])

Any help or suggestions is greatly appreciated.

A: df %>%
  # The original data was loaded as factors, which have their uses, but
  #   converting those to characters will be simpler to work with here.
  mutate_if(is.factor, as.character) %>%
  # I'm replacing NA in Subj & Recip with an empty string, and trimming
  #    excess spaces from the start and end. One of the recipients is " "
  #    but I assume that's functionally the same as blank.
  mutate_at(c("Subject", "Recipient"), ~if_else(is.na(.), "", stringr::str_trim(.))) %>%
  filter(Subject != '') %>%
  mutate(Date = as.POSIXct(Date, format = '%m/%d/%Y %H:%M:%OS')) %>%
  mutate(cond = Edit & Folder %in% c('out', 'draft') & Message == '') %>%
  mutate(segment = cumsum(!cond)) %>%
  filter(cond) %>%   # EDIT: Added to exclude rows matching cond

  # Get summary stats for each segment
  group_by(Subject, Recipient, Length, segment) %>%
  summarize(Start = min(Date),
            End = max(Date),
            Duration = End - Start) %>%

  # This counts the number of times that these columns don't match their
  #   predecessor. TRUE = 1, so we get 1 when anything changes.
  #   Look at ?lag for more on what those parameters mean.
  mutate(new_group = (Subject   != lag(Subject, 1, "")) *
                     (Recipient != lag(Recipient, 1, "")) *
                     (Length    != lag(Length, 1, ""))) %>%
  ungroup() %>%
  mutate(group = LETTERS[cumsum(new_group)])

# A tibble: 3 x 9
  Subject Recipient                   Length segment Start               End                 Duration new_group group
  <chr>   <chr>                        <int>   <int> <dttm>              <dttm>              <drtn>       <int> <chr>
1 hey     sarah@mail.com,gee@mail.com     80       0 2020-01-02 01:00:10 2020-01-02 01:00:30 20 secs          1 A
2 hey     sarah@mail.com,gee@mail.com     80       3 2020-01-02 01:02:00 2020-01-02 01:02:05  5 secs          0 A
3 hey     sarah@mail.com,gee@mail.com     80       7 2020-01-02 01:03:00 2020-01-02 01:03:20 20 secs          0 A


text:
Q: Filtering a recursive CTE as view i'm using MSSQL Server 2017 and have a CTE used in a view to get the root element of a hirarchical tree linked to one specific element.
If the CTE is used directly and the base elements are allready filtered the CTE is very fast.
The main problem is the performance when used as view because there it is not possible to filter directly in the base part of the CTE.
Example:
Create tmp table with 1000 entries:
SELECT TOP 1000 ID INTO #tElements from Elements

This is the CTE equivalent of the view which is slow:
WITH
Tree AS
(SELECT        Element AS Node, Element, Parent
  FROM            Elements AS E
  UNION ALL
  SELECT        T.Node, E.Element, E.Parent, E.ProductID
  FROM         Elements AS E INNER JOIN
               Tree AS T ON T.Parent = E.Element)
SELECT DISTINCT Tree.Node, Tree.Element, Tree.Parent
FROM            Tree
INNER JOIN      #tElements tmp on Tree.Node = tmp.ID
WHERE Tree.Parent IS NULL

This is the CTE directly filtered which is fast
WITH
Tree AS
(SELECT        Element AS Node, Element, Parent
  FROM            Elements AS E
  INNER JOIN      #tElements tmp on E.Element = tmp.ID
  UNION ALL
  SELECT        T.Node, E.Element, E.Parent, E.ProductID
  FROM         Elements AS E INNER JOIN
               Tree AS T ON T.Parent = E.Element)
SELECT DISTINCT Tree.Node, Tree.Element, Tree.Parent
FROM            Tree
WHERE Parent IS NULL

Maybe someone has a hint how to tell the server to filter the base elements first for the join and do the recursive part afterwards?
Thanks
Mike

A: You can create it as an inline Table Valued Function
CREATE OR ALTER FUNCTION GetElementsTree (
  @ID int
)
RETURNS TABLE AS RETURN

WITH Tree AS (
    SELECT       Element AS Node, Element, Parent
    FROM         Elements AS E
    WHERE        E.Element = @ID

    UNION ALL

    SELECT       T.Node, E.Element, E.Parent, E.ProductID
    FROM         Elements AS E INNER JOIN
                 Tree AS T ON T.Parent = E.Element
)
SELECT
  Tree.Node,
  Tree.Element,
  Tree.Parent
FROM            Tree
WHERE Tree.Parent IS NULL;

go

SELECT DISTINCT
  Tree.Node,
  Tree.Element,
  Tree.Parent
FROM            #tElements tmp
CROSS APPLY     getElementsTree (tmp.ID) Tree


text:
Q: Passing data from view to net-mvc controller using AngularJS  public class Home
{
    string CustEmail { get;set;}
    string CustName { get; set;}

    int id { get; set;}
}

Model
[HttpPost]
    public void CreateCustomer(Home cust)
    {
        if (ModelState.IsValid)
        {

        }

    }

Controller
angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
    debugger;
    $scope.cust = {};
    $scope.message = '';
    $scope.result = "color-default";
    $scope.isViewLoading = false;

    //get called when user submits the form
    $scope.submitForm = function () {
        $scope.isViewLoading = true;
        console.log('Form is submitted with:', $scope.cust);
        //$http service that send or receive data from the remote server

        var cust = {
            CustEmail: $scope.cust.CustEmail,
            CustName: $scope.cust.CustName,
            id: 1,
        };

        $http(
        {
            method: 'POST',
            url: '/Home/CreateCustomer',
            data: cust,
        }).then(function (data, status, headers, config) {
            $scope.errors = [];
            if (data.success === true) {
                $scope.cust = {};
                $scope.message = 'Form data Submitted!';
                $scope.result = "color-green";
                $location.path(data.redirectUrl);
                $window.location.reload();
            }
            else {
                $scope.errors = data.errors;
            }
        })
        $scope.isViewLoading = false;
    }
}).config(function ($locationProvider) {
  //default = 'false'
  $locationProvider.html5Mode(true);
});

I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.

A: The .then method of a promise only exposes one value, not four values.
$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
})

For more information, see

*

*AngularJS $http Service API Reference - returns

UPDATE
You can add a .catch block to console log any errors:
$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
    console.log("OK:", response.data);
}).catch(function(response) {
    console.log("ERROR:", response);
});


text:
Q: Getting "mismatched input '>' expecting {, IDENTIFICATION, REPLACE}" when trying to run COBOL code COMPLETE NOOB here just trying to learn some COBOL. I'm following a YT video and the code I have written verbatim just won't run because of this error. Do I need to install another extension?
       >>SOURCE FORMAT FREE

IDENTIFICATION DIVISION.
PROGRAM-ID. coboltut.
AUTHOR. John Doe.
DATE-WRITTEN. November 24th 2021
ENVIRONMENT DIVISION.

DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 UserName PIC X(30) VALUE "You".
01 Num1    PIC 9 VALUE ZEROS.
01 Num2    PIC 9 VALUE ZEROS.
01 Total PIC 99 VALUE 0.
01 SSNum.
       02 SSArea   PIC 999
       03 SSGroup  PIC 99
       03 SSSerial PIC 9999

PROCEDURE DIVISION.
DISPLAY "WHAT IS YOUR NAME " WITH NO ADVANCING
ACCEPT UserName
DISPLAY "Hello " USERNAME

STOP RUN.

A: Try this:
$ cat coboltut.cbl
IDENTIFICATION DIVISION.
PROGRAM-ID. coboltut.
AUTHOR. John Doe.
DATE-WRITTEN. November 24th 2021

ENVIRONMENT DIVISION.

DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 UserName PIC X(30) VALUE "You".
01 Num1    PIC 9 VALUE ZEROS.
01 Num2    PIC 9 VALUE ZEROS.
01 Total   PIC 99 VALUE ZEROS.
01 SSNum.
       03 SSArea   PIC 999.
       03 SSGroup  PIC 99.
       03 SSSerial PIC 9999.

PROCEDURE DIVISION.
DISPLAY "WHAT IS YOUR NAME " WITH NO ADVANCING
ACCEPT UserName
DISPLAY "Hello " USERNAME
STOP RUN.

Execution:
$ cobc -F -x coboltut.cbl
$ ./coboltut
WHAT IS YOUR NAME Halley
Hello Halley


text:
Q: Stata Using Putexcel with bysort() command I have a large set of categorical data that I need moved to Excel. I also need to sort the data by specific criteria - whether a state has adopted a certain policy - which I'll call var1. For each var2, var3, ... , var n, I want to write something similar to
bysort var1: tab var2 [aw = weight]

Because the data are categorical, I'm not interested in mean, sd, etc., only the number and proportion of responses for each category. But when I write
putexcel A1 = bysort var1: tab var2 [aw = weight]

the console tells me "weights not allowed." If I add parentheses and write
putexcel A1 = (bysort var1: tab var2 [aw = weight])

the console says "bysort not found."
Any idea what's going on here?


text:
Q: Accessing to files included in the app bundle The following code works fine before iOS 8.
Now I am compiling for iOS 8 beta 5 I can not access to those files.
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
sprintf(appPath, "%s/%s/extfiles", [NSHomeDirectory() UTF8String],
[[[NSFileManager defaultManager] displayNameAtPath:bundlePath] UTF8String]);

The result of app Path should be like:
appPath char *  "/var/mobile/Containers/Data/Application/97726814-AA76-41AB-A9A7-296AAEF4F898/MyApplication.app/extfiles"   0x0054f44c

My application uses the files included in that folder to start so the result is that my app crashes upon reading the files.

A: That code isn't right and should not work on any version of iOS as it makes no sense to concatenate the app bundle root and the Home Directory.  If it works then I assume that's just luck.
What you want is:
NSBundle *bundle = [NSBundle mainBundle];
NSURL *extFilesURL = [[bundle resourceURL] URLByAppendingPathComponent:@"extfiles"];

A: You can simply try this
NSString *str=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"extfiles"];

Hope it helps.


text:
Q: How to get username from authentication prompt popup I have SharePoint Online classic page which has some custom JavaScript and jQuery scripts implemented and third party .NET app requiring some basic auth. When the user visits the page he is prompted to enter username and password. How can I get the username from this prompt? Prompt is standard and looks like this (picture is not mine)

A: You can use SharePoint's javascript API to retrieve the current user's information.
_spPageContextInfo.userId

see: https://social.technet.microsoft.com/wiki/contents/articles/29766.sharepoint-understanding-the-sppagecontextinfo-object.aspx
Another suggestion is to use the API:

Currently Logged User:

MS reference: https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-client-library-code

A: If someone is still interested in this I found a way to get the user principal name with microsoft graph API  https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
https://graph.microsoft.com/v1.0/me?$select=mailnickname,onpremisesUserprincipalName was the actual request I needed


text:
Q: In VB .NET 2015, when autofocusing on the Datetimepicker and changing the time, it changes the hours I have a datetimepicker with custom formatting. When I don't click the minute value, but just change the time with the up & down buttons, it always starts changing the hour value instead of the minute value.
Automatically changing the minute value would be much better, at least with the program I'm working on.
How can I change this default setting?
A short gif explaining the problem

A: Hans Passant's answer about using the SendKeys.Send-command in the Enter-event technically works, but then the caret switches between the hour and minute values every time the DateTimePicker is entered/left.
But I figured out a solution:
This is assuming that the DateTimePicker's Format is set to Custom.
When the DateTimePicker's DateTimePickerFormat is changed to DateTimePickerFormat.Time and right back to DateTimePickerFormat.Custom, the caret resets to the hour, so after switching the DateTimePickerFormat back and forth once, we can use the SendKeys.Send("{RIGHT}") without worrying about it switching back to the hour value.
Now this most certainly is a hack, so you'll need to include some code for special situations, but here's the code in its simplicity:
Private Sub DateTimePicker1_Enter(sender As Object, e As EventArgs) Handles DateTimePicker1.Enter
    DateTimePicker1.Format = DateTimePickerFormat.Time
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    SendKeys.Send("{RIGHT}")
End Sub


text:
Q: Python type hints: type hint a function in the middle of another function Calling a function(func2) within func1, the return of func2 will go into variable.  Is this a correct way to type hint func2 that is within func1?  I should type hint the func2 call within func1?
def func1():
   variable: Callable[[str, str], object] = func2(arg1, arg2)

def func2(arg1: str, arg2: str) -> object:

A: No, you're not assigning a function to variable, so it shouldn't be declared with a Callable type. You're assigning the result, which is object.
variable: object = func2(arg1, arg2)

You should use Callable if you're assigning the function itself, not calling it
variable: Callable[[str, str], object] = func2

Of course, in either of these cases, any type checker worth its salt is more than capable of inferring the types, so unless your function is unusually long and complicated, adding type annotations to local variables generally just adds noise without adding anything of value. And if your function is long enough to warrant it, you may consider refactoring before spamming annotations.
Personally, the only time I'll annotate a local variable is if its type is the result of a complicated generic function.
def complicated_thing(x: T, y: list[T]) -> dict[str, MyClass[T]]:
  ...

variable: dict[str, MyClass[int]] = complicated(foobar, [])

In this case, it may not be obvious, at a glance, what T is, so the annotation potentially adds something of value.