text:
Q: Best strategy to script a web journey in jmeter with too many json submits in requests I am in process of developing a Jmeter script for a web journey which has close to 30 transactions, I observe that there are like 20 requests(API calls) which are submitting heavy Json load(with lots of fields) and this Json structure varies significantly with key data( Account number), it doesn't look like corelating 100s of fields of each of these json requests is an efficient way of scripting. I did give a try to submit predefined Json files in the requests, but that way I would need at least 10 Json( 1 json per request) for each Account number and considering I am looking to test like 200 Account numbers, this also doesn't look like a reasonable approach. Can someone please suggest pointers to approach this ? Should I test APIs independently ?

A: There is only one strategy: your load test must represent real life application usage with 100% accuracy so I would go for separate APIs testing in 2 cases:

*

*As the last resort if for some reason realistic workload is not possible

*When one particular API is known to be a bottleneck and you need to repeat the test focusing on one endpoint only

With regards to correlation there are some semi and fully automated correlation solutions like:

*

*Correlations Recorder Plugin for JMeter where you can specify the correlation rules prior to recording and all matching values will be automatically replaced with the respective extractors/variables

*BlazeMeter Proxy Recorder which is capable of exporting recorded scripts in "SmartJMX" mode with automatic detection and correlation of dynamic elements

*If the next request can be "constructed" from the previous response but with some transformation of the JSON structure you can amend the response and convert it to the required form using JSR223 Test Elements - see Apache Groovy - Parsing and Producing JSON article for more information


text:
Q: How do I set `skip` (offset) for reactivemongo mongodb driver? I need to skip a number of documents (offset) from a query, and only return limit number of documents that go after. I know the following naive approach:
collection.find(BSONDocument())
  .cursor[T].collect[List](offset+limit).map(_.drop(offset))

but it is not really desired because it will load offset+limit number of documents in JVM memory, whereas I'd like to filter them on the "database" side.

A: Solution: use QueryOpts. Example:
collection.find(BSONDocument())
  .options(QueryOpts(skipN = offset))
  .cursor[T].collect[List](limit)

Note that using skip is not very efficient because mongodb does not support effective pagination, it will just skip the desired number by iterating through all the documents.

A: VasyaNovikov answer is certainly correct. Reactive mongo offers a more intuitive API:
collection.find(BSONDocument())
  .skip(offset)
  .cursor[T]
  .collect[List](limit, Cursor.FailOnError[List[T]]())

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get near by places with in radius of 5 kilometer from current location? What i have done so far is that i m successfully  getting the near by places like Atm Banks Restaurant from the whole twin cities
But i just want to show the nearby places that is with in 5 kilometer to the current user location i have searched a lot but could not find any answer to my question
"This is my code where i m getting the places by names "
myLocation = new MyLocation(context);

    if (myLocation.isLocationAvailable() && myLocation.getUserLocation() != null)
    {
        current_location_lat =  myLocation.getUserLocation().latitude;

        current_location_lng =  myLocation.getUserLocation().longitude;

        latStr = current_location_lat + "";

        longStr = current_location_lng + "";

        myLatLng = new LatLng(current_location_lat, current_location_lng);

        //url = url_part1 + latStr + "," + longStr + url_part2;

        Log.d("LATITUDE", String.valueOf(current_location_lat));

        Log.d("LONGITUDE", String.valueOf(current_location_lng));

        new PlaceTask(context, positionOfType, latStr, longStr, new onTaskDoneListener()
        {
            @Override
            public void onTaskDone(JSONObject jsonObject)
            {
                if(jsonObject!=null)
                {
                    try
                    {
                        JSONObject obj = jsonObject;//new JSONObject(jsonObject);

                        String status = obj.getString("status");

                        if(status.equals("OK"))
                        {
                            JSONArray arr = obj.getJSONArray("results");

                            for(int i = 0; i < arr.length(); i++)
                            {
                                double lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");

                                double lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

                                String place_name = arr.getJSONObject(i).getString("name");

                                String vicinity = arr.getJSONObject(i).getString("vicinity");

                                HashMap<String, String> map = new HashMap<String,String>();

                                map.put("placeName", place_name);

                                map.put("vicinity", vicinity);

                                map.put("lat", String.valueOf(lat));

                                map.put("lng", String.valueOf(lng));

                                list.add(map);
                                Global_Var.latvalue.add(i,String.valueOf(lat));
                                Global_Var.longtvalue.add(i,String.valueOf(lng));
                            }

                            NearByPlaceAdapter adapter = new NearByPlaceAdapter(context, list);

                            listView.setAdapter(adapter);
                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    Toast.makeText(context, "Response is Null", Toast.LENGTH_LONG).show();
                }

            }
        }).execute();

        //showSearchDialog(map);
    }
    else
    {
        Toast.makeText(context, "Please Enable Location Services and GPS From your Device",
                Toast.LENGTH_LONG).show();
    }

MyLocation
public MyLocation(Context context) {
    this.context = context;

    try {
        manager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            islocavailable = true;
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
                    1, this);
            Log.d("gps enabled", "gps enabled");
            String locationProvider = LocationManager.GPS_PROVIDER;

            Location lastKnownLocation = manager
                    .getLastKnownLocation(locationProvider);
            userLocation = new LatLng(lastKnownLocation.getLatitude(),
                    lastKnownLocation.getLongitude());
            Log.d("gps disabled 1", lastKnownLocation.getLatitude() + ","
                    + lastKnownLocation.getLongitude());
            // map.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,
            // 15));
            // islocavailable=true;
        } else if (manager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            islocavailable = true;
            manager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 1000, 1, this);
            String locationProvider = LocationManager.NETWORK_PROVIDER;

            Location lastKnownLocation = manager
                    .getLastKnownLocation(locationProvider);
            userLocation = new LatLng(lastKnownLocation.getLatitude(),
                    lastKnownLocation.getLongitude());
            // map.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,
            // 15));
            Log.d("gps disabled 2", lastKnownLocation.getLatitude() + ","
                    + lastKnownLocation.getLongitude());
            // islocavailable=true;
        } else {
            Log.d("all disabled", "all disabled");

            islocavailable = false;
            // showAlertDialog();
        }
    } catch (NullPointerException ex) {
                ex.printStackTrace();
    }

}


text:
Q: Getting weird results when attaching the same respone to multiple listeners I'm attaching a single submit() to a button and the enter key. On a fresh page they both attach and respond normally running submit() a single time. The issue arises only after the click event has run, then the keypress event starts running submit() two times thereafter instead of once, while the click continues to respond normally.
I feel like I've done this before and solved it (or just missed) after implementing a getSubmit() with some if()'s or returning something but I feel like this should work.
var bindCtrlr = (function() {

    var submit = () => console.log('hi')

    document.querySelector('.add__btn').addEventListener('click', submit, false)

    document.addEventListener('keypress', function(e) {
        if (e.keyCode === 13 || e.which === 13) {
            submit()
        }
    }, false)

})()

The submit() should always run a single time when .add__btn is clicked or the enter key is pressed.

A: The reason why it is firing twice is because the button click event triggers also on enter. But it only triggers twice if the focus is still on the button after you click it. When the focus is not on the button it only fires once. Hope this will help you.


text:
Q: Gitignore: trailing character is any inter In a git repository mainly for LaTeX, I'm writing my .gitignore.
I would ignore all .mtc, .mtc1, .mtc2, .mtc3 ... files (with no upper value but it's not the problem). There are others like .stc, .stc1 ...;  .slf, .slf1 ...
To match them I write
*.mtc[0-9]*

This doesn't match the "root" .mtc file (with no number after).
I prefer to avoid *.mtc*wich could have side effect
Is there any other solution than writing it on two lines?
*.mtc[0-9]*
*.mtc

A: From gitignore man page, section "pattern format":

Otherwise, Git treats the pattern as a shell glob:

*

*"*" matches anything except "/",

*"?" matches any one character except "/" and

*"[]" matches one character in a selected range.

  See fnmatch(3) and the FNM_PATHNAME flag for a more detailed description.

Based on that pattern specification, you already have the most precise one:
*.mtc[0-9]*
*.mtc


text:
Q: Android Custom View Fade/Delay Animation I have quite easy class that draws circles. I'm giving the parameter, view calculates the rest. All I want to give some delay and fade effect for each during draw to canvas. I reviewed a few articles about animators and handlers but I couldn't figure out. Please, show me some implementations. Thanks.
    @Override
protected void onDraw(final Canvas canvas) {
    super.onDraw(canvas);
    int w = getWidth();
    int pl = getPaddingLeft();
    int pr = getPaddingRight();
    int totalWidth = w - (pl + pr);
    major = totalWidth / circleCount;
    radius = major / 2;
    startPoint = totalWidth / (circleCount * 2);
    for (int i = 0; i < circleCount; i++) {
        canvas.drawCircle(startPoint + major * i, radius, radius, paint);
    }
}

A: Here's a simple alpha animation of a button view [it makes the button blink](it's not so hard ;O) ):
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;

final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
animation.setDuration(500); // duration - half a second
animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
animation.setRepeatCount(Animation.INFINITE);        // Repeat animation infinitely
animation.setRepeatMode(Animation.REVERSE);          // Reverse animation at the end so the button will fade back in

final Button btn = (Button) findViewById(R.id.but4);//replace this with your view
btn.startAnimation(animation);

A: You could use the setAlpha(int a) method from the Paint class.
It should work when you do it on a separate Thread with a little time delay in a loop where you count down from 255 to 0.
Here is a code sample where I tried this for earlier versions of Android some years ago :
private final int FADE_TIME = 10;  // modify to your needs

private void fade() {

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                int i = 255;

                while (i >= 0) {

                    paint.setAlpha(i);
                    Thread.sleep(FADE_TIME);
                    i--;
                }

            } catch (InterruptedException e) {
                // do something in case of interruption
            }
        }
    }).start();

}

Nowadays I would probably use a Handler with postDelayed() for this job, but this should give you an impression of how it can be done.


text:
Q: Using md-primary on div I would like to use the primary style which has been defined with  $mdThemingProvider.definePalette on a div, like this:
<div class="md-primary">

However this does not work (no styling is applied).
Are there any way I can use the styles (colors) definied as "md-primary" on any element (a div in this case) without duplicating the style to a css?

A: It is because the primary is not exactly a color, but a pallete, if is a button there is pre loaded values for it <md-button class="md-raised md-primary">My Button</md-button>, but in a div you need to specify like: md-colors="::{background: 'palletename-primary-800'}" and in the app config define the pallet
$mdThemingProvider.theme('palletname')
     .primaryPalette('blue-grey')
     .accentPalette('lime')
     .warnPalette('red');
