text:
Q: What is a proper way to store key:value returned by registerForActivityResult()? I am trying to catch and store the file path selected by user using registerForActivityResult. It returns the path, I can print the path but I am not able to store it using SharedPreferences class as it requires an app context which I cannot get using getApplicationContext() in static SettingsFragment.
public class SettingsActivity extends AppCompatActivity
        implements SharedPreferences.OnSharedPreferenceChangeListener {
    protected void onCreate(Bundle savedInstanceState) {...}
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {...}

    public  class SettingsFragment extends PreferenceFragmentCompat {
        ActivityResultLauncher<String> mGetContent = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                new ActivityResultCallback<Uri>() {
                    SharedPreferences sharedPreferences;
                    SharedPreferences.Editor editor;
                    @Override
                    public void onActivityResult(Uri uri) {
                        Log.i("MYAPP", "File selected:" + uri.toString());
// the added code is right below.
                        sharedPreferences = getSharedPreferences( BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE );
                        editor = sharedPreferences.edit();
                        editor.putString("audio_filename", uri.toString());
                        editor.apply();

                    }
                });

        @Override
        public boolean onPreferenceTreeClick(Preference preference) {
            String key = preference.getKey();
            if (key.equals("audio_filename")) {
                mGetContent.launch("*/*");
                return true;
            }
            return super.onPreferenceTreeClick(preference);
        }
  }
}

The code I used from documentation but it seems missing integration between SharedPreferences and registerForActivityResult.
UPDATE1 (Clarification): This is a podcast player, actually I try to play audio using MediaPlayer class. The app has MainActivity and SettingActivity. The idea is the SettingActivity is to select an audio file and save its file path (SharedPreferences) then on the next app start (MainActivity retrieves last file path from SharedPreferences) I do not need to select it again but continue listening selected file instead.
UPDATE2: When I define SharePreferences it asks me to remove static from SettingsFragment definition. But when I run the app an error thrown:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.audiotranscriptd/com.example.audiotranscriptd.SettingsActivity}: java.lang.IllegalStateException: Fragment com.example.audiotranscriptd.SettingsActivity.SettingsFragment must be a public static class to be  properly recreated from instance state.

A: Found solution here . It appears in Fragment the getSharedPreferences should be called with getActivity(), like this
sharedPreferences = getActivity().getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE);

Works for me!


text:
Q: Laravel 5.2 - Delete from db I am using Laravel Framework version 5.2.45.
I have created a simple view that outputs my todos:
@foreach($todos as $todo)
    {{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>

@endforeach

Within my routes I have created the following route to delete a todo:
Route::get('/todo/delete/{id}', [
    'uses' => 'TodosController@delete',
    'as' => 'todo.delete'
]);

Within my TodosController I created the following delete method:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Todo;

class TodosController extends Controller
{

    public function delete($id) {
        $todo = Todo::find($id);

        $todo->delete();

        return redirect()->back();
    }
// ...

When I press the button in the frontend nothing happens. I do not get any error...
Any suggestions what is wrong with my implementation?
Appreciate your replies!

A: Try Below code, You have used a button instead of a tag
@foreach($todos as $todo)
            {{ $todo->todo }}  $todo->id]) }}" class="btn btn-danger">x

        @endforeach

A: You are using button not tag
turn your code from
@foreach($todos as $todo)
   {{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>

@endforeach

to
@foreach($todos as $todo)
   {{ $todo->todo }}  $todo->id]) }}" class="btn btn-danger">x

@endforeach

A: You should do like this :
Delete Button :
 id) }}">Delete

And delete function look like below :
public function delete($id) {
    try {
        $delete_flag = Todo::where(['id' => $id])->first();
        $delete_flag->delete();
        return redirect()->back()->with('success', 'Todo deleted successfully');
    } catch (Exception $ex) {
        return redirect()->back()->with('error', 'Something went wrong');
    }
}

A: @foreach($todos as $todo)
   {{ $todo->todo }}  $todo->id]) }}" class="btn btn-danger">x

@endforeach

delete code--
$toDo = Todo::findOrFail($id)->delete();
if($toDo){
   return response()->josn(['message'=>'deleted']);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Socket.io : How to handle/manage multiple clients requests and responses? I am very eager to integrate Socket.io to my node.js project, but I have some confusions on how to properly use socket.io. I have been looking through documentations and tutorials, but I have not been able to understand some concepts on how socket.io works.
The scenario I have in mind is the following:

*

*There are multiple clients C1, C2, ..., Cn

*Clients emit request to the server R1,...,Rn

*Server receives request, does data processing

*When data-processing is complete, Server emits response to clients Rs1, .., Rs2

The confusion I have in this scenario is that, when the server has finished data processing it emits the response in the following way:
// server listens for request from client
socket.on('request_from_client', function(data){
    // user data and request_type is stored in the data variable
    var user = data.user.id
    var action = data.action

    // server does data processing
    do_some_action(..., function(rData){
        // when the processing is completed, the response data is emitted as a response_event
        // The problem is here, how to make sure that the response data goes to the right client
        socket.emit('response_to_client', rData)
    })
})

But here I have NOT defined which client I am sending the response to!

*

*How does socket.io handle this ?

*How does socket.io make sure that: response Rs1 is sent to C1 ?

*What is making sure that: response Rs1 is not sent to C2 ?

I hope I have well explained my doubts.

A: The instance of the socket object corresponds to a client connection. So every message you emit from that instance is send to the client that opened that socket connection. Remember that upon the connection event you get (through the onDone callback) the socket connection object. This event triggers everytime a client connects to the socket.io server.
If you want to send a message to all clients you can use
io.sockets.emit("message-to-all-clients")
and if you want to send an event to every client apart the one that emits the event
socket.broadcast.emit("message-to-all-other-clients");


text:
Q: Place div in golden ratio: Alternative to absolute position? I have build a page like in this sample below. You can also play around with it on codepen.
The idea was, that the dark grey hero box is placed on the bottom of the viewport. So far so easy.
BUT if the screen is too small in height (e.g. for a small laptop), so that the text would fill most (or even all) of the viewport, the background image could hardly be realized. In this case the hero box should be placed in the golden ratio instead of the bottom of the viewport.
I have already build that solution in the sample as well. Just reduce the height of your browser window.
I just have the feeling that I am doing soemthing wrong in general. At the moment I am placing hero, content and footer in absolute positioned divs. It's working ok as long as there is only static content inside the #content div. But if there is for example an accordion or some other collapsing/dynamic stuff, the position of the footer has to be re-calculated.
I can easily do this in re-calling the ratio function. But meanwhile the whole solution does look wrong or maybe too complex to me.
Isn't there another and more easy solution to place the content div with a RELATIVE position after the hero container?

// call function after everything has been loaded
$(window).load(function() {
    checkRatio();
});

window.dispatchEvent(new Event('resize'));

$(window).resize(function() {
    checkRatio();
});

function checkRatio() {

    var ratio = 0;
    var contentTopPos = 0;
    var footerTopPos = 0;

    var windowHeight = $(window).height();
    var headerHeight = $("#hero").height();
    var contentHeight = $("#content").height();

    ratio = (windowHeight / headerHeight);
    contentTopPos = (windowHeight / 1.618);

    if(ratio < 1.618) {
        // Window too small or Content too long
        $("#hero").css('bottom', 'initial');
        $("#hero").css('top', contentTopPos);
    } else {
        // Default Position: bottom 0
        $("#hero").css('top', 'initial');
        $("#hero").css('bottom', 0);
    }

    var sumHeight  = $("#hero").offset().top + $("#hero").height();
    $("#content").css('top', sumHeight + "px");

    footerTopPos = (sumHeight + contentHeight);
    $("#footer").css('top', footerTopPos + "px");
}
body {
     padding: 0;
     margin: 0;
     font-family:Verdana, Geneva, Tahoma, sans-serif;
}
#header_img {
     position: fixed;
     top: 0;
     height: 100vh;
     width: 100%;
     background-size: cover;
     z-index: 1;
 }

 #hero_container {
     position: relative;
     height: 100vh;
     width: 100%;
 }
 #hero {
     position: absolute;
     margin: 0 5%;
     bottom: 0;
     width: 90%;
     height: auto;
     background-color: #333;
     box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.46);
     z-index: 2;
 }

 #hero_text {
     padding: 20px;
     color: #fff;
 }

 #content {
     position: absolute;
     width: 100%;
     background-color: transparent;
     z-index: 3;
 }

 section {
     background-color: #dedede;
     padding: 20px;
     border-bottom: solid 1px #333;
 }

 #footer {
     position: absolute;
     width: 100%;
     z-index: 3;
     background-color: #999;
     color: #555;
 }
 #footer_text {
     padding: 10px 20px;
 }

Lorem ipsum dolor sit

Cras felis leo, pellentesque non dui ut, molestie mollis lorem.

Fusce venenatis metus id est venenatis ornare. Aliquam id ante et nulla rutrum malesuada vel sit amet felis. Maecenas maximus, quam vitae cursus ultrices, est augue consequat magna, vitae bibendum ex urna eget lacus. Donec quis sagittis diam.

Vivamus molestie

Sem sit amet posuere elementum, ligula dolor laoreet eros, sed ultrices mi lacus quis est. Sed ut venenatis metus, id consectetur mauris.

Mauris sollicitudin ante est

Ut ultrices neque volutpat quis. Aenean bibendum dui sed pulvinar vestibulum. Vestibulum finibus ornare dui at lobortis.

Sed consequat euismod sem

In venenatis lacus luctus in. Nam elementum dolor a magna eleifend consectetur. Curabitur efficitur magna erat, et eleifend enim placerat sit amet. Fusce cursus, sem vel porta tempor, diam dolor auctor lorem, eu venenatis velit lorem ac lectus.

© 2020 SchweizerSchoggi

A:

.hero-container {
    height: 100vh;
    display: flex;

}
.hero-content {
    width: 100%;
    background: grey;
    align-self: flex-end;
}

@media only screen and (max-height: 300px) {
  .hero-container{
    padding-top: 25vh;
  }
  .hero-content{
    align-self: flex-start;
  }
}

Lorem ipsum dolor sit

Cras felis leo, pellentesque non dui ut, molestie mollis lorem.

Fusce venenatis metus id est venenatis ornare. Aliquam id ante et nulla rutrum malesuada vel sit amet felis. Maecenas maximus, quam vitae cursus ultrices, est augue consequat magna, vitae bibendum ex urna eget lacus. Donec quis sagittis diam.

Vivamus molestie

Sem sit amet posuere elementum, ligula dolor laoreet eros, sed ultrices mi lacus quis est. Sed ut venenatis metus, id consectetur mauris.

Mauris sollicitudin ante est

Ut ultrices neque volutpat quis. Aenean bibendum dui sed pulvinar vestibulum. Vestibulum finibus ornare dui at lobortis.

Sed consequat euismod sem

In venenatis lacus luctus in. Nam elementum dolor a magna eleifend consectetur. Curabitur efficitur magna erat, et eleifend enim placerat sit amet. Fusce cursus, sem vel porta tempor, diam dolor auctor lorem, eu venenatis velit lorem ac lectus.

© 2020 SchweizerSchoggi


text:
Q: import React from "react"; resulting in Uncaught SyntaxError: Unexpected identifier I am new to ReactJS and all the solutions I found for this problem used npm cli and suggested to use babel-plugin-transform-es2015-modules-amd. However I am using CDN and here is my code:-

1] Here is my index.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello World</title>

where browser.min.js is actually babel
and the other two react files are of version 16.5.2

2] And hello.jsx:-
import React from "react";
import { render } from "react-dom";

class App extends React.Component {
    render() {
        return (

Hello!

        );
    }
}

render(<App />, document.getElementById("root"));

This code throws an error at line 1 in hello.jsx saying "Uncaught SyntaxError: Unexpected identifier"
Any help is much appreciated. Thanks!

A: Since hello.jsx is JSX. You need to indicate this to the browser by setting the script attribute.
This is done by setting the script type attribute to text/babel e.g.

The babel standalone script traverses the DOM for scripts with this attribute and replaces them with their transpiled equivalents.
Edit
A couple of changes to hello.jsx

*

*Remove the import statements
ReactDOM and React are globals in the context of window object.

*Replace
render(<App />, document.getElementById("root"));

with
ReactDOM.render(<App />, document.getElementById("root"));


text:
Q: Return object with specific attributes lets say i have an array of objects
var x = [{
   a:'asd',
     b:'ss'
},{
   a:'s',
     b:'f',
     c:'asd'
},{
  a:'tt',
    g:'f',
    b:'ulaN'
}];

and i want to return array of objects , with objects only having a and b attributes.
I solved this with
x = x.map( y => {
   return {
     a:y.a,
     b:y.b
     }
});

but it seems not quite efficent in my opinion , is there any better way how to do so?

A: You could certainly shorten this code by doing:
x = x.map( y => ({
  a: y.a,
  b: y.b
}));


text:
Q: N:M eager loading (include) using sequelizejs So I found myself into troubles trying to use the include eager loading feature in M:N relations
The user model relation:
User.belongsToMany(models.rol, {
      through: {
        model: models['usuario_rol']
      },
      as: {
        plural: 'roles',
        singular: 'rol'
      },
      foreignKey: 'idusuario'
});

The rol model relation:
Rol.belongsToMany(models.usuario, {
      through: {
        model: models['usuario_rol']
      },
      foreignKey: 'idrol'
});

Finally the query:
db.usuario.findOne({
    where: {
      id: insert.id
    },
    include: [
      {
        model: db.rol
      }
    ]
});

If we try this the it crashes with Error: rol is not associated to usuario!
The curious is that with an instance of the sequelize user object I can fetch the roles using user.getRoles()
Do you have any idea of why is this happening?

A: When you specify an alias in the association function (in this case roles) you have to pass that to the include as well:
return User.findOne({
  where: {
    id: 52
  },
  include: [
    {
      model: rol,
      as: 'roles'
    }
  ]
});

You can also save the association and pass that instead:
User.Roles = User.belongsToMany(models.rol, {
  through: {
    model: models['usuario_rol']
  },
  as: {
    plural: 'roles',
    singular: 'rol'
  },
  foreignKey: 'idusuario'
});

return User.findOne({
  where: {
    id: 52
  },
  include: [
    {
      association: User.Roles
    }
  ]
});


text:
Q: App crashes on button press 2.9 version of Genymotion but works on 2.8 I have two activities in my app Alarm, which works fine on both Genymotion 2.8 and Genymotion 2.9.
I also have a Media Player which works fine on 2.8 but crashes on 2.9 when I press the MediaPlayer button.
This is the screen of my Alarm activity:

This is the screen I get after I press the button on 2.9:
.
This is the logcat after i press the button on the phone:
09-01 16:12:06.451 31541-31541/com.never.mediaalarmplayer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.never.mediaalarmplayer, PID: 31541
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.never.mediaalarmplayer/com.never.mediaalarmplayer.MediaPlayer}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=31541, uid=10174 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
                                                                            at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                            at android.os.Looper.loop(Looper.java:203)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6251)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
                                                                         Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=31541, uid=10174 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.os.Parcel.readException(Parcel.java:1683)
                                                                            at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
                                                                            at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
                                                                            at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                                                                            at android.content.ContentResolver.query(ContentResolver.java:537)
                                                                            at android.content.ContentResolver.query(ContentResolver.java:479)
                                                                            at com.never.mediaalarmplayer.MediaPlayer.getSongList(MediaPlayer.java:138)
                                                                            at com.never.mediaalarmplayer.MediaPlayer.onCreate(MediaPlayer.java:41)
                                                                            at android.app.Activity.performCreate(Activity.java:6666)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
                                                                            at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                            at android.os.Looper.loop(Looper.java:203)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6251)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
I had the command for requesting permission inserted in the manifest already but maybe it needs something more:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.never.mediaalarmplayer">
android:versionCode = "1"
    android:versionName="1.0">
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:fullBackupContent="@xml/backup_descriptor">
        <activity android:name=".Alarm"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       <activity android:name=".MediaPlayer"
           android:launchMode="singleTop"
           android:screenOrientation="portrait"
           android:label="@string/app_name"
           />

        <service android:name="com.never.mediaalarmplayer.MusicService" />
        <receiver android:name=".AlarmReceiver"/>
    </application>

</manifest>

Logcat 2.9:
09-02 06:34:47.269 666-677/system_process I/ActivityManager: START u0 {cmp=com.never.mediaalarmplayer/.MediaPlayer} from uid 10060 on display 0
09-02 06:34:47.269 666-723/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 48000 Hz, output 44100 Hz
09-02 06:34:47.313 1148-1167/android.process.media E/DatabaseUtils: Writing exception to parcel
                                                                    java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2012, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                        at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
                                                                        at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
                                                                        at android.content.ContentProvider$Transport.query(ContentProvider.java:211)
                                                                        at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                                        at android.os.Binder.execTransact(Binder.java:507)
09-02 06:34:47.313 2012-2012/com.never.mediaalarmplayer D/AndroidRuntime: Shutting down VM
09-02 06:34:47.318 2012-2012/com.never.mediaalarmplayer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.never.mediaalarmplayer, PID: 2012
                                                                          java.lang.RuntimeException: Unable to start activity ComponentInfo{com.never.mediaalarmplayer/com.never.mediaalarmplayer.MediaPlayer}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2012, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                           Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2012, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                              at android.os.Parcel.readException(Parcel.java:1599)
                                                                              at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                                                                              at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
                                                                              at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                                                                              at android.content.ContentResolver.query(ContentResolver.java:491)
                                                                              at android.content.ContentResolver.query(ContentResolver.java:434)
                                                                              at com.never.mediaalarmplayer.MediaPlayer.getSongList(MediaPlayer.java:138)
                                                                              at com.never.mediaalarmplayer.MediaPlayer.onCreate(MediaPlayer.java:41)
                                                                              at android.app.Activity.performCreate(Activity.java:6237)
                                                                              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

It doesn't work on my phone either - I have Nokia 3 with Android 7.0.
Thank you for the answers!

A: According to this part of the  logcat:
EXCEPTION: main Process: com.never.mediaalarmplayer, PID: 31541 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.never.mediaalarmplayer/com.never.mediaalarmplayer.MediaPlayer}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=31541, uid=10174 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

Your application is trying to access external storage, so you must add the matching permission to your Android Manifest file. Look at https://developer.android.com/guide/topics/data/data-storage.html#filesExternal for more details.

A: READ_EXTERNAL_STORAGE is Runtime Permission since Android 6.0.
Adding the permission request in manifest is not enough. App should request permission in run time. If you don't want to do that, change  to 22 or less.
The reason of crash exist in Genymotion's implementation. IMHO(my guess), MediaProvider in Genymotion 2.8 does not access to external storage but 2.9 does.


text:
Q: Where xterm Escape sequences like "Esc | 112 m" are defined? While implementing xterm-256-colors in ConEmu I have discovered some unknown for me Escape sequences (used by Vim) like
Esc | 7 m
Esc | 15 m
Esc | 112 m

From Vim sources I realize that these codes are used for changing bold or inverse attributes, but I can't find any docs about them.
Are there any specifications for Esc | N m sequences? They were not mentioned here.

A: I believe these are internal vim codes for internal processing only: first set of \033| is labeled
/*
 * GUI pseudo term-cap.
 */

and AFAIR is processed in gui.c or gui_*.c, second set is labeled
/*
 * These codes are valid for the pc video.  The entries that start with ESC |
 * are translated into conio calls in os_msdos.c. Default for MSDOS.
 */

