text:
Q: My application doesn't run itself MainActivity I got some error in my logcat and my application doesn't run in my smartphone...
I changed some codes in my manifest and MainActivity (named as HomaActivity )
THIS IS MY MANIFEST:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ir.homa">
<permission
    android:name="android.permission.INTERNET">
</permission>
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="24" />
    <application
        android:name=".AppController"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".HomaActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"   >
            <intent-filter >
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" >
            <category android:name="android.intent.category.DEFAULT" />
        </activity>
        <activity
            android:name=".RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" >

            <category android:name="android.intent.category.DEFAULT" />
        </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>

THIS IS HomaActivity.Java :
   package ir.homa;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

public class HomaActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homa);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    /**
     * Logging out the user. Will set isLoggedIn flag to false in shared
     * preferences Clears the user data from sqlite users table
     */

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
   public GoogleApiClient client;
    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
     GoogleApiClient client = null;
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Homa Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://ir.homa/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Homa Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://ir.homa/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}

THESE ARE ERRORS IN MY LOGCAT:
   07-02 20:26:44.441 26501-26501/ir.homa E/AndroidRuntime: FATAL EXCEPTION: main
                                                         Process: ir.homa, PID: 26501
                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.homa/ir.homa.HomaActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                             at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                             at android.os.Looper.loop(Looper.java:145)
                                                             at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
                                                             at ir.homa.HomaActivity.onStart(HomaActivity.java:127)
                                                             at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
                                                             at android.app.Activity.performStart(Activity.java:6258)
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2621)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                             at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                             at android.os.Looper.loop(Looper.java:145)
                                                             at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

A: In onStart(), you have:
GoogleApiClient client = null;
client.connect();

client is null. Hence, you cannot call connect() on it without getting a NullPointerException.

A: This is your problem, you're calling a method on a null variable:
GoogleApiClient client = null;
client.connect();

you need to initialize the client first. something like this
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this /* FragmentActivity */,
                  this /* OnConnectionFailedListener */)
    .addApi(Drive.API)
    .addScope(Drive.SCOPE_FILE)
    .build();

Check this link.


text:
Q: How to do a controller wait for a response sent from a service throutout a resolve? I'm working in an Ionic project, and would like to pass an object from a service, to a controller, throughout a resolve on my router. However, the controller does not receive the object. In fact, this is an ascynchronous operation and I think, that the return in my service occurs before the promisse returns. How do I resolve this?
Thanks
I have a route in an app.js.
.config(function($stateProvider, $urlRouterProvider) {

   $stateProvider
   .state('home', {
      url: '/',
      templateUrl: 'templates/home.html',
      controller: 'MainCtrl as vm',
      resolve: {
         weather: function(MyService) {
             return MyService.getData();
         }
      });

   $urlRouterProvider.otherwise('/');
});

The Service is here:
.factory('MyService', function($http) {

   var data = {};
   $http.get('http://something.api?format=json')
   .then(
      function(res) {
         data = res.data;
      },
      function(err) {
         data = err.status;
      });

    return {
       getData: function() {
          return data;
       }
    }
});

And finally, my Controller is...
.controller('MainCtrl', function(weather) {

   var vm = this;
   vm.weather = weather;
});

A: You can make the $http request for the weather data inside the getData() function of your service and return the $http promise from the function.
.factory('MyService', function($http) {

    function getData() {
        return $http.get('http://something.api?format=json')
            .then(function(res) {
                return res.data;
            });
    }

    return {
        getData: getData
    };
});

Now, you can just return this promise from the resolve in your route definition just how you have done it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux. create thread in assembler ASM code
 PROT_READ          equ     1
 PROT_WRITE         equ     2
 PROT_EXEC          equ     4
 PROT_NONE          equ     0

 MAP_SHARED         equ     1
 MAP_PRIVATE        equ     2
 MAP_FIXED          equ     10h
 MAP_TYPE           equ     0Fh
 MAP_FILE           equ     0
 MAP_ANON           equ     20h
 MAP_ANONYMOUS      equ     MAP_ANON
 MAP_32BIT          equ     40h
 MAP_NORESERVE      equ     4000h
 MAP_GROWSDOWN      equ     0100h
 MAP_DENYWRITE      equ     0800h
 MAP_EXECUTABLE     equ     1000h
 MAP_LOCKED         equ     2000h
 MAP_POPULATE       equ     8000h
 MAP_NONBLOCK       equ     10000h
 MAP_STACK          equ     20000h
 MAP_HUGETLB        equ     40000h

 CLONE_VM               equ     00000100h
 CLONE_FS               equ     00000200h
 CLONE_FILES            equ     00000400h
 CLONE_SIGHAND          equ     00000800h
 CLONE_PTRACE           equ     00002000h
 CLONE_VFORK            equ     00004000h
 CLONE_PARENT           equ     00008000h
 CLONE_THREAD           equ     00010000h
 CLONE_NEWNS            equ     00020000h
 CLONE_SYSVSEM          equ     00040000h
 CLONE_SETTLS           equ     00080000h
 CLONE_PARENT_SETTID    equ     00100000h
 CLONE_CHILD_CLEARTID   equ     00200000h
 CLONE_DETACHED         equ     00400000h
 CLONE_UNTRACED         equ     00800000h
 CLONE_CHILD_SETTID     equ     01000000h
 CLONE_NEWUTS           equ     04000000h
 CLONE_NEWIPC           equ     08000000h
 CLONE_NEWUSER          equ     10000000h
 CLONE_NEWPID           equ     20000000h
 CLONE_NEWNET           equ     40000000h
 CLONE_IO               equ     80000000h
 SIGCHLD                equ     17

 stdout             equ     1

 STACK_SIZE         equ     1024 * 200

 .data

     msg0               db 10, "thread created", 10

 .code

 _start:

main proc

         mov rdi, 0
         mov rsi, 4095
         mov rdx, PROT_WRITE or PROT_READ
         mov r10, MAP_ANONYMOUS or MAP_PRIVATE or MAP_GROWSDOWN
         mov r8, -1
         mov r9, 0

         mov rax, 9 ; mmap
         syscall

         lea rdi, [thread]
         lea rsi, [rax + STACK_SIZE - 8]
         mov rdx, SIGCHLD or CLONE_FS or CLONE_FILES or CLONE_SIGHAND or CLONE_VM
         mov r10, 0

         mov rax, 56 ; clone
         syscall

         jmp $

main endp

thread proc

         mov rdi, stdout
         mov rsi, offset msg0
         mov rdx, sizeof msg0

         mov rax, 1 ; SYS_WRITE
         syscall

     mov rax, 0
     ret

thread endp

end

Its not working return oxffffffffffffffea after call clone


text:
Q: Value of $\sum_{i=1}^{p} i^k \pmod{p}$ I found a statement that
$$\sum \limits_{i=1}^{p} i^k \equiv \begin{cases} -1 && (p-1) \mid k \\ 0 && \text{otherwise}\end{cases} \pmod{p}$$ for a prime $p$ and positive integer $k$. The result is obvious when $k$ is odd or equals $p-1$ but I can't prove it for all even values of $k$.

A: From Ribenboim's book,
Let $S=\sum j^k$    where $(j,m)=1$ and $1≤j<m$ where m is any natural number.
Let $ag\equiv bg\pmod m$ where $1\leq a\leq b\leq m$ and $(g,m)=1$
$\implies m\mid g(b-a)\implies m|(b-a)$ as $(g,m)=1$
But $m∤(b-a)$ as $1\leq a\leq b\leq m$, so, $ag≢bg\pmod m$.
So, the sets of reduced residue classes  ${g, 2g, . . . , (m − 1)g}$ and
${1, 2, . . . , (m − 1)}$ are the essentially same only in some different order.
Then $g^kS ≡\sum(gj)^k ≡\sum j^k≡S \pmod m.$
Hence $(g^k−1)S ≡ 0 \pmod m$.
So, $m\mid  S$ if $k ∤ ord_mg  \implies g^k ≢ 1 \pmod m$
If $g$ is so chosen that o$rd_mg =\phi(m)$ i.e., if $g$ be a primitive root modulo $m$(assuming $m$ has at least one), then $m\mid  S$  if $k ∤ \phi(m) \implies g^k ≢ 1 \pmod m$.
If $m$ becomes prime $p,\phi(m)=\phi(p)=p-1$ and all primes have  primitive root(s).

A: If $p-1|k$, it's obvious due to Fermat's little theorem.
If not, let's start $k=1$. We have $\displaystyle\sum_{i=1}^p i^k = p + \sum_{i=1}^{p-1}i = 1 + (p-1) + 2+(p-2)+\dots + E(p/2)-1 + E(p/2)+1 = 0\mod p$.
In the general case (still, when $p-1$ doesn't divide $k$), we have the function $\varphi(i) = i^k\mod p$ that is a bijection of $\mathbb{[}1,p-1\mathbb{]}$. Indeed, if we could find $i\neq j \in \mathbb{[}1,p-1\mathbb{]}$ such as $i^k = j^k\mod p$, we would have $i-j$ that would be a divisor or $p$ which is impossible as $p$ is prime.
We can then rewrite $\displaystyle\sum_{i=1}^{p-1}i^k$ as $\displaystyle\sum_{i=1}^{p-1}j_{i,k}$ where $j_{i,k} = i^k = \varphi(i)$, and since $\varphi$ is bijective,  $\varphi([1,p-1] =[1,p-1]$, and so the sum is also equal to $\displaystyle\sum_{i=1}^{p-1} i = 0\mod p$.


text:
Q: extracting from a string without delimiters excel This site has been a veritable treasure chest of answers and ideas to many of my vba problems in the past, but i have not been able to find any concerning what i am sure is for many, if not most, here in this forum a simple task. I have to deal with a lot of xml report files that all have a header string and my problem is how to parse the string for the nuggest i require for my macro.
This is a sample string:
<Function IDREF="TST_RxRccsMatrix_Rx64" Start="2011-04-07T14:21:35.593000+02:00" Status="Success" Tags="SystemSerialNumber:41009" End="2011-04-07T14:29:16.625000+02:00">

I need to extract
 - the report type: TST_RxRccsMatrix (length of this string is not constant)
 - the start date-time stamp: 2011-04-07T14:21:35.593000+02:00 (length is constant)
 - the serial number: 41009 (length is constant)
I have tried methods using Split and InStr and Find but none produce the desired results for all three extractions.
I truely appreciate any help on this!

A: The old fashion way is to use instr to find beginning. Then use instr to find ending. Then use mid to suck it out.
Begin = instr(1,xmlstring,"IDREF=") + Len("IDREF")
'look for first space after IDREF= in string
End = instr(Begin, xmlstring, " ")
Report = mid(xmlstring, begin, end - begin)

I didn't test it.
But I's split on space, then go through the array splitting on =. That will give you an array of 2 element arrays with value name in (0) and value in (1).
But xml has it's own query language and libraries to access stuff.
This is some code splitting a command line and then splitting 320x200 into 300 and 200.
CmdLine = Command()

A = Split(CmdLine, Chr(32), 2, 1)
B = Split(A(0), "x", 2, 1)

A: After some polishing:
Private Sub GetFileInfo()
 Dim fso As New FileSystemObject, strText As Variant, i As Integer
Dim X(0 To 2) As String, Y(0 To 2) As String, B, E As Variant
'get header string from xml file
'FName (file name) was ascertained by a previous sub and is made public
Set strText = fso.OpenTextFile(FName, ForReading, False)
'header string is in second (i = 2) line of file
For i = 1 To 2: [A1] = strText.ReadLine: Next: strText.Close: Set fso = Nothing
'User Oded's search and extract routine
X(0) = "IDREF=": X(1) = "Start=": X(2) = "Tags="
For i = LBound(X(), 1) To UBound(X(), 1)
  B = InStr(1, [A1], X(i)) + Len(X(i)) + 1 ' + 1 includes trailing " character
  E = InStr(B, [A1], " ") - 1 ' - 1 includes leading " character
'required if a search string in X() is at the end of the header which ends with a ">"
  If (InStr(B, [A1], " ") - 1) < 0 Then E = InStr(B, [A1], ">")
  Y(i) = Mid([A1], B, E - B)
Next
[D1] = "Test = " & Y(0)
[D2] = "Tested on : " & Left(Y(1), 10) & " at " & Mid(Y(1), 12, 8)
[D2] = [D2] & " - " & Y(2)
End Sub

A: xmlstring = "<Function IDREF=""TST_RxRccsMatrix_Rx64"" Start=""2011-04-07T14:21:35.593000+02:00"" Status=""Success"" Tags=""SystemSerialNumber:41009"" End=""2011-04-07T14:29:16.625000+02:00"">"
Set regEx = New RegExp
regEx.Pattern = "IDREF=""([a-z0-9_]+)"""
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(xmlstring)
If Matches.count <> 1 then msgbox "no match or too many"
For Each Match in Matches
    Msgbox match.submatches(0)
Next

I answered your qustions. The other person deleted two easier ways of doing it.
Ask Oded to put back my explanation of this code. And to restore the MS tutorial on how to do it with XML DOM objects. I showed FOUR ways.


text:
Q: Angular web build deploy shows white screen when I refresh the page I have made Angular web build successfully , I deploy successfully on live server , change the path base_href path in index.html,and it works fine .
Now the issue is when I refresh the page it appears white screen why ?
How to resolve it ?
Can anyone help me to overcome from this solution ?
Any help would be appreciated.

A: Well, you have to insert a wb.config file and configure routing to in your angular app so that on build it will depending on the server you have to specify web.config or you have to use other strategies. Follow the link for using other strategies.
http://joeljoseph.net/angular-6-deploy-on-apache-server-by-solving-404-not-found-error-on-page-refresh/


text:
Q: react-dropzone The files parameter in onDrop = (files) returning null import {Component} from 'react';
import Dropzone from 'react-dropzone';

import style from './LogUploader.css';

export class LogUploader extends Component {
    state = {
        message: t('logreader', 'Load log file')
    };

    isLog (content) {
        return content[0] === '{' && content[content.length - 1] === '}';
    }

    onDrop = (files) => {
        const file = files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            const content = e.target.result.trim();
            if (!this.isLog(content)) {
                this.setState({message: t('logreader', 'Invalid log file')});
                return;
            }
            this.props.onLogFile(content);
        };
        reader.readAsText(file);
    };

    render () {
        const dropStyle = {
            display: 'inline-block',
            margin: '5px'
        };

        return (
            <Dropzone multiple={false} accept="text/*" className={"button"} style={dropStyle}
                      onDrop={this.onDrop}>
                {({getRootProps, getInputProps}) => <button {...getRootProps()}>{this.state.message}<input {...getInputProps()}/></button>}
            </Dropzone>
        );
    }
}

debug info
As shown in the above code, after selecting the upload file, the files parameter in onDrop = (files) always returns a null value. Is there anything wrong with the code above? Thanks!

A: Instantiate with useDropzone() instead of importing * from the library. This will give you more control over customization.
// handler function
const onDrop = (files) => {
    // files is an array of all uploaded files
    console.info("accepted file!!", files[0]);
};

// at the top-level in your component
const { getRootProps, getInputProps } = useDropzone({
    onDropAccepted: onDrop, // your handler function
    multiple: false,
    accept: {
        "image/png": [".png"]
    }
});

return () {
    <div>
        <button {...getRootProps({ className: "myDropZoneButton" })}>
            upload
        </button>
        <input {...getInputProps()} />
    </div>
}

Here's a live demo using functional component.


text:
Q: mysql - good pratice: table with more then one index? Sorry all,
I do have this mini table with 3 columns but, I will list the values either by one or other column.
1) Is it ok to have two of those columns with indexes?
2) Should we have only one index per table?
3) At the limit, if we have a table with 100 columns for example, and we have 50 of them with indexes, is this ok?
Thanks,
MEM