$mdThemingProvider.setDefaultTheme('palletname');


text:
Q: How to make nativescript orientation qualifiers work with Angular2? NativeScript supports very convenient orientation qualifiers.
Unfortunately, I'm unable to get this work in NativeScript with Angular.
My layout.land.html or layout.land.css is not loaded.
Even if I will create both layout.port.html and layout.land.html and delete land.html -> app complains that layout.html can not be found.
I suppose it is not supported for Angular apps. If this is the case, are there any workoarounds to load different layout based on orientation or other qualifiers?
I'm aware about this plugin but I would preffer above solution bevause it is built in and allows for complete different layouts.

A: Screen qualifiers are not currently supported for Angular-2 application.
Also, you can't change templateUrls in Angular-2 at this very moment as noted here.
You can track this issue where the screen qualifiers usage for NativeScript + Angular-2 is logged as a desired feature.


text:
Q: 1 input field not working correctly all others work fine - Laravel 5 I have a very weird bug where 1 input field always returns an empty value even though it is filled with a value.
My form:
<form method="post" action="{{url('webclix-admin/gebruikers/opslaan')}}">
    {{ csrf_field() }}
    <fieldset class="form-horizontal">

Gebruiker Toevoegen

            @if(count($errors))

              @foreach($errors->all() as $error)

{{ $error}}

              @endforeach

            @endif

Gebruikersnaam *

<input type="text" value="{{old('name')}}" name="name" class="form-control">

Email *

<input type="text" value="{{old('email')}}" name="email" class="form-control">

Wachtwoord *

<input type="password" class="form-control" name="password">

Bevestig wachtwoord *

<input type="password" class="form-control" name="password_confirmation">

Telefoonnummer *

<input type="text" value="{{old('phone')}}" name="phone" class="form-control">

Voornaam *

<input type="text" value="{{old('first_name')}}" name="first_name" class="form-control">

Familienaam *

<input type="text" value="{{old('surname')}}" name="surname" class="form-control">

Geboortedatum

                      <input id="date_added" type="text" name="date_of_birth" class="form-control" value="{{old('date_of_birth')}}">

Straat *

                        <input type="text" value="{{old('street')}}" name="street" class="form-control">

                          Huisnummer + postbus *

<input type="text" value="{{old('house_number')}}" name="house_number" class="form-control">

Postcode *

                        <input type="text" value="{{old('zipcode')}}" name="zipcode" class="form-control">

                          Stad *

                            <input type="text" value="{{old('city')}}" name="city" class="form-control">

                          Land *

                            <select class="form-control m-b" name="country">
                              @foreach($countries as $country)
                                  <option value="{{$country->id}}">{{$country->name}}</option>
                              @endforeach
                            </select>

Facturatiegegevens

 <input type="radio" checked="" value="same" id="billing1" name="billing" {{ old('billing')=="same" ? 'checked='.'"'.'checked'.'"' : '' }}> Gebruik dit adres zowel voor facturatie als voor levering

 <input type="radio" value="different" id="billing2" name="billing" {{ old('billing')=="different" ? 'checked='.'"'.'checked'.'"' : '' }}> Factureer op een ander adres

BTW-nummer

<input type="text" value="{{old('btw_number')}}" name="first_name" class="form-control">

Straat *

                        <input type="text" value="{{old('d_street')}}" name="d_street" class="form-control">

                          Huisnummer + postbus *

<input type="text" value="{{old('d_house_number')}}" name="d_house_number" class="form-control">

Postcode *

                        <input type="text" value="{{old('d_zipcode')}}" name="d_zipcode" class="form-control">

                          Stad *

                            <input type="text" value="{{old('d_city')}}" name="d_city" class="form-control">

                          Land *

                            <select class="form-control m-b" name="d_country">
                              @foreach($countries as $country)
                                  <option value="{{$country->id}}">{{$country->name}}</option>
                              @endforeach
                            </select>

                  <button type="submit" class="btn btn-primary">Voeg Gebruiker toe</button>

        Velden met een * zijn verplicht

Rollen toewijzen

Rollen

             <input type="checkbox" checked disabled>Klant
          @foreach($roles as $role)
             <input type="checkbox" name="role[]" value="{{$role->id}}" id="Checkbox1"> {{$role->display_name}}
          @endforeach

Gebruikers kunnen meerdere rollen hebben. Elke gebruiker heeft standaard de rol van Klant

</fieldset>
</form>

When i click submit and i dd() the values i get this:
  #attributes: array:7 [▼
    "email" => "testing@test.com"
    "name" => "Christina testname"
    "password" => "$2y$10$njMYm6uJMxoI4e9n/157vOLPLBBkViUE6uI3I3K8apdkhLnExQs7."
    "first_name" => ""
    "surname" => "Furler"
    "date_of_birth" => "2009-01-14"
    "phone" => "123456798"
  ]