third set is labeled
/*
 * These codes are valid for the Win32 Console .  The entries that start with
 * ESC | are translated into console calls in os_win32.c.  The function keys
 * are also translated in os_win32.c.
 */

(I am talking about builtin_termcaps array). Further mentions: only in update_tcap function, there are no direct references that these are processed by some other function, but it is unlikely that it is something else (not familiar with pseudo-termcap processing code). Except for term.c it is only seen directly (i.e. grep finds \033|) in screen.c (twice) and gui.c (once).
And, by the way, I failed to see this code in output of vim launched in logging screen session using env TERM=xterm vim {args}.


text:
Q: Explicit formula for $e_k = 4e_{k-1} + 5$ The sequence looks like this:
$e_0 = 2$
$e_1 = 4(e_{1-1}) + 5 = 13$
$e_2 = 4(e_{2-1}) + 5 = 57$
$e_3 = 4(e_{3-1}) + 5 = 233$
$e_4 = 4(e_{4-1}) + 5 = 937$
How would I go about finding the explicit formula for this?  For something a little simpler it's fairly easy to make a guess, and I've been told that 'guessing' is exactly how one is supposed to find the formula.  However, I'm a little stumped on this.

A: A general approach to deal with recurring sequences of the form $$u_{n+1} = au_n +b$$

*

*if $a = 1$, it's an arithmetic progression.

*otherwise, let $r=\frac{b}{1-a}$. Consider $v_n = u_n -r$. we have
$$
v_{n+1} = u_{n+1} - r = au_n+b - r = a(v_n + r) + b - r = a v_n
$$
and $(v_n)_n$ is a geometric progression. You can then get the closed form for $v_n$, and $u_n = v_n + r$ will give you that of $u_n$.

A: Let $e_n=4^nu_n$, then
$$
4^{n}u_{n}=e_{n}=4e_{n-1}+5=4\cdot 4^{n-1}u_{n-1}+5=4^{n}u_{n-1}+5
$$
and thus
$$
u_{n}=u_{n-1}+\frac{5}{4^{n}}=\left(u_{n-2}+\frac{5}{4^{n-1}}\right)+\frac{5}{4^{n}}=\cdots=u_0+\frac{5}{4}+\frac{5}{4^2}+\cdots+\frac{5}{4^{n}} \\
=u_0+\frac{5}{4}\left(1+\frac{1}{4}+\cdots+\frac{1}{4^{n-1}}\right)=u_0+\frac{5}{4}\left(\frac{1-\frac{1}{4^{n}}}{1-\frac{1}{4}}\right)=u_0+\frac{5}{3}\left(1-\frac{1}{4^n}\right)
$$
and as $u_0=2$,
$$
e_n=4^nu_{n}=2+\frac{5}{3}( 4^n-1)
$$

A: $e_0 = 2$
$e_1 = 4e_0 + 5$
$e_2 = 4e_1 + 5=4^2e_0 + 4(5) + 5$
$e_3 = 4e_2 + 5=4^3e_0 + 4^2(5)+ 4^1(5) + 5= 4^3e_0+5(1 + 4^1 + 4^2 + 4^3)$
Now you should be able to guess that:
$e_k = 4^ke_0+5(1 + 4^1 + 4^2 + 4^3+...+4^{k-1})=4^ke_0 + \frac{5(4^k-1)}{3}$
and then you can prove that your "guess" is correct using induction.


text:
Q: Spring security , password with non-English characters like "š, č, ć, ž, đ" login failed I have Grails app with spring-security-core plugin. In my conf/spring/resources.groovy file I defined
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder
beans = {
    passwordEncoder(PlaintextPasswordEncoder)
}

so I can save plain text passwords in MySql DB like it was explained here Spring security no password encoding
in views/login/auth.gsp I also added in <head> block
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

and in Datasource.groovy
url = "jdbc:mysql://localhost:3306/blabla?useUnicode=true&characterEncoding=utf8"

I created User with username = ččč and password = ččč succesfully , but when I try to login with this user I get login error "Sorry, we were not able to find a user with that username and password." I checked database and user exists with those field values.
I tried to login with some other user that has username = admin , password = admin , and it works fine.
So I guess that it has something to do with j_username and j_password not accepting non-English characters ... How to enable login form fields to accept utf-8 character set?
I have:
Grails 1.3.7
Spring-Security-Core 1.2.6
STS 2.8.1
mysql-connector-java-5.1.18
Windows 7

A: First advice: don't use plaintext passwords. Second advice: check what SQL queries are sent to database. You need this in your Config.groovy to see Hibernate statements and its parameter values:
log4j = {
        debug 'org.hibernate.SQL'
        trace 'org.hibernate.type'
}


text:
Q: Why is dd reading from and writing to the same disk? I've been using dd in Linux to overwrite an external USB hard drive.
When I use the default block size of 512 bytes, with this command:
# dd if=/dev/zero of=/dev/sdb

throughout the whole operation, the hard drive (/dev/sdb) is being read from and written to alternately, approximately 1GB at a time. I.e. read 1GB...write 1GB...read 1GB...write 1GB etc. As much data is read from the hard drive as is written to it.
I know this is happening because it's showing in my custom Conky panel (diskio_read, diskio_write), which I know to be a 100% reliable indicator of disk I/O activity.
I've repeated this using a different external hard drive on a different computer. It happens via both USB 2.0 and USB 3.0.
In contrast, when I do the same thing, but use a block size of 1MB instead, with this command:
# dd if=/dev/zero of=/dev/sdb bs=1M

apart from a small amount of reading at the start, the hard drive is not read from at all during the operation.
Given that this phenomenon has happened on two different computers and two different hard drives of mine, using a standard Linux distro (Xubuntu 14.04), anyone who wants to should presumably be able to replicate it on their own computer.
Can someone please explain what is happening here?

A: If you specify a block size (512 bytes) of less than the block size of the disk (often 4096 bytes, but nowadays maybe more), the block will be partially written, so that the contents of the rest of the block must be preserved before writing.
This is because disk blocks cannot be written to with only 512 bytes, but you have to write a full block at once (4096 or larger). When you write this (4096) amount or more, there is no partial write, so it does not have to read.

A: This is basically a symptom of buffered I/O on a Linux system. A good overview of this in relation to the dd command is located at Is there a way to determine the optimal value for the bs parameter to dd? which supports ctrl-d's answer. However, this also suggests that even larger block sizes (i.e., greater than 1M) might improve performance further.


text:
Q: Mysql InnoDB table size performance I have a table that is closely approaching 2 million records.  This table stores a history of transactions.  This is on a high traffic website but also the table is not accessed regularly.  We currently have no slow queries due to this table, but am looking as to when I should expect to need to migrate data from this table to a data archival method.
The server is an amazon ec2 high cpu medium box.
High-CPU Medium Instance

1.7 GB of memory
5 EC2 Compute Units (2 virtual cores with 2.5 EC2 Compute Units each)
350 GB of instance storage
32-bit platform
I/O Performance: Moderate
API name: c1.medium

         Engine: InnoDB
        Version: 10
     Row_format: Compact
           Rows: 1677878
 Avg_row_length: 71
    Data_length: 120209408
Max_data_length: 0
   Index_length: 246497280
      Data_free: 0
 Auto_increment: 1914179
    Create_time: 2011-08-07 20:15:29
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options:
        Comment: InnoDB free: 7168 kB

Few questions:

*

*At which point might I start seeing performance degrade due to the
amount of records in this table?

*What settings should I be checking on the mysql server, via SHOW
INNODB STATUS and on the table itself(ie, row format) to ensure I am
maximizing performance as I need it?

*What metrics should I be gathering to calculate performance over
time?

A: So many questions!!  To your first point, you will probably start to notice performance problems if you start to cause full table scans or joins that create temp tables.  You can track this by looking at the EXPLAIN output for your queries.  Here is some info on EXPLAIN:
http://weevilgenius.net/2010/09/mysql-explain-reference/
For the settings, ideally it is great if you can fit your entire database in memory.  Here are the variables that are probably most helpful to tune:
innodb_buffer_pool_size=8192M
innodb_additional_mem_pool_size=512M
innodb_log_buffer_size=8M
innodb_flush_method = O_DIRECT
key_buffer_size=4096M
read_buffer_size=1M
read_rnd_buffer_size=10M
sort_buffer_size=1M
join_buffer_size=1M
tmp_table_size=32M

You'll want to make most of these as big as reasonable (you will want to research some of these as some are per connection and some are global).  You mentioned SHOW INNODB STATUS which is a great place to start, try looking at these fields:
--------
FILE I/O
--------
Pending normal aio reads: 0, aio writes: 0,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
28889 OS file reads, 52982178 OS file writes, 35063424 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 2.67 writes/s, 2.67 fsyncs/s

These should show you if you are bound by IO somewhere.  Then check:
----------------------
BUFFER POOL AND MEMORY
----------------------

Free buffers       342668

to make sure you have free buffers.
Regarding your last question of what to monitor, more is better.  I use OpenNMS to monitor our MySQL server performance.  Here are the things we currently trend/alert on drastic changes:
EventCount
Uptime
Bytes_received
Bytes_sent
Com_delete
Com_delete_multi
Com_insert
Com_insert_select
Com_select
Com_stmt_execute
Com_update
Com_update_multi
Created_tmp_disk_tables
Created_tmp_tables
key_buffer_size
key_cache_block_size
Key_blocks_unused
Key_read_requests
Key_reads
Key_write_requests
Key_writes
Open_files
Open_tables
table_open_cache
Questions
Slow_queries
Connections
Threads_created
Threads_cached
Threads_connected
Threads_running