A: It's fine to have many indexes, even multiple indexes on one table, as long as you are using them.
Run EXPLAIN on your queries and check which indexes are being used. If there are indexes that are not being used by any queries then they aren't giving you any benefit and are just slowing down modifications to the table. These unused indexes should be removed.
You may also want to consider multiple-column indexes if you have not already done so.

A: There is no problem with having more than one index per table, and no, one index per table isn't really a guideline.
Having too many indexes is inefficient because

*

*It requires additional storage

*MySQL needs to determine which index to use for a particular query

Edit : As per Pablo and Mark, you need to understand how your data is being accessed in order for you to build effective indices. You can then refine and reduce the indexes.

A: To quickly answer your questions, I think:

*

*Yes, it's OK to have two or even more columns with indexes

*Not necessarily. You can have more than one index per table.

*It might be OK, it might be not OK. It depends. The thing with indexes is that they take space (in DISK) and they make operations that modify your data (INSERT/UPDATE/DELETE) slower since for each and everyone of them, there will be a TABLE and INDEX update involved.

Your index creation should be driven by your queries. See what queries are you going to have on your system and create indexes accordingly.


text:
Q: Token based Authentication mechanism for REST API I have a network device (running c++) in my local network which runs a http(s) server and provides a Restlike webservice interface to provide an API to control the device.
Now my question is, how can i authorize the user (an android smartphone in the same network) for using the Rest api?
The scenario is as like this: The user on the smartphone has to enter a PIN cod (4-digits) in order to get access to the api from then on it should be possible to call all the other REST API methods.
My idea:
1) the pin code will be send to the device via http(s) POST body, the device checks if it is okay.
2) if the PIN is right, the device will generate a token, which has to be used on every future request.
so my questions are:
* how should i generate such a token (what algorithm) on the device using c++
* how should the token be transmitted on every request? As a query parameter? Or in the POST body? or in the Header?
EDIT: i also read about http basic authentication. could this be used in my setup too?
kind regards

A: When submitting tokens using headers or POST body, never in the Url as part of query string.
See OWASP page for REST: https://www.owasp.org/index.php/REST_Security_Cheat_Sheet#Authentication_and_Session_Management

A: The short answer is: store it in the header, the code could use a hash algorithm to generate the token and your idea is right in the first point, but make sure those tokens have finite lifetime.


text:
Q: Attempting to create a json object from ruby I'm attempting to create this string in Ruby.
{
quantity: 1,
discount_type: :dollar,
discount_amount: 0.01,
discount_message: 'this is my message',
}

By reading up on the classes I can see that I can initialize it like so:
class DiscountDisplay
    def initialize(quantity, type, amount, message)
        @quantity = quantity
        @discount_type = type
        @discount_amount = amount
        @discount_message = message
    end
end

f = DiscountDisplay.new( 1, :dollar, 0.01, 'this is my message' )

How can I actually create the json string? Not using the require 'json' others have indicated on some other answers.

A: I would add a to_json method to the DiscountDisplay class like this:
class DiscountDisplay
  require 'json'

  def initialize(quantity, type, amount, message)
    # ...
  end

  def to_json
    JSON.generate(
      quantity: @quantity,
      discount_type: @discount_type,
      discount_amount: @discount_amount,
      discount_message: @discount_message,
    )
  end
end

And call it like this:
discount_display = DiscountDisplay.new(1, :dollar, 0.01, 'this is my message')
discount_display.to_json
#=> '{"quantity":1,"discount_type":"dollar","discount_amount":0.01,"discount_message":"this is my message"}'