Question
Only the field first_name always returns an empty string . All other input fields work fine. The empty value gets stored in the database , so the controller part is working as intended.
Extra Code (UserController where i handle the requests)
public function store(CreateUserRequest $userRequest, CreateAddressRequest $addressRequest)
    {

      $user = new User([
        'email'         => $userRequest->email,
        'name'          => $userRequest->name,
        'password'      => bcrypt($userRequest->password),
        'first_name'    => $userRequest->first_name,
        'surname'       => $userRequest->surname,
        'date_of_birth' => $userRequest->date_of_birth,
        'phone'         => $userRequest->phone
      ]);
      $user->save();

A: You have two text input field with the same name check it out. Might be the cause

<input type="text" value="{{old('first_name')}}" name="first_name" class="form-control">

<input type="text" value="{{old('btw_number')}}" name="first_name" class="form-control">


text:
Q: Isomorphism map between $\frac{\mathbb{Z}_3[x]}{(x^2+x+2)}$ and $ \frac{\mathbb{Z}_3[x]}{(x^2 + 1)} $ $\frac{\mathbb{F}_3[x]}{(x^2+x+2)} \cong \frac{\mathbb{F}_3[x]}{(x^2 + 1)} $
I know $\frac{\mathbb{F}_3[x]}{(x^2+x+2)} $ and $ \frac{\mathbb{F}_3[x]}{(x^2 + 1)} $ is isomorphic because they are both 2-degree extension of $ \mathbb{F}_3 $ .
But I cannot contract explicit isomorphism between them.

Could you show me isomorphism map between $\frac{\mathbb{F}_3[x]}{(x^2+x+2)}$  and $ \frac{\mathbb{F}_3[x]}{(x^2 + 1)} $?

Thank you for your help.

A: Try $\phi:\mathbb{F}_3[X]\to\mathbb{F}_3[X]$ defined by $\phi:X\mapsto X+1$ whilst leaving everything in $\mathbb{F}_3$ alone.
This sends $X^2+X+2$ to $X^2+1$, so it sends the ideal $(X^2+X+2)$ to the ideal $(X^2+1)$, so when you quotient out $\mathbb{F}_3[X]$ by $(X^2+X+2)$ or by $(X^2+1)$, you get isomorphic fields.


text:
Q: How to create datalab with a compute engine with a GPU?
*

*I can create datalab with specific CE instance type, but then can't add GPU to that instance.

*I can create CE instance with GPU, but then don't know how to run datalab on it.
Please, help.

A: Edit:
Rose's answer above is correct.  There now exists a 'datalab beta create-gpu' command.
Original Answer (out of date):
Datalab doesn't currently support using GPUs.  This is an datalab github issue #1275.
The VM that Datalab is running on doesn't have the NVidia drivers installed (unless you install them yourself), and the Datalab Docker image itself doesn't have the CUDA or GPU support installed due to the NVidia license required.
The datalab create tool just uses "gcloud compute instances create" calls to make the VMs, and you could theoretically copy those commands and convert them to "gcloud beta compute instances create" with "--accelerator" options, but you'd still have to create your own version of the Datalab docker image to run on it with the NVidia drivers installed (which requires accepting the NVidia license agreement).  And that may also require running it using nvidia_docker instead of normal docker.
See also: https://stackoverflow.com/a/42703626/5441818

A: Datalab supports GPUs now. See the docs on datalab beta create-gpu here:
https://cloud.google.com/datalab/docs/quickstart#create_and_connect_to_a_cloud_datalab_instance


text:
Q: Can't install haskell package http-enumerator Got the following bash transcript when run cabal install.
It looks it complainted many packages required by http-enumerator is not available. I am not sure what "Backjump" mean in the last line of the printout.
How do I resolve the package dependencies?
$ cabal install http-enumerator
Resolving dependencies...
cabal: Could not resolve dependencies:
trying: http-enumerator-0.7.3.3 (user goal)
next goal: asn1-data (dependency of http-enumerator-0.7.3.3)
rejecting: asn1-data-0.7.1, 0.7.0 (conflict: http-enumerator =>
asn1-data>=0.5.1 && <0.7)
trying: asn1-data-0.6.1.3
next goal: text (dependency of asn1-data-0.6.1.3)
rejecting: text-1.2.0.0/installed-18f... (conflict: text =>
bytestring==0.10.4.0/installed-6da..., http-enumerator => bytestring>=0.9.1.4
&& <0.10)
trying: text-1.2.0.4
next goal: certificate (dependency of http-enumerator-0.7.3.3)
rejecting: certificate-1.3.9, 1.3.8, 1.3.7, 1.3.6, 1.3.5, 1.3.3, 1.3.2, 1.3.1,
1.3.0, 1.2.9, 1.2.8, 1.2.7, 1.2.6, 1.2.5, 1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0
(conflict: http-enumerator => certificate>=1.1 && <1.2)
trying: certificate-1.1.1
next goal: tls-extra (dependency of http-enumerator-0.7.3.3)
rejecting: tls-extra-0.6.6, 0.6.5, 0.6.4, 0.6.3, 0.6.1, 0.6.0, 0.5.1, 0.5.0
(conflict: http-enumerator => tls-extra>=0.4.3 && <0.5)
rejecting: tls-extra-0.4.7.1, 0.4.7, 0.4.6.1, 0.4.6, 0.4.5 (conflict:
certificate==1.1.1, tls-extra => certificate>=1.2.0 && <1.3.0)
rejecting: tls-extra-0.4.4, 0.4.3 (conflict: text==1.2.0.4, tls-extra =>
text>=0.5 && <1.0)
rejecting: tls-extra-0.4.2.1, 0.4.2, 0.4.1, 0.4.0, 0.3.1, 0.3.0, 0.2.3, 0.2.2,
0.2.1, 0.2.0, 0.1.9, 0.1.8, 0.1.7, 0.1.6, 0.1.5, 0.1.4, 0.1.3, 0.1.2, 0.1.1,
0.1.0 (conflict: http-enumerator => tls-extra>=0.4.3 && <0.5)
Backjump limit reached (change with --max-backjumps).

Thanks!

A: In general, this sort of problem happens because you're trying to install package A, which depends (directly or indirectly) on package B. However, you already have package C installed, which also depends on package B, but the version of B that C was linked with won't work with A.
In some cases you might be able to resolve this sort of problem using:
cabal install --max-backjumps=-1 --reorder-goals <pkg-name>

...but that only works sometimes. A cleaner way to address this sort of thing is to use sandboxes. This will help if you don't need both A and C in the same sandbox, or you can re-link C with a different version of B. You can do what you want in the sandbox without messing up your main Haskell installation.
If you've written A or C yourself, you may need to examine the dependencies of your packages and make adjustments. I'm going translate part of that output into English, to give you an example of how to diagnose dependency problems.
$ cabal install http-enumerator
Resolving dependencies...
cabal: Could not resolve dependencies:
trying: http-enumerator-0.7.3.3 (user goal)

You requested http-enumerator. The latest version is 0.7.3.3, so I'll try to install that.
next goal: asn1-data (dependency of http-enumerator-0.7.3.3)

Now, http-enumerator-0.7.3.3 requires the package asn1-data, so let me try to install that.
rejecting: asn1-data-0.7.1, 0.7.0 (conflict: http-enumerator =>
asn1-data>=0.5.1 && <0.7)

The latest two versions of asn1-data are 0.7.1 and 0.7.0. But http-enumerator-0.7.3.3 requires an earlier version of asn1-data. So let me try an older version of asn1-data
trying: asn1-data-0.6.1.3

The next available version of asn1-data is 0.6.1.3.
next goal: text (dependency of asn1-data-0.6.1.3)

But that version of asn1-data requires text, so I need to install that first.
rejecting: text-1.2.0.0/installed-18f... (conflict: text =>
bytestring==0.10.4.0/installed-6da..., http-enumerator => bytestring>=0.9.1.4
&& <0.10)

The latest version of text is 1.2.0.0, but that won't work because it needs a different version of bytestring than http-enumerator wants. So let me try an older version of text.
trying: text-1.2.0.4
next goal: certificate (dependency of http-enumerator-0.7.3.3)

Now, that version of text requires certificate, so I need to install that first.
rejecting: certificate-1.3.9, 1.3.8, 1.3.7, 1.3.6, 1.3.5, 1.3.3, 1.3.2, 1.3.1,
1.3.0, 1.2.9, 1.2.8, 1.2.7, 1.2.6, 1.2.5, 1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0
(conflict: http-enumerator => certificate>=1.1 && <1.2)

But all these versions of certificate are incompatible with http-enumerator.
trying: certificate-1.1.1

Finally a bit of success. I can use certificate-1.1.1, and satisfy all of the dependencies of asn1-data text.
next goal: tls-extra (dependency of http-enumerator-0.7.3.3)

But http-enumerator-0.7.3.3 also requires tls-extra.
rejecting: tls-extra-0.6.6, 0.6.5, 0.6.4, 0.6.3, 0.6.1, 0.6.0, 0.5.1, 0.5.0
(conflict: http-enumerator => tls-extra>=0.4.3 && <0.5)

We can't use the latest versions of tls-extra because they are incompatible with http-enumerator.
rejecting: tls-extra-0.4.7.1, 0.4.7, 0.4.6.1, 0.4.6, 0.4.5 (conflict:
certificate==1.1.1, tls-extra => certificate>=1.2.0 && <1.3.0)

We can't use these versions of tls-extra because they are incompatible with certificate.
rejecting: tls-extra-0.4.4, 0.4.3 (conflict: text==1.2.0.4, tls-extra =>
text>=0.5 && <1.0)

We can't use these versions of tls-extra because they are incompatible with text.
rejecting: tls-extra-0.4.2.1, 0.4.2, 0.4.1, 0.4.0, 0.3.1, 0.3.0, 0.2.3, 0.2.2,
0.2.1, 0.2.0, 0.1.9, 0.1.8, 0.1.7, 0.1.6, 0.1.5, 0.1.4, 0.1.3, 0.1.2, 0.1.1,
0.1.0 (conflict: http-enumerator => tls-extra>=0.4.3 && <0.5)

And older versions of tls-extra aren't compatible with http-enumerator.
Backjump limit reached (change with --max-backjumps).

I give up!


text:
Q: bootstrap 4 - placing one table under another and centering I want to have my tables centered horizontally and I expect them to be displayed one under another. Using some bootstrap 4 classes I've managed to have the tables displayed very unevenly or to have one missing. That is why I am looking for help, and I'm delivering the code, where the two tables exists in one row.

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Lidzbark Warmiński
            08:00
            12:00
            15:00
            19:00

            Kraszewo
            08:20
            12:20
            15:20
            19:20

            Dobre Miasto
            08:30
            12:30
            15:30
            19:30

            Olsztyn PKP
            09:00
            13:00
            16:00
            20:00

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Olsztyn PKP
            09:00
            13:00
            17:00
            21:00

            Dobre Miasto
            09:30
            13:30
            17:30
            21:30

            Kraszewo
            09:50
            13:50
            17:50
            21:50

            Lidzbark Warmiński
            10:00
            14:00
            18:00
            22:00

A: You just need set flex direction to column instead rows (that is by default), and then align items. In bootstrap it will be simply flex-column and align-items-center.
Docs: https://getbootstrap.com/docs/4.4/utilities/flex/
Also this div
 is not needed. Just set text-center on table.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Lidzbark Warmiński
            08:00
            12:00
            15:00
            19:00

            Kraszewo
            08:20
            12:20
            15:20
            19:20

            Dobre Miasto
            08:30
            12:30
            15:30
            19:30

            Olsztyn PKP
            09:00
            13:00
            16:00
            20:00

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Olsztyn PKP
            09:00
            13:00
            17:00
            21:00

            Dobre Miasto
            09:30
            13:30
            17:30
            21:30

            Kraszewo
            09:50
            13:50
            17:50
            21:50

            Lidzbark Warmiński
            10:00
            14:00
            18:00
            22:00

A: Why don't you change your layout a little bit? You can put each table inside a column col-12 and second table will be positioned below the first one. This is how bootstrap layout works and you don't need extra classes to center tables. Even more - you can adjust table width by changing columns for example to col-md-8. You can use offset classes offset-* to center them horizontaly.
Here you have Bootstrap DOCS: https://getbootstrap.com/docs/4.5/getting-started/introduction/

/*DEMO*/body{padding:3rem}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">

Przystanek	(A)	(A)	(A)	(A)

Lidzbark Warmiński	 08:00	12:00	15:00	19:00

Kraszewo	08:20	12:20	15:20	19:20

Dobre Miasto	08:30	12:30	15:30	19:30

Olsztyn PKP	09:00	13:00	16:00	20:00

Przystanek	(A)	(A)	(A)	(A)

Olsztyn PKP	09:00	13:00	17:00	21:00

Dobre Miasto	09:30	13:30	17:30	21:30

Kraszewo	09:50	13:50	17:50	21:50

Lidzbark Warmiński	10:00	14:00	18:00	22:00


text:
Q: How to join blank tables Table1
Names   assigned
Xyz.        123
Wxy.        456

Table 2
Names. Unassigned
Xyz.        789
Tty.        123

Table 3
Names.    Closed
Wxy.        456
Twr.        123

Table 4
Names.  Open

This table doesn't contain any values
I want output like
Names   assigned      unassigd      closed     open
Xyz.       123.          789.          0.        0
Wxy.       0             457.          0.        0
Tty.       0             123.          0.        0
Twr.       0             0             123.      0

How to join them?

A: try
SELECT
    n.NAMES,
    ISNULL(t1.Assigned, 0) Assigned,
    ISNULL(t1.Unassigned, 0) Unassigned,
    ISNULL(t1.Closed, 0) Closed,
    ISNULL(t1.Open, 0) Open
FROM
    (           SELECT NAMES FROM Table1
        UNION   SELECT NAMES FROM Table2
        UNION   SELECT NAMES FROM Table3
        UNION   SELECT NAMES FROM Table4
    ) AS n
    LEFT JOIN (SELECT NAMES, SUM(Assigned) FROM Table1 GROUP BY NAMES) t1 ON n.NAMES = t1.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Unassigned) FROM Table2 GROUP BY NAMES) t2 ON n.NAMES = t2.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Closed) FROM Table3 GROUP BY NAMES) t3 ON n.NAMES = t3.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Open) FROM Table4 GROUP BY NAMES) t4 ON n.NAMES = t4.NAMES


text:
Q: How to present contents in a book chapter and sections in a highly normalized repository What is wrong with the below function, and how can I fix it.
  list() {
    return this.bookRepo.all().then(books =>
      Promise.all(books.map(book =>
        Promise.all([
          this.bookRepo.contents(book.id),
          this.bookRepo.chapters(book.id)
        ]).then(([contents, chapters]) =>
          Promise.all(chapters.map(chapter =>
            Promise.all([
              this.bookRepo.contents(chapter.id),
              this.bookRepo.sections(chapter.id)
            ]).then(([contents, sections]) =>
              Promise.all(sections.map(section =>
                this.bookRepo.contents(section.id).then(contents => [
                  section, contents
                ])))
                .then(sections => [chapter, contents, sections]))))
            .then(chapters => [book, contents, chapters])))));
  }

Problem is the return value of this function. I don't want to maintain it, write types for it, traverse it for rendering etc. It seems cumbersome, how can I abstract this or make it simpler?
This is my schema:
type BookId = string
type ChapterId = string
type SectionId = string
type ContentId = string

export type SourceId =
| ChapterId
| SectionId
| BookId

type Book = {
  id: BookId,
  name: string,
}

type Chapter = {
  id: ChapterId,
  bookId: BookId,
  name: string
}
type Section = {
  id: SectionId,
  chapterId: ChapterId,
  name: string
}

type Content = {
  id: ContentId,
  name: string,
  sourceId: SourceId,
  content: string
}