text:
Q: system("pause") has "stopped" working I have been using the command system("pause") in Visual C++ 2008 and Visual C++ 2012 for many years. But recently when I was trying to use that command, it stopped working in both compilers. The recent activity that I did was installing Java with all the components.
What is the reason for this?  What can be done about this?

A: Don't use system("pause"): http://www.gidnetwork.com/b-61.html
Try cin.get() to get a keystroke.


text:
Q: Unity OnApplicationQuit() doesn't work on android all the time Android has been designed in a way that OnApplicationPause corresponds to onPause/onResume events of the activity.OnApplicationQuit corresponds to onDestroy event of activity lifecycle.
According to android docs, you are guaranteed to get a call back for onPause but anything after it may not be called. Therefore, you may not get a call to OnApplicationQuit if Android destroys the activity after onPause(Pre Honeycomb) or onStop.
Any idea how do I check if the application is being quit on android on Unity that works on all devices and all android versions

A: You need to act like OnPause will close the application! Waiting for OnApplicationQuit on Android will not let you act accordingly. Attach both methods OnPause and OnApplicationQuit as Quit or act as examples below:
If you are making a Single-Player game - just save all the content of the game just in case. If the activity will resume it all good, if not you have the backup.
If you are making a Multi-Player game - checking "Run in the Background" will let you keep a connection while the application is paused, but the user can kill your app anytime. I would make a coroutine and wait (around 30 seconds) and kill the connection. If you do not intend to make it work in the background, just kill the connection.
Quote from Android Developers on onDestroy() which is mapped to OnApplicationQuit if paused

onDestroy
Perform any final cleanup before an activity is destroyed.
This can happen either because the activity is finishing (someone
called finish() on it), or because the system is temporarily
destroying this instance of the activity to save space. You can
distinguish between these two scenarios with the isFinishing() method.
Note: do not count on this method being called as a place for saving
data! For example, if an activity is editing data in a content
provider, those edits should be committed in either onPause() or
onSaveInstanceState(Bundle), not here. This method is usually
implemented to free resources like threads that are associated with an
activity, so that a destroyed activity does not leave such things
around while the rest of its application is still running. There are
situations where the system will simply kill the activity's hosting
process without calling this method (or any others) in it, so it
should not be used to do things that are intended to remain around
after the process goes away.

A: You can use Application.quitting event to check if the application is quitting.
    static Example(){
        Application.quitting += Quit;
    }

    static void Quit(){
        Debug.Log("Quitting the Application");
    }

Or you can use OnApplicationQuit() method in this way:
    bool isApplicationQuitting = false;

    void OnApplicationQuit() {
        isApplicationQuitting = true;
    }

A: OnApplicationQuit is called when you explicitly call Application.Quit() which is usually done by either back button or an exit dialogue.
void Update ()
{
    if (Input.GetKeyDown(KeyCode.Escape)
    {
        Application.Quit();
    }
}

OnApplicationQuit  will not be called when user press Home button or task list button and closes your game afterward, a phone battery die or game crash. none of the above.
To do any operation on user exit, I recommend implementing OnFocus or OnPause which happens when user press home button or tasks list on android.
remember if user does tasks list and immediately close your game any write on disk operation will halt and results in unfinished and corrupted save file. and next time you load that file, it fails to read the stream and throws exception. you can prevent that by specifying a temporary name for your save file during the write operation and when it's finished replace the temporary file with the save file. an extra disk operation but a fail safe, or categorize your save file into chunks of data less than 10kb, by doing that no matter how fast user goes from task list button to close all button, there was enough time to write 10kb to disk.
other alternative to that is creating a service using this
or create another activity beside unity activity and set a process name for it too in AndroidManifest.xml

https://answers.unity.com/questions/780406/androidunity-launching-activity-from-unity-activit.html

void StartPackage(string package){
          AndroidJavaClass activityClass;
         AndroidJavaObject activity, packageManager;
          AndroidJavaObject launch;

          activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
          activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
          packageManager = activity.Call<AndroidJavaObject>("getPackageManager");
          launch = packageManager.Call<AndroidJavaObject>("getLaunchIntentForPackage",package);
          activity.Call("startActivity",launch);
     }

and in AndroidManifest.xml
<activity
   android:name=".YourActivity"
   android:process=".YourActivity" />


text:
Q: Block does not react to outside property change After some questions here I decided to run a server like this:
@implementation Server
-(id)init
{
if (self = [super init])
{
    shouldRun = true;
    __block Server* blocksafeSelf = self; // should prevent retain cycle

    myServer = ^() {
                    dispatch_async(dispatch_get_main_queue(), ^{
            NSString* currentText = controller.output.text;
            controller.outputTextField.text = [currentText stringByAppendingString:@"Server ready. \n"];
        });

        while (blocksafeSelf.shouldRun) {
           int bytes_received = recvfrom(...);
            if (bytes_received > 0) {
                switch (TYPE OF RECEIVED PACKET) {
                    case 1: {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSString* currentText = controller.outputTextField.text;
                            controller.outputTextField.text = [currentText stringByAppendingString:@"S: Received Typ 1 "];
                        });
                        [blocksafeSelf methodToDealWithPacket:(PACKETTYPE*) buffer];
                        break;
                    }
                    ...
                    default: {
                       ...
                    }
                }

            }
        }

return self;
}
@synthesize shouldRun;

the corresponding .h file:
@interface Server : NSObject {
    ServerBlock myServer;
    ....
}
@property BOOL shouldRun;
....
@end

Now I have a ViewController, which has the Server as a property and following method in its implementation:
// called when the user clicks the stop button
- (IBAction) clickedStop
{
    if(theServer != nil) {
        theServer.shouldRun = false;
    }
}

When I click the stop button however, the server does not exit his while loop. Why?
edit: Here is, how the server is started in the ViewController:
// called when the user clicks the start button
  - (IBAction) clickedStart
   {
   dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    if (...) { // all needed data has been entered
        // start server here
        if(theServer == nil) {
            theServer = [[SNPTServer alloc] initWithHost:serverIP.text AndPort:    [serverPort.text intValue] AndViewController:self];
            dispatch_async(queue, theServer.myServer);
        }
    }

}
As you see, I have altered the constructor above a bit.

A: My answer will only work if the body of your while loop looks similar to the following (I will assume it does)
while (blocksafeSelf.shouldRun) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                             beforeDate:[NSDate distantFuture]];
}

In this case, just setting shouldRun to NO is not enough. That while loop is running on a different thread/runLoop so an event must happen to cause the run loop to pop so that the condition is checked again.
The easiest way to do that is to set shouldRun to NO from the thread that server is running on. I would do something like this:
myServer = ^() {
    self.runThread = [NSThread currentThread]; // runThread declared elsewhere
    while (blocksafeSelf.shouldRun) {
          ....
        }
    }

And then when you want to cancel it do:
- (IBAction) clickedStop
{
    if ([NSThread currentThread] == theServer.runThread) {
        if(theServer != nil) {
            theServer.shouldRun = NO;
        }
    } else if (theServer.runThread) {
        [self performSelector:_cmd
                     onThread:theServer.runThread
                   withObject:nil
                waitUntilDone:NO];
    }
}


text:
Q: How to call the API in sequential order in Angular9 with rxjs? I am trying to call the API in sequential order and I will use the previous response for the next API call. And I will be having the N number of API calls, Lets consider below is my sample array I have,
data = [
    {
        api: '/api/allGeneTables/',
    },
    {
        api: '/api/tables/',
        fieldName: 'profiles', // I am using this for building api
        concatWithPrevField: true,
        prevField: 'positions' // I am using this for building api
    },
    {
        api: '/api/tables/superpositions',
        fieldName: 'identical', // I am using this for building api
        concatWithPrevField: true,
        prevField: 'length' // I am using this for building api
    }
]

First API will produce the data like this
https://myurl/api/allGeneTables/
API Response:
{
    'positions': 10,
    'index': 12,
    'name': 'triosephaspate'
}

I need to create the next api with the previous value (positions) along with given fieldName (profiles), so the the second api would be
https://myurl/api/tables/10/profiles
// 10 came from the previous response value (positions)
// profiles is one of field's value of the current array

API Response:
{
    'lipidprofile': 15,
    'maxvalue': 12,
    'name': 'triosephaspate',
    'length':232
}

similar way I need to create the next API.
https://myurl/api/tables/superpositions/232/identical
// 232 came from the previous response value (length)
// identical is one of field's value of the current array

I have tried with the map operator and following is my code
from(data).pipe(map(res => {
  const eachObj: any = res;
  let urlConcat = '';
  console.log(res);
  if (eachObj.concatWithPrevField) {
    // urlConcat = eachObj.api + ;
  } else {
    urlConcat = eachObj.api;
  }
  return this.dhs.getGeneData(urlConcat).subscribe();
})).subscribe();

I stuck at, how to join the previous API response value with the current data to make the API URL so I can call the next API. I am trying this with the RXJS methods.

A: In general, to use results from one request to form and execute another request, you can chain them together using switchMap:
function httpCall_1(id) { ... }
function httpCall_2(id) { ... }
function httpCall_3(id) { ... }

myFinalData$ = httpCall_1('abc').pipe(
  switchMap(resp1 => httpCall_2(resp1.id)),
  switchMap(resp2 => httpCall_3(resp2.id))
);

If calls further down the chain need access to prior responses, you can nest like this:
function httpCall_1(id) { ... }
function httpCall_2(id) { ... }
function httpCall_3(id1, id2) { ... }

myFinalData$ = httpCall_1('abc').pipe(
  switchMap(resp1 => httpCall_2(resp1.id).pipe(
    switchMap(resp2 => httpCall_3(resp1.id, resp2.id))
  ))
);