text:
Q: HashMap in ArrayList dosent exist outside of loop I have an ArrayList which contains a HashMap.
Example of one of the Arraylist lines:
1 = {HashMap@831906200928}  size = 10
 0 = {HashMap$HashMapEntry@831906220224} "0" -> "false"
 1 = {HashMap$HashMapEntry@831906220256} "1" -> "false"
 2 = {HashMap$HashMapEntry@831906220288} "2" -> "false"
 3 = {HashMap$HashMapEntry@831906220320} "3" -> "false"
 4 = {HashMap$HashMapEntry@831906220352} "4" -> "false"
 5 = {HashMap$HashMapEntry@831906220384} "5" -> "false"
 6 = {HashMap$HashMapEntry@831906220416} "6" -> "false"
 7 = {HashMap$HashMapEntry@831906220448} "7" -> "false"
 8 = {HashMap$HashMapEntry@831906220480} "8" -> "false"
 9 = {HashMap$HashMapEntry@831906220512} "9" -> "false"

When I exit the loop, all of the HashMap is gone and istead, the ArrayList size remains but that is all the list:
iscompleted = {ArrayList@831906354944}  size = 11
 0 = {HashMap@831906354968}  size = 0
 1 = {HashMap@831906354968}  size = 0
 2 = {HashMap@831906354968}  size = 0
 3 = {HashMap@831906354968}  size = 0
 4 = {HashMap@831906354968}  size = 0
 5 = {HashMap@831906354968}  size = 0
 6 = {HashMap@831906354968}  size = 0
 7 = {HashMap@831906354968}  size = 0
 8 = {HashMap@831906354968}  size = 0
 9 = {HashMap@831906354968}  size = 0
 10 = {HashMap@831906354968}  size = 0

>         ArrayList<HashMap<String, Boolean>> iscompleted = new ArrayList<HashMap<String, Boolean>>();
>         HashMap map = new HashMap<String, Object>();
>         for (i=0; i<_listDataHeader.size(); i++) {
>             for (int j=1; j<_listDataChild.size(); j++){
>                 map.put(j-1, tasks.get(x).get("isCompleted"));
>                 x++;
>             }
>             iscompleted.add(map);
>             map.clear();
>         }

A: You are putting the same HashMap instance in the list, and you clear it after each iteration.
You should create a new HashMap for each element you are adding to the List :
     ArrayList<HashMap<String, Boolean>> iscompleted = new ArrayList<HashMap<String, Boolean>>();
     for (i=0; i<_listDataHeader.size(); i++) {
         HashMap map = new HashMap<String, Object>();
         for (int j=1; j<_listDataChild.size(); j++){
             map.put(j-1, tasks.get(x).get("isCompleted"));
             x++;
         }
         iscompleted.add(map);
     }


text:
Q: AppSync Custom Resolver to count DynamoDB entries I have a React AppSync app with AWS resources provisioned using the Amplify CLI. I need to fetch the number of entities in one of my tables that contains several thousand entries, without having to fetch the entries themselves. Besides the stupidity of fetching thousands of entities just to count them, I'm also running into the problem that I can't even get all those records in one request anyway. A simple call like this:
import { API, graphqlOperation } from "aws-amplify";

const nodeData = await API.graphql(
  graphqlOperation(
    `query allNodeIds {
      listNodes(limit: 10000) {
        items {
          id
        }
      }
    }`,
    {}
  )
);

const nodeCount = nodeData.data.listNodes.items.length;

Causes the following console error:
...
errorType: "MappingTemplate"
message: "List size cannot exceed 1000"

It seems I need to write a custom query & resolver to count and return the number of entries in the table, but don't know where to start with writing resolvers (in VTL?), where to put them in the project, etc. Any help?
EDIT: Wrote a resolver based on one of my other generated resolvers, but it still seems to be capped at 1001 records, though I set the limit to 9999.
Schema
...
countResponses(filter: ModelResponseFilterInput, limit: Int, nextToken: String): Int

Request Mapping Template
#set( $limit = $util.defaultIfNull($context.args.limit, 9999) )
#set( $ListRequest = {
  "version": "2017-02-28",
  "limit": $limit
} )
#if( $context.args.nextToken )
  #set( $ListRequest.nextToken = "$context.args.nextToken" )
#end
#if( $context.args.filter )
  #set( $ListRequest.filter = $util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)") )
#end
#if( !$util.isNull($modelQueryExpression)
                        && !$util.isNullOrEmpty($modelQueryExpression.expression) )
  $util.qr($ListRequest.put("operation", "Query"))
  $util.qr($ListRequest.put("query", $modelQueryExpression))
  #if( !$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC" )
    #set( $ListRequest.scanIndexForward = false )
  #else
    #set( $ListRequest.scanIndexForward = true )
  #end
#else
  $util.qr($ListRequest.put("operation", "Scan"))
#end
$util.toJson($ListRequest)

Response Mapping Template
## [Start] Determine request authentication mode **
#if( $util.isNullOrEmpty($authMode) && !$util.isNull($ctx.identity) && !$util.isNull($ctx.identity.sub) && !$util.isNull($ctx.identity.issuer) && !$util.isNull($ctx.identity.username) && !$util.isNull($ctx.identity.claims) && !$util.isNull($ctx.identity.sourceIp) && !$util.isNull($ctx.identity.defaultAuthStrategy) )
  #set( $authMode = "userPools" )
#end
## [End] Determine request authentication mode **
## [Start] Check authMode and execute owner/group checks **
#if( $authMode == "userPools" )
  ## No Static Group Authorization Rules **

  ## [Start] If not static group authorized, filter items **
  #if( !$isStaticGroupAuthorized )
    #set( $count = 0 )
    #foreach( $item in $ctx.result.items )
      ## No Dynamic Group Authorization Rules **

      ## [Start] Owner Authorization Checks **
      #set( $isLocalOwnerAuthorized = false )
      ## Authorization rule: { allow: owner, ownerField: "owner", identityClaim: "cognito:username" } **
      #set( $allowedOwners0 = $item.owner )
      #set( $identityValue = $util.defaultIfNull($ctx.identity.claims.get("username"), $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), "___xamznone____")) )
      #if( $util.isList($allowedOwners0) )
        #foreach( $allowedOwner in $allowedOwners0 )
          #if( $allowedOwner == $identityValue )
            #set( $isLocalOwnerAuthorized = true )
          #end
        #end
      #end
      #if( $util.isString($allowedOwners0) )
        #if( $allowedOwners0 == $identityValue )
          #set( $isLocalOwnerAuthorized = true )
        #end
      #end
      ## [End] Owner Authorization Checks **

      #if( ($isLocalDynamicGroupAuthorized == true || $isLocalOwnerAuthorized == true) )
        #set( $count = $count + 1)
      #end
    #end
    #set( $ctx = $count )
  #end
  ## [End] If not static group authorized, filter items **
#end
## [End] Check authMode and execute owner/group checks **

$util.toJson($ctx)


text:
Q: Retrieve login time of users among billion records There is a table which keeps the login information of users:
UserID       LoginTime               MacAddress     IPAdress
1        2017-02-05 20:02:40           --        192.168.10.3

This table has billion of records, we are going to get the last login time of each user with different filters, for example in 6 month ago. Also, this table should be join with Users Table for retrieving users information, also filters on Users table may be requested for example :
Where UserName='xxxx' and Last_Login_Time in  6 Month Ago, and any other filters.
I know that  there are ways like RowNumber and a way like this:
SELECT MAX(LoginTime) AS [Last Login Time], UserID
FROM UsersLoginHistory
GROUP BY UserID;

But these ways takes long time.
Can anyone suggest a better query (prefer to use offset for paging) for this issue?

A: With current data model you will need to read through all table anyway to retrieve information about all users and all their last logins. To make this kind of report fast, you should pre-calculate it.
You can suggest one of the following ways:

*

*Store the last login time in the UsersLogin table. Your back-end should properly update this table in the same transaction with inserting into UsersLoginHistory.

*Create index on UserID, LoginTime.

*You can replicate the logic of #1 somewhere in the database (using after insert trigger, for example), but i do not recommend doing this, because business logic will eventually bloat in your database.


text:
Q: Aerodynamic Problem in regards to a ping pong ball and and an open hole tube I have a ping pong levitation system with a ping pong ball in a tube being pushed by a dc motor fan (shown below) and I'd like to define a relation of the balls height with the air velocity or airflow. Does anyone know the force effect of a slit on the side of the tube on the pin pong ball?
I know based on research that if the tube was sealed on the side, there is only a drag force applied by the fan going against the balls weight, but with the slit on the side, I don't know how exactly it's impacting the motion physically. I believe it may be related to a decrease in air pressure but I'm not 100% sure?? The setup and and what I believe FBD of the system have currently are attached. Does anyone know how to represent the unknown force made by the slit. Appreciate it. Cheers.


text:
Q: CSS Height auto with overflow scroll and a max-height I have in the moment this window

Those 3 parents div are using float to stay side by side each other and with max-height equal to the window height, so those 3 divs are responsive, the 3 div is a chat and inside it i have 3 more div, a title, chat and options. I want the height of the chat to always fill all div without taking the remaining divs out, I already tried with height: 80%; but of course this doesnt work because this is relative to the parent and option comes out, but using height: 80vh; also doenst work and i dont know why.
When i decrease the height window this happens:

How can i resolve this problem to always I decrease window and the chat automatically adjusting without happening what shows in the previous image.
Code of 3 div:
-HTML:

                <input type="text" class="form-control form-control-sm send-message" name="send-message" style="height:auto;">

            RNI

-CSS:
#talk-CQ-SP {
    width: 38%;
    height: 100%;
    float: right;
}