A: Answer: It's horrible and nobody would ever want to read or modify code written that way unless they like to torture themselves for a living.
The below is marginally more maintainable, principally through avoiding a christmas-tree of promises and giving things different names, although you'd have to get the types to align better with yours, and maybe hoist some of these loops steps into their own functions to finish the job.
type Id = string;

interface Entry {
  id: Id;
}

interface Doc {}

interface BookRepo {
  all: () => Promise<Array<Entry>>;
  sections: (id: Id) => Promise<Array<Entry>>;
  chapters: (id: Id) => Promise<Array<Entry>>;
  contents: (id: Id) => Promise<Doc>;
}

class Lister {
  constructor(readonly bookRepo: BookRepo) {}

  async list() {
    const { all, contents, sections, chapters } = this.bookRepo;
    const allBooks = await all();

    for (const bookRecord of allBooks) {
      const bookContents = await contents(bookRecord.id);
      const chapterRecords = await chapters(bookRecord.id);
      const bookChapters = await Promise.all(
        chapterRecords.map(async (chapterRecord) => {
          const chapterContents = await contents(chapterRecord.id);
          const chapterSectionRecords = await sections(chapterRecord.id);
          const chapterSections = await Promise.all(
            chapterSectionRecords.map(async (sectionRecord) => {
              const sectionContents = await contents(sectionRecord.id);
              return [sectionRecord, sectionContents];
            })
          );
          return [chapterRecord, chapterContents, chapterSections];
        })
      );
      return [bookRecord, bookContents, bookChapters];
    }
  }
}


text:
Q: Acquiring data point coordinates from Geotiff and converting to numpy array I would like to use scipy.interpolate.griddata to interpolate my Sentinel-1 products (see two sample images below) taken from different orbits resulting in having the uniform datapoint coordinates.
I would like to use a similar approach as describe in Smoothing/interpolating raster in Python using GDAL?
However, I am not able to figure it how to get points at which to interpolate data from a geotiff. So far, I have this for values and for basic geographic description:
from osgeo import gdal
# Loading terrain corrected image
master = gdal.Open("S1A_TC.tif")
# Data values of master image
master_array = master.ReadAsArray()
# Getting geographic data (e.g. pixelSizeX)
gt = master.GetGeoTransform()

For getting array of data point coordinates or points at which to interpolate data, I found this topic:
https://stackoverflow.com/questions/43370069/converting-xy-co-ords-of-geotiff-to-numpy-array-positions-in-python
The GDAL link is dead and I am not able to found something useful.
How can I read the data point coordinates as np.array?


text:
Q: Delete row from Realm via SwiftUI occurs exception 'Object has been deleted or invalidated.' I trying to delete row from SwiftUI list which load data from Realm DB, it's implemented like here:
struct MyView: View {
    private let realm = try! Realm()

    var body: some View {
            List {
                ForEach(realm.objects(MyModelDB.self)) { model in
                    MyRow(model: model)
                  }
                }.onDelete { indexSet in
                  try? realm.write {
                    indexSet.forEach { index in
                      realm.delete(words[index])
                    }
                  }
                }
            }
        }
    }
}

but when I perform deleting, I receive an exception:
*** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'
Whats wrong?

A: A couple of options are: delete the objects in reverse order OR delete all of the objects at once.
Here's why. Suppose you have three objects
a  index 0
b  index 1
c  index 2

so the total count is 3 and your indexSet contains indexes 0 1 and 2.
If you were to iterate over that, there would be three loops, however, realm is live updating so if you delete the object at index 0, then only two indexes remain, so when it tries to perform the third loop, it will crash.
Deleting in reverse alleviates that issue as index 2 is deleted first, then index 1 and then index 0.
I would suggest gathering up the objects you want deleted into an array or list and then deleting them all at once without iterating
realm.delete(objects: Sequence>)

where Sequence would be an Array or List.


text:
Q: Proposition Translation
For this, I got (not p and not s)---> not T.
Here is my thinking. The word unless is giving me a hard time so I used an anolgy and made a random sentence.
"Open the door unless you are sick" = " Open the door if you are not sick" = "If you are not sick, then open the door".
My thinking could be totally wrong, so I'm interested in your input. The solutions have not been posted  so i want to know the answer.

A: Unless is usually transalted as $\lor$ ("or").
Thus, your thinking is correct :

"Open the door unless you are sick" must be "Open the door or you are sick", i.e. (due to the equivalence between $p \lor q$ and $\lnot p \to q$) "If you are not sick, then open the door".


text:
Q: What is the best way to make versioned files available for download I have a small PHP framework which I want to make available for download. It is located in a git repository. But the last version is not always the one that I want to make available for download. Is there some place I can make the versions available for download.
Another thing about this framework is that I bring out additional components for the framework. These also have different versions.
Is there somewhere where I can add the whole project, and people can browse trough everything and download what they need.
Or should I make this myself?

A: Use tagging. It is a way to make note of a "snapshot" of your repository at a particular time (or, rather, at a particular commit) in its history.
Also, look at git-archive. The command exports the content of your repository at any particular commit (e.g., using tag!) into an archive (unversioned).

A: Just put it on github.com and use tags to mark particular states and may be usable states of your development.

A: If it is opensource you could try Google Project Hosting or Sourceforge


text:
Q: Oauth Client creation User_controller ERROR Rails 'fitgem' I'm trying to let my user make GET requests to the Fitbit API. Currently the user has all of their tokens, but I'm struggling to create a client.
User_controller.rb
def show
@user = User.find(params[:id])
if (@user.device != nil)
  p "PRINTING DEVICES"
  p @user.device
  @device = @user.device

  @client = Fitgem::Client.new(
    :consumer_key => 'b4aacb5c2c8c43e2a6873877cd2ad9b1',
    :consumer_secret => '88bd78fc86d84d6c9aa7b1c0b8d4511f',
    :token => @device.oauth_token,
    :secret => @device.oauth_token_secret
  )
end
end

The error I am receiving is:
        /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:        16: syntax error, unexpected tASSOC, expecting ')'
    :consumer_key => 'b4b1',
                    ^
    /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:16: syntax error, unexpected ',', expecting keyword_end
    /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:17: syntax error, unexpected ',', expecting keyword_end
    /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:19: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
    :secret => @device.oauth_token_secret
              ^
    /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:21: syntax error, unexpected ')', expecting keyword_end
    /Users/Marcus/Sites/Rails/rails_projects/BattleOfTheBands/app/controllers/users_controller.rb:86: syntax error, unexpected $end, expecting keyword_end


text:
Q: Jboss & EJB3 deploy Error for I am a newer for EJB3 dev.
When I write a EJB3 mdb and I want to deploy it to my jboss (jboss-4.2.3.GA)
some error info is here:

--- MBeans waiting for other MBeans --- ObjectName: jboss.j2ee:jar=HelloWorldEjb.jar,name=QueneMDB01,service=EJB3   State:
  FAILED   Reason: org.jboss.deployment.DeploymentException: Required
  config property RequiredConfigPropertyM
  etaData@12c08c7[name=destination
  descriptions=[DescriptionMetaData@1941dc9[language=zh]]] for messag
  ingType 'javax.jms.MessageListener' not found in activation config
  [ActivationConfigProperty(destina tionType=javax.jms.Queue),
  ActivationConfigProperty(acknowledgeMode=Auto-acknowledge)]
  ra=jboss.jca: service=RARDeployment,name='jms-ra.rar'
--- MBEANS THAT ARE THE ROOT CAUSE OF THE PROBLEM --- ObjectName: jboss.j2ee:jar=HelloWorldEjb.jar,name=QueneMDB01,service=EJB3   State:
  FAILED   Reason: org.jboss.deployment.DeploymentException: Required
  config property RequiredConfigPropertyM
  etaData@12c08c7[name=destination
  descriptions=[DescriptionMetaData@1941dc9[language=zh]]] for messag
  ingType 'javax.jms.MessageListener' not found in activation config
  [ActivationConfigProperty(destina tionType=javax.jms.Queue),
  ActivationConfigProperty(acknowledgeMode=Auto-acknowledge)]
  ra=jboss.jca: service=RARDeployment,name='jms-ra.rar'

and my mdb is :
@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })

public class QueneMDB01 implements MessageListener
{
    public void onMessage(Message msg) {
        // TODO Auto-generated method stub
        try {
            TextMessage textMessage = (TextMessage) msg;
            System.out.println("MyQueneMDBBean is called "
                    + textMessage.getText() + " ");
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

A: From your error i'd say you forgot to add the destination name (queue name probably).
FAILED Reason: org.jboss.deployment.DeploymentException: Required config property RequiredConfigPropertyM etaData@12c08c7[name=destination descriptions=[DescriptionMetaData@1941dc9[language=zh]]

Example:
http://www.javaissues.com/2011/06/ejb3-message-driven-bean-hello-world.html
BTW, you've set up your queues/topics in JBoss right?
Hope this helps,
Dave


text:
Q: How do I reach a layer inside a GroupLayer? I am having problems in ArcObjects. I am struggling to get to the individual (feature-)layers inside a GroupLayer. Does anyone know how to do that ?

A: Try this:
public List<ILayer> GetLayers(string groupLayerName)
{

    ICompositeLayer compositeLayer = GetGroupLayer(groupLayerName);
    List<ILayer> layers = new List<ILayer>();

    if (compositeLayer != null)
    {
        for (int j = 0; j < compositeLayer.Count; j++)
        {
            layers.Add(new Layer(compositeLayer.Layer[j]));
        }
    }
    return layers;
}

ICompositeLayer GetGroupLayer(string groupLayerName)
{
     var mapLayers = _map.Layers;
     for (var layer = mapLayers.Next(); layer != null; layer = mapLayers.Next())
     {
            var comLayer = layer as ICompositeLayer;
            var groupLayer = layer as IGroupLayer;
            if ((comLayer != null) && (groupLayer != null) && (layer.Name.Equals(groupLayerName)))
                return groupLayer;
     }
}

A: Cast the group layer to ICompositeLayer which allows you to access the individual sublayers.

Provides access to members that work with a collection of layers that
  behaves like a single layer.


text:
Q: Why trim zeros from decimal part php not accurate for .00? I have this float value 1290.00 and I would like to trim the zeros on the right in the cleanest way to get 1290, but Why I got 129 if using trim function?
Code:
<?php
$var = '1290.00';
printf ("value: %s -> %s\n", $var, trim($var, '.00'));

The output:
value: 1290.00 -> 129

I have seen different solutions to it by not using trim function, but why is trim not working? I also tried with GoLang and got the same behavior.

A: Trim removes characters from the end, individually, not as a phrase. It removes all found characters until it can't find any more in the list. So it removes the 0, the 0, the period, then the 0. In this case, I would recommend either round or number_format
number_format($var, 0, '', ''); // 1290

A: trim doesn't work like that.  You only specify the characters you want to trim once, and two periods are used to specify a range. It will then trim all of those characters from the end.
A more efficient method might be intval($var)

A: Depending on your usage, note that number_format() also rounds the value (see the first example of the documentation). If you need to truncate the number you could use floor():
number_format(1.9, 0, '', '');    // string(1) "2"
floor(1.9);                       // 1


text:
Q: Is Multi-Threaded algorithm required to make use of Multi-core processors? I was just wondering whether we actually need the algorithm to be muti-threaded if it must make use of the multi-core processors or will the jvm make use of multiple core's even-though our algorithm is sequential ?
UPDATE:
Related Question:

*

*Muti-Threaded quick or merge sort in java

A: Your implementation needs to be multi-threaded in order to take advantage of the multiple cores at your disposal.
Your system as a whole can use a single core per running application or service. Each running application, though, will work off a single thread/core unless implemented otherwise.

A: I don't believe any current, production JVM implementations perform automatic multi-threading. They may use other cores for garbage collection and some other housekeeping, but if your code is expressed sequentially it's difficult to automatically parallelize it and still keep the precise semantics.
There may be some experimental/research JVMs which try to parallelize areas of code which the JIT can spot as being embarrassingly parallel, but I haven't heard of anything like that for production systems. Even if the JIT did spot this sort of thing, it would probably be less effective than designing your code for parallelism in the first place. (Writing the code sequentially, you could easily end up making design decisions which would hamper automatic parallelism unintentionally.)

A: Java will not automatically split your program into threads. Currently, if you want you code to be able to run on multiple cores at once, you need to tell the computer through threads, or some other mechanism, how to split up the code into tasks and the dependencies between tasks in your program. However, other tasks can run concurrently on the other cores, so your program may still run faster on a multicore processor if you are running other things concurrently.
An easy way to make you current code parallizable is to use JOMP to parallelize for loops and  processing power intensize, easily parellized parts of your code.

A: I dont think using multi-threaded algorithm will make use of multi-core processors effectively unless coded for effectiveness. Here is a nice article which talks about making use of multi-core processors for developers -
http://java.dzone.com/news/building-multi-core-ready-java


text:
Q: Checking presence of an element in subset of a mongodb array I need to select the documents in the mongodb database in which a condition has to be met which is described below.
I have an array in each of the document which looks something like this:
Payload.Signal.value[0.0,0.1,2.0,3.0,3.2,.......]
I need to select only the documents in the database where a certain value should be present at-least once in the subset of the above array. The desired subset of the array is from 300th position (if it exists) to the end of the array.
I need to write a mongodb query where the document needs to be selected if the desired value is present in the slice of the array from 300th position to the end of the array.
I looked into $slice operator documentation but it doesn't have any provision to specify the end of the array when the end position is unknown.
Any help in this regard is highly appreciated.
Thanks in advance.


text:
Q: How to setup a simple color scheme via CSS Root Variables? I would like to set the color scheme based on simple CSS root variables.
The JavaScript does not work: it does not see/set the root variables when one of the options are clicked. What have I overlooked to make this simple color scheme work?

const setTheme = theme => document.documentElement.className = theme;
document.getElementById('themeoptions').addEventListener('change', function() {
    setTheme(this.value);
});
#themeoptions p{ /* User Interface */
  display: inline-block;
  text-decoration: underline;
}#themeoptions p:hover{cursor: pointer}

:root.light {
  --bgr: #ddc;
  --txt: #456;
}
:root.dark {
  --bgr: #222;
  --txt: #844;
}
:root.blue {
  --bgr: #046;
  --txt: #dde;
}

body {
  background-color: var(--bgr);
  color: var(--txt);
}

Light

Dark

Blue

Click on a theme to change the color scheme!

A: There are three problems to address in your JavaScript code:

*

*The value property on an element does not refer to the attribute that you have named value on your paragraph elements. To access the value of this property, you'll need to use Element.getAttribute().

*this in your event listener callback function does not refer to the target element of the event. To access the target element, you'll need to use Event.target.

*The event that you want to listen for is most likely the click event (not the change event).

const setTheme = theme => document.documentElement.className = theme;
document.getElementById('themeoptions').addEventListener('click', ({target}) => {
  setTheme(target.getAttribute('value'));
});
#themeoptions p{ /* User Interface */
  display: inline-block;
  text-decoration: underline;
}#themeoptions p:hover{cursor: pointer}

:root.light {
  --bgr: #ddc;
  --txt: #456;
}
:root.dark {
  --bgr: #222;
  --txt: #844;
}
:root.blue {
  --bgr: #046;
  --txt: #dde;
}

body {
  background-color: var(--bgr);
  color: var(--txt);
}

Light

Dark

Blue

Click on a theme to change the color scheme!


text:
Q: Android - Is there a way to bypass the need to request user permission for gps? I am developing single application mode in android, in which there is no need to request for user's approval.
It even can be done as Native application (ndk) on root device.
But still, I am not sure if there is a way to handle it with GPS permissions.
It seems not to be enough to declare permissions in manifest file.
Is there a way to do it without asking user's permission ?

A:
I am developing single application mode in android, in which there is no need to request for user's approval.

For privacy reasons system thinks otherwise and unless you build your own system, root your device (and plant some patches) or (perhaps) sign your app with system certificate you are not able to prevent system from asking for user consent prior granting you GPS access.


text:
Q: Remove Out of Bounds Warning on In Bounds Array Element I have a c++ function, that determines whether or not a rectangle can fit on a 10 by 10 board at pt (x, y), with a width of w and a height of h .  There are 2 ways the rectangle will not fit on the board:

*

*The rectangle would overlap with a already taken square on the board.

*The rectangle would go out of the board.

The second bullet point is where the problem is. If I look for any points that would prevent the rectangle from working (point 1) it may result in a out of bounds exception. At first, I thought this would be quite easy to work around, just make sure x + w < 10 and y + h < 10, and if they are, then do the checks for already taken points, and if they aren't, return false. The problem, is that nothing that I have tried has gotten around the big message saying that there were security issues, and the green underline in visual studio that tells me that it might be out of bounds.
Here is my current code:
bool canFit(int board[10][10], int x, int y, int width, int height)
{
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            int py = y + j;
            int px = x + i;
            if (px > 10 || py > 10)
            {
                return false;
            }
            else {
                if (board[py][px] != 0)
                {
                    return false;
                }
            }
        }
    }
    return true;
};

The code is really simple, and I can't see why it won't detect that it can not thow an out of bounds expection. The pop up is really annoying, and I do not want it in the consumer version.


text:
Q: XML parser having issues i have been trying to parse a xml which look like this. is this correct format of xml is so how to parse it. And i want to know what is the format of xml.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1|3|195,317,65,108|342,227,66,99|280,98,84,112</string>

and my xml parser activity
is
public class RetrieveFeed extends AsyncTask {

URL url;
ArrayList<String> headlines = new ArrayList();
ArrayList<String> links = new ArrayList();
@Override
protected Object doInBackground(Object[] objects) {
    // Initializing instance variables

    try {
        url = new URL("http://54.179.134.139/viViewapi/api/values");

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(false);
        XmlPullParser xpp = factory.newPullParser();

        // We will get the XML from an input stream
        xpp.setInput(getInputStream(url), "UTF_8");

        boolean insideItem = false;

        // Returns the type of current event: START_TAG, END_TAG, etc..
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {

                if (xpp.getName().equalsIgnoreCase("html")) {
                    insideItem = true;
                } else if (xpp.getName().equalsIgnoreCase("pre")) {
                    if (insideItem)
                        headlines.add(xpp.nextText()); //extract the headline
                }
                /*else if (xpp.getName().equalsIgnoreCase("link")) {
                    if (insideItem)
                        links.add(xpp.nextText()); //extract the link of article
                }*/
            } else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("html")) {
                insideItem = false;
            }

            eventType = xpp.next(); //move to next element
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return headlines;
}

public InputStream getInputStream(URL url) {
    try {
        return url.openConnection().getInputStream();
    } catch (IOException e) {
        return null;
    }
}

public ArrayList<String> heads()
{
    return headlines;
}

}
i don't know whether the approach is right or wrong

A: XML like JSON needs at least one root element. In your example you do have a root element called "string" so no problems here.
Check out this XML Syntax Guide for a quick XML tutorial. Note that "string" can be used as it is not a reserved word (see XML Reserved Words).
The XML snippet you posted is valid XML. You can validate XML using this XML Validator.
You don't necessarily need the xmlns property (namespace) here so it could become:
<string>1|3|195,317,65,108|342,227,66,99|280,98,84,112</string>

This XML is just describing a single string. If you wanted to describe an object with a string property you would have something like this as the XML:
<root>
  <string>1|3|195,317,65,108|342,227,66,99|280,98,84,112</string>
</root>

If you want to know more about reading the values from the XML then check out this previous simple xml parsing Stack Overflow answer.


text:
Q: KML File into Google Bigquery I have a KML file that I exported after making my own Google Map. I was wondering if anyone knows a way I can get this map into BigQuery as a table of the Precinct name and the coordinates of their borders? Thanks in advance!

A: You can't load KML directly into a BigQuery GEOGRAPHY column. But BigQuery does support loading from WKT, WKB or GeoJSON.
So you'll have to first convert the KML into one of the above formats, perhaps using GDAL?
After that you can run a bq load. Alternatively to a load, it also works well as an external table, for example with WKB embedded as one column in a CSV.


text:
Q: Inner Join Ambiguous Error Postgresql Select * from "EstoqueCultura"
Inner Join "Cultura" on "Cultura"."Id" = "EstoqueCultura"."CulturaId"
Inner Join "Estoque" on "Estoque"."ClienteId" ="EstoqueCultura"."ClienteId"
where "ClienteId" = 7957

//// O ERRO ////
ERROR:  column reference "ClienteId" is ambiguous
LINE 4: where "ClienteId" = 7957
              ^
SQL state: 42702
Character: 185

A: Conforme mencionado antes, você deve informar de qual tabela o campo ClienteId deverá ser referenciado, neste caso o SGBD não sabe resolver de qual tabela ele deve utilizar para usar dentro do where.
Select * from "EstoqueCultura"
Inner Join "Cultura" on "Cultura"."Id" = "EstoqueCultura"."CulturaId"
Inner Join "Estoque" on "Estoque"."ClienteId" ="EstoqueCultura"."ClienteId"
where "EstoqueCultura.ClienteId" = 7957