A: You could use the expand operator for this type of operation. expand recursively calls the provided function
I will give a simple example and you can do the rest:
const data = [{ id: 1 }, { id: 2 }];
const source = from(data);
source
  .pipe(
    //recursively call supplied function
    expand((val, i) => {
      console.log(`Passed value: `, val, i);
      // prepare your next value here
      return of(data[i+1]);
    }),
    //call N times (data.length)
    take(data.length)
  )
  .subscribe(val => console.log(`RESULT: `, val));

stackblitz to play around: https://stackblitz.com/edit/typescript-kfkrga?file=index.ts&devtoolsheight=100

A: *

*Store the result from an API-call in a function scoped variable (last_result).

*Use concatMap to wait for the API calls being completed before the next one is initiated and use the new value in last_result.

*Use reduce to complete the observable stream and emit the latest API-response (last_result).

Stackblitz: https://stackblitz.com/edit/rxjs-v5pg4n?file=index.ts
import { from, interval } from "rxjs";
import { concatMap, map, reduce, take } from "rxjs/operators";

const data_source = [
  {
    api: "/api/allGeneTables/"
  },
  {
    api: "/api/tables/",
    fieldName: "profiles", // I am using this for building api
    concatWithPrevField: true,
    prevField: "positions" // I am using this for building api
  },
  {
    api: "/api/tables/superpositions/",
    fieldName: "identical", // I am using this for building api
    concatWithPrevField: true,
    prevField: "length" // I am using this for building api
  }
];

call_sequence(data_source).subscribe(console.log);

function call_sequence(data) {
  let last_result = null;
  return from(data).pipe(
    // concatmap awaits finishing of request ( last_result is being set and emits the API response)
    concatMap(fake_fetch),
    // reduce only emit last result from the stream
    reduce(() => last_result)
  );

  function fake_fetch(data) {
    let endpoint = data.api;
    if (data.concatWithPrevField) {
      endpoint = endpoint.concat(`${last_result[data.prevField]}`);
      endpoint = endpoint.concat(`/${data.fieldName}`);
    }
    return fake_API_call(endpoint).pipe(
      map(data => {
        last_result = data;
        return data;
      })
    );
  }
}

function fake_API_call(endpoint) {
  console.log(`making API call to ${endpoint}`);
  return interval(1000).pipe(
    take(1),
    map(data => {
      switch (endpoint) {
        case "/api/allGeneTables/":
          return {
            positions: 10,
            index: 12,
            name: "triosephaspate"
          };
        case "/api/tables/10/profiles":
          return {
            lipidprofile: 15,
            maxvalue: 12,
            name: "triosephaspate",
            length: 232
          };
        case "/api/tables/superpositions/232/identical":
          return "Hurray, I am the final result";
        default:
          console.error("This endpoint doesn't exist");
      }
    })
  );
}

A: You should go with recursion in order to make this work for N number (not to hardcode things...).
Easier to understand is to do this with Promises:

// Array of apis
const data: Array<{ api: string, fieldName?: string, concatWithPrevField?: boolean, prevField?: string }> = [];

// Create api call (convert it to a promise)
const createApiCall = (url) => {
    return this.dhs.getGeneData(url).toPromise();
};

const overall = data.reduce((prevCall, nextAPI) => {

    return prevCall.then((prevResult) => {
        let url = nextAPI.api;
        if (nextAPI.concatWithPrevField) {
            url += `${prevResult[nextAPI.prevField]}/${nextAPI.fieldName}`
        }

        return createApiCall(url);
    });

}, Promise.resolve());

// Subscribe to start...
overall.then(() => {

});

Ofc same can be done wih Observaables (with same approach or expand operator)


text:
Q: how to replace full part of the input from the user How can I change part of the input in Python? for example, if the user writes down: "I like to eat hot food" or "I want to eat junk food" etc, all the parts "eat... food", no matter what there is between them, will change into "running" so the output became "I like to running", "I want to running".
Thank you.
Edit: this is my first post so I still learning. try again:
in the meantime I have this:
  def eat_food(s):
        if "eat" and "food" in s:
            return s.replace( ? , "running")
        else:
            return s

what I need is this:
 input ("I want to eat junk food")
    output = "I want to running"
    or
    input ("I like to eat hot food")
    output = "I like to running"

hope now it's more clear

A: For a task like this you need to use a "regular expression".
It lets you define a template like "everything between words eat and food" and then search the text for that template.
To start, import the regular expression module in to your program:
import re

In regular expression '.' (dot) means match every letter, and '*' (asterisk) means match zero or more times.
So, you want a regex like this: 'eat.*food' which means match "eat" then zero or more of any character, than "food".
To replace what you found use the function sub from the re module:
def eat_food(s):
    return re.sub('eat.*food', 'running', s)

answer = input('What do you like?')

print(eat_food(answer))

Some things to note:

*

*String in Python are immutable - meaning you sub will return a new string with the replacement, not change your existing one.

*If the user inputs "I like to ..." you should replace it with "run" not "running" for correct English grammar.


text:
Q: Get brief help for a set of functions When we are in console mode or working with a notebook we can get brief help about a function just by shift-entering
?function
I would like to have a list like the following
{Map, Function, List, Transpose, Outer, Sequence, Apply, Tuples, \
Distribute, Thread, Equal, Fold, Slot, Reverse, Plus, Times, Total, \
MapThread, Inner, ReplaceAll, Rule, Composition, Through, Nest, \
ToExpression, ToString, Row, Part, Range, ComposeList, Compose, \
SlotSequence, Flatten, FoldList, NestList, Hold, Release}

and get a list of strings containing the corresponding help(s).
? cannot be mapped to a list of course so i am trying to find another way.
? works with Wildcards like ?*Plot* so i suppose it accepts some kind of pattern matching.
Any ideas ?