#talk-CQ-SP .chat_talkCQ_SP {
    border: 1px solid gray;
    background: #fff;
    top: 0;
    padding: 5px;
    position: relative;
    width: 100%;
    height: 100%;
}

#talk-CQ-SP .messages {
    position: relative;
    width: 100%;
    height: 80%;
    padding: 10px;
    border: 1px solid gray;
    overflow-y: auto;
    overflow-x: hidden;
}


text:
Q: Android Best Practice In Navigating To Another Activity Is It better to call on finish(); before calling intent to navigate to another activity, or just call the intent. also note if up navigation is used which way is better
thank you

A: When you need to close the current Activity and start new Activity you  need to call finish().
But whenever you don't need to close current activity and start new one. Then you don't need to call finish().
When you don't call finish(). you can access the same activity back from new Activity.
I don't think one is better and other not. We can use both for based on our needs.
Note : If you don't call finish() then you don't need to create Activity again. Back from new activity. So it is faster.

A: Everything depends on what you want the user experience to be. The default is that the Activitys are left on the backstack in the order the user navigated them. So when he presses back, he returns to the previous Activity. And if he presses the HOME button and restarts the app again later, the app begins with the same Activity where he had left off. Calling finish() for each Activity will subvert this behavior.
You can customize the backstack & history behavior in a wide variety of ways. Take a look at the following links:
1. Activity tags in App Manifest. (launchMode is of particular interest here).
2. Tasks and Back Stack.

A:
also note if up navigation is used which way is better

Although the Amsheer answer is good one but I want to add on your above stated statement and that is YES. If you are using Up navigation it is more convenient from the point of view of user experience. you can set up navigation drawer and move from fragment to fragment which looks more great then going from activity to activity.
Keep it in mind that I am talking about user perspective I am not saying that moving from one activity to another is bad. But it looks great from navigating from one fragment to another using navigation drawer.


text:
Q: Display bulma carousel I am new to Bulma. I'm trying the carousel extension but it doesn't work. I have copied one example and I followed the documentation and did research but still it does not work. Thank you for helping! Heres my code:

A: First of all, You can't include scripts directly from Github.
Try using a CDN instead.
In order to integrate Bulma-Carousel to your project follow the steps below:
Link the CSS file of Bulma and the CSS and JS files of Bulma-Carousel.
Then, initialize Bulma-Carousel in a seperate .js file.
Here's a starter project to help you get started:
index.html
<!DOCTYPE html>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma-carousel@4.0.4/dist/css/bulma-carousel.min.css" />

                Mon titre 1

                Ici une petite description pour tester le slider

                Mon titre 2

                Ici une petite description pour tester le slider

                Mon titre 3

                Ici une petite description pour tester le slider

                Mon titre 4

                Ici une petite description pour tester le slider

                Mon titre 5

                Ici une petite description pour tester le slider

                Mon titre 6

                Ici une petite description pour tester le slider

scripts.js
bulmaCarousel.attach('#slider', {
  slidesToScroll: 1,
  slidesToShow: 3,
  infinite: true,
});


text:
Q: Need my fully working javascript rewritten in proper javascript Can someone please help me with simplifying my - fully working script at least that i wrote to swap images?
Here is it:

Thanks very much in advance!
Torsten

A: function swap(color){
    document.getElementById("swap_" + color + "_img").src='facebook_like_icon_' + color + '_50x43.png';
}

Note: not fully fits your code, but should be done this way

A:


text:
Q: Should I create another table? I have a table with this structure:

col1 would be "product_name" and col2 "product_name_abbreviated".
Ignoring the id colum I've this data:
1 1 43
1 1 5
1 1 6
1 1 7
1 1 8
2 2 9
2 2 10
2 2 34
2 2 37
2 2 38
2 2 39
2 2 50

I can do another table and put there col1 and col2 columns becouse they are repeated. Something like this:

But I'm sure that it'll not be repeated more than 15 times, so... Is it worth?
Thanks in advanced.

A: Yes, you should split them out into separate tables - this is an example of normalisation to Second Normal Form.

A: You are sure NOW, but what about when you will extend your application in one year time? Split the tables

A: Use only one table with the ID, two VARCHAR columns for the name and abbreviation and a NUMBER for the price.

A: Normalization is good for avoiding repeating data. Your model is tiny, the data is small, you should not worry and leave one entity (table).
In real projects sometimes we normalize and then realize we got a mess. It's always good to balance between repeating data and easy of understanding the model and querying. Not to mention when working with data warehouse databases...

A: This is a very basic question in database design and the answer is a resounding "Two Tables"!
Here are just some of the reasons:

*

*If you have one table, then by mistake someone could enter a new row with product name "1" and abbreviated product name "2" The only way to stop this would be to add rules and constraints - far more complicated than just splitting the tables in the first place.

*Looking at the database schema should tell you meaningfully about what it represents. If it's a FACT that you can't have a product with product name "1" and abbreviated product name "2" then this should be clear from looking at the table structure. A single table tells you the opposite, which is UNTRUE. A database should tell the truth - otherwise it is misleading.

*If anyone other than yourself looks at or develops against this database, they may be confused and misled by this deviation from such basic rules of design. Or worse, it could lead to broken window syndrome, if they assume it was not carefully designed and therefore don't take care with their own work.
The principle is called "Normalisation" and is at the heart of what it means for something to be a relational database rather than just some data in a pile :)


text:
Q: Expandable rows on material table are not working after sorting Based on the samples in Angular Material Table I added expandable rows and sorting to my table. Each feature works like a charm for itself. But when I try to expand a row after the table was sorted, the first click seems to do nothing at all. The second click opens the row and instantly closes it again. When I click the same row again, it behaves normally again.
Here's a simplified version on stackblitz: https://stackblitz.com/edit/angular-mnqztk
As far as I could find out with logging, the expandedElement property is set correctly for each click, no matter if the table was sorted or not. So I guess there's somthing wrong with the animations trigger detailExpand. I just cannot figure out why it's not getting triggered, when expandedElement is set after the table is sorted.

A: I stumbled over this github issue, which indirectly solves my problem. Instead of the animation used in on the Angular Material page, use the following:
animations: [
    trigger('expandDetail', [
      state('collapsed, void', style({ height: '0px' })),
      state('expanded', style({ height: '*' })),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
      transition('expanded <=> void', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))
    ])

That's it. Problem solved.


text:
Q: Lottery Program Ignores Function I'm meant to write a program that lists one random number after the other, which it does (along with a beep). However, it ignores a fundamental function needed for the program to run correctly. The ask() function does what it implies, it asks the user to input an integer between the range (1000-9999) which is then compared to the winning number (random) to see if the user correctly guessed it and thus won. I've only recently started writing in Java so I'm not very sure if there's a basic mistake I'm making. Any help would be appreciated!
package edu.pupr.pega4;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class Pega4Driver {
    public static void main(String[] args) {
        Pega4 test = new Pega4(2000, true);
        test.start();
        JOptionPane.showMessageDialog(null, "Quit program?");
        JOptionPane.showMessageDialog(null, "Perdiste!!!");
        System.exit(0);
    }
}

class Pega4 {
    private int interval; //Time interval for new number to appear
    private boolean beep; //BEEP
    private int number; //The input number
    private int tiradas = 1; //Counter
    private int winNum; //The winning number
    //Constructor
    public Pega4(int interval, boolean beep) {
        this.interval = interval;
        this.beep = beep;
    }
    //Returns a random number within a specified range
    public double getRandomIntegerBetweenRange(double min, double max){
        double x = (int)(Math.random()*((max-min)+1))+min;
        return x;
    }
    public void start() {
        class Pega4Inner implements Asker, ActionListener {
            Scanner input = new Scanner(System.in);
            Date now = new Date();
            @Override
            public void ask() {
                System.out.println("Entrar numero deseado: ");
                number = input.nextInt();
                //Input Validation
                if (number < 1000 || number > 9999)
                {
                    System.out.println("Entrada invalida. Entrar numero deseado: ");
                    number = input.nextInt();
                }
                System.out.println(now);
            }
            @Override
            public void actionPerformed(ActionEvent e) {
                winNum = (int) getRandomIntegerBetweenRange(1000, 9999);
                System.out.println("Tirada #" + (tiradas++) + ": " + winNum);
                if (beep)
                    Toolkit.getDefaultToolkit().beep();
                if (winNum == number)
                {
                    JOptionPane.showMessageDialog(null, "Ganaste!!!");
                    System.exit(0);
                }
            }
        }
        ActionListener listener = new Pega4Inner();
        Timer timer = new Timer(interval, listener);
        timer.start();
    }
}

The Pega4Inner class implements an interface named Asker created by me. Its code is as follows:
package edu.pupr.pega4;

public interface Asker {
    void ask();
}