Material para referência


text:
Q: How to get environment variables based on build environment dynamically in external extconfig.js file in angular I have configuration in angular.json file pointing towards different "urls" for different build
angular.json
configuration:{
   'dev':{
      "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
    },
   qa:{

  }
}

environment.dev.ts
export const environment = {
 appServer: "https://....."
}

environment.prod.ts
export const environment = {
 appServer: "https://....."
}

I want to create a extconfig.js file(external js) keeping in assets and putting it in angular.json file
config.js
var baseUrl = '' ; <==========// environment.appServer based on build condition

It should serve the purpose of handling "appServer" of environment variables based on build environment when run through either "ng serve --configuration=dev or ng build --configuration=prod.
This is required beacuse "extconfig.js" file will hold global variables containing configuration variables serving for other external js which may require baseUrl for ajax call

A: If i am understanding correctly, you can create a config.prod.ts and a config.ts under the same folder, each one holds a version of your appServer url. then you can import your config from the folder in your services.
import { extConfig } from './config-specifics';
var baseUrl = extConfig.appServerUrl
and in your angular.json.
"fileReplacements": [
        {
          "replace": "apps/app-name/src/app/config-specifics/config.ts",
          "with": "apps/app-name/src/app/config-specifics/config.prod.ts"
        }
      ]


text:
Q: is this possible? integrating two airflow servers Consider two airflow server is running A, B. I want B's DAG(one particular dag) running status to be available on A's Dags dashboard. is this possible? if possible how?
thanks in advance
Sundar


text:
Q: Existence of certain homogenous forms Let $D(X,Y), E(X,Y)\in\mathbb{Z}[X,Y]$ forms of the same degree $n$ and suppose  that the resultant $R=Res(D,E)$ of $D$ and $E$ is not $0$.
Show that there are homogenous forms $L_0(X,Y),M_0(X,Y), L_1(X,Y),M_1(X,Y)\in\mathbb{Z}[X,Y]$ with
$$L_0D+M_0E=R\cdot X^{2n-1}$$
and
$$L_1D+M_1E=R\cdot Y^{2n-1}$$
I encountered this problem while preparing a talk about the proof of the Mordell-Weil theorem for elliptic curves over $\mathbb{Q}$ and don't know how to solve it.

A: If $D(x)$ and $E(x)$ are polynomials of degree $n$ with coefficients in a commutative ring, then it is a standard property of resultants that there are polynomials $L$ and $M$ of degree $n-1$ such that $$L(x)D(x)+M(x)E(x)=R$$ where $R$ is the resultant of $D$ and $E$.
Given forms $D(x,y)$ and $E(x,y)$, we get $$L(x)D(x,1)+M(x)E(x,1)=R$$ then we let $x=X/Y$ and multiply by $Y^{2n-1}$ to get $$L_1(X,Y)D(X,Y)+M_1(X,Y)E(X,Y)=RY^{2n-1}$$ and we do the same with $D(1,y)$ and $E(1,y)$ to get the other equation you want.


text:
Q: What is default behavior of PostgreSQL without specifying COLLATION? What is default behavior of PostgreSQL, if i don't specify collation externally? One of the main questions, is it case-sensitive or not?

A: A collation is an SQL schema object that maps an SQL name to operating system locales. Whatever you shall setup as a default collation settings for the database. By default implicitly that collation will choose your database.

In PostgreSQL nevertheless, the initial set of collation names is
platform-dependent.

There are no case insensitive collations, but there is the citext extension.
The standard approach to doing case-insensitive matches in PostgreSQL has been to use the lower function when comparing values, for example
SELECT * FROM tab WHERE lower(col) = LOWER(?);

This works reasonably well, but has a number of drawbacks:
It makes your SQL statements verbose, and you always have to remember to use lower on both the column and the query value.
It won't use an index, unless you create a functional index using lower.
If you declare a column as UNIQUE or PRIMARY KEY, the implicitly generated index is case-sensitive. So it's useless for case-insensitive searches, and it won't enforce uniqueness case-insensitively.
From the documentation:

The citext data type allows you to eliminate calls to lower in SQL queries, and allows a primary key to be case-insensitive. citext is locale-aware, just like text, which means that the matching of upper case and lower case characters is dependent on the rules of the database's LC_CTYPE setting. Again, this behavior is identical to the use of lower in queries. But because it's done transparently by the data type, you don't have to remember to do anything special in your queries.

For your reference: PostgreSQL Documentation & StackOverFlow Ref Here


text:
Q: Bullet points are not displayed I guess this should be a simple question, but I just don't get it done.
I have a ul with li's and I want to use bullet points here, but they just won't be displayed, even though I included them in my CSS.
HTML looks like that:
<?php
  session_start();
  if (!isset($_SESSION["email"])) {
    header('Location: ../login_error.php');
    exit;
  }
?>
<!doctype html>

<meta charset="utf-8">
<title>The A Room</title>
<link type="text/css" rel="stylesheet" href="../../login.css">

      Blabla blabla blabla blabla blabla blabla blabla blabla blabla blabla     blabla blabla blabla

blabla blabla blabla blabla blabla blabla blabla blabla blabla blabla

blabla blabla blabla blabla blabla blabla blabla blabla blabla blabla

blabla blabla blabla blabla blabla blabla blabla blabla blabla blabla

CSS looks like that:
html, body, div {
    margin: 0;
    padding: 0;
    font-size: 1.2vw;
    font-family: "Arial Rounded", Arial, sans-serif;
}

body {
    background-color: #A9E2F3;
}

ul {
    list-style-type: circle;
    list-style-position: inside;
    list-style-color: white;
}

li {
    display: inline-block;
    width: 80%;
    top: 1%;
    right: 20%;
    margin-top: 1.5%;
    margin-bottom: 1.5%;
    padding-top: 1%;
    padding-bottom: 1%;
    padding-left: 7%;
    background-color: white;
    text-align: left;
    border-color: black;
    border-style: solid solid solid solid;
    border-radius: 0.5em 0.5em 0.5em 0.5em;
    border-width: 0.15em;
}

.explanations {
    display: inline-block;
    background-color: black;
    color: #A9E2F3;
    width: 31%;
    vertical-align: middle;
    position: fixed;
    right: 2.5%;
    border-color: black;
    border-style: solid solid solid solid;
    border-radius: 0.5em 0.5em 0.5em 0.5em;
    border-width: 0.15em;
    text-align: center;
    padding: 0.5%;
    font-size: 1.2vw;
}

#explanation_qas {
    top: 15%;
}

#explanation_sources {
    top: 74%;
    padding: 1%;
    width: 30%;
}

.explanation_list {
    background-color: black;
}

.explanation_list:hover {
    color: #A9E2F3;
}

Thanks in advance, I highly appreciate it!

A: display: list-item; css property is default for
 tag. By applying display: inline-block you're overriding it, which causes bullet points to disappear.  You should use a pseudo class to solve your problem:
ul.explanations>li:before{
    content: "";
    display: list-item;
    position: absolute;
}

A: the display property on the li should be
display: list-item;

instead of
 display: inline-block;

(see W3C CSS3 specification)
If you want your li element to stay inline-block , you could use :before and content
ul li {
  display: inline-block;
}

ul li:before {
  content: "• ";
}

list item1

list item3

list item3

as pappy suggested in this thread.

A: You should not use display:inline-block, because of this bullets are disappearing.


text:
Q: Why is git clone --recursive cloning detached submodules I've added some submodules to my git repo using the following (note the -b switch):
git submodule add -b dev-master git@github.com:OurCompany/The_Submodule.git

and when cloning the module recursively with
git clone --recursive -b dev-master git@github.com:OurCompany/The_Repository.git

the submodules get cloned, but running
git branch

indicates that the submodule is in a detached state.
I can fix by checking out the submodule with
git checkout dev-master

but isn't there a way to clone recursively with the submodules checked out on the tracked dev-master branch I added in the git submodule add step, instead of giving me a detached branch?

A: The parent project does not track the tags (i.e. master or dev-master). It only pins the sha1-ids of each submodule.
If you now want to have all submodules point to the current master (which might not be the one you expected), you can run:
git submodule foreach git checkout dev-master


text:
Q: MySQL: "Sending data" vs "Copying to tmp table" I have 2 queries that do the same thing and give the same result set, but writing differently. Looking at their profile, they take almost the same time to execute: around 0.075 seconds
The fascinating thing is that query#1 takes almost all of  the entire process execution time in the state "Copying to tmp table". As query#2 takes almost the entire process execution time in the state "Sending data".
So, my question is:
What state is better for a MySQL query to spent all of its time, "Sending data" or "Copying to tmp table"?
query#1 (spends execution time in the state "Copying to tmp table")
SELECT ac.album_category_id, ac.name, ac2.album_category_id, ac2.name, ac2.description, t2.total
FROM album_category ac
JOIN album_category ac2 ON ac2.parent_album_category_id = ac.album_category_id
JOIN (
    SELECT a.album_category_id cat_id, SUM(result.count_image) total
    FROM album a
    JOIN (
        SELECT IFNULL(a.parent_album_id, a.album_id) p_album_id, COUNT(ai.image_id) count_image
        FROM album_image ai
        JOIN album a ON a.album_id = ai.album_id
        JOIN image i ON i.image_id = ai.image_id
        WHERE i.is_listed = 1
        GROUP BY p_album_id
    ) result ON result.p_album_id = a.album_id
    GROUP BY a.album_category_id
) t2 ON t2.cat_id = ac2.album_category_id
ORDER BY ac.position, ac2.position

query#2 (spends execution time in the state "Sending data")
SELECT ac.album_category_id, ac.name, ac2.album_category_id, ac2.name, ac2.description, t3.total
FROM album_category ac
JOIN album_category ac2 ON ac2.parent_album_category_id = ac.album_category_id
JOIN (
    SELECT a2.album_category_id cat_id, SUM(t2.sum_image) total
    FROM album a2
    JOIN (
        SELECT IFNULL(a.parent_album_id, a.album_id) p_album_id, SUM(t1.count_image) sum_image
        FROM album a
        JOIN (
            SELECT ai.album_id album_id, COUNT(ai.image_id) count_image
            FROM album_image ai
            JOIN image i ON i.image_id = ai.image_id
            WHERE i.is_listed = 1
            GROUP BY ai.album_id
        ) t1 ON t1.album_id = a.album_id
        GROUP BY p_album_id
    ) t2 ON t2.p_album_id = a2.album_id
    GROUP BY a2.album_category_id
) t3 ON t3.cat_id = ac2.album_category_id
ORDER BY ac.position, ac2.position