A: You can map ?. Just turn off its LongForm form -- like this:
Information[#, LongForm -> False] & /@ {Map, Function}

Update
The OP has asked why
cl::usage = "blabla"; cl := {1, 2, 3}^2;
Information[#, LongForm -> False]& /@ {cl}

Information::ssym: {1,4,9} is not a symbol or a valid string pattern. >>

produces the error message shown. The message is pretty clear. Information has attribute HoldAll and wants a symbol or a string as its argument. But the message shows  cl got evaluated before Information saw it. Here are two ways to avoid this problem.
Information[#, LongForm -> False]& /@ {Unevaluated @ cl};
Information[cl, LongForm -> False]

both of which produce

as does
?cl
which is equivalent to Information[cl, LongForm -> False].

A: Is this what you are after?
#::usage & /@ {Map, Scan}

{Map[f,expr] or f/@expr applies f to each element on the first level in expr.
Map[f,expr,levelspec] applies f to parts of expr specified by levelspec.,
Scan[f,expr] evaluates f applied to each element of expr in turn.
Scan[f,expr,levelspec] applies f to parts of expr specified by levelspec. }


text:
Q: Nvidia Nightmare I have an old AMD64 box that was working quite nicely on in 12.04 LTS with onboard Nvidia GeForce 6150SE nForce 430 chip but ONLY running Nvidia 302.7 which I learned the HARD way after trying just about every other driver. My son gave me an Nvidia GeForce 8800GTS card and my nightmare began.
To make a VERY long story short, the new to me graphics card ran just fine in the XP part of the dual-boot but Linux was Hell. Finally I gave up and "upgraded" to Ubuntu 14.04 LTS in an effort to fix the problem. I'm about sixty hours in and removed the 8800GTS card. I just want my system to work again. Nouveau graphics so slow they look like they are in another time zone. Move the mouse, go get a cup of coffee, and when I come back, I see the cursor move. I know that sudo sh NVIDIA-Linux-x86_64-302.07.run has fixed my graphics problems in the past. However, I get the error that [...]/version.h does not exist, most likely reason is that source files in /lib/modules/3.13.0-32-generic/build have not been configured. HOW do I get them configured?
Yes, I have updated, upgraded, installed linux linux-headers-generic ubuntu-minimal ubuntu-standard ubuntu-desktop and linux-generic all without having a version.h file appear. And yes, I wiped my drive and made a fresh install of 14.04 after removing the 8800 card because the gui was horribly broken.
Can anyone offer help getting my box to work with just the onboard graphics? I do not care about the 8800 card. I am pretty sure if I can JUST install nvidia 302.7 that my life will return to the halcyon days of 12.04, but in 14.04. Thank you.

A: Reinstalling Ubuntu 12.04.1 was the only solution to get a copy of version.h, but planting it in Ubuntu 14.04 did not help. Eventually I realized that within 14.04 I could load the oldest available driver in Ubuntu, Nvidia 173.14.39, with only one problem. Coming out of hibernate the entire screen is too distorted to read.
That can be fixed with unity --replace & which repaints the entire display screen.
So I edited ~/.bash_aliases to add an alias I called "fixit."
alias fixit 'unity --replace &'

When you wake from hibernation and cannot read anything, hit Ctrl+Alt+T to open a terminal. Type fixit and hit Enter. You do not have to be able to read to do this. The screen blinks and everything is rewritten perfectly legibly. Then close the terminal window that you opened a moment ago.
Note: If I knew where to add the unity --replace command so that it runs every time the box wakes up from hibernation, I would put it there so that it works automatically.


text:
Q: How do I preserve escaped character values when using XSLT? I am using XSLT to remove unnecessary attributes from some nodes in a file. Nodes which should not be transformed use the following simple template:
<!-- Copy everything else over -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

However, I have found that some nodes are loosing escaped characters contained in their attribute values.
For example, this input:
<field value="Lei Complementar No. 116/2003, Art. 6, § 2º, I."/>

end up looking like this:
<field value="Lei Complementar No. 116/2003, Art. 6, § 2º, I."/>

How can I prevent this unwanted transformation?

A: I. XSLT 1.0 solution:
Just add this attribute to xsl:output:
encoding="us-ascii"

This causes any non-ascii character to be rendered with its character code.
However, you may still get different outputs, such as:
<field value="Lei Complementar No. 116/2003, Art. 6, § 2º, I."/>

and
<field value="Lei Complementar No. 116/2003, Art. 6, § 2º, I." />

And, of course, all of these three are just different represenatations of the same string of (unicode) characters.
II. XSLT 2.0 solution:
This uses the <xsl:character-map> instruction and must always produce the same output:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes"
   indent="yes" use-character-maps="chmEscapes"/>

 <xsl:character-map name="chmEscapes">
  <xsl:output-character character="§"
                        string="&#167"/>
  <xsl:output-character character="º"
                        string="&#186"/>
 </xsl:character-map>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<field value="Lei Complementar No. 116/2003, Art. 6, § 2º, I."/>

the wanted, correct result is produced:
<field value="Lei Complementar No. 116/2003, Art. 6, &#167 2&#186, I."/>


text:
Q: Remove the Parent Element without removing the childs-DOM Have to convert my raw XML to desired XML which will be understood by my application.
Using DOM(take it as a restriction) and unfortunately i can only use Java,DOM.Have tried XSLT but unfortunately not allowed to use it.
Input:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ns0:EMessage xmlns:ns0="http://www.abc/Something">
        <ns0:Header>
        <ns0:Snumber>1613</ns0:Snumber>
        </ns0:Header>
        <ns0:Name>SomeEvent</ns0:Name>
        <ns0:NameSpace>http://www.abc/Something.xsd</ns0:NameSpace>
        <ns0:Id>3</ns0:Id>
        <ns0:myProperty>
          <ns0:Name>ExtId</ns0:Name>
          <ns0:Value>TEST_ID_12</ns0:Value>
        </ns0:myProperty>
        <ns0:myProperty>
          <ns0:Name>CVersion</ns0:Name>
          <ns0:Value>0</ns0:Value>
        </ns0:myProperty>
        </ns0:EMessage>

Till now with my trials and google i have reached here.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ns0:EMessage xmlns:ns0="http://www.abc/Something">
<ns0:Header>
<ns0:Snumber>1613</ns0:Snumber>
</ns0:Header>
<ns0:Name>SomeEvent</ns0:Name>
<ns0:NameSpace>http://www.abc/Something.xsd</ns0:NameSpace>
<ns0:Id>3</ns0:Id>
<ns0:eventProperty>
    <ExtId>TEST_ID_12</ExtId>
  </ns0:eventProperty>
  <ns0:eventProperty>
    <CVersion>0</CVersion>
  </ns0:eventProperty>
</ns0:EMessage>

In my above code i have taken root as <ns0:EMessage> element and taken all the nodes as list node.Converted the element to desired form by creating a new element with values pulled from the input raw XML.But as i have taken </ns0:eventProperty> as the parent.I do not need this element,So basically i need to remove this parent node and the child to this parent should become the immideate child of <ns0:EMessage>.I do not need to touch other elements.
Desired OUTPUT
 <?xml version="1.0" encoding="UTF-8" standalone="no"?><ns0:EMessage xmlns:ns0="http://www.abc/Something">
    <ns0:Header>
    <ns0:Snumber>161003</ns0:Snumber>
    </ns0:Header>
    <ns0:Name>SomeEvent</ns0:Name>
    <ns0:NameSpace>http://www.abc/Something.xsd</ns0:NameSpace>
    <ns0:Id>3</ns0:Id>
     <ExtId>TEST_ID_12</ExtId>
     <CVersion>0</CVersion>
    </ns0:EMessage>

Have tried my best.Hope SO helps now.Thanks in Advance

A: It's strange to asnwer my own question.But finally i got the logic and answer for this.
Inspite of adding the elements to the <ns0:eventProperty> parent,should add the newly created element directly to the root which is <ns0:EMessage>.
NOTE::This whole process will be done in one loop.Use the Current Parent and using the data create immideate child to root by doing root.appendChild(newChildElement) and then in the same loop which will be running for all the child elements put the removing current parent logic in END.So that once your new elements got created just remove off the current parent.


text:
Q: Arab NVARCHAR variable is nor working properly on T-SQL I tried to put some Arab text into an nvarcahr column but it didn't work.
I know that using a simple text works, but when I try to use a variable it writes '??? ??' in database.
Does anyone know how to fix it using a variable?
Just the last insert is working properly
create table #test
(
name1 nvarchar(max)
)

declare @name nvarchar(max) = 'اسم اللقب'
insert into #test values(@name)

insert into #test values(N''+ @name)

insert into #test values('اسم اللقب')

insert into #test values(N'اسم اللقب')

select * from #test

Result:

name1

??? ?????

??? ?????

??? ?????

اسم اللقب


text:
Q: c# System.Windows.Media.MediaPlayer I don't have available the class System.Windows.Media.MediaPlayer.
What I have to do to add System.Windows.Media.MediaPlayer?
I have System.Windows.Media but i don't have available MediaPlayer method.
There is another way to add a clãss that read mp3 ou wmv sounds?

A: You can find this class in PresentationCore.dll assembly.


text:
Q: Get the last redirected url in iOS 5? Can someone please post the simplest of working code that can get the last redirected url(nth) when I GET request a url?
I know I need to use asynchronous requests but I am not able to work out a complete working code that solves the problem.
I am using ios5 so I can use the latest added asynchronous inbuilt functionalities in ios5.
I have tried a lot of things but I am not successful still. Using the below code I am trying to send a get request with parameters but somehow those parameters are getting lost due to site's redirection :(!
NSURLRequest *request = [NSURLRequest requestWithURL:urlOriginal];

[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
    NSLog("the returned data should be the final data of the redirected url with parameters but it is not");
}];

}

EDIT
So this is what I have done now :
NSURLRequest *requestOriginal = [NSURLRequest requestWithURL:urlOriginal];

 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:requestOriginal delegate:self];

[connection start];

and delegate :
-(NSURLRequest *)connection:(NSURLConnection *)connection
        willSendRequest:(NSURLRequest *)request
       redirectResponse:(NSURLResponse *)redirectResponse
{

    if (redirectResponse) {
    NSMutableURLRequest *r = [request mutableCopy]; // original request
    [r setURL: [request URL]];
    return r;
} else {
     NSLog(@"redirecting to : %@", [request URL]);
    return request;
}
}

and the log gives me the correct request url that i need along with the originally passed get parameters.
Now how to I get the data from this request? Another completionHandler delegate method?
edit2 :
Ok so I implemented the other delgates as well :

*