A: You would need to actually call your ask() method from somewhere :)
I think a proper point to do that in your current code would be in the beginning of your actionPerformed() method in Pega4Inner :
 public void actionPerformed(ActionEvent e) {
     ask();
     winNum = (int) getRandomIntegerBetweenRange(1000, 9999);
     …

EDIT
Based on your requirement to call ask() only once, one way to do it is by taking this method out of your inner class and put it in your outer class, then call it explicitly in your driver class. So your Pega4 class could look like this :
class Pega4 {
    private int interval; //Time interval for new number to appear
    private boolean beep; //BEEP
    private int number; //The input number
    private int tiradas = 1; //Counter
    private int winNum; //The winning number
    //Constructor
    Date now = new Date();
    Scanner input = new Scanner(System.in);

    public Pega4(int interval, boolean beep) {
        this.interval = interval;
        this.beep = beep;
    }

    //Returns a random number within a specified range
    public double getRandomIntegerBetweenRange(double min, double max) {
        double x = (int) (Math.random() * ((max - min) + 1)) + min;
        return x;
    }

    public void ask() {
        System.out.println("Entrar numero deseado: ");
        number = input.nextInt();
        //Input Validation
        while (number < 1000 || number > 9999) { // not IF here
            System.out.println("Entrada invalida. Entrar numero deseado: ");
            number = input.nextInt();
        }
        System.out.println(now);
    }

    public void start() {
        class Pega4Inner implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent e) {
                // ask();
                winNum = (int) getRandomIntegerBetweenRange(1000, 9999);
                System.out.println("Tirada #" + (tiradas++) + ": " + winNum);
                if (beep) {
                    Toolkit.getDefaultToolkit().beep();
                }
                if (winNum == number) {
                    JOptionPane.showMessageDialog(null, "Ganaste!!!");
                    System.exit(0);
                }
            }
        }
        ActionListener listener = new Pega4Inner();
        Timer timer = new Timer(interval, listener);
        timer.start();
    }
}

And then in your Pega4Driver class :
...
Pega4 test = new Pega4(2000, true);
test.ask();
test.start();
...


text:
Q: Create a user who cannot see other bank objects How do I create a user who does not see any bank object. Only the materialized view that I will release to him via grant?
I create the user like this:
CREATE USER PAPER WITH LOGIN PASSWORD 'secure password' NOSUPERUSER NOINHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinite';
GRANT SELECT ON vw_visao TO user;
but when I logged in with him on pgadmin3 they can see the entire structure of the bank.
Like seeing how many tables you have, the functions and the sql within the functions and the ddl of the tables. Do not select anything for lack of privilege.
I am trying to prevent the user from being allowed to execute these commands.
There are several interesting options, see some examples:
\d  list the database tables
\dv list database views
\di list enter code here the indexes of the database
\db list the tablespaces
\l list the databases
\dg list existing roles (users or groups)
\conninfo displays information about the current connection
\h list SQL commands
\h command displays details about the command

A: There is no way to do that inside a single database in PostgreSQL.
One possibility would be to use a postgres_fdw foreign table to refer to a table in a different database, whose definition could not be seen.


text:
Q: How to properly add consecutive numbers after text for ID in attribute table So after trying this expression 'GI_' + lpad($id, 2, 0) I get this;

and I have about 12650 rows, and the id freezes in GI_10. I want the rows to start from GI_00 and end with GI_12650.


text:
Q: Role based authentication in React Native app using Firebase Currently using Firebase in my react native app. I have to manage two roles for admin and user. I am not able to manage roles in firebase authentication here is the code in which i am simply registering a user. Any one please help regarding managing roles. Thanks
 register: async (email, password) => {
          try {
            await auth().createUserWithEmailAndPassword(email, password);
          } catch (e) {
            console.log(e);
          }
        },

A: Take a look at this medium auth flow tutorial, I'm using this to handle multiple user roles in my mobile app and it works flawlessly.
You don't need to use AWS, just replace it with you backend server auth api.
To handle multiple roles, alter AppNavigator return like this:
return (
    <NavigationContainer>
        {userToken ?
            isAdmin
                <AdminModule />
            :
                <UserModule />
        :
            <AuthModule />
        }
    </NavigationContainer>
);

All of these Modules are just StackNavigators, or BottomTabNavigators or both combined, it's up to you.
Use react hooks to get token or admin/user from auth:
const { userToken, isAdmin } = useAuthState();

Alter the reducer to handle multiple roles:
case 'SIGN_IN':
  return {
    ...prevState,
    isSignout: false,
    userToken: action.token,
    isAdmin: false,
  };
case 'SIGN_IN_ADMIN':
  return {
    ...prevState,
    isSignout: false,
    userToken: action.token,
    isAdmin: true,
  };

Also alter the AuthProvider to handle multiple roles (these are default values):
const [state, dispatch] = React.useReducer(AuthReducer, {
    isLoading: true,
    isSignout: false,
    userToken: null,
    isAdmin: false,
  });

After successful login dispatch desired type according to role:
dispatch({ type: 'SIGN_IN_ADMIN', token: global.token });

The reason this works, is you need to wrap all your application in the AuthProvider like this:
<AuthProvider>
    <AppNavigator />
</AuthProvider>

Then everytime you dispatch() something, the app re-renders UI according to the role you dispatched.
The login/register call should return admin/user role, so you can render user/admin UI. It should look something like this:
return Api.login(username, password)
.then(response => {
    if (response.role == 'user') {
        dispatch('SIGN_IN', token: response.token);
    } else if (response.role == 'admin') {
        dispatch('SIGN_IN_ADMIN', token: response.token);
    }
})

I spent days on this, hope you will get it done faster with this help.


text:
Q: Android project wont pull facebook events Hi I am trying to make a app that will pull a list the logged in users friends from facebook into my application I am using the facebook SDK the code compiles and seems to work but hangs on the spinner animation when I select the get friends option from the menu! here is the code I am using bellow
public static final String APP_ID = "IDHERE";

private static final String[] PERMISSIONS =
    new String[]{ "offline_access", "read_stream",
            "publish_stream","create_event","user_events","friends_events",
            "publish_checkins", "friends_checkins" };

private TextView mText;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private final ArrayList<Friend> friends = new ArrayList<Friend>();
private FriendsArrayAdapter friendsArrayAdapter;
private ListView listView;
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Make sure the app client_app has been set
    if (APP_ID == null) {
        Util.showAlert(this,
        "Warning", "Facebook Applicaton ID must be set...");
    }

    // Initialize the content view
    setContentView(R.layout.main);
    // Get the status text line resource
    mText = (TextView) workdammit.this.findViewById(R.id.txt);

    // Setup the ListView Adapter that is loaded when selecting "get friends"
    listView = (ListView) findViewById(R.id.friendsview);
    friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout, friends);
    listView.setAdapter(friendsArrayAdapter);

    // Define a spinner used when loading the friends over the network
    mSpinner = new ProgressDialog(listView.getContext());
    mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mSpinner.setMessage("Loading...");

    // Initialize the Facebook session
    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

}

//////////////////////////////////////////////////////////////////////

public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  Log.d("FB Sample App", "onActivityResult(): " + requestCode);
  mFacebook.authorizeCallback(requestCode, resultCode, data);
}

//////////////////////////////////////////////////////////////////////
// Get Friends request listener
//////////////////////////////////////////////////////////////////////

/**
 * FriendsRequestListener implements a request lister/callback
 *  for "get friends" requests
 */
public class FriendsRequestListener implements
        com.facebook.android.AsyncFacebookRunner.RequestListener {

    /**
     * Called when the request to get friends has been completed.
     * Retrieve and parse and display the JSON stream.
     */
    public void onComplete(final String response) {
        mSpinner.dismiss();
        try {
            // process the response here: executed in background thread
            Log.d("Facebook-Example-Friends Request", "response.length(): " + response.length());
            Log.d("Facebook-Example-Friends Request", "Response: " + response);

            final JSONObject json = new JSONObject(response);
            JSONArray d = json.getJSONArray("data");
            int l = (d != null ? d.length() : 0);
            Log.d("Facebook-Example-Friends Request", "d.length(): " + l);

            for (int i=0; i<l; i++) {
                JSONObject o = d.getJSONObject(i);
                String n = o.getString("name");
                String id = o.getString("id");
                Friend f = new Friend();
                f.id = id;
                f.name = n;
                friends.add(f);
            }

            // Only the original owner thread can touch its views
            workdammit.this.runOnUiThread(new Runnable() {
                public void run() {
                    friendsArrayAdapter = new FriendsArrayAdapter(
                            workdammit.this, R.layout.rowlayout, friends);
                    listView.setAdapter(friendsArrayAdapter);
                    friendsArrayAdapter.notifyDataSetChanged();
                }
            });
        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");
        }
    }

    @Override
    public void onComplete(String response, Object state) {
        mSpinner.dismiss();

    }

    @Override
    public void onIOException(IOException e, Object state) {
        mSpinner.dismiss();

    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e,
            Object state) {
        mSpinner.dismiss();

    }

    @Override
    public void onMalformedURLException(MalformedURLException e,
            Object state) {
        mSpinner.dismiss();

    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        mSpinner.dismiss();

    }
}

//////////////////////////////////////////////////////////////////////
// Wall Post request listener
//////////////////////////////////////////////////////////////////////

/**
 * WallPostRequestListener implements a request lister/callback
 *  for "wall post requests"
 */