EDIT
As per jkavalik request, i've added the EXPLAIN. I'm not sure how to add it in text, so i've added images instead. Hope that's ok.
EXPLAIN for query #1

EXPLAIN for query #2

A: Copying to tmp table: The server is copying to a temporary table in memory.
Sending data: The thread is reading and processing rows for a SELECT statement, and sending data to the client. Because operations occurring during this state tend to perform large amounts of disk access (reads), it is often the longest-running state over the lifetime of a given query.
http://dev.mysql.com/doc/refman/5.6/en/general-thread-states.html
Sending data will happen on most queries but the query state will change so fast on quick queries that you won't even notice it. However, since you are noticing it, there may be a lot of IO going on at that time. When you run that query, in a terminal window also look at iostat -x 10 and watch the disk IO wait (assuming you are using Linux/Unix). If the wait shoots up, the MySQL is reading from disk, doing its work and then preparing to push the data to client.
Copying to tmp table means that the result of a part of query or subquery is moved to memory so that more work can be done using that temporary data (temp table). Whenever I have encountered this state, there's a possibility of optimization. I'd be more concerned about both states if query is taking several seconds to return. I'd optimize query 1 in your case. You might want to try increasing innodb_buffer_pool_size (assuming you are using innodb engine)
https://dev.mysql.com/doc/refman/5.5/en/innodb-buffer-pool.html


text:
Q: What is the diference between using base images and using apt? I have read this question and I understand that you need some kind of foundation to build your docker image. However, I still don't see the purpose of docker images like python.
Why do I need this:
FROM python:latest

when I can just do that:
FROM ubuntu
RUN apt install python3

Say I want to run a container where a python server is hosted using apache. What would be the difference between

*

*Using the apache base image and installing python manually

*Using the python base image and installing apache manually

*Using the ubuntu base image and installing both manually

A: The difference is slim in the given example because in the end you will get the same thing but using slightly different commands.
Things change when you need to use either latest or specific version of the software. The required version may not be available in standard Ubuntu repositories or may come with a delay.
What you get from using python or apache2 as a base is the ability to choose the version you need with just one line of code as soon as it's published.
More significantly, there may be no need to combine python and apache. Docker containers are usually made to host a single process and it is more common to have a python backend in one container and a web-server as a proxy in another.
In this case you don't care about installing apache at all, you just mount its config into the container at runtime. Eliminating the web server you only need to focus on the application and its dependencies, so in the end you will have less code and easier time maintaining it.


text:
Q: How can I combine hashes in Perl? What is the best way to combine both hashes into %hash1?  I always know that %hash2 and %hash1 always have unique keys.  I would also prefer a single line of code if possible.
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';

A: For hash references. You should use curly braces like the following:
$hash_ref1 = {%$hash_ref1, %$hash_ref2};

and not the suggested answer above using parenthesis:
$hash_ref1 = ($hash_ref1, $hash_ref2);

A: Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)

Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.
If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:
my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.
foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:
@hash1{ keys %hash2 } = values %hash2;

A: Quick Answer (TL;DR)

    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

*

*Context: Perl 5.x

*Problem: The user wishes to merge two hashes1 into a single variable

Solution

*

*use the syntax above for simple variables

*use Hash::Merge for complex nested variables

Pitfalls

*

*What do to when both hashes contain one or more duplicate keys

*

*(see e.g., Perl - Merge hash containing duplicate keys)

*(see e.g., Perl hashes: how to deal with duplicate keys and get possible pair)

*Should a key-value pair with an empty value ever overwrite a key-value pair with a non-empty value?

*

*What constitutes an empty vs non-empty value in the first place? (e.g. undef, zero, empty string, false, falsy ...)

See also

*

*PM post on merging hashes

*PM Categorical Q&A hash union

*Perl Cookbook 5.10. Merging Hashes

*websearch://perlfaq "merge two hashes"

*websearch://perl merge hash

*https://metacpan.org/pod/Hash::Merge

Footnotes
1 * (aka associative-array, aka dictionary)

A: This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge


text:
Q: How can I update a map using the `update` function?    (def p {:name "James" :age 26})

I'm trying update method, like
(update p :name "David")

which does not work since the second argument has to be a function.

A: Try this:
(assoc p :name "David")

Please see this list of documentation, especially the Clojure CheatSheet!  See also assoc-in and update-in as described under
Collections -> Maps

P.S. What you have there is a Clojure map value, which is different than an object in JavaScript or a JSON string.


text:
Q: Passing post data back after OpenIdConnectAuthentication callback (signin-oidc) event The entry point of my web app requires some post data.  It needs those post data back during the callback from the IdentityServer4 (the signin-oidc callback).
Is the AuthenticationProperties to right place to store the post data?
This is the workflow I plan:

*

*During the OpenIdConnectEvents's OnRedirectToIdentityProvider event,
store the post data in the AuthenticationProperties

*After the authentication, at the OnTokenResponseReceived event, get back the
post data from the AuthenticationProperties and put it in the
HttpContext.

*In the controller, if the post data does not exist, check the
HttpContext for them.

Is it the right approach?
Thanks in advance.


text:
Q: C++, an empty destructor for a class I've read one of your answers (Will an 'empty' constructor or destructor do the same thing as the generated one?). You wrote:
"Let's assume the object of type C is created in the definition of A's constructor in the .cpp file, which also contains the definition of struct C. Now, if you use struct A, and require destruction of an A object, the compiler will provide an implicit definition of the destructor, just like in the case above. That destructor will also implicitly call the destructor of the auto_ptr object. And that will delete the pointer it holds, that points to the C object - without knowing the definition of C! That appeared in the .cpp file where struct A's constructor is defined". Could you please explain 2 things for me:
1. why should the destructor of A know C's definition?
2. How does adding A's empty destructor help the sityation?
Thank you

A: 1) The destructor of A should know how to destroy C since A may contain an auto_ptr to C. auto_ptr'd objects are expected to die when the containing object died. Therefore, the destructor of A should know how to destroy a C.
2) The key is that the destructor definition is only written in the .cpp file. This means that calls to the destructor are linked to the object compiled from the .cpp file. When the .cpp file is compiled, it has access to the definition of C (that is what was written in the answer). Therefore, the destructor in the .cpp file can destruct C as needed instead of failing to destruct C as in the case where the destructor was not defined and/or defined at a point where the compiler only saw a forward declararion of class C.
Also, see
The relation between Forward declaration and destructors


text:
Q: How to query similar records in SQLite database from Android? Let's say an SQLite database column contains the following value:
U Walther-Schreiber-Platz
Using a query I'd like to find this record, or any similar records, if the user searches for the following strings:

*

*walther schreiber

*u walther

*walther-schreiber platz

*[Any other similar strings]

However I cannot figure out any query which would do that. Especially if the user does not enter the - character.
Example:
select * from myTable where value like '%walther schreiber%'; would not return the result because of the missing -.
Thanks,
Robert

A: So, as I said in my comment, I think you can have a query along the lines of:
select * from myTable where LOWER(value) like <SearchValue>

I'm assuming you're collecting the <SearchValue> from the user programmatically, so would be able to do the following: <SearchValue> would need to be:  The user's search string, appropriately cleansed to avoid SQL injection attacks, converted to lower case, with all of the spaces converted to '%', so that they match zero or more characters...
So you would have (for example):
select * from myTable where LOWER(value) like '%walther%schreiber%'
select * from myTable where LOWER(value) like '%walther-schreiber%platz%'

etc...  however, this does assume that the word order is the same, which in your examples it is...


text:
Q: Caught AttributeError while rendering: 'DecimalField' object has no attribute 'attrs' following on from this question. I have the following:
models.py
VARIABLE_CHOICES = (
    ('bool', 'On/Off'),
    ('date', 'Date'),
    ('float', 'Number'),
    ('text', 'Text'),
)

class Variable(models.Model):
    template = models.ForeignKey(Template)
    name = models.CharField(max_length=20)
    type = models.CharField(max_length=5, choices=VARIABLE_CHOICES, default=2)
    data = models.CharField(max_length=100, blank=True, null=True)

forms.py
class VariableForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(VariableForm, self).__init__(*args, **kwargs)

        if self.instance:
            if self.instance.type == 'bool':
                self.fields['data'].widget = BooleanField()
            if self.instance.type == 'date':
                self.fields['data'].widget = DateField()
            if self.instance.type == 'float':
                self.fields['data'].widget = DecimalField()
            if self.instance.type == 'text':
                self.fields['data'].widget = TextInput()
            self.fields['data'].label = self.instance.name

views.py
def template_variables_view(request,tID):
    ...
    templateVariables = Variable.objects.filter(template=template)
    lvForm = []
    for ltVars in templateVariables:
        lvForm.append(VariableForm(instance=ltVars))

and I am cycling through the forms in lvForm like so in the template:
{% for lo in ltvForm %}
    {% for field in lo %}
        {{ field.label }}:	{{ field }}
    {% endfor %}
{% endfor %}

but I keep getting the error Caught AttributeError while rendering: 'DecimalField' object has no attribute 'attrs'
Any ideas?

A: You're setting the data field's widget to a field, for some reason. You should just be setting the field.
if self.instance.type == 'bool':
    self.fields['data'] = BooleanField()

etc.


text:
Q: driver is failing to switch to default content So I am able to send keys to the input box in the iframe but my script fails once it gets to driver.switch.to.default_content()
try:
    # iframe/textbox
    iframe = driver.find_element(By. XPATH, "/html/body/div[3]/div[4]/div/nz-modal-container/div/div/div[2]/div[2]/nz-form-item[1]/nz-form-control/div/div/app-richtext/div/div[2]/div[1]/div[2]/div[1]/iframe")
    driver.switch_to.frame(iframe)
    time.sleep(2)
    driver.find_element(By. XPATH, "/html/body/p").send_keys('Test')
    driver.switch_to.default_content()

    #....
    driver.find_element(By. CSS_SELECTOR, "#cdk-overlay-9 > nz-modal-container > div > div > div.ant-modal-footer.ng-tns-c101-267.ng-star-inserted > button.ant-btn.orange.ant-btn-primary.ng-star-inserted").click()

the iframe is nested in a div, but the div is inside of the body tag so I do not understand why it keeps failing.