*(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

*(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

*(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

*(void)connectionDidFinishLoading:(NSURLConnection *)connection

A: Please read Handling Redirects and Other Request Changes in the documentation. Briefly, you'll want to a) provide a delegate for your connection, and b) implement the method connection:willSendRequest:redirectResponse: in said delegate. I don't understand exactly what you're trying to do in your question -- do you just want the data from URL to which your connection is redirected, or do you want to see the redirected request? Either way, implementing the method above should help. Your delegate will be able to see the redirected request, and returning it unchanged should cause the connection to load the new URL.

A: We can achieve this with NSMutableURLRequest.
I had followed these steps, it's working fine for me. Go through with below mentioned Link.
URL: Click here: Get the final redirected url
P.S: Let me know if you need further help.


text:
Q: XML Schema, One of each child element? I want to define a schema that allows child elements to occur in any order, similar to <choice minOccurs="0" maxOccurs="unbounded"> but will allow only one of each element, similar to <sequence minOccurs="1" maxOccurs="1">
can this be done?
for example
<Root>
 <ele1>
 <ele3>
 <ele2>
</Root>    <!--Valid-->

And as below:
<Root>
 <ele1>
 <ele1>
 <ele3>
</Root> <!--Invalid-->

A: You can add maxOccurs="1" to the element.

A: Use xs:all rather than xs:sequence, so you'd write:
<xs:element name="Root">
    <xs:complexType>
            <xs:all>
                <xs:element name="element1"/>
                <xs:element name="element2"/>
                <xs:element name="element3"/>
            </xs:all>
    </xs:complexType>
</xs:element>


text: Q: I want to push information to a running AngularJS page What I'm trying to do is have a webpage running on a rasberrypi and display that is showing a photo, a name, a title, and a current status. I already have the page running and can change those files in a local file that, when saved, does update the page without having to refresh it. However, I want to be able to change one or all of those items from a remote computer by pushing a file to my pi and without having to reload the page. I'm using angularJS and node.js in this project. Any advice?


text:
Q: Making aluminium conductive for an RF shield enclosure I'm not sure if it's appropriate to ask here, but I would assume many people in electronics would have experience with this.
I'm enclosing an RF sensitive PCB into an sealed aluminium enclosure. Aluminum is chosen because it is lightweight for shipping, and also a good thermal conductor which is required as the enclosure acts as the heatsink.
The big concern however, is that the circuit needs to be grounded to the aluminium enclosure for proper shielding. If the enclosure is not conductive and low impedance GNDed to the PCB then there are problems with internal noise generation from switching circuits being transferred to RF sensitive parts of the circuit.
The PCB slides into a railing and the edges of the PCB have exposed GND rails. Aluminum is not conductive on the surface due to its oxidization effects, and I have no way of applying some sort of pressure or screw to the enclsoure to force conductivity through the oxide layer.
What can be changed however it the coating on the aluminium. From doing research it looks like the coating I require is nickel plating, or tin plating. I've also looked into RoHs safe class 3 chromate conversion, but even this writes that some contact pressure is needed for conduction. Tin plated steel may be an alternative, but is a poor thermal conductor and is much heavier.
Does anyone have experience with conductive aluminum for RF shielded enclosures? What is commonly used? Does tin or nickel plating aluminum cost a lot more?
EDIT: Added an example image of the enclosure and PCB.

A: If I need to ensure good contact to a housing, regardless of the metal it is made of, I use EMI-fingers or collars where possible.
You can get them made to almost any spec, from cheap tin plated to 3μm paladium-gold finish.
Here are a few examples:
Weird little spring-finger that might be slotted in
A type of EMI-Gasket/collar
And another EMI-Gasket
A wrap around EMI-Finger, that gets mounted on the lower flange and then presses down onto the board after wrapping around it
Those beat out any, and I mean any solid metal object with any kind of finish, because rails and other such do not apply any force. Try it at home: Get a nice clean metal surface (copper, steel, whatever), apply a voltage and then measure that voltage, preferably with a light load, like a 1k resistor, while softly laying a contact on that plate. Then apply a tiny bit of pressure. Note the difference in the measurement accuracy.
Contact resistance is directly proportional to the amount of pressure applied.

That said, I agree with Andy's comment that if you need good contact to the housing to eliminate noise that comes from your own PCB! there's something very wrong in the design.
It sounds more like you require the casing to be a ground plane, than an actual shield.
Good use of ground planes and stitching vias and though through layout of noisy and noise sensitive areas should take care of all of that, even if the board is dangling in free space. The reason to need reliable contact between housing and board ground is noise from the outside, not noise from the inside. The latter being one that requires much fewer connection points. (usually one global connect and one accompanying any sensitive signal, through coaxial wire for example)


text:
Q: Set Focus outline on containing label on checkbox When tabbing through a list of checkboxes I want to see the outline of a checkbox around the whole label. The code I have just puts the outline on the input itself:

    <input class="b-input" name="Hello" type="checkbox" value="Hello">

    Hello12

Codepen: https://codepen.io/anon/pen/gyeGZG
The idea is to make the checkboxes as accessible as possible for keyboard users etc.
Cheers

A: You don't need JS to do this, CSS can manage it.

:focus-within
The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.)
MDN
Support is non-IE/Edge, although the latter may change when Edge switches to Chromium-based

body {
  text-align: center;
}

.b-label {
  margin:1em;
  display: inline-block;
  padding:.25em;
}

.b-label:focus-within {
  outline :1px solid red;
}

    <input class="b-input" name="Hello" type="checkbox" value="Hello">

    Hello1

    <input class="b-input" name="Hello" type="checkbox" value="Hello">

    Hello2

    <input class="b-input" name="Hello" type="checkbox" value="Hello">

    Hello3


text:
Q: How to get debugging statements for Android in Eclipse I've read the lame documentation, and checked other answers.  I'd like my Android app to print some debug statements in the logcat window of Eclispe.  If I use the isLoggable method on the various types of debug levels on the Log class, I find that WARN and INFO are returning true.
Log.w, and Log.i do not produce any output.  Does anyone know which gotchas I've missed?
And just to vent, why should this be hard?  I've published apps for iphone and bberry and while appreciate the use of java, the platform is reeking of too many "genuiuses" being involved.  I suppose Activities and Intents are very flexible, but why?  I just want to put up some screens, take some input and show some results.  The bberry pushscreen and popscreen is a lot less pretentious.
Thanks,
Gerry

A: The problem with debugging with Android in Eclipse is that from Eclipse's point of view, you're debugging the emulator and not your specific app. The emulator isn't crashing, so there aren't any logs to show. What you need to use is LogCat, Android's debugging plug-in. See this answer for details on how to bring that up.

A: It is not clear to me what the problem is. I use "Log.d(TAG, "special message");" all the time in Eclipse in Android code running in the emulator. Since you say "Log.w" gives no output, I assume you already know about the need to import android.util.Log. Otherwise you would not have got even that far.
The only other thing I can think of is for you to check your Eclipse Preferences under Window>Preferences>Android>DDMS (DDMS is needed for Logcat). Make sure the timeout is reasonable (mine defaulted to 5000mS). Make sure the base local debugger port is open, too.


text:
Q: Making a swipe transition infinite in both direction I have a mobile website and would like to be able to swipe left and right to transition between pages, but in an infinite loop. When a left swipe occurs on the first page, the last page should be displayed, and when a right swipe occurs on the last page, the first page should be displayed.
How can I achieve this effect? Here is my jsfiddle link.

var oUl = document.getElementById('test');
var aLi = oUl.getElementsByTagName('li');

var sX = 0;
var sLeft = 0;
var index = 0;
var curLeft = 0;
var disX = 0;

oUl.addEventListener('touchstart', touchstart, false);

function touchstart(e) {
    e.preventDefault();
    sX = e.changedTouches[0].pageX;

    sLeft = oUl.style.transform ? -parseInt(/\d+/.exec(oUl.style.transform)[0]) : 0;
    oUl.style.transition = 'none';

    document.addEventListener('touchmove', touchmove, false);
    document.addEventListener('touchend', touchend, false);
}

function touchmove(e) {
    disX = e.changedTouches[0].pageX - sX;
    curLeft = sLeft + disX;
    oUl.style.transform = 'translateX(' + curLeft + 'px)';
}

function touchend(e) {
     if (disX > 100) {
        if (index != 0) {
            index -= 1;
        }
    }
    if (disX < -100) {
        if (index != aLi.length - 1) {
            index += 1;
        }
    }
    oUl.style.transition = '.5s';
    oUl.style.transform = 'translateX(' + -index*aLi[0].offsetWidth + 'px)';
}
body { margin: 0; }
.box { width: 100%; overflow: hidden; }
ul,li { margin: 0; padding: 0; list-style: none; }
ul { width: 500%; overflow: hidden; transition: .5s; }
li { width: 20%; float: left; }
li { font-size: 40px; color: #fff; text-align: center; line-height: 150px; }
li:nth-of-type(1) { background: orange; }
li:nth-of-type(2) { background: red; }
li:nth-of-type(3) { background: pink; }
li:nth-of-type(4) { background: green; }
li:nth-of-type(5) { background: #333; }

1

2

3

4

5

A: I would try to "swipe" the content between the first and last "li"
Something like this:
$('.box li:first-child').html( $('.box li:last-child') )

I don't know if it could work in your project. Good luck :)


text:
Q: Why .NET 4.8 is recommended version despite 4.8.1 latest version available Looking at the available .NET Frameworks, 4.8.1 is the latest. However 4.8 is recommended by Microsoft here. I am curious why is that. Is 4.8.1 in beta or something? I couldn't find any information about that.

A: 4.8.1 is not supported on older windows version but 4.8 is supported. (strange decision for a minor version like this)
(even windows 10 is only supported from specific build 20H2)


text:
Q: How to put a property class as a variable in php? So hi, I'm actually a very very beginner and i'd like to know how to set a property that is in a class as a variable to do condition?
class Utilisateur
{
public $mdp, $nom;
   function mot($mdp)
   {
     if (strlen($mdp)<=8)
     {
      echo "Votre mot de passe n'est pas fort. ";
     }
   }
}

So the property i want to set as a variable is $mdp, but i'm not sure if i can really do this.
Thanks for your future replies.

A: What you might typically do would be to assign the variables as parameters to the class constructor and define them as properties within the class - allowing access afterwards using $this->var style syntax
class Utilisateur{
    public $mdp;
    public $nom;

    public function __construct($mdp=false,$nom=false){
        $this->mdp=$mdp;
        $this->nom=$nom;
    }

    function mot(){
        if ( strlen( $this->mdp ) <= 8 ) {
            echo "Votre mot de passe n'est pas fort.";
        }
    }
}

$obj=new Utilisateur('banana','fred');
$obj->mot();


text:
Q: How would you calculate a derivative of $ f(x)= \frac{\sqrt{x+1}}{2-x}$ by the limit definition? I have a function defined as follows:
$$
f(x)= \frac{\sqrt{x+1}}{2-x}
$$
I tried to calculate the derivative using the limit definition using four methods, but I was unsuccessful in any. Could someone help me calculate it and explain the method?
$$
1) \lim_{h\to 0} =\frac{\frac{\sqrt{(x+h)+1}}{2-(x+h)}-\frac{\sqrt{x+1}}{2-x}}h
$$
$$
2)\lim_{z\to x} =\frac{\frac{\sqrt{z+1}}{2-z}-\frac{\sqrt{x+1}}{2-x}}{z-x}
$$
$$
3)\;f(x)= \frac{\sqrt{x+1}}{2-x}; u=\sqrt{x+1}
$$
$$
\lim_{h\to 0} =\frac{\frac{u+h}{3-(u+h)^2}-\frac{u}{3-u^2}}h
$$
$$
4)\;f(x)= \frac{\sqrt{x+1}}{2-x}; u={x+1};
$$
$$
\lim_{h\to 0} =\frac{\frac{\sqrt{u+h}}{3-(u+h)}-\frac {\sqrt{u}}{3-u}}h
$$

A: Note that we have
$$\begin{align}
\frac{\sqrt{x+1+h}}{2-x-h}-\frac{\sqrt{x+1}}{2-x}&=\frac{\sqrt{x+1+h}-\sqrt{x+1}}{2-x-h}+\frac{h\sqrt{x+1}}{(2-x-h)(2-x)}\\\\
&=\frac{h}{(2-x-h)(\sqrt{x+1+h}+\sqrt{x+1})}+\frac{h\sqrt{x+1}}{(2-x-h)(2-x)}\\\\
\end{align}$$
Now divide by $h$ and let $h\to 0$ to find
$$\frac{d}{dx}\left(\frac{\sqrt{x+1}}{2-x}\right)=\frac{1}{2(2-x)\sqrt{x+1}}+\frac{\sqrt{x+1}}{(2-x)^2}$$