public class WallPostRequestListener implements
        com.facebook.android.AsyncFacebookRunner.RequestListener {

    /**
     * Called when the wall post request has completed
     */
    public void onComplete(final String response) {
        Log.d("Facebook-Example", "Got response: " + response);
    }

    @Override
    public void onComplete(String response, Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onIOException(IOException e, Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e,
            Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMalformedURLException(MalformedURLException e,
            Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        // TODO Auto-generated method stub

    }

}

//////////////////////////////////////////////////////////////////////
// Wall post dialog completion listener
//////////////////////////////////////////////////////////////////////

/**
 * WallPostDialogListener implements a dialog lister/callback
 */
public class WallPostDialogListener implements
        com.facebook.android.Facebook.DialogListener {

    /**
     * Called when the dialog has completed successfully
     */
    public void onComplete(Bundle values) {
        final String postId = values.getString("post_id");
        if (postId != null) {
            Log.d("FB Sample App", "Dialog Success! post_id=" + postId);
            mAsyncRunner.request(postId, new WallPostRequestListener());
        } else {
            Log.d("FB Sample App", "No wall post made");
        }
    }

    @Override
    public void onCancel() {
        // No special processing if dialog has been canceled
    }

    @Override
    public void onError(DialogError e) {
        // No special processing if dialog has been canceled
    }

    @Override
    public void onFacebookError(FacebookError e) {
        // No special processing if dialog has been canceled
    }
}

/////////////////////////////////////////////////////////
// Login / Logout Listeners
/////////////////////////////////////////////////////////

/**
 * Listener for login dialog completion status
 */
private final class LoginDialogListener implements
        com.facebook.android.Facebook.DialogListener {

    /**
     * Called when the dialog has completed successfully
     */
    public void onComplete(Bundle values) {
        // Process onComplete
        Log.d("FB Sample App", "LoginDialogListener.onComplete()");
        // Dispatch on its own thread
        mHandler.post(new Runnable() {
            public void run() {
                mText.setText("Facebook login successful. Press Menu...");
            }
        });
    }

    /**
     *
     */
    public void onFacebookError(FacebookError error) {
        // Process error
        Log.d("FB Sample App", "LoginDialogListener.onFacebookError()");
    }

    /**
     *
     */
    public void onError(DialogError error) {
        // Process error message
        Log.d("FB Sample App", "LoginDialogListener.onError()");
    }

    /**
     *
     */
    public void onCancel() {
        // Process cancel message
        Log.d("FB Sample App", "LoginDialogListener.onCancel()");

}
    }
/**
 * Listener for logout status message
 */
private class LogoutRequestListener implements RequestListener {

    /** Called when the request completes w/o error */
    public void onComplete(String response) {

        // Only the original owner thread can touch its views
        workdammit.this.runOnUiThread(new Runnable() {
            public void run() {
                mText.setText("Thanks for using FB Sample App. Bye bye...");
                friends.clear();
                friendsArrayAdapter.notifyDataSetChanged();
            }
        });

        // Dispatch on its own thread
        mHandler.post(new Runnable() {
            public void run() {
            }
        });
    }

    @Override
    public void onComplete(String response, Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onIOException(IOException e, Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e,
            Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMalformedURLException(MalformedURLException e,
            Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        // TODO Auto-generated method stub

    }

}

///////////////////////////////////////////////////////////////////
// Menu handlers
///////////////////////////////////////////////////////////////////

/**
 * Invoked at the time to create the menu
 * @param menu is the menu to create
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

/**
 * Invoked when preparing to display the menu
 * @param menu is the menu to prepare
 */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem loginItem = menu.findItem(R.id.login);
    MenuItem postItem = menu.findItem(R.id.wallpost);
    MenuItem getfriendsItem = menu.findItem(R.id.getfriends);
    if (mFacebook.isSessionValid()) {
        loginItem.setTitle("Logout");
        postItem.setEnabled(true);
        getfriendsItem.setEnabled(true);
    } else {
        loginItem.setTitle("Login");
        postItem.setEnabled(false);
        getfriendsItem.setEnabled(false);
    }
    loginItem.setEnabled(true);
    return super.onPrepareOptionsMenu(menu);
}

/**
 * Invoked when a menu item has been selected
 * @param item is the selected menu items
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        // Login/logout toggle
        case R.id.login:
            // Toggle the button state.
            //  If coming from login transition to logout.
            if (mFacebook.isSessionValid()) {
                AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
                asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
            } else {
                // Toggle the button state.
                //  If coming from logout transition to login (authorize).
                mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
            }
            break;

        // Wall Post
        case R.id.wallpost: // Wall Post
            mFacebook.dialog(workdammit.this, "stream.publish", new WallPostDialogListener());
            break;

        // Get Friend's List
        case R.id.getfriends: // Wall Post
            // Get the authenticated user's friends
            mSpinner.show();

            mAsyncRunner.request("me/friends", new FriendsRequestListener());
            break;

        default:
            return false;

    }
    return true;
}

}
there are also two other classes that work with the application the code for these are bellow also
/**
 * ListView Friends ArrayAdapter
 */
public class FriendsArrayAdapter extends ArrayAdapter {
    private final Activity context;
    private final ArrayList friends;
    private int resourceId;
/**
 * Constructor
 * @param context the application content
 * @param resourceId the ID of the resource/view
 * @param friends the bound ArrayList
 */
public FriendsArrayAdapter(
        Activity context,
        int resourceId,
        ArrayList<Friend> friends) {
    super(context, resourceId, friends);
    this.context = context;
    this.friends = friends;
    this.resourceId = resourceId;
}

/**
 * Updates the view
 * @param position the ArrayList position to update
 * @param convertView the view to update/inflate if needed
 * @param parent the groups parent view
 */
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (rowView == null) {
        LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = vi.inflate(resourceId, null);
    }
    Friend f = friends.get(position);
    TextView rowTxt = (TextView) rowView.findViewById(R.id.rowtext_top);
    rowTxt.setText(f.name);
    return rowView;
}

}
public class Friend {
public String id;
public String name;
public byte[] picture;
public Bitmap pictureBitmap;;

}
any help would be great  :D

A: Code looks good!
Here is one thing to try... check to see if your "@Override" onComplete() method is being called and do something there.
Eg.
   public class FriendsRequestListener implements
        com.facebook.android.AsyncFacebookRunner.RequestListener {

...
...
   @Override
    public void onComplete(String response, Object state) {
        mSpinner.dismiss();
        // Got a response... now process it
        onComplete(response);
    }


text:
Q: Dynamic button link to a page with different content I need to click a lesson(button) to go to a page(showcontent.php). As my lesson number is created by using the sql statement:
"SELECT DISTINCT lesson FROM table"

This is my php file
<?php
$con=mysqli_connect("localhost", "root", "password","database");

if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT DISTINCT lesson FROM table");

while($row = mysqli_fetch_array($result)) {
//depending on the lesson number in the database
//If lesson column only have lesson 2 and 5; it will show 2 buttons, lesson 2 and lesson 5
$lesson = $row['lesson'];
echo "LESSON ". $row['lesson'] ."\n";
echo "
";
}
mysqli_close($con);
?>

So what I want is to click the lesson button to link a page(showcontent.php) but the content which I retrieve from the database will be different. Means when I click lesson 2 it will go to (showcontent.php) and when I click lesson 5 it will go to (showcontent.php) but the contents will be different. And the content I have to retrieve from the database.
What I have done is only (showcontent.php), it only display for lesson 1.
This is the php file.
<?php
$con=mysqli_connect("localhost","root","password","database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$x = 7;

$sql="select * from sen where id = ".$x." limit 10";

if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$output = $row[1];
}
mysqli_free_result($result);
}
mysqli_close($con);
?>

So what I need is make the program knows that when I click lesson 1(button) it will go to (showcontent.php) and get the content for lesson 1 from that database. However, when I click lesson 5(button) it will go to (showcontent.php) and get the content for lesson 5 from that database. How can I make that work? Any examples?


text:
Q: How to I convert custom function in JPA to a Predicate? I've got a custom implementation of function (interface SQLFunction) that looks as follows:
public class FilterFunction implements SQLFunction {

    @Override
    public boolean hasArguments() {
        return true;
    }

    @Override
    public boolean hasParenthesesIfNoArguments() {
        return false;
    }

    @Override
    public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
        return StandardBasicTypes.STRING;
    }

    @Override
    public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException {
        return arguments.get(0).toString();
    }
}

So it simply takes a parameter and replaces the function with it. The SQL might look like this:
HUGE_SQL = 'SOME_VALUE' AND HUGE_SQL2 = 'SOME_VALUE'

So it is some kind of predicate. I'm using the function in the following way:
ParameterExpression parameterExpression = criteriaBuilder.parameter(String.class);
criteriaBuilder.function("filter", String.class, parameterExpression));

I would like to use disjunction with several such functions passing an array of them to CriteriaBuilder.or. The function is an Expression implementation. But CriteriaBuilder.or takes an array of Predicate's. I've tried to convert such function to a Predicate but I'm getting cast exception on runtime.
I've tried to wrap this function in CriteriaBuilder.isTrue. Then I have to specify the return type of the function Boolean.class instead of String.class but then I'm getting another runtime exception saying it can't convert my function to boolean.
I have to do it because I have to use JPA Criteria API.
How do I chain such functions in CriteriaBuilder.or? Thank you very much!


text:
Q: strange behavior expect script under cron i have simple expect script
#!/usr/local/bin/expect -f

#TFTP

exp_internal 1
log_file expect.stdout.log

set timeout 60
set hostname [lindex $argv 0];
set login [lindex $argv 1];
set password [lindex $argv 2];
set iptftp [lindex $argv 3];
set file [lindex $argv 4];

match_max 1000000
spawn telnet $hostname

sleep 1
expect "login:" {send "$login\n"}
sleep 1
expect "Password:" {send "$password\n"}
sleep 3
expect "*#" {send -- "upload cfg_toTFTP $iptftp $file config_id 1\n"}
sleep 3

expect "*#" {send -- "logout\n"}

this script run via php script which connect to mysql DB and get hostname, login etc and . If I run script via shell /usr/bin/php /home/swbackup/backup.php - all OK. Under cron, after script login to switch send only first letter from command upload cfg_toTFTP u and nothing more
expect: does " \r\n\r\n\rDGS-1100-06/ME:5# " (spawn_id exp7) match glob pattern "*#"? yes
expect: set expect_out(0,string) " \r\n\r\n\rDGS-1100-06/ME:5#"
expect: set expect_out(spawn_id) "exp7"
expect: set expect_out(buffer) " \r\n\r\n\rDGS-1100-06/ME:5#"
send: sending "upload cfg_toTFTP 10.0.4.240 174610_backup.cfg config_id 1\n" to { exp7 }

expect: does " " (spawn_id exp7) match glob pattern "*#"? no
u
expect: does " u" (spawn_id exp7) match glob pattern "*#"? no
Connection closed by foreign host.