text:
Q: How to simplify the product of $(x^{2^k}+x^{-2^k})$ over $k$?
Simplify $$\left(x+\frac1x\right)\left(x^2+\frac1{x^2}\right)\left(x^4+\frac1{x^4}\right)\ldots\left(x^{2^{n-1}}+\frac1{x^{2^{n-1}}}\right)$$ for $n\in\Bbb N$.

Should I be using mathematical induction on $n$ for this, or is there another way?

A:
am I gonna solve it by using mathematical induction or..

I don't know how you're going to solve it, or what comes after the ellipsis.  But let me tell you, I multiplied that thing by $\displaystyle \left( x - \frac{1}{x}\right)$ and the craziest thing happened...

A: You will eventually use mathematical induction in your solution.
However, you have some work to do before you get to that point: the first thing you need to do before you can solve this problem is to figure out what's going on.
One of the usual approaches to solving problems where you don't know what's going on is to look at special cases. This is especially true in problems where you have something going on "$n$ times" or the like.
Before trying to tackle the general problem, you first tackle the $n=1$ case in isolation. Then you look at the $n=2$ case. Then the $n=3$ case, and maybe a few more.
Frequently, after working through these special cases, the it becomes clear how th general case is going to look. At that point, you write down what you think the answer is going to be, and then use some means (e.g. induction, as you thought) to verify that your answer is correct.


text:
Q: Java Generics Map Key-Value Typing I'm wanting a method to return something like
Map<Class<T>, List<T>>

where the map's keys correspond to lists of instances of that class, but the map can contain many different types of classes.  Is there a way to enforce that the typing of the key and value must correspond, while allowing all different types to be stored in the map?


text:
Q: How to use Go to create account and add/remove friend in ejabberd? I found this library: golang xmpp, and it is quite low level (exposed the details of xmpp protocol).I took some time to dig into it, but quite time consuming. Since,right now,I just need three functions:

*

*create account

*add friend(I think it should be divided into send request/approve request)

*remove friend

So, can anybody tell me how to do it in this library?

A: I assume you want to manage an XMPP server from you backend. I would not use an XMPP bot to perform those task.
You should consider using ejabberd XMLRPC API to perform those tasks. All commands available from ejabberdctl are exposed. It means that you can control a lot of ejabberd behaviour using that API.


text:
Q: How can I create a shortcode based on the current Wordpress user? I want to create a shortcode with conditions based on who the current user is
I have the essence of my shortcode...
function my_shortcode_function() {
     return 'here is the content of my shortcode!';
}

add_shortcode('coolshortcodename', 'my_shortcode_function');

But I need to add conditions to it...I want to say if user ID is Jonny then show this, if the user is Sally show that, if the user is Jamie something else...
function my_shortcode_function() {
IF JONNY
     return reblex_display_block(610);
ELSE IF SALLY
     return reblex_display_block(199);
ELSE IF JAMIE
     return reblex_display_block(554);
}

add_shortcode('coolshortcodename', 'my_shortcode_function');

A: function my_shortcode_function() {
    $current_user_id = get_current_user_id();
    if ($current_user_id == 5) // where user ID of Jonny is 5
        return reblex_display_block(610);
    else if ($current_user_id == 6) // where user ID of Sally is 6
        return reblex_display_block(199);
    else if ($current_user_id == 7) // where user ID of Jamie is 7
        return reblex_display_block(554);
}

A: basically you have to check the current user id by get_current_user_id()
here is the code that i have modified. I think it will work for you.
function my_shortcode_function() {
ob_start();
$jonny_id = 1; // You have to collect the specific user id from wp dashboard
$sally_id = 2; // You have to collect the specific user id from wp dashboard
$jamie_id = 3; // You have to collect the specific user id from wp dashboard

if(is_user_logged_in()){

    if( $jonny_id == get_current_user_id() ){
        return reblex_display_block(610);
    }
    elseif( $sally_id == get_current_user_id() ){
        return reblex_display_block(199);
    }
    elseif( $jamie_id == get_current_user_id() ){
        return reblex_display_block(554);
    }
}

return ob_get_clean();
}

add_shortcode('coolshortcodename', 'my_shortcode_function');


text:
Q: Density of radiation at CMB I was trying to find the radiation density at the CMB time.
For two different methods, the first one is using the Planck Law and the data for the actual measured temperature $T_{0}=2.7255° K$.
$$ \rho_{r}=\rho_{\gamma}+\rho_{\nu}$$
$$\rho_{\gamma}=\frac{a_{b}}{c^2}T_{0}^{4}$$
$$\rho_{\nu}=3.046\frac{7}{8}(\frac{4}{11})^{4/3}\rho_{\gamma}$$
$$\frac{a_{b}}{c^2}=8.41805*10^{-33}$$
The second way to find it is using the  $\Lambda CDM$ model, we know that the equation for density of radiation in this model is given by
$$\rho_{r}=c(1+z)^4$$
The constant C is determined to be the actual value for radiation density i.e $c=7.85846*10^{-31} kg\, m^{−3}$
Know with this two formulas we can calculate the radiation density at CMB in two different ways:-
1. Using the value of the themperature at CMB $T_{CMB}=3000°K$.
2. Using the redshift at CMB $z_{CMB}\approx 1100$
For the first method I obtain $$\rho_{r}^{CMB}=1.15355*10^{-18}kg\, m^{−3}$$
For the second method
$$\rho_{r}^{CMB}=8.51682*10^{-26}kg\, m^{−3}$$
Clearly I am doing something wrong, maybe Planck's Law is not a good aproximation at CMB time?

A: If you look the wiki link on neutrino decoupling,

In Big Bang cosmology, neutrino decoupling refers to the epoch at which neutrinos ceased interacting with other types of matter , and thereby ceased influencing the dynamics of the universe at early times. Prior to decoupling, neutrinos were in thermal equilibrium with protons, neutrons and electrons, which was maintained through the weak interaction. Decoupling occurred approximately at the time when the rate of those weak interactions was slower than the rate of expansion of the universe. Alternatively, it was the time when the time scale for weak interactions became greater than the age of the universe at that time. Neutrino decoupling took place approximately one second after the Big Bang, when the temperature of the universe was approximately 10 billion kelvins, or 1 MeV.

In your first method you assume the same temperature at CMB time for the neutrino flux too, and this must be wrong because decoupling means no thermal equilibrium with other matter.
If you want to include the neutrino flux at the the time of the CMB  I think you  should start from the 1 second when it decouples, going forwards.


text:
Q: Rails - HTTParty request through AJAX I am new to both Rails and AJAX.
I want to consume an API which is hosted on a different website.  I ran into problems with cross origin HTTP request.  So I tried doing this by using HTTParty.
In the code below, I am setting the text of $(".result") as JSON.parse(HTTParty()) request, so that it can query the website and give me the result.
Rails code:
<%= form_for(@profile) do |f| %>
  <%= f.label :content %>
  <%= f.text_field :content, class: 'ajax-control' %>
  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>

Javascript code:

Now comes the weird problem.  The code above does send the GET request to example.com (placeholder), but gets a response saying that it is not a valid query.
However, if I pass the str1 as follows -
var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param=xyz"))%>'
 $(".result").text(str1);

I get the expected response. If the $(".ajax-control") text field is "xyz", I get a response saying not a valid query.
Does string concatenation in javascript introduces new characters because of which it is throwing an error?

A: That javascript (which in turn has ruby code via erb) is not going to execute after its been rendered the first time by Rails.
That is, its not going to be invoked each time that keypress callback is called, which means that when Rails is rendering that Javascript it obviously has no knowledge of the client-side DOM so the URL is affectively:
JSON.parse(HTTParty.get("http://example.com/api.php?param="))

And the remote server has an empty param which it doesnt like...
If you really need to invoke that API for every keypress you have two options:

*

*Get it to work via Ajax using CORS

*Invoke an endpoint in your Rails app,
which in turn uses Ruby-side HTTParty to invoke the API and relay
the response back to the client.


text:
Q: Narrow a union type based on properties already set within an object interface MockHTMLDivElement {
  divPropA: string,
  divPropB: string,
}

interface MockHTMLButtonElement {
  buttonPropA: string,
  buttonPropB: string,
}

type MockElement =
  | MockHTMLDivElement
  | MockHTMLButtonElement

const el: MockElement = {
  buttonPropA: 'foo', // implies that this is a MockHTMLButtonElement
  d // intellisense shows divPropA, divPropB here, even though buttonPropA is already
    // present and implies this is a MockHTMLButtonElement and not a MockHTMLDivElement
}

Intellisense will still show divPropA and divPropB as possible properties for this object even though the object already has a buttonPropA property, which would imply that it's a MockHTMLButtonElement.
Is there a way to type this better so that Intellisense knows this is either a MockHTMLButtonElement or a MockHTMLDivElement and only show properties for one type or the other rather than showing properties from both types?

A: The buttonPropA property is not a discriminant for the union, because the type of this property is not prohibited by the MockHTMLDivElement type, so {buttonPropA: 'foo', divPropA: 'bar', divPropB: 'baz'} is allowed as a value of type MockHTMLDivElement.
If you use a discriminated union instead, then only the properties from the consistent branch will be suggested. In the example below, kind is the discriminant.
interface MockHTMLDivElement {
  kind: 'div',
  divPropA: string,
  divPropB: string,
}

interface MockHTMLButtonElement {
  kind: 'button',
  buttonPropA: string,
  buttonPropB: string,
}

type MockElement = MockHTMLDivElement | MockHTMLButtonElement

const el: MockElement = {
  kind: 'button',
  buttonPropA: 'foo',
  b, // suggestions include 'buttonPropB'
  d, // no suggestions
}

Playground Link


text:
Q: How to get from region code to its timezone with C#/.Net I've been puzzling around with RegionInfo and CultureInfo, but I still haven't managed to get a timezone with to determine the UTC offset.
I've got codes like NL for Netherlands and US-TX for the state of Texas, USA.
How can I get the UTC offset given an ISO 3166 or ISO 3166-2 code?


text:
Q: Lost Xbox 360 data I have had my 360 for a couple years now and just recently upgraded to an xbox live account. I created a brand new one using a gamertag that xbox live choose for me. After doing that, however, I found that any of the offline saved data from previous games was erased (NBA 2k14 and NCAA10). I have signed in to all the gamertags on my account and can't find it anywhere. Is there a way to recover this? Or am I just out of luck?

A: Unfortunately the achievements and save data in your other profiles can't be transferred to your new Live account.  Like you, I found that out the hard way.