A: We have that
$$\frac{\frac{\sqrt{(x+h)+1}}{2-(x+h)}-\frac{\sqrt{x+1}}{2-x}}h=\frac{\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}-\frac{\sqrt{x+1}}{2-x}\right)\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)}{h\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)}=$$
$$=\frac{\frac{(x+h)+1}{(2-(x+h))^2}-\frac{x+1}{(2-x)^2}}{h\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)}=\frac{\frac{((x+h)+1)(2-x)^2-(x+1)(2-(x+h))^2}{(2-(x+h))^2(2-x)^2}}{h\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)}=\ldots$$
and since (the cancellation in red is the crucial step)
$$((x+h)+1)(2-x)^2-(x+1)(2-(x+h))^2=$$
$$=\color{red}{(x+1)(2-x)^2}+h(2-x)^2\color{red}{-(x+1)(2-x)^2}+2h(x+1)(2-x)-h^2(x+1)=$$
$$=h(2-x)^2+2h(x+1)(2-x)-h^2(x+1)$$
we obtain
$$\ldots=\frac{\frac{h(2-x)^2+4h(x+1)(2-x)+h^2(x+1)}{(2-(x+h))^2(2-x)^2}}{h\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)}=\frac{(2-x)^2+2(x+1)(2-x)-h(x+1)}{\left(\frac{\sqrt{(x+h)+1}}{2-(x+h)}+\frac{\sqrt{x+1}}{2-x}\right)\left((2-(x+h))^2(2-x)^2\right)}\to$$
$$\to \frac{(2-x)^2+2(x+1)(2-x)}{\left(\frac{\sqrt{x+1}}{2-x}+\frac{\sqrt{x+1}}{2-x}\right)(2-x)^4}=\frac{(2-x)+2(x+1)}{2\sqrt{x+1}(x-2)^2}=\frac{x+4}{2\sqrt{x+1}(x-2)^2}$$

A: Taking the first definition :
$$\lim_{h\to 0} \frac{\frac{\sqrt{(x+h)+1}}{2-(x+h)}-\frac{\sqrt{x+1}}{2-x}}h  = \lim_{h\to 0} \frac{\sqrt{(x+h)+1}(2-x)-\sqrt{x+1}(2-(x+h))}{(2-(x+h))(2-x)h}$$$$=
\lim_{h\to 0} \frac{(x+h+1)(2-x)^2-(x+1)(2-x-h)^2}{(2-x-h)(2-x)h( \sqrt{(x+h)+1}(2-x)+\sqrt{x+1}(2-(x+h)) )} $$
$$= \lim_{h\to 0} \frac{h^2(-x-1)+h(-x^2-2x+8)}{(2-x-h)(2-x)h( \sqrt{(x+h)+1}(2-x)+\sqrt{x+1}(2-(x+h)) )} $$ $$= \frac{-x^2-2x+8}{(2-x)^2\cdot(2\sqrt{x+1}(2-x))}=-\frac{x+4}{2(2-x)^2\sqrt{x+1}}
$$
Too heavy calculations though, don't use the definition for such derivatives.


text:
Q: Magento 2 JS Merge Undeifned Varaible Issue I have defined admin form field dependency in my uicomponent form
<field name="redirect_in">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Namespace\Modulename\Model\Config\Source\Options</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">int</item>
            <item name="label" xsi:type="string" translate="true">Store Info</item>
            <item name="component" xsi:type="string">Namespace_Modulename/js/form/element/options</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_in</item>
            <item name="default" xsi:type="string">0</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>
<field name="storeviews">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Magento\Store\Ui\Component\Listing\Column\Store\Options</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">int</item>
            <item name="label" xsi:type="string" translate="true">Store View</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_store_id</item>
            <item name="visibleValue" xsi:type="string">0</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>
<field name="external_url">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">External Link</item>
            <item name="formElement" xsi:type="string">input</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_external_url</item>
            <item name="visibleValue" xsi:type="string">1</item>
            <item name="visible" xsi:type="boolean">false</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
                <item name="validate-url" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>

The dependent js to get and reterive the value

Namespace\Modulename\Model\Config\Source\Options

define([
    'underscore',
    'uiRegistry',
    'Magento_Ui/js/form/element/select',
    'Magento_Ui/js/modal/modal'
], function (_, uiRegistry, select, modal) {
    'use strict';

    return select.extend({

        initialize: function () {
            this._super();
            var storeviewField = uiRegistry.get('index = storeviews');
            var externalUrl = uiRegistry.get('index = external_url');
            if(this.value() == 1){
                externalUrl.show();
                storeviewField.hide();
            } else {
                storeviewField.show();
                externalUrl.hide();
            }

            return this;
        },

    });
});

This works great until I merge JS from magento setting.
I get the following error

storeviewField undifined

Why is it causing issue when I merge the JS Files?

A: I had the same issue I moved my column above.
Try moving your storeviews column above redirect_in:
<field name="storeviews">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Magento\Store\Ui\Component\Listing\Column\Store\Options</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">int</item>
            <item name="label" xsi:type="string" translate="true">Store View</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_store_id</item>
            <item name="visibleValue" xsi:type="string">0</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>
<field name="external_url">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">External Link</item>
            <item name="formElement" xsi:type="string">input</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_external_url</item>
            <item name="visibleValue" xsi:type="string">1</item>
            <item name="visible" xsi:type="boolean">false</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
                <item name="validate-url" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>
<field name="redirect_in">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Namespace\Modulename\Model\Config\Source\Options</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">int</item>
            <item name="label" xsi:type="string" translate="true">Store Info</item>
            <item name="component" xsi:type="string">Namespace_Modulename/js/form/element/options</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">modulename</item>
            <item name="dataScope" xsi:type="string">redirect_in</item>
            <item name="default" xsi:type="string">0</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>


text:
Q: How to simulate a clicking visual effect when clicking on a JLabel? I have a JLabel (sorry I can't have a JButton) and a mouse listener to trap the click. All I need now is to simulate some kind of clicking visual effect/animation. This seems complicated because repaints are asynchronous. How do I go about doing that???

A: Use a MouseListener.

*

*On mousePressed() you set a Border

*On mouseReased() you reset the Border.


text:
Q: Retrieve Colour - Value Mapping From ggplot I assume the ggplot scales creates some sort of function which reads the appropriate aes value and returns the colour, size, etc. Can this be used as a standalone function?
For example, to this function I will pass the necessary arguments (range, limits, high, low, etc.) and a value which I want to get the mapping for, and the output of the function will be the colour / size / etc.
# example of usage
HypotheticalScaleFunction(
   range = c(0,10),
   high = '#000000',
   low = '#222222',
   ValueToLookup = 5
)
# this should return -
"#111111"

A: You can find this by reading through the source, by typing in scale functions. For example, if you read through the source for ggplot2::scale_color_continuous, you will find that it uses seq_gradient_pal from the scales package.
So, for color on a continious scale, we can define the following function (with the defaults that ggplot uses):
ColorScaleFunction <- function(Range, high = "#56B1F7", low = "#132B43", ValueToLookup) {
  seq_gradient_pal(low, high)((ValueToLookup - Range[1]) / diff(Range))
}

This results in the typical dark blue colors that you get by default, in heatmaps for example.
It produces #161616 on your example though.


text:
Q: Structure of level sets of a noncritical point of a smooth function on a two dimensional domain Let $\psi$ be a smooth function on a two dimensional simply connected domain $\Omega$ such that $\psi=0$ on the boundary $\partial \Omega$. Suppose $\rho$ is not a critical value of $\psi$ then it is claimed that the level set $\psi= \rho$ consists of finitely many closed disjoint curves. How does one prove / see this? Also, if we were working on the two torus rather than a simply connected domain would this still be true?

A: *

*You need $\Omega$ to be bounded. Otherwise the halfplane $\Omega=\{(x,y)\in\mathbb R^2:x>0\}$ with $\psi (x,y)=\sin x$ and $\rho=1/2$ is a counterexample. (Infinitely many level curves, not closed)

*You need $\rho\ne 0$. Otherwise $\Omega=\{(x,y)\in\mathbb R^2:x^2+y^2<1 \}$ with $\psi (x,y)=x(1-x^2-y^2) $ and $\rho=0$ is a counterexample. (Level curve is not closed).

With the above assumptions, the statement is true, and you don't even need $\Omega$ to be simply connected. Indeed, let $M=\{(x,y)\in \Omega:\psi(x,y)=\rho\}$. This set is closed in $\Omega$ and has no limit points on $\partial \Omega$. Therefore, $M$ is compact. Since $\nabla \psi\ne 0$ on $M$, the implicit function theorem implies that $M$ is a $1$-dimensional manifold (not necessarily connected). A $1$-manifold can be covered by open sets each of which is homeomorphic to a line interval. By compactness, finitely many such sets are enough. It follows that $M$ has finitely many connected component. Each component is homeomorphic to $S^1$ by the classification of $1$-manifolds.
The above works just as well when $\Omega$ is a bounded open subset of a $2$-dimensional manifold (torus, etc.)


text:
Q: How to check for null values with Dapper I'm having an SQL table Countries, with CountryId and StateId. StateId can be null, as not all countries have States.
I'd like to check if the combination of country/state exists in the table. If I have the country "NL" and state NULL in the table, and I use the following query where countryId = "NL" and stateId = null:
return await conn.ExecuteScalarAsync<bool>(@"SELECT COUNT(*)
                                             FROM [dbo].[Countries]
                                             WHERE [CountryId] = @CountryId
                                             AND [StateId] = @StateId",
                                             new { countryId, stateId });

It will return false. I expected a true response. Could someone explain this behaviour and what is the best approach to solve this?

A: That is not a Dapper issue. Comparing anything to NULL with the = operator will usually return false. You will have to use "is null" for comparison, ie
AND [StateId] is null

(at least on SQL Server). That means of course that your query will have to look differently in case stateid is null.

A: Check this:
SELECT COUNT(*)
       FROM [dbo].[Countries]
       WHERE [CountryId] = @CountryId
       AND ([StateId] IS NULL OR ([StateId] IS NOT NULL AND [StateId] = @StateId))

It will check if StateId is null, then only the 'CountryId' will be checked for those countries with no state, if StateId is not null, then StateId would be checked too