I tried different options, but nothing helps


text:
Q: Need to know common scenarios to test netsuite application I need to know what are all testing types and scenarios (manual testing) can do for NetSuite application and how?
I have tested integration with netsuite and sales force
In that I verified cases such as whether all the mapped data can sync or not, in negative cases I verified such as left mandatory field of netsuite as empty in sales force and try to sync and vice verse, data type, Max length and min length of field limit, negative value


text:
Q: Connectivity period of oracle JDBC connection or session While loading up my java spring application , i am making a jdbc connection using url, username and password through drivermanagerDatasource and it was able to connect to jdbc successfully .
Consider a scenario:  The application was processing a file for a period of 10 AM - 11 AM.
Now suppose if i change the oracle password at 10:30 AM .
Q1. What will happen to the application? will it throw error?
Q2. What will happen to the connection object? whats its validity period?
Q3. before inserting or updating a single record into DB , does every time the application checks the username and password ?
Would be great help if anyone answer this.
Thanks in advance


text:
Q: Dynamic Image in Android? (Beginner Question) I would like to display a .png file from the R.drawable to the screen.  Eventually I would like this image to be dynamic, meaning that it's position can move based on specified x,y coordinates.
I have looked into it but I am confused by the many options.  Here are most of my questions:
What is the best data type/object to use for the situation?
What is the best way to instatiate the image?
Does it need to be a Drawable?
Does the Drawable then need its own View?
To display it, do I just add the new View to the main view?
I have experience with numerical method algorithms, but this is my first venture into graphics and I'm a bit overwhelmed, so any advice is greatly appreciated.
Edit - For the movement of the image, it will be moving around a lot, eventually as a user controlled movement.

A: As you note, there are many ways to do this. The "best" way depends on lots of things. If you want something like a ball bouncing around inside an area on the screen, the best approach might be to create a custom View and draw your .png in the onDraw() method at whatever coordinates you want. You can load your .png as a Bitmap using BitmapFactory.decodeResource().

A: Adding to what Ted said, if you want the image to later move around, you may want to draw it to a canvas. There are several useful draw methods for Canvas. SurfaceView is another option as well.
pic = BitmapFactory.decodeResource(getResources(), img);

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(pic, x, y, null);
    //canvas.drawRect(x, y, right, bottom, null);
}


text:
Q: Beginner Simple Mileage Calculator: Can't return Var I have been trying to educate myself and look at other work on how to get this simple calculator to work with JS. I have debugged it via google chrome and I can't identify what fundamentals I am missing;

var theForm = document.forms["mmacalc"];

function getsjourn()
{
    var theForm = document.forms["mmacalc"];
    var sjourn = theForm.elements["sjourn"];
    var smile =0;
    if(sjourn.value!="")
    {
        smile = parseInt(sjourn.value);
    }

    return smile;
}

function getrjourn()
{
    var theForm = document.forms["mmacalc"];
    var rjourn = theForm.elements["rjourn"];
    var rmile =0;
    if(rjourn.value!="")
    {
        rmile = parseInt(rjourn.value);
    }

  return rmile;
}

function getmilalallow()
{
    var tmile = sjourn() * rjourn() ;

    document.getElementById('tjourn').innerHTML =
                                     "Your total mileage is"+tmile;
    var milal = sjourn() * rjourn() * 0.25 ;

     document.getElementById('mmac').innerHTML =
                                      "Your MMA Claim is: £"+milal;

}

<form name="mmacalc" id="mmacalc" action="" method="post" target="_self">
     Single Journey Mileage
    <input type="text" id="sjourn" name="sjourn" value="" onclick="calculateTotal()">

     Amount of Return Journeys
    <input type="text" id="rjourn" name="rjourn" value="1" onclick="calculateTotal()">

    <input type="submit" value="Submit" onsubmit="getmilalallow()">

</form>

A: Using a form for this is unwise, because when you click the input[type=submit] button, it will POST the data and refresh the page. You can get around this with event.preventDefault(), but there's no need - we will change it to a div for this. Use a form when you need to send data to a server - for client-side stuff, avoid forms.
Also, you were binding your logic to the text inputs' onclick eventListener, so whenever a user tapped on a textfield it would do the computation. I removed those eventListeners and moved it to the submit button instead, so the UI updates when a user taps the button.
We will combine all of the logic into one function, updateTotals, which will calculate the total and update the innerHTML of the two paragraphs when the button is clicked.

var theForm = document.forms["mmacalc"],
      sjourn = document.getElementById('sjourn'),
      rjourn = document.getElementById('rjourn'),
      tjourn = document.getElementById('tjourn'),
      mmac = document.getElementById('mmac');

function updateTotals() {
  let total = sjourn.value * rjourn.value;

  tjourn.innerHTML = `Your total mileage is ${total}`,
  mmac.innerHTML = `Your MMA Claim is ${total*0.25}`;
}

   Single Journey Mileage
  <input type="text" id="sjourn" name="sjourn" value="">

   Amount of Return Journeys
  <input type="text" id="rjourn" name="rjourn" value="1">

  <button onclick="updateTotals()">Submit</button>

  </form>


text:
Q: Can C# cast const? If an object is readonly or const, is it possible to cast that object to make it writable?
Something similar to C++ const_cast.

A: It's not possible in C#, just like it's not possible in C++. In C++, if the object is really const, you cannot const_cast the constness away and write to it without invoking undefined behaviour:
struct foo { const int x; };

foo a;
int& b = const_cast<int&>(a.x);
b = 17; // invokes undefined behaviour

A readonly field in C# only means that the field itself cannot be reassigned. It's akin to T *const or T& in C++. You can change the referenced object at will through its members.
class Foo { public int x; }
class Bar { public readonly Foo y = new Foo(); }

Bar a = new Bar();
a.y.x = 3; // valid
a.y = new Foo(); // invalid

Well, I'm not telling the whole truth. You can cheat and change readonly fields through reflection1:
typeof(string).GetField("Empty").SetValue(null, "bar");
// this effectively makes string.Empty equal to "bar", with disastrous consequences
// It requires full trust though.
// Obviously, it's evil.

If it is a const field however, not even this trick will work.
const fields are hardcoded in assemblies that use them, instead of keeping references to the original assembly:
// Assembly A.dll
public class Foo { public static const int X = 42; }

// Assembly B.dll
int y = Foo.X;
// this is the equivalent to:
int y = 42;

This means that if you recompile A.dll and change the value of Foo.X to 23, B.dll will still use 42 until it is recompiled.
All that said, if you want to have a field that you want to change, just don't make it readonly. If you want it to be mutable by the class, but immutable from the outside, make it private and add a read-only property (note: this is not the same as a readonly field):
class Foo
{
    private int bar;
    public int Bar
    {
        get { return bar; }
    }
}

1This is not really guaranteed, but it works on the Microsoft implementations. If you're wondering why this hack works at all, you can read Eric Lippert's explanation. Be sure to also read the answer about readonly on value types. And it goes without saying, don't do this at home.

A: You won't be able to amend the value of the const itself.  All you can do is take a copy and change that copy.  Unless I'm misunderstanding the question...?
Bear in mind that in C# const is quite a limited keyword anyway, you can only declare certain things as const and only at compile time:
http://msdn.microsoft.com/en-us/library/e6w8fe1b(v=VS.100).aspx
Not sure why you'd want to mutate a constant.

A: No. The reference or value will be read only.
You can however modify the properties of references or you could just make a copy of a value.

A: Objects are not readonly or const, only variables are. That means you can assign a value to such a variable only once (in the case of const) or only until the owner object is constructed (in the case of readonly).
The object assigned to a readonly variable can still be changed, though, unless it's immutable (like string).

A: You can cast in CSharp readonly away (which is equilant to C++ const). CSharp const could be translated to C++ with constexpr which can't be casted away.
To do so you can call Unsafe.AsRef - which has the same meaning as C++ const_cast:
using System;

class App{
   static readonly int i = 42;
   static void Main(){
       Console.WriteLine(i);
       System.Runtime.CompilerServices.Unsafe.AsRef(i) = 777;
       Console.WriteLine(i);
   }
}

The same would look in C++ like:
#include <iostream>

class App{
public:
    static inline int iStorage= 42;
    static inline const int& i = iStorage;

    static void Main(){
       std::cout << i << '\n';
       *const_cast<int*>(&i) = 777;
       std::cout << i <<'\n';
   }
};

int main(){
    App::Main();
}

Just in case of static const C++ implementations are allowed to store the data in readonly-memory (which is explicitly allowed by the standard).
This is done usually for simple types like int - the reason is that there was no constexpr but the same behaviour was wished - therefore static const has sometimes the same meaning as constexpr.


text:
Q: Receiving messages back to my platform Use Case   SMS leaves my platform and goes out to a receiver (SMS).  I would like to attach some sort of custom identifier so when the user responds back to the SMS..and my platform received the message..I know how to internally route the response back in my platform.
Any ideas?

A: Maybe set up a system where when the code is sent out
For instance:
Code - 11832
The user then has to enter this code on your website. A program will then match to see if it's the identical code. So you are then able to log the information
No expert on this though and Where is your code ?

A: Twilio evangelist here.
There isn't really a great way to attach an identifier to the message itself.  You could force the user to prepend/append a code in their reply, but depending on your specific scenario that might not be a great user experience.
Another option is to save the to/from phone number as a unique pair when you send the message.  Then as your application receives replies you can check the incoming to/from phone number against what you saved.
Hope that helps.


text:
Q: Non deterministic behavior on dependencies - nodejs I would solve a warning: when I run yarn install all dependencies are installed but I receive this warning:

warning Pattern ["esprima-fb@~3001.0001.0000-dev-harmony-fb"] is
  trying to unpack in the same destination
  "/Users/Me/Library/Caches/Yarn/v1/npm-esprima-fb-3001.1.0-dev-harmony-fb-b77d37abcd38ea0b77426bb8bc2922ce6b426411"
  as pattern ["esprima-fb@~3001.1.0-dev-harmony-fb"]. This could result
  in a non deterministic behavior, skipping.

If I delete node_modules folder and I run yarn install I don't receive the warning, when I re-execute yarn install I receive it again.
I suppose the problem is in yarn-lock file.
package.json
{
  "name": "n1",
  "version": "1.0.0",
  "description": "none ",
  "author": "none",
  "main": "src/index.js",
  "private": false,
  "engines": {
    "node": ">=7.6",
    "yarn": "*"
  },
  "scripts": {
    "precommit": "yarn lint",
    "prestart": "yarn docs",
    "start": "cross-env NODE_ENV=production pm2 start ./src/index.js",
    "dev": "nodemon ./src/index.js",
    "lint": "eslint **/*.js --ignore-path .gitignore --ignore-pattern internals/scripts",
    "lint:fix": "yarn lint -- --fix",
    "lint:watch": "yarn lint -- --watch",
    "test": "cross-env NODE_ENV=test nyc --reporter=html --reporter=text mocha --timeout 20000 --recursive src/api/tests",
    "test:unit": "cross-env NODE_ENV=test mocha src/api/tests/unit",
    "test:integration": "cross-env NODE_ENV=test mocha --timeout 20000 src/api/tests/integration",
    "test:watch": "cross-env NODE_ENV=test mocha --watch src/api/tests/unit",
    "coverage": "nyc report --reporter=text-lcov | coveralls",
    "postcoverage": "opn coverage/lcov-report/index.html",
    "validate": "yarn lint && yarn test",
    "postpublish": "git push --tags",
    "docs": "apidoc -i src -o docs",
    "postdocs": "opn docs/index.html"
  },
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "blubird": "^0.0.1-security",
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.2",
    "chalk": "^2.3.0",
    "color": "^2.0.1",
    "compression": "^1.7.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.4",
    "cross-env": "^5.1.3",
    "dotenv-safe": "^4.0.4",
    "espree": "^3.5.2",
    "esprima": "^4.0.0",
    "express": "^4.16.2",
    "express-validation": "^1.0.2",
    "express-winston": "^2.4.0",
    "helmet": "^3.9.0",
    "http-status": "^1.0.1",
    "joi": "^10.6.0",
    "jwt-simple": "^0.5.1",
    "lodash": "^4.17.4",
    "method-override": "^2.3.10",
    "moment": "^2.20.1",
    "moment-timezone": "^0.5.14",
    "mongoose": "^4.13.7",
    "morgan": "^1.9.0",
    "morgan-body": "^2.0.2",
    "mysql": "^2.15.0",
    "mysql2": "^1.5.1",
    "nedb": "^1.8.0",
    "node-geocoder": "^3.21.1",
    "only": "0.0.2",
    "passport": "^0.4.0",
    "passport-jwt": "^3.0.1",
    "pm2": "^2.9.1",
    "readline-sync": "^1.4.7",
    "request-promise": "^4.2.2",
    "sequelize": "^4.28.6",
    "serve-favicon": "^2.4.5",
    "winston": "^2.4.0",
    "yarn": "^1.3.2"
  },
  "devDependencies": {
    "apidoc": "^0.17.5",
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "coveralls": "^2.13.1",
    "eslint": "^4.13.1",
    "eslint-config-airbnb-base": "^12.1.0",
    "eslint-plugin-import": "^2.8.0",
    "husky": "^0.14.3",
    "mocha": "^3.5.3",
    "nodemon": "^1.14.1",
    "nyc": "^11.4.1",
    "opn-cli": "^3.1.0",
    "sinon": "^3.3.0",
    "sinon-chai": "^2.14.0",
    "supertest": "^3.0.0"
  },
  "license": "MIT"
}

yarn-lock
https://pastebin.com/vTrLHWff

A: Try removing both node_modules and yarn.lock:
rm -rf node_modules and rm yarn.lock
And then try running:
npm run rebuild which seem to help to resolve the issue.


text:
Q: Vimeo Feed gived dead link with RSS widget? I have RSS widget on my home page (footer) pointing to a RSS feed from Vimeo.
The videos pull in fine, and the links for these work.
The orange RSS icon also takes you to the actual RSS feed.
However, the title takes you to a 404.
I am not sure if this is a fault of how Vimeo is setup, or the widget.
Can anyone think of a workaround to ensure this title is not a dead link?
This short screencast explains the situation.

A: The link in the title comes from the RSS feed: it contains a <link> element describing the URL of the entire channel. I think Vimeo (recently?) changed their URL structure so http://vimeo.com/user3235740/videos/uploaded no longer points to the recently uploaded videos, but http://vimeo.com/user3235740/videos/sort:newest does.
It looks like Vimeo should update their feeds to include the correct URL. The default RSS widget does not allow you to change the URL easily, so I suggest you duplicate this widget code and add a fix for the URL yourself.


text:
Q: How to find out who is sending email I have a server which doesn't have much activity. Today, suddenly server load went higher than 12 which compared to its normal value(0.5) is way too high. I checked and found out that postfix is being used by a program named smpt  to send emails. Its full arguments:
 smtp -t unix -u

I use CentOS release 6.7 , I update my server on regular basis. netstat  shows me something like this:

I also checked /var/log/maillog  which told me in last 10 hours hundreds of thousands of email has been sent.
How can I find out who is behind this? How can I find out if it's internal or external?
P.S: postfix is down.

A: To find out how this is happening, you need to look at postfix logs. Either your postfix is misconfigured or you have some authorized host that is compromised (usually a webserver). If the postfix logs say this is coming from your local host, an lsof -i -n can yield useful information.

A: Most probably you have open relay enabled and some bot/scanner has picked you up. See your postfix config file (/etc/postfix/main.cf) and look for something like:

mynetworks = 0.0.0.0/0

If it is the case here, you will have to decide which networks are allowed to relay mail, or even disable it altogether leaving just the localhost.


text:
Q: Apache NIFi MergeContent processor - set demarcator as new line I want to use MergeContent processor to merge tweets to bulk insert into Elasticsearch index. For this I need command and tweets (each) to be separated by \n.
This is how it should look like
{ action: { metadata }}\n
{ request body        }\n

Which will be
{ "index"}
{ tweet1 }
{ tweet2 }

When I put \n as separator the processor actually adds \n as a string instead of new line separator. Is it possible to make it actual new line?
Also is it possible to leave or make footer empty?
Thanks in advance.

A: You are correct in that it takes the literal representation of what is entered.  There are two ways to handle this:

*

*With delimiter strategy of 'Text': Hit shift + enter to provide a new line

*With delimiter strategy of 'Filename': Provide a path to a file that is only a newline character

With regards to your question on leaving the footer empty, it should work as you anticipate for the Merge Format of 'Binary Concatenation.' Making a quick test flow, I have verified this, but please let us know if it is not working for your particular configuration.


text:
Q: iPhone NSURLConnection download file logging Situation:
Application downloads very small file every time it starts. IIS7 server logs keep track of this file.
Problem:
Server doesn't log every download (unless 50% people downloaded app and didn't even start it).
.
What may be the cause? Could it be that iPhone users from some area use proxy instead of connecting to my server every time?
How to solve it? Is there some kind of request I can make (and how?) so that users always download the file from server? Or some other way to make IIS log every file transfer (possibly without changing anything in IIS setup).
Thanks in advance!


text: Q: how to check all SNS topics and no of subscriptions from the CloudWatch? SNS service has default dashboard with no of SNS topics and no of subscriptions. I want to send them to a Cloudwatch dashboard. As far as I know, the Cloudwatch inbuilt metrics don't give this all the information. Is it possible to do that?


text:
Q: change zip file comment on the fly in php I want to change zip file comment on the fly.
I read the file like this :
$file         = file_get_contents($download_url);

and I send it to the user without saving the file temporarily. (using headers .... )
I want to know is it possible to change zip file comment without saving it temporarily?


text:
Q: How can i grab data from a NSE chart with python? I am trying to get data showing on the chart when I move the mouse.
NSE chart Images

A: This chart read data from urls
https://www.nseindia.com/api/chart-databyindex?index=BERGEPAINTEQN
https://www.nseindia.com/api/chart-databyindex?index=BERGEPAINTEQN&preopen=true
and you can get it with requests
This page needs header User-Agent but it can be even short 'Mozilla/5.0'.
import requests
import datetime

headers = {'User-Agent': 'Mozilla/5.0'}

url = 'https://www.nseindia.com/api/chart-databyindex?index=BERGEPAINTEQN'
#url = 'https://www.nseindia.com/api/chart-databyindex?index=BERGEPAINTEQN&preopen=true'

r = requests.get(url, headers=headers)

# --- response ---

#print(r.status_code)

data = r.json()

print('name:', data['name'])
print('identifier:', data['identifier'])
print('close price:', data['closePrice'])

prices = data['grapthData'][:10]

for item in prices:
    dt = datetime.datetime.utcfromtimestamp(item[0]/1000)
    value = item[1]
    print(dt, value)

Result
name: BERGEPAINT
identifier: BERGEPAINTEQN
close price: 551.45

2020-08-11 09:15:00 553.7
2020-08-11 09:15:01 553.7
2020-08-11 09:15:02 553
2020-08-11 09:15:03 553.95
2020-08-11 09:15:04 553.9
2020-08-11 09:15:05 553.6
2020-08-11 09:15:06 553.85
2020-08-11 09:15:07 553.35
2020-08-11 09:15:08 553.35
2020-08-11 09:15:09 553.35