text:
Q: Android Studio: how to propperly sign in Firebase using fragments I have searched several StackOverflow questions such as:
Android app crashing when displaying firebase database entries
Is it necessary to add an AuthStateListener in every activity of Android Firebase?
App crashes with java.lang.NullPointerException
FirebaseAuth.getCurrentUser() is returning null value
android- java.lang.NullPointerException using getCurrentUser firebase auth
application crashes during the first launch while using FirebaseAuthentication
What is a NullPointerException, and how do I fix it?
And finally the closest question regarding to the problem I am facing:
Getting Null Object Reference on getCurrentUser().getUid() on Fragment
I have not found an answer yet. In the last link, a StackOverflow member explained that the NullPointerException happens because somehow the app ignores the redirection from the MainActivity to the LoginActivity in the case of getCurrentUser().getUid() == null and executes the ChatFragment, where the NullPointerException occurs.
My app had this kind of problem at the beginning on the Emulator, but somehow it works fine on the Emulator.
But now, I tried to install the app in my physical device and the app is crashing. I get the NullPointerException because the user is not yet signed in.
My app is similar to WhatsApp ChatApp. It has sliding TabLayout with two fragments. My app launchs the MainActivity which should redirect the AppUser to LoginActivity in case of first use of the app.
Here is my MainActivity
public class MainPageActivity extends AppCompatActivity implements GroupListAdapter.DataChangeListener {

    public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;

    private Toolbar mToolBar;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;

    private TabsAccessAdapter mTabsAcessAdapter;

    private FirebaseAuth mAuth;
    private DatabaseReference RootRef;

    private String currentUserID;

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

        FirebaseApp.initializeApp(this);

        mAuth = FirebaseAuth.getInstance();
        RootRef = FirebaseDatabase.getInstance().getReference();

        mToolBar = (Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolBar);
        getSupportActionBar().setTitle("MyApp");

        mViewPager = (ViewPager) findViewById(R.id.tabs_pager);
        mTabsAcessAdapter = new TabsAccessAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mTabsAcessAdapter);

        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        mTabLayout.setupWithViewPager(mViewPager);

        getPermissions();

    }

    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSIONS_MULTIPLE_REQUEST);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        Log.i("debinf mainpage", "onStart");

        FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                FirebaseUser currentUser = firebaseAuth.getCurrentUser();

                if (currentUser == null) {
                    //Here is the place to redirect the AppUser to LoginActivity
                    sendUserToLoginActivity();
                }else {

                    VerifyUserExistance();
                }

            }
        });
    }

    private void VerifyUserExistance() {
        String currentUserID = mAuth.getCurrentUser().getUid();

        RootRef.child("user").child(currentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Toast.makeText(MainPageActivity.this, "Bem vindo(a)!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    // Dealing with MENU > starts here
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        getMenuInflater().inflate(R.menu.options_menu,menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        if (item.getItemId() == R.id.main_logout_option) {

            mAuth.signOut();
            sendUserToLoginActivity();
        }
        if (item.getItemId() == R.id.main_settings_option) {
            //sendUserToSettingsActivity();
            Toast.makeText(this, "Settings from MainAct", Toast.LENGTH_SHORT).show();
        }

        return false;
    }

    private void sendUserToLoginActivity() {
        Intent loginIntent = new Intent(MainPageActivity.this,LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);

    }

    @Override
    public void onDataSetChanged(String groupKeyFromSender, boolean addToCall) {
        String tag = "android:switcher:" + R.id.tabs_pager + ":" + 1;
        CallFragment rf = (CallFragment) getSupportFragmentManager().findFragmentByTag(tag);
        rf.getDataFromGroupFragment(groupKeyFromSender, addToCall);
    }
}

Here is my LoginActivity which should be called by MainActivity in the first usage, but it isn't.
public class LoginActivity extends AppCompatActivity {

    private EditText mPhoneNumber, mCode;
    private Button mSend;

    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

    String mVerificationId;

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

        FirebaseApp.initializeApp(this);

        userIsLoggedIn();

        mPhoneNumber = findViewById(R.id.phoneNumber);
        mCode = findViewById(R.id.code);

        mSend = findViewById(R.id.send);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVerificationId != null) {
                    verifyPhoneNumberWithCode();
                } else {
                    startPhoneNumberVerification();
                }

            }
        });

        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                sighInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {

            }

            @Override
            public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(verificationId, forceResendingToken);

                mVerificationId = verificationId;
                mSend.setText("Enviar codigo");
            }
        };
    }

    private void verifyPhoneNumberWithCode(){
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, mCode.getText().toString());
        sighInWithPhoneAuthCredential(credential);
    }

    private void sighInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
        FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    //userIsLoggedIn();
                    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                    // I think add child named user and inside other child named userId = user.getUid()
                    if (user != null) {
                        // Do not forget to add database implementation in the gradle (module app)
                        final DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("user").child(user.getUid());
                        mUserDB.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                if (!dataSnapshot.exists()) {
                                    // if user has never loged in, add a new user
                                    Map<String, Object> userMap = new HashMap<>();
                                    userMap.put("phone", user.getPhoneNumber());
                                    //userMap.put("name", user.getPhoneNumber());
                                    userMap.put("name", "babaloo");
                                    mUserDB.updateChildren(userMap);
                                }
                                userIsLoggedIn();
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });
                    }
                }
            }
        });
    }

    private void userIsLoggedIn() {

        FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (user != null) {
                    startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
                    finish();
                    return;
                }
            }
        });

    }

    private void startPhoneNumberVerification() {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                mPhoneNumber.getText().toString(),60,
                TimeUnit.SECONDS, this, mCallbacks);
    }
}

And here is the onCreateView of the GroupFragment where the NullPointerException happens.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.group_fragment, container, false);

    groupTablePath = getContext().getFilesDir().getPath()+"/GroupDataBase/";
    rootPath = Environment.getExternalStorageDirectory() + "/";

    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser().getUid();

    GroupRef = FirebaseDatabase.getInstance().getReference().child("Group");
    UserRef = FirebaseDatabase.getInstance().getReference().child("user");

    StoreRef = FirebaseStorage.getInstance().getReference();

    FloatingActionButton findUser = (FloatingActionButton) view.findViewById(R.id.addContact);
    findUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            startActivity(new Intent(view.getContext(), FindUserActivity.class));

        }
    });

    //getPermissions();

    CreateRootFolder();
    initializeRecyclerView();
    loadGroupListDatabase();
    populateTeamTableInternet();
    OwnerGroupUploadClientListTable();
    updateClientListInternet();

    // Inflate the layout for this fragment
    return view;
}

This part of the error
at com.example.aliton.myapp.Fragments.GroupFragment.onCreateView(GroupFragment.java:107)

corresponds to this line of the code in the onCreateView of the GroupFragment:
currentUser = mAuth.getCurrentUser().getUid();
And here is FATAL error:
02-09 20:24:10.950 24837-24837/com.example.aliton.myapp E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.NullPointerException
        at com.example.aliton.myapp.Fragments.GroupFragment.onCreateView(GroupFragment.java:107)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
        at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1244)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1092)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:15294)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:665)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:447)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4818)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4818)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1421)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:712)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:605)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4818)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4818)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1421)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:712)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:605)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4818)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2432)
        at android.view.View.measure(View.java:15294)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1872)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1115)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1296)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1013)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4245)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
        at android.view.Choreographer.doCallbacks(Choreographer.java:555)
        at android.view.Choreographer.doFrame(Choreographer.java:525)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5076)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
        at com.

I appreciate any help.

A: There are 3 problems here

*

*Auth listener is async, so that create race conditions with the fragments adapter

*You are attaching the auth listener on onStart after onCreate by that moment the fragment is already attached

*You are making the main logic screen to be the entry point if the user is not logged then it returns to login. It should be backward, you should make the login allows the user to move forward to the next activity.

For fixing 1 and 2 you will have to refactor your code.
For fixing number 3 you should set login as default activity in the manifest.
For fixing what you have now, add this in the onCreate method of the main
FirebaseApp.initializeApp(this);

        mAuth = FirebaseAuth.getInstance();
        RootRef = FirebaseDatabase.getInstance().getReference();
if (mAuth.getCurrentUser() == null) return;

Returning in that point will make the code jump to onStary where you have the auth listener making your logic work

A: If mAuth.getCurrentUser() returns null, that means the user isn't signed in yet, or more accurately: that the Firebase client hasn't verified that the user has signed in yet. The verification happens asynchronously and it could be that your mAuth.getCurrentUser() runs before it has completed.
The solution for this problem is always the same: use an AuthStateListener like you do in the activity.
So something like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.group_fragment, container, false);

    groupTablePath = getContext().getFilesDir().getPath()+"/GroupDataBase/";
    rootPath = Environment.getExternalStorageDirectory() + "/";

    mAuth = FirebaseAuth.getInstance();
    FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            if (firebaseAuth.getCurrentUser() != null) {
                currentUser = mAuth.getCurrentUser().getUid();

                // TODO: any code that needs the UID should be in here

            }
        }

The onAuthStateChanged gets executed whenever the authentication state of the user changes. So in this case also once the client has verified the authentication state. And from that moment on, you can safely get the user's UID.


text:
Q: Show factory variable in view without controller inheritance I currently have 1 factory that looks like this:
export function PageFactory() {
    var title = 'default';
    return {
      title: function() { return title; },
      setTitle: function(newTitle) { title = newTitle }
    };
  }

In a controller i'm injecting the factory like:
constructor(private $scope:IMainScope, $rootScope, $window, $route, Page) {
    Page.setTitle('home');
}

Now i want to display the variable in the view, like {{ Page.title }} but this doesn't work, only if i inject the factory and point the title to an variable in the controller like:
constructor(private $scope:IMainScope, $rootScope, $window, $route, Page) {
    $scope.title = Page.setTitle('home');
}

And display the variable like: {{ title }} but i would like to be able to do this without doing so.

A: You could do $scope.Page = Page; that should point to the factory and access it in view with {{ Page.title }}

A: For class-based coding style controllerAs syntax is preferred. In current guidelines the use of $scope is limited to operations where it is indispensable (watchers and events).
Considering that controllerAs is $ctrl, it is
constructor(..., private Page) {}

and
{{ $ctrl.Page.title() }}

It always depends on the particular case if it is admissible to expose the whole service to view or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.Net web service always return XML not JSON Currenly i use asp.net web service but when i call web service method by ajax call it always return XML not json
i try
ASP.Net web service won't return JSON - Always XML
but its also not work for me..
JS :-
$.ajax({
            type: "Post",
            contentType: "application/json; charset=utf-8",
            url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
            dataType: "jsonp",
            success: function (data) {
                alert("1" + data);
            },
            error: function (result) {
                alert("2" + JSON.stringify(result));
            }
});

LoginWebservice.asmx :-
 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string Demo()
    {
        return "Harshit";
    }

where i am wrong..
jsfiddle Example:-
http://jsfiddle.net/EXvqc/

A: First you have to use Post method to send a request to your web service. And as you have used JSONP as it always looks for the callbacks, and you have to define callback methods for it.
Please Refer
And the other thing you have to add like following
[System.Web.Script.Services.ScriptService]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class LoginWebservice : System.Web.Services.WebService
    {

        [WebMethod]
        public string Demo()
        {
            return "Harshit";
        }
    }

Indicates that a Web service can be invoked from script. This class cannot be inherited.
Your aspx/HTML will contain
$.ajax({
            type: "Post",
            contentType: "application/json; charset=utf-8",
            url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
            dataType: "json",
            success: function (data) {
                alert("1" + data);
            },
            error: function (result) {
                alert("2" + JSON.stringify(result));
            }
});

See output below

A: JSONP is not JSON, JSONP is used to get over the same origin policy (site A cannot make ajax request to site B). To solve this problem site A will create a script tag:
document.createElement("script")

Then set it's source to site B, usually specifying a callback like www.B?callback=callMe
A typical response of site B would be:
callMe({siteBSays:"hello"});

JQuery hides creating the javascript element for you so it looks like a normal ajax request. Make sure site B has the right response type headers I think it's text/javascript
Another way to do cross domain requests is that site B has a response header that allows site A making ajax requests to it (cors) by setting a response header Access-Control-Allow-Origin


text:
Q: Cronjob to exec into a pod and print output of a command I am trying to put this command
kubectl exec -t pod/phase4c-helloworld-7b8bb54559-lsl4t -n phase4c -- /bin/bash -c "echo testing1

in a script and run as cronjob. This is a simple version of my script. I want to run commands in the container and get the output to a file.
But getting an error => Must be running in a tty to pass the '--tty flag'.
How can I get the output to a file like this :
00 05 * * sun /home/dcosadmin/scripts/imageCleanup.sh > /tmp/cleanup.out

A: Remove the -t argument. It's the TTY option.


text:
Q: How to access Pages document when I forgot the password for it? Sometimes I set up a password for my Pages document, and I forget it. Is there a way to access the document without a password or recover password back anyway?

A: No. What would be the purpose of a password if you didn't need it to open the document.
Next time, write down the password if you forget easily.

A: I'm having the same problem. As far as I know there is absolutely no way to open a locked document without the password. I have searched many different websites and the all came up with this same answer.  And I hope for your sake that those documents aren't to important. But don't give up and delete your documents just yet, because maybe if you look in the right places you'll find a way. I recommend that next time you lock a document you add a hint you know will help you.(I didn't do that and that's where my problem started.) I'll come back and let you know if I find a better answer. I hope this helped!

A: *

*Open a new document

*Go to original document

*Go to edit and select all

*They go back to the new document and paste

Now, write down the new password or make it something that you can remember
Hope that works for you.

A: Pages, as any iWork documents with password protection, are AES-128 encrypted. As of today, there is no easy way around it.
The following describes the hard way: Attacking the password with brute force. It can only help you, if the password is somewhat weak:

*

*Short password (~ less than 6 characters)

*You know which characters/words are used in the password (and they are not many)

*Common words of your language

Get a copy of "John the Ripper" (jumbo version):
git clone https://github.com/openwall/john.git

Build JtR:
cd john/src
./configure
make

The jumbo-version of JtR provides a tool to convert an iWork (pages) file into a problem JtR can tackle.
john/run/iwork2john.py encrypted.pages > encryped.hash

Now, your copy of JtR can try to brute force the password. For a dictionary attack, try the rockyou.txt dictionary of commonly used passwords:
wget https://www.scrapmaker.com/data/wordlists/dictionaries/rockyou.txt

./john/src/john --wordlist='rockyou.txt' encryped.hash

John the Ripper will work on all available threads to try out all passwords. If you know anything about the password, you can run JtR with a mask.
For example: You know that the PW starts with an uppercase letter and continues with 5 lowercase letters:
./john/src/john --mask='?u?l?l?l?l?l' encrypted.hash

For more brute-force mechanisms and techniques, please check the documentation
Please note that the longer the password is, the time to brute-force it grows by an order of magnitude. JtR will give you an estimation on when it's going to be finished. If you need more computational power, there are cloud-services which can help you.


text:
Q: Boto3 - Can I get items with batch_get_item whose sort key begins with a variable? I'm using boto3 to deal with AWS Dynamo DB.
I'd like to query once to get items whose sort key begins with some variable in two partition keys.
I've read documents many times, but the examples are all about getting items that exactly match partition key and sort key.
I know it's possible for one partition key to get items whose sort key begins with ABC_.
response = table.query(
    KeyConditionExpression=Key('partition_key').eq(partition_key1) &
                           Key('sort_key').begins_with('ABC_')
)
response2 = table.query(
    KeyConditionExpression=Key('partition_key').eq(partition_key2) &
                           Key('sort_key').begins_with('ABC_')
)

But is it also possible to query once to get multiple items in two partition keys whose sort key begins with ABC_?
response = dynamodb.batch_get_item(
    RequestItems={
        'test_table': {
            'Keys': [
                {
                    'partition_key': partition_key1,
                    'sort_key': 'ABC_1',  # begins with 'ABC_'
                },
                {
                    'partition_key': partition_key2,
                    'sort_key': 'ABC_2',  # begins with 'ABC_'
                },
            ],
        }
    }
)

A: No, you will need to use two queries. Execute them in parallel if you need a faster response.


text:
Q: set default new text file line delimiter to Unix in spring STS IDE How to set new text file line delimiter as Unix in Spring STS ? I am looking for setting that can apply for all workspace while IDE loading, not for each workspace.
Not expecting this answer:
Workspace: Window -> Preferences -> General -> Workspace -> New text file line delimiter.

A: You can set default preferences for everything in the plugin_customization.ini file for the product. This file is normally in the main product plug-in directory.
The line separator preference is called line.separator in the org.eclipse.core.runtime preferences, so the entry in the plugin_customization.ini file would be something like:
org.eclipse.core.runtime/line.separator=\n

for Unix line separators. \r\n for Windows.


text:
Q: Using ReplaceAll on matrix to produce new list of complete matrices This seems like something simple but I can't find the answer.
If I have as input:
{{1, 2}, {3, d}} /. d -> {4, -4}

Mathematica outputs:
{{1, 2}, {3, {4, -4}}}

(which is logical as it simply replaces d with the list given)
What I'd like is the following output, i.e., a new list of complete 2x2 matrices:
{{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}}

To give a bit more context, I have two lists of matrices that I'd like to multiply to give all the combinations, e.g.:
list1 = {A,B,C}
list2 = {D,E}

into
{A.D,A.E,B.D,B.E,C.D,C.E}

I already found this trick:
Dot @@@ Tuples[{list1, list2}]

But prior to multiplying the list I need to do a replace all as described above to produce the actual matrices to multiply together.
Thanks

A: You can just use Table:
Table[{{1, 2}, {3, d}}, {d, {4, -4}}]
(* {{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}} *)

A: rules =  List /@ Thread[d -> {4, -4}]

{{d -> 4}, {d -> -4}}

{{1, 2}, {3, d}} /. rules

{{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}}

Note: With a list of rules ReplaceAll uses the first matching rule:
x /. {x -> 1, x -> a, x -> 2}

1

To apply each rule separately, you need to wrap each rule with List:
x /. {{x -> 1}, {x -> a}, {x -> 2}}

{1, a, 2}


text:
Q: Windows fnmatch substitute I have the following code in Linux that looks for files that matches the given wildcard:
    std::vector<std::string> listFilenamesInPath(std::string wildcard = "*", std::string directory = "./")
    {
        std::vector<std::string> result;
        DIR* dirp = opendir(directory.c_str());

        if (dirp)
        {
            while (true)
            {
                struct dirent* de = readdir(dirp);

                if (de == NULL)
                    break;

                if (fnmatch(wildcard.c_str(), de->d_name, 0))
                    continue;
                else
                    result.push_back (std::string(de->d_name));
            }

            closedir(dirp);
        }

        std::sort(result.begin(), result.end());

        return result;
    }

I´m porting this code to Windows and found out that fnmatch is not available  (dirent is also not available, but I could find one according to the following SO link.
Is there a fnmatch substitute function that does exactly the same thing ?
How can I make this code compile and run in a VS2012 without breaking up my logic ?

A: Thanks for SergeyA for the help. Here is my final solution in case someone needs in future...
#ifdef _WIN32
#include "dirent.h"
#include "windows.h"
#include "shlwapi.h"
#else
#include <dirent.h>
#include <fnmatch.h>
#endif
    std::vector<std::string> listFilenamesInPath(std::string wildcard = "*", std::string directory = "./")
    {
        std::vector<std::string> result;

        DIR* dirp = opendir(directory.c_str());

        if (dirp)
        {
            while (true)
            {
                struct dirent* de = readdir(dirp);

                if (de == NULL)
                    break;

#ifdef _WIN32
            wchar_t wname[1024];
            wchar_t wmask[1024];

            size_t outsize;
            mbstowcs_s(&outsize, wname, de->d_name, strlen(de->d_name) + 1);
            mbstowcs_s(&outsize, wmask, wildcard.c_str(), strlen(wildcard.c_str()) + 1);

            if (PathMatchSpecW(wname, wmask))
                result.push_back (std::string(de->d_name));
            else
                continue;
#else
                if (fnmatch(wildcard.c_str(), de->d_name, 0))
                    continue;
                else
                    result.push_back (std::string(de->d_name));
#endif
            }

            closedir(dirp);
        }

        std::sort(result.begin(), result.end());

        return result;
    }

Please comment if something can be improved...

A: Looks like PathMatchSpec is your guy.


text:
Q: Confused about implementing multipiping in a shell So I have been trying to implement piping in my own shell program so that I can actually understand what UNIX is doing. I'm very very close at the moment, but for some reason my program is going into an infinite loop when I pipe. I'm pretty sure my problem is stemming from my waitpid arguments not ever letting the last pipe close, because if I make the final loop in the code below be i is less than count-1 instead of i is less than count it will run the command on the left of the pipe. But once I put it back to i is less than count it just loops forever.
           if(pipes)
                   {
            for (i=0;i<count-1;i++)
            {

                 if( pipe(fd) ==-1)
                 {
                 perror("Pipe failure");
                 return;
                 }

                read[i+1] = fd[0];
                write[i] = fd[1];
            }
        }

    for(i=0;i<count;i++)
    {
        pid = fork();

        if(pid < 0)
        {printf("fork failed");}

        else if(pid>0)
        {pids[i] = pid;}
        else
        {
            if(write[i] != -1)
            {
                if(dup2(write[i],STDOUT_FILENO) ==-1)
                {
                perror("dup2 failure");
                exit(1);
                }
            }
            if(read[i] !=-1)
            {
                if (dup2(read[i], STDIN_FILENO)==-1)
                {
                perror("dup2 failure");
                exit(1);
                }
            }
        for (j=0; j<count; j++)
            {
            close(write[j]);
            close(read[j]);
            }

    execvp(input[i], input);
    exit(1);
        }//end else
    }//end for

  for(i=0; i < count; i++){

  if(write[i] != -1)
  close(write[i]);

  if( read[i] != -1)
  close (read [i]);

  waitpid(pids[i], &status,0);
 }
           }
    return (status);}

I think I'm really really close to the solution but for the time being I'm stuck. I've researched piping a ton, but I guess I'm just not quite getting it. Thanks for any help.

A: Please format your code.  It is unreadable right now.
That being said, a few errors:

*

*You are not setting write[0].  You are setting write[count-1] and read[count].

*You are waiting for pids[i] while the parent still has read[i] open.  If input[i] wants will not exit until it gets EOF on stdin, it will never happen.


text:
Q: Joomla Website - Whenever user gets a link without "www." in the URL, the website automatically redirects to homepage For example, if my link is: "http://example.com/about/blahblahblah"
It automatically redirects to example.com (homepage)
On the other hand if I write http://www.example.com/about/blahblahblah - it takes the user to that specific page properly like it is intended to.
I wanted to know how I can make the first link (that is without "www." in the URL) also take the user to the specific page properly as intended.
If it helps, from what I googled so far, it seems like something that the .htaccess file can fix but I have no experience with coding in there.
Thanks in advance!

A: Seem that something is wrong with your .htaccess file or server configuration.
Please check if you have renamed htaccess.txt to .htaccess and it's not altered with custom rules.
To make permanently htaccess redirects you have to add:
Force the www.
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Remove the www.
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

Here is the complete helpful guide.
Good Luck!


text: Q: Error with creating virtualenv on windows 10 When i try to run virtualenv env on cmd at the folder desired I get this error: virtualenv env FileNotFoundError: [Errno 2] No such file or directory: 'c:\\users\\zac\\appdata\\local\\programs\\python\\python37\\Lib\\venv\\scripts\\nt\\python.exe'


text:
Q: How to rename qrc file? There is project based on MDI example. I work with it in Visual Studio 2013.
I want to rename mdi.qrc file. But after renaming I get error

1>main.obj : error LNK2019: unresolved external symbol "int __cdecl qInitResources_mdi(void)" (?qInitResources_mdi@@YAHXZ) referenced in function _main

What do I need to do?

A: There is need to edit Q_INIT_RESOURCE argument.
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(mdi);


text:
Q: Plotting a Heat map using x, y and z arrays I have a data set that consists of:
x = [ 4.e-06  4.e-06  4.e-06  4.e-06  4.e-06  4.e-06  4.e-06  4.e-06  4.e-06
  3.e-06  3.e-06  3.e-06  3.e-06  3.e-06  3.e-06  3.e-06  3.e-06  3.e-06
  2.e-06  2.e-06  2.e-06  2.e-06  2.e-06  2.e-06  2.e-06  2.e-06  2.e-06
  1.e-06  1.e-06  1.e-06  1.e-06  1.e-06  1.e-06  1.e-06  1.e-06  1.e-06
  0.e+00  0.e+00  0.e+00  0.e+00  0.e+00  0.e+00  0.e+00  0.e+00  0.e+00
 -1.e-06 -1.e-06 -1.e-06 -1.e-06 -1.e-06 -1.e-06 -1.e-06 -1.e-06 -1.e-06
 -2.e-06 -2.e-06 -2.e-06 -2.e-06 -2.e-06 -2.e-06 -2.e-06 -2.e-06 -2.e-06
 -3.e-06 -3.e-06 -3.e-06 -3.e-06 -3.e-06 -3.e-06 -3.e-06 -3.e-06 -3.e-06
 -4.e-06 -4.e-06 -4.e-06 -4.e-06 -4.e-06 -4.e-06 -4.e-06 -4.e-06 -4.e-06]
and
y = [ 4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06
  4.e-06  3.e-06  2.e-06  1.e-06  0.e+00 -1.e-06 -2.e-06 -3.e-06 -4.e-06]
and
z = [[-1.51449500e+23 -1.38106793e+15 -1.38106793e+15 ... -1.38106793e+15
  -1.38106793e+15 -1.38106793e+15]
 [-1.66499269e+15 -1.51449500e+23 -1.66499269e+15 ... -1.66499269e+15
  -1.66499269e+15 -1.66499269e+15]
 [-2.00000000e+15 -2.00000000e+15 -1.51449500e+23 ... -2.00000000e+15
  -2.00000000e+15 -2.00000000e+15]
 ...
 [-2.49999997e+17 -2.49999997e+17 -2.49999997e+17 ... -1.51449500e+23
  -2.49999997e+17 -2.49999997e+17]
 [-1.99999999e+18 -1.99999999e+18 -1.99999999e+18 ... -1.99999999e+18
  -1.51449500e+23 -1.99999999e+18]
 [-1.99999999e+18 -1.99999999e+18 -1.99999999e+18 ... -1.99999999e+18
  -1.99999999e+18 -1.51449500e+23]]

Here x and y both have a size of 81 and z has a size of (81,81). I was wondering how to make a heat map of this. Currently I have  contour plot that looks like:
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(x, y, z, 50)

Contour plot of x,y,z
I was looking to use a heatmap instead here because the contour plot is messy and you can't see what's going on. A top down view of this plot could work as well with a colour bar on the side to show the magnitude in the z direction.


text:
Q: Get a excel dropdown from the cell addreess I have  a excel worksheet .There is a drop down columns . I need to get a specific drop down from the cell address .
i get the worksheet from following code
             Application application;
             Workbook activeWorkBook;
             Worksheet activeWorkSheet;

             application = (Application)Marshal.GetActiveObject("Excel.Application");

             activeWorkBook = (Workbook)application.ActiveWorkbook;

             activeWorkSheet = activeWorkBook.ActiveSheet;

how to get a drop down in a specific cell using cell address in active worksheet.

A: The easiest solution is: Do it manually without VBA. Assuming you know that and you would like to automate the procedure
Scroll down on this page..


text:
Q: javascript not working from network drive I'm trying to run the below file. It runs perfectly fine when I run it on a local drive but if I place it on a network drive it no longer works. Any idea why this might be?
The below is code that I am trying to run. It is using pivottable from here: https://github.com/nicolaskruchten/pivottable.
<!DOCTYPE html>

    <title> Demo</title>

    <link rel="stylesheet" type="text/css" href="../dist/pivot.css">

A: File:/// urls will run in a different context than HTTP/HTTPS and other contexts (internal, public, private, unsafe).  What limitations in question depend on the specific browser, the OS and the context itself.
If you must execute JavaScript within HTML, the safest and most assured way to run is to have it running via a web server.

Also worth noting, there are a few local/relative files. ../dist/pivot.js and ../dist/pivot.css are you sure you're saving those files, and they are in the correct relative path as well?


text:
Q: Strange Problem, Navigation Code Only Works In The Morning (California Time) I've encountered a strange problem where this code only runs in the morning (12am ~ 6am) California time.
 Directions.shared.calculate(options){ (session, result) in

        print("Here: \(result)")
        guard case let .success(response) = result,
            let route = response.routes?.first else{
                print("This did't work")
                return
        }

It's been happening for the past two days. I don't think it's on my end but what should I do? This is for the iOS-Navigation-SDK.
I get the error:
 failure(MapboxDirections.DirectionsError.unableToRoute)

A: If anyone is reading this and having the same issue, they're upgrading their service early July. Just wait for the update and problem solved.


text:
Q: NotificationChannel setSound and vibration not working I have a problem to play sound, when notification will come, notification is showing, but there is no sound or vibration, I saw many question and answers to how to set the sound and vibration to notificaiton channels, but it doesn't works, this is how I'm trying that
val pattern = longArrayOf(0, 200, 60, 200)
val chatSound = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" + context.packageName + "/" + R.raw.chat_alert)
val mBuilder = NotificationCompat.Builder(context, CHANNEL_ID)
  .setSmallIcon(R.mipmap.ic_launcher)
  .setContentTitle(title)
  .setContentText(body)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val notification = mBuilder.build()

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  val mChanel = NotificationChannel(CHANNEL_ID, "test", NotificationManager.IMPORTANCE_HIGH)
  val audioAttributes = AudioAttributes.Builder()
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build()
  mChanel.setSound(chatSound, audioAttributes)
  mChanel.enableVibration(true)
  mChanel.enableLights(true)
  mChanel.vibrationPattern = pattern
  mNotificationManager.createNotificationChannel(mChanel)
}
mNotificationManager.notify(i, notification)

I'm testing it for Android Pie
targetSdkVersion 28

A: Seems when notification channel is created at first time then it doesn't automatically update if something where changed, like in my case, at first, I ran notification channel without sound and vibration.
Solution: Clear app data or just uninstall the app, after that it worked properly


text:
Q: Match in awk disregarding white space  1 #!/bin/bash
 2 KEY_FILE="keys"
 3 TABLE_FILE="table" #pipe delimited data
 4
 5 i=0;
 6 while read key #print out rows in table file with key in keys file
 7 do
 8   let i=i+1
 9   # key is first column in table
10   # print status to stderr
11   (echo "$KEY_FILE : line $i" >&2)
12   awk -F '|' "\$1 == $key {print \$0}" $TABLE_FILE
13 done < $KEY_FILE
14

From line 12, will awk match the first column against the key if there is a white space discrepancy?

A: No, because you set your field separator. Whitespace characters are now significant.
You can set your field separator to be a regular expression to slurp up whitespace.  Also, pass the value of the shell variable into an awk variable to avoid quoting hell.
gawk --posix -F '[[:space:]]*\|[[:space:]]*' -v k=$key '$1 == k' $TABLE_FILE

Note that {print $0} is the default action, so that can be omitted.
Also, awk can handle two files, so you don't need the bash loop:
gawk --posix -F '[[:space:]]*\|[[:space:]]*' '
  NR == FNR {key[$1] = ""; next}
  ($1 in key)
' $KEY_FILE $TABLE_FILE

The expression NR == FNR means that awk is looking at the first file in the list of files (NR is the "total record number" and FNR is the record number of the current file: they will only be the same for the first file). This program saves the keys in the key array, and the prints the records in the table file that have a key in that array.


text:
Q: Using commas inside a macro without parenthesis: How can I mix and match with a template? Consider a simple macro:
#define ECHO(x) x

ECHO(foo(1, 2))

This produces the exact output we expect:
foo(1, 2)

The above example works because the parenthesis adjacent to the function call are recognized by the preprocessor.
Now consider what happens if I use a template instead of a function call:
ECHO(template<int, bool>)

This causes an error because the preprocessor interprets the template<int and the bool> as two separate arguments to the macro. The preprocessor doesn't recognize <> for scope!
Is there anyway to use a template like this in a macro?

A: A variadic macro may help:
#define ECHO(x...) x

ECHO(foo(1, 2))
ECHO(template<int, bool>)

A: #define COMMA ,
ECHO(template<int COMMA bool>)

A little painful, but it works.
FWIW, if the syntax for the argument allows ()s, you don't need the substitution, e.g.,
ECHO((a, b))

will work for a single argument macro but that doesn't work in all cases (including yours).

A: if you allow usage of Cog in your project, your code becomes more readable:
/*[[[cog
# definitions ----
import cog

def AddDeclaration( templateArg , restOfDeclaration ):
    cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))

# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
    AddDeclaration( 'template<int, %s>' % types[index] , names[index])
]]]*/
//[[[end]]]

After you run cog over this file, you'll get:
/*[[[cog
# definitions ----
import cog

def AddDeclaration( templateArg , restOfDeclaration ):
    cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))

# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
    AddDeclaration( 'template<int, %s>' % types[index] , names[index])
]]]*/
template<int, bool> struct Foo; <---------------- generated by Cog!!
template<int, std::string> struct Bar;
//[[[end]]]

You can even move your definitions in separate .py files and the cog section will look like:

declarations.py
import cog

def AddDeclaration( templateArg , restOfDeclaration ):
    cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))

my.h
/*[[[cog
# definitions ----
import declarations
# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
    AddDeclaration( 'template<int, %s>' % types[index] , names[index])
]]]*/
template<int, bool> struct Foo;
template<int, std::string> struct Bar;
//[[[end]]]

the main advantage of using cog is that you gain complete control of your code generation, completely avoid unreadable messes using boost preprocessor or stuff like that.
the main disadvantage is that you add a new tool dependency to your project, also since you need to wrap its usage in comments with the cog section markers, it might actually be worse than writing the code manually for small usages. It really pays off when you need to declare big enums or lot of unavoidable boilerplate code


text:
Q: How does this "Sort((x, y) => x.CompareTo(y))" work? Please look at this block of code:
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(6);
        list.Add(2);
        list.Add(3);
        list.Add(8);
        list.Sort((x, y) => x.CompareTo(y));
        int[] arr = list.ToArray();
        foreach (var i in arr)
        {
            Console.WriteLine(i);
        }

I know that when executed, the code above will print the list in ascending order. If I switch the positions of x and y in "x.CompareTo(y)", then the list will be sorted in descending order instead. I know what CompareTo() does, but here how does it work with x and y to decide the order of sorting? what does x and y represent here?

A: Sort method signature is public void Sort(Comparison<T> comparison), and if you see the declaration of Comparison it is public delegate int Comparison<in T>(T x, T y).
Just see the comments for Comparison.
//
// Summary:
//     Represents the method that compares two objects of the same type.
//
// Parameters:
//   x:
//     The first object to compare.
//
//   y:
//     The second object to compare.
//
// Type parameters:
//   T:
//     The type of the objects to compare.
//
// Returns:
//     A signed integer that indicates the relative values of x and y, as shown in the
//     following table.
//     Value – Meaning
//     Less than 0 –x is less than y.
//     0 –x equals y.
//     Greater than 0 –x is greater than y.

So it does the comparison for all the elements in the order, and if you swap x and y then it will do just the reverse of it.

A: In simple terms, (x, y) => x.CompareTo(y) is like a one line version of a method - it goes by various names, usually "lambda" or "delegate". You can think of it as a method that is stripped down as much as possible. Here's the full method, I'll talk about stripping it down shortly:
int MyComparer(int x, int y){
  return x.CompareTo(y);
}

The list will perform a sort and will call this method every time it wants to make a choice as to which of the two ints it's considering, is larger than the other. How it does the sort is irrelevant, probably quicksort ish, but ultimately it will often want to know whether x is larger, same or smaller than y
You could take that method I wrote up there and call sort with it instead:
yourList.Sort(MyComparer)

So c# has this notion of being able to pass methods round in the same way that it passes variable data around. Typically when you pass a method you're saying "here's some logic you should call when you need to know that thing you want to know" - like a custom sort algorithm trhat you can vary by varying the logic you pass in
In stripping MyComparer down, well.. we know this list is full of ints so we know that x and y are ints, so we can throw the "int" away. We can get rid of the method name too, and because it's just one line we can ditch the curly brackets. The return keyword is unnecessary too because by definition to be useful the single line is going to have to evaluate to something returnable and it shall be returned implicitly. The => separates the parameters from the body logic
(method,parameters) => logic_that_produces_a_value(

So that long winded method can be boiled down to
(x,y) => x.CompareTo(y)

x,y are whatever type the list holds, the result value is a -1, 0 or 1 which list will use to determine how x and y relate sorting wise. They could be called anything; just like when you declare a method MyMethod(int left, int right) and choose to call the parameters "left" and "right", here we do the same because this is just declaring name parameters   - you could easily write (left,right) => left.CompareTo(right) and it'd work the same
You'll see it a lot in c#, because c# devs are quite focused on representing logic in a compact fashion. Often the most useful way of making something flexible and powerful is to implement some of the logic but then leave it possible for another dev to finish the logic off. Microsoft implemented sorting into list, but they leave it up to us to decide "which is greater or lesser" so we can supply logic that influences sort order. They just mandated "any time we want to know which way round two things are we'll ask you" - which means they don't need to have SortAscending and SortDescending - we just flip the logic and declare that 10 is less than 9 if we want 10 to come first.
LINQ relies on "supply me some logic" heavily - you might be looking for all ints less than 3 in your list:
myList.Where(item => item < 3)

LINQ will loop over the list calling your supplied logic (lambda) here on every item and delivering only those where your lambda is true. item is one of the list entries, in this case an int. if the list held Person objects, item would be a Person. To that end I'd recommend calling it p or person to make it clearer what it is. This will become important when you start using more complex lambdas like
string[] wantedNames = new [] { "John", "Luke" };
people.Where(p => wantedNames.Any(n => p.Name == n));

This declares multiple names you're looking for then searches the list of people for all those whose name is in the list of wanted names. For every person p, LINQ asks "wantedNames, do Any of your elements return true for this supplied logic" and then it loops over the wantedNames calling the logic you supplied (n, the item from wantedNames is equal to the person name?).
Here you've used two different methods that take custom logic that LINQ calls repeatedly - Where is a method that takes a delegate, and so is Any; the Any operates on the list of names, the Where operates on the list of people so keeping it clear which is a Person p and which is a name string n using variable names is better than using bland names like a and b.
Got more into on your Sort method see the docs:
See List.Sort(Comparer) for more info
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=net-5.0#System_Collections_Generic_List_1_Sort_System_Comparison__0__


text:
Q: Looking for a fantasy short story/novel - an adventuring party explores a dungeon, dies one by one, and the one survivor becomes a dungeon master In the early 2000s, I read a fantasy short story. I'm 90% sure it was a short story but it honestly could be a novel. It was in French (I live in France) but I can't remember if it was translated from another language.
The story was about a typical adventuring party exploring a dungeon. The main character was a human, but there was also an elf woman and maybe a dwarf. Most of the party ends up dying one by one to monsters or traps, and the human is the only survivor. He is so traumatized by the experience that he chooses to become the master of this dungeon.
This is pretty weird and honestly might not help but I also remember something about an insectoid-looking armor in the story. Maybe the hero puts it on at the end? I'm honestly not too sure about that, maybe I'm mixing it up with another story.
I think also I recall one of the party members getting eaten by a monster?
I keep thinking about this story and would love to read it again, but my memories are too vague to find it on Google.
Would love you guys' help on this one!


text:
Q: Is there a way to monitor an Apache server with Prometheus and Grafana? My requirement is to monitor a Linode Virtual machine that contains Apache using Prometheus and Grafana. (PS - Prometheus and Grafana are running in a seperate Linode VM)
I used the following document to install Apache exporter :
https://www.techbeginner.in/2021/01/install-and-configure-apache-node.html.
The service file is like this :
[Unit]
Description=Prometheus
Documentation=https://github.com/Lusitaniae/apache_exporter
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=prometheus
Group=prometheus
ExecReload=/bin/kill -HUP $MAINPID
ExecStart=/usr/local/bin/apache_exporter \
  --insecure \
  --scrape_uri=http://localhost/server-status/?auto \
  --telemetry.address=0.0.0.0:9117 \
  --telemetry.endpoint=/metrics

SyslogIdentifier=apache_exporter
Restart=always

[Install]
WantedBy=multi-user.target

I've changed the --scrape_uri to http://usr_name:password@localhost/server-status/?auto \ and --telemetry.address to 127.0.0.1:9117 though I'm sure it wouldn't make any difference. Prometheus is able to scrape the data. But when I import a grafana dashboard (ID - 3894) to visualize the data, I don't get any data. Among 7 panels in the entire dashboard (Current total kbytes sent, Current total apache accesses, Apache scoreboard statuses  Apache worker statuses, Apache CPU load, Uptime and Apache Up/Down), I can see the grapf for Apache Up/Down. The other 6 say no data available.
This is the prometheus.yml config:
#Apache Servers
  - job_name: apache-web-server
    static_configs:
      - targets: ['x.x.x.x:9117']
        labels:
          alias: server-apache

PS - Both the Linode instances contain Debian GNU/Linux 9.8 (stretch) as their OS.
What am I missing here? How can I get the graphs for the rest of the panels? Any and all help is appreciated. Thanks a lot in advance.

A: From what you have mentioned, it looks like you have not set the ExtendedStatus on.
Check it out here: https://httpd.apache.org/docs/2.4/mod/mod_status.html.
The details given are:

The number of workers serving requests
The number of idle workers
The status of each worker, the number of requests that worker has     performed and the total number of bytes served by the worker (*)
A total number of accesses and byte count served (*)
The time the server was started/restarted and the time it has been running for
Averages giving the number of requests per second, the number of bytes served per second and the average number of bytes per request (*)
The current percentage CPU used by each worker and in total by all workers combined (*)
The current hosts and requests being processed (*)

The lines marked "(*)" are only available if ExtendedStatus is On.

An example configuration that worked for me covering all the metrics:
ExtendedStatus On

<Location /server-status>
SetHandler server-status
Order deny,allow
Deny from all
Allow from localhost
</Location>

That said, ExtendedStatus is On by default from 2.3.6. I guess you are using an Apache version lower than that.

Side note: I've written an article that covers most aspects of monitoring Apache including granular traffic metrics: https://www.giffgaff.io/tech/monitoring-apache-with-prometheus
It also covers the Apache configuration that uses ExtendedStatus.


text:
Q: Can I use HUD menu for unfocused applications? Example: if I am running LibreOffice Writer on one desktop and Audacious on another, can I train or alter the Unity HUD Alt Command to allow me access to menu items in Audacious even as Writer is the focused window?
I did a little looking around, but I'm stumped. Fuzzy matching seems simply to allow access to focused windows at any given point, unless no windows are focused. Thanks!

A: No, It isn't possible.
Hud is made to replace traditional menu system. As you can't access a menu without bringing the application is focus, You can't do this also in Hud.
Have a look at Mark Shuttleworth's blog. It is saying

It covers the focused app (because that's where you probably want to act) as well as system functionality


text:
Q: Documenting a PHP extension with PHPdoc I've written a PHP extension in C, and I want to create PHPdoc documentation so that my users will get inline docs in their PHP IDE (in this case, Netbeans) when calling my extension.
Ideally I'd like to do this by embedding the PHPdocs in the C code, to keep implementation and documentation together.
Assuming it's possible to embed PHPdocs into the C, what extra steps are needed to make the documentation appear in Netbeans (as it would for PHPdocs of PHP code)?
edit:
O'Reilly Programming PHP refers to the /* {{{ proto comment format being used in doc generation, though I'm not sure if the referred scripts generate PHPdocs:

The {{{ proto line is not only used
  for folding in the editor, but is also
  parsed by the genfunclist and
  genfuncsummary scripts that are part
  of the PHP documentation project. If
  you are never going to distribute your
  extension and have no ambitions to
  have it bundled with PHP, you can
  remove these comments.

A: One approach that works is to have a PHP file with stub functions with the appropriate PHPdocs, then DON'T include it in the PHP application, but DO add it to Netbean's PHP include path (in File->Project Properties->PHP Include Path).
This way type completion and inline docs work, but PHP isn't confused by multiple declarations of the function.
This seems a bit hacky, since it would be good keep the docs in the same file as the implementation, but it does actually seem to the correct approach, since that's how the built in functions and extensions are documented - see ~/netbeans-6.7/php1/phpstubs/phpruntime/*.php
eg:
In the C file:
PHP_FUNCTION(myFunctionStringFunction)
{
// extension implementation
}

And then in a PHP file, the stub declaration:
/**
 * My docs here
 * @param string $myString
 */
function myFunctionStringFunction($myString)
{
  die("Empty stub function for documenation purposes only.  This file shouldn't be included in an app.");
}

A: you only need to use the right TAGS inside your Comments.
 /**
 * Returns the OS Languages for an Subversion ID
 *
 * @access  public
 * @param   int         $subVersionId   Subversion ID
 * @return  array       $results        Languages for Subversion ID
 */

You can find all available tags on the documenation
PHPDoc

A: I think it is possible to use Reflection API to generate the prototype file, though I could not find existing code that does exactly that.

A: As written in extension skeleton:
/* {{{ */ and /* }}} */

The previous line is meant for vim and emacs, so it can correctly fold
  and unfold functions in source code. See the corresponding marks just
  before function definition, where the functions purpose is also
  documented. Please follow this convention for the convenience of
  others editing your code.


text:
Q: Open for Files Only on POSIX It is well known that in C calling open() will return a file descriptor, given a pathname and optional flags.
int fd;
if ((fd = open(pathname, O_RDONLY)) == -1) {
    printf("Could not open file\n");
    return;
}

In the man page for open(), a flag O_DIRECTORY is defined where:

If pathname is not a directory, cause the open to fail.  This
    flag was added in kernel version 2.1.126, to avoid denial-of-
    service problems if opendir(3) is called on a FIFO or tape
    device.

But I couldn't seem to find something like O_FILE, which would cause open() to fail on directories, rather than files.
Is there such a flag that can be passed to open() or another way of determining if pathname is a file, rather than calling stat()?

A: No, there is no such flag.  The stat function is unacceptable as well because it has a race condition.  (In general, you should only call stat by itself, not in combination with open.)
Your options are:

*

*Use fstat.

*Open the file for writing, which returns EISDIR for directories.

*Call read, which returns EISDIR for directories.


text:
Q: Kendo MVVM Bindings Add/Insert Item, How to? I have defined a kendo datasource with transport methods (create, read, update, and destroy), as well as a schema definition:
$(document).ready(function() {
        var viewModel = kendo.observable({
            dsMedication: new kendo.data.DataSource({
                type: "json",
                serverFiltering: true,
                serverPaging: true,
                pageSize: 6,
                error: function(e) {
                    //alert(e.responseText);
                    //var error_obj = $.parseJSON(e.responseText);
                    //if (error_obj.Message != null) {
                    //alert(error_obj.Message);
                    //}
                },
                transport: {
                    read: {
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        url: "../Services/svcMedication.asmx/SearchMedication",
                        dataType: "json",
                        cache: false
                    },
                    update: {
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        url: "../Services/svcMedication.asmx/SaveMedication",
                        dataType: "json",
                        cache: false
                    },
                    destroy: {
                        url: "../Services/svcMedication.asmx/DeleteMedication",
                        type: "DELETE",
                        dataType: "json",
                        cache: false
                    },
                    create: {
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        url: "../Services/svcMedication.asmx/SaveMedication",
                        cache: false
                    },
                    parameterMap: function(options, operation) {
                        if (operation !== "read" && options.models) {
                            return kendo.stringify({ models: options.models });
                        }
                        options.MedicationParam = $('#acMedications').val();
                        return kendo.stringify(options);
                    }
                },
                batch: true,
                schema: {
                    data: "d",
                    model: {
                        id: "MedicationId",
                        fields: {
                            MedicationId: {
                                type: "number",
                                editable: false // this field is not editable
                            },
                            Name: {
                                type: "text",
                                validation: { // validation rules
                                    required: true // the field is required
                                }
                            }
                        }
                    }
                }
            }),
            SelectedMedication: null,
            HasChanges: false,
            save: function() {
                //if (this.SelectedMedication == null) {
                    //this.dsMedication.add({ MedicationId: this.get("MedicationId"), Name: this.get("Name") });
                //}
                this.dsMedication.sync();
                this.set("HasChanges", false);
            },

            remove: function() {
                if (confirm("Are you sure you want to delete this record?")) {
                    this.dsMedication.remove(this.SelectedMedication);
                    this.set("SelectedMedication", this.dsMedication.view()[0]);
                    this.change();
                }
            },
            showForm: function() {
                return this.get("SelectedMedication") !== null;
            },
            change: function() {
                this.set("HasChanges", true);
            }
        });

        kendo.bind($("#fmMedication"), viewModel);
    });

My form elements contain appropriate data-bind attributes to form elements, and I am calling kendo.bind passing the form. The goal is that the form is used for both adding and editing records.
If I search an item and make changes to it, everything works like a charm!
MY PROBLEM IS:
I am not sure how to write the code to initialize the form for adding a new record to the datasource.
I've been unsuccessful finding an example or resources on this anywhere!!
Any help would be appreciated! Thanks!

A: Basically since you have not defined the Model explicitly you cannot easily create instances of it. So if you have declared the model separately like here - it will be a little bit easier to create instance and most probably you would know what to do next.
In your case you can create instance of the model like this:
var newRecord = new viewModel.dsMedication.reader.model();

Once you have new record you can easily add it to the dataSource either via the add or the insert methods (they are both described in the documentation).
And finally when you have the records added locally (you should be able to see the changes immediately on the screen) you can call the sync method of the dataSource to send these new records to be saved on the server - the create transport option will be used.


text:
Q: Thread Pool: DispatchQueue.main.async I'd worked on Java, and pretty much clear with the working of threads and thread pool.
I was wondering if anyone can explain the working of how thread's are created and allocated space in the thread pool in swift ?.
Also, does
Dispatch.main.async {
 // some code
}

Creates a new Thread or Asynchronously executes the task ?
Thanks in advance =)

A: Your code queues the block of code on the main queue (Dispatch.main) and returns immediately (.async), before executing the code.
You do not have control over which thread is used by the queue. Even if you create an own queue:
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.async {
    ...
}

you do not know which thread your code will be running on.

Update:
As correctly stated by Paulw11 in the comment,

... if you dispatch a task on the main queue, it is guaranteed to execute on the main thread. If you dispatch a task on any other queue, you don't know which thread it will execute on; it may execute on the main thread or some other thread.

A: Queues and threads are separate concepts. Queues are ordered (sometimes prioritized) sequences of blocks to execute. As (mostly) an implementation detail, blocks must be scheduled onto threads in order to execute, but this is not the major point of them.
So Dispatch.main.async dispatches (appends) a block to the main queue. The main queue is serial and somewhat special in that it is promised to also be run exclusively on the main thread (as noted by Paulw11). It also promises to be associated with the main runloop. Understanding this "appends a block to a queue" concept is critical, because it has significant impact on how you design things in queues vs how you design things in threads. async does not mean "start running this now." It means "stick this on a queue, but don't wait for it."
As a good example of how the designs can be different, placing something on a queue doesn't mean it will ever run (even without bugs or deadlocks). It is possible and useful to suspend queues so that it stops scheduling blocks. It's possible to tie queues to other queues so that when a queue "schedules" something, it just puts it onto another queue rather than executing it. There are lots of things you can do with queues unrelated to "run things in the background." You can attach completion handlers to blocks. You can use groups to wait on collections of blocks. GCD is a way of thinking about concurrency. Parallelism is just a side benefit. (A great discussion of this concept is Concurrency is not parallelism by Rob Pike. It's in Go, but the concepts still apply.)
If you call Dispatch.main.async while running on the main queue, then that block is absolutely certain to not execute until the current block finishes. In UIKit and AppKit, "the current block finishes" often means "you return from a method that was called by the OS." While not implemented this way, you can pretend that every time you're called from the OS, it was wrapped in a call to Dispatch.main.async.
This is also why you must never call Dispatch.main.sync (note sync) from the main queue. That block will wait for you to return, and you'll wait until the block finishes. A classic deadlock.
As a rule, the thread pool is not your business in iOS. It is an implementation detail. Occasionally you need to think about it for performance reasons, but if you are thinking too much about it, you probably are designing your concurrency incorrectly.
If you're coming from Java, you definitely want to read Migrating Away From Threads in the Concurrency Programming Guide. It's the definitive resource for how to rethink thread-based patterns in queues.


text:
Q: all.equal on object with NULL names causes 'Error: not compatible with STRSXP' -- bug or expected? In the example below, when names are set to NULL, all.equal throws 'Error: not compatible with STRSXP'
However, if names are set to NA (or some other value), all.equal works as normal.
Is this expected behavior or a bug?
## SAMPLE DATA
set.seed(1)
x <- data.frame(LETTERS[1:3], rnorm(3))
names(x) <- NULL

x
#   NA        NA
# 1  A -0.626454
# 2  B  0.183643
# 3  C -0.835629

all.equal(x, x)
# Error: not compatible with STRSXP

# add names back in, even 'NA'
names(x) <- c(NA, NA)
all.equal(x, x)
# [1] TRUE

A: As @Joran points out, this seems to be related to dplyr.
Filed as an issue: https://github.com/hadley/dplyr/issues/219
Temporary work around (for my need at least. Will not work for all) is to use
 all.equal.default(x, x)

FYI:
  ## STARTING FROM A FRESH SESSION:

  set.seed(1)
  x <- data.frame(LETTERS[1:3], rnorm(3))
  names(x) <- NULL

  all.equal(x, x)
  # [1] TRUE

  ## Load in dplyr
  library(dplyr)
  all.equal(x, x)
  # Error: not compatible with STRSXP


text:
Q: NetworkPolicy on Kubernetes to allow only the UI talk to the Backend? The caveat seems to be that the backend (flask service) needs to talk to the MongoDB for fetching the data. If in the network policy, I add the nodeSelector as my flask service, and add UI to ingress and UI and MongoDB on the Egress to rules, it still does not work.
NAME                                            READY   STATUS      RESTARTS   AGE
pod/xyz-mongodb-replicaset-0                    1/1     Running     0          10d
pod/xyz-mongodb-replicaset-1                    1/1     Running     0          7d
pod/xyz-mongodb-replicaset-2                    1/1     Running     0          6d23h
pod/xyz-svc-7b589fbd4-25qd6                     1/1     Running     0          20h
pod/xyz-svc-7b589fbd4-9n8jh                     1/1     Running     0          20h
pod/xyz-svc-7b589fbd4-r5q9g                     1/1     Running     0          20h
pod/xyz-ui-7d6f44b57b-8s4mq                     1/1     Running     0          3d20h
pod/xyz-ui-7d6f44b57b-bl8r6                     1/1     Running     0          3d20h
pod/xyz-ui-7d6f44b57b-jwhc2                     1/1     Running     0          3d20h
pod/mongodb-backup-check                        1/1     Running     0          20h

NAME                             TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)     AGE
service/xyz-mongodb-replicaset   ClusterIP   None          <none>        27017/TCP   10d
service/xyz-prod-service         ClusterIP   10.3.92.123   <none>        8000/TCP    20h
service/xyz-prod-ui              ClusterIP   10.3.49.132   <none>        80/TCP      10d

--Deployment--
--Replicasset--
--Statefulset--

My ingress looks like -

Name:             xyz-prod-svc
Namespace:        prod-xyz
Address:
Default backend:  default-http-backend:80 (<none>)
TLS:
  prod terminates xyz.prod.domain.com
Rules:
  Host                      Path  Backends
  ----                      ----  --------
  xyz.prod.domain.com
                            /           xyz-prod-u:80 (10.7.2.4:80,10.7.4.22:80,10.7.5.24:80)
                            /endpoint4    xyz-prod-servic:8000 (IPS...)
                            /endpoint3    xyz-prod-servic:8000 (IPS...)
                            /endpoint2        xyz-prod-servic:8000 (IPS...)
                            /endpoint1   xyz-prod-servic:8000 (IPS...)

Do I have to specify my Ingress in the podSelector option of my Network Policy?
So far my Network Policy looks like this -

---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: application-network-policy
  namespace: app-prod-xyz
  labels:
    app: application-network-policy
spec:
  podSelector:
    matchLabel:
        run: xyz-svc
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: xyz-ui
    - podSelector:
        matchLabels:
          app: application-health-check
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: xyz-ui
    - podSelector:
        matchLabels:
          app: xyz-mongodb-replicaset
    - podSelector:
        matchLabels:
          app: mongodb-replicaset

Troubleshooting:
I have already tried to spin up a pod and add that pod into the ingress. I was able to ping the xyz-svc from the pod when it was allowed in the ingress and denied when i removed it from ingress, hence proving that the network policy was working.
I want to understand labels, selectors and matchLabels.
I have read through these links, but I want an intuitive explanation for my NetworkPolicy like:

podSelector: pod to which the network policy needs to be applied (it
  can be a deployment or app name or tier name or run)
ingress: traffic that is allowed or denied access to the above
  mentioned pod
egress: traffic that is allowed or denied access going out from the
  above mentioned pod. Thee names of pod should match which labels?
namespaceSelector?
podSelector?

EDIT: Ingress YAML
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-expires: "3600"
    nginx.ingress.kubernetes.io/session-cookie-max-age: "3600"
  name: xyz-{{ .Values.environment }}-ingress-svc
  namespace: acoe-{{ .Values.environment }}-xyz
  labels:
    app: xyz-{{ .Values.environment }}-ingress-svc
spec:
  tls:
  - hosts:
    - xyz{{ .Values.ingressDomain }}
    secretName: {{ .Values.tlsSecret }}
  rules:
  - host: xyz{{ .Values.ingressDomain }}
    http:
      paths:
      - path: /
        backend:
          serviceName: xyz-{{ .Values.environment }}-ui
          servicePort: 80
      - path: /endpoint4
        backend:
          serviceName: xyz-{{ .Values.environment }}-svc
          servicePort: 8000
      - path: /endpoint3
        backend:
          serviceName: xyz-{{ .Values.environment }}-svc
          servicePort: 8000
      - path: /endpoint2
        backend:
          serviceName: xyz-{{ .Values.environment }}-svc
          servicePort: 8000
      - path: /endpoint1
        backend:
          serviceName: xyz-{{ .Values.environment }}-svc
          servicePort: 8000

A: Does it work without the NetworkPolicy applied? If it does not work even without the NetworkPolicy, it is likely to be caused by another problem (e.g. wrong service endpoint configured to communicate with), since the default NetworkPolicy allows all traffic between pods inside the same namespace.
The following selector looks like you are applying the NetworkPolicy to all pods in that namespace. If I understood you correctly, you actually want the NetworkPolicy only to be applied on the backend pods (xyz-svc).
spec:
  podSelector: {}

So the solution therefore would probably be something like this (assuming that the backend service pod got the label app = xyz-svc):
spec:
  podSelector:
    matchLabels:
      app: xyz-svc


text: Q: ClickOnce application uninstalls every time computer resets I have multiple ClickOnce applications I have made for a few departments within the company I work for. These applications range from database entry to full QA reporting systems. I have noticed (and also had reported) that whenever I or any of the people using the programs restart their computer it seems to uninstall the program leaving only an icon that directs to the installer where they have to reinstall the application. They are small applications that install in seconds but it is still a little agitating that every time they restart their computers they have to reinstall the software. Is there something I am missing on the manifest/config/security settings within VS2012/VS2015 that will fully install the application and keep it from needing reinstall ever reset? I have tried making it available offline, making it full trust, and a couple other things i found within the app properties and nothing seems to work.


text:
Q: Query running long despite having "good" plan I have a query which is a UNION query which joins multiple tables. All the stats are updated. The query used to run fine and completed within 30-40 seconds but in 12c it's taking insane amount of time(~10 mins to 5 mins)
I have captured the actual plan.
lan hash value: 1038754298

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                                        | Name                   | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |  OMem |  1Mem |  O/1/M   |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                                 |                        |      1 |        |     50 |00:00:49.93 |     960K|      7 |       |       |          |
|   1 |  SORT ORDER BY                                   |                        |      1 |   1791 |     50 |00:00:49.93 |     960K|      7 |   267K|   267K|     1/0/0|
|   2 |   UNION-ALL                                      |                        |      1 |        |   2648 |00:00:49.93 |     960K|      7 |       |       |          |
|   3 |    NESTED LOOPS SEMI                             |                        |      1 |      1 |   2648 |00:00:42.36 |     498K|      0 |       |       |          |
|*  4 |     HASH JOIN                                    |                        |      1 |   1589 |   9111 |00:00:42.22 |     469K|      0 |  7900K|  2299K|     1/0/0|
|*  5 |      HASH JOIN                                   |                        |      1 |   1140K|  50569 |00:00:19.50 |     342K|      0 |  8321K|  2379K|     1/0/0|
|*  6 |       HASH JOIN                                  |                        |      1 |  44335 |  59660 |00:00:16.01 |     252K|      0 |  1817K|  1817K|     1/0/0|
|*  7 |        TABLE ACCESS FULL                         | PROMHEAD               |      1 |    870 |    870 |00:00:00.01 |     602 |      0 |       |       |          |
|*  8 |        HASH JOIN                                 |                        |      1 |   1168K|    172K|00:00:15.94 |     251K|      0 |  1148K|  1148K|     1/0/0|
|*  9 |         TABLE ACCESS FULL                        | PRICE_BATCH_TRAN       |      1 |    857 |    857 |00:00:00.01 |     315 |      0 |       |       |          |
|  10 |         TABLE ACCESS FULL                        | PROMSTORE              |      1 |     36M|     36M|00:00:04.64 |     251K|      0 |       |       |          |
|* 11 |       TABLE ACCESS FULL                          | PROMSKU                |      1 |   6665K|   6665K|00:00:01.49 |   90224 |      0 |       |       |          |
|  12 |      PARTITION RANGE ALL                         |                        |      1 |     37M|     37M|00:00:10.72 |     127K|      0 |       |       |          |
|  13 |       INDEX FAST FULL SCAN                       | PK_ITEM_ZONE_PRICE     |     24 |     37M|     37M|00:00:04.75 |     127K|      0 |       |       |          |
|  14 |     PARTITION RANGE ITERATOR                     |                        |   9111 |  32376 |   2648 |00:00:00.13 |   28752 |      0 |       |       |          |
|  15 |      PARTITION HASH ITERATOR                     |                        |   9111 |  32376 |   2648 |00:00:00.11 |   28752 |      0 |       |       |          |
|* 16 |       TABLE ACCESS BY LOCAL INDEX ROWID BATCHED  | FDT_PRICE_FUTURE       |   9111 |  32376 |   2648 |00:00:00.09 |   28752 |      0 |       |       |          |
|* 17 |        INDEX RANGE SCAN                          | FDT_PRICE_FUTURE_PK    |   9111 |      1 |   2668 |00:00:00.07 |   26089 |      0 |       |       |          |
|* 18 |    HASH JOIN                                     |                        |      1 |   1790 |      0 |00:00:07.31 |     450K|      7 |  1599K|  1599K|     1/0/0|
|  19 |     TABLE ACCESS FULL                            | PRICE_SUSP_HEAD        |      1 |   2056 |   2056 |00:00:00.01 |     965 |      0 |       |       |          |
|* 20 |     HASH JOIN                                    |                        |      1 |   1912 |      0 |00:00:07.30 |     449K|      7 |    39M|  8299K|     1/0/0|
|  21 |      PART JOIN FILTER CREATE                     | :BF0000                |      1 |    745K|    745K|00:00:00.12 |    1682 |      0 |       |       |          |
|  22 |       TABLE ACCESS FULL                          | PRICE_ZONE_GROUP_STORE |      1 |    745K|    745K|00:00:00.03 |    1682 |      0 |       |       |          |
|* 23 |      HASH JOIN                                   |                        |      1 |    496K|      0 |00:00:07.03 |     448K|      7 |    73M|  6638K|     1/0/0|
|  24 |       PARTITION RANGE ALL                        |                        |      1 |   1138K|   1138K|00:00:01.70 |     154K|      7 |       |       |          |
|  25 |        PARTITION HASH ALL                        |                        |     26 |   1138K|   1138K|00:00:01.53 |     154K|      7 |       |       |          |
|  26 |         TABLE ACCESS BY LOCAL INDEX ROWID BATCHED| FDT_PRICE_FUTURE       |    208 |   1138K|   1138K|00:00:01.35 |     154K|      7 |       |       |          |
|* 27 |          INDEX SKIP SCAN                         | FDT_PRICE_FUTURE_I1    |    208 |   1138K|   1138K|00:00:00.89 |     125K|      7 |       |       |          |
|* 28 |       HASH JOIN                                  |                        |      1 |     25M|      0 |00:00:04.84 |     293K|      0 |   977K|   977K|     1/0/0|
|* 29 |        HASH JOIN                                 |                        |      1 |    252K|   1123 |00:00:03.33 |   90826 |      0 |  1344K|  1344K|     1/0/0|
|* 30 |         TABLE ACCESS FULL                        | PROMHEAD               |      1 |    870 |    870 |00:00:00.01 |     602 |      0 |       |       |          |
|* 31 |         TABLE ACCESS FULL                        | PROMSKU                |      1 |   6665K|   6665K|00:00:01.47 |   90224 |      0 |       |       |          |
|  32 |        PARTITION RANGE JOIN-FILTER               |                        |      1 |   6719K|  32778 |00:00:01.51 |     202K|      0 |       |       |          |
|* 33 |         TABLE ACCESS FULL                        | PRICE_SUSP_DETAIL      |     24 |   6719K|  32778 |00:00:01.51 |     202K|      0 |       |       |          |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("IZP"."ITEM"="PSK"."SKU" AND "IZP"."ZONE_GROUP_ID"="PBT"."ZONE_GROUP_ID" AND "IZP"."ZONE_ID"="PBT"."NEW_ZONE_ID")
   5 - access("PS"."PROMOTION"="PSK"."PROMOTION")
   6 - access("PH"."PROMOTION"="PS"."PROMOTION")
   7 - filter("PH"."STATUS"='A')
   8 - access("PS"."STORE"="PBT"."STORE")
       filter("PS"."START_DATE">"PBT"."EFFECTIVE_DATE")
   9 - filter("PBT"."FDC_STATUS"='A')
  11 - filter(("PSK"."CHANGE_TYPE"='MA' OR "PSK"."CHANGE_TYPE"='PC'))
  16 - filter("PRICE_MOD_TYPE"='ZC')
  17 - access("STORE"="PS"."STORE" AND "SKU"="PSK"."SKU" AND "START_DATE"<"PS"."START_DATE")
  18 - access("PSH"."PRICE_CHANGE"="PSD"."PRICE_CHANGE")
       filter("FDT"."START_DATE">"PSH"."ACTIVE_DATE")
  20 - access("PSD"."ZONE_ID"="PZGS"."ZONE_ID" AND "PSD"."ZONE_GROUP_ID"="PZGS"."ZONE_GROUP_ID" AND "FDT"."STORE"="PZGS"."STORE")
  23 - access("PSK"."PROMOTION"="FDT"."PRICE_MOD_NO" AND "PSD"."SKU"="FDT"."SKU")
  27 - access("FDT"."PRICE_MOD_TYPE"='PR')
       filter("FDT"."PRICE_MOD_TYPE"='PR')
  28 - access("PSK"."SKU"="PSD"."SKU")
  29 - access("PH"."PROMOTION"="PSK"."PROMOTION")
  30 - filter("PH"."STATUS"='A')
  31 - filter(("PSK"."CHANGE_TYPE"='MA' OR "PSK"."CHANGE_TYPE"='PC'))
  33 - filter("PSD"."STATUS"='A')

Note
-----
   - this is an adaptive plan

As you can see Oracle predicts the cardinality correctly in most cases. Can you suggest where should I start looking from.
    SELECT
        PBT.STORE                                                                                ,
        PSK.SKU                                                                                ,

        0 MULTI_UNITS                                                                                ,
        0 MULTI_UNIT_RETAIL                                                                                ,
        PS.START_DATE PS_START_DATE                                                                                ,
        PBT.EFFECTIVE_DATE PC_ACTIVE_DATE                                                                                ,
        PBT.ZONE_CHANGE PRICE_CHANGE                                                                                ,
        PH.PROMOTION PRICE_MOD_NO                                                                                ,
        'PR' PRICE_TYPE                                                                                ,
        'U' REC_TYPE
FROM    PROMHEAD PH         ,
        PROMSTORE PS        ,
        PROMSKU PSK         ,
        PRICE_BATCH_TRAN PBT,
        ITEM_ZONE_PRICE IZP
WHERE   PH.PROMOTION         =PS.PROMOTION
        AND PS.PROMOTION     =PSK.PROMOTION
        AND PBT.FDC_STATUS   ='A'
        AND PH.STATUS        ='A'
        AND PS.STORE         =PBT.STORE
        AND PSK.CHANGE_TYPE IN('MA','PC')
        AND IZP.ITEM         =PSK.SKU
        AND IZP.ZONE_GROUP_ID=PBT.ZONE_GROUP_ID
        AND IZP.ZONE_ID      =PBT.NEW_ZONE_ID
        AND PS.START_DATE    > PBT.EFFECTIVE_DATE
        AND EXISTS
        (
                SELECT  1
                FROM    FDT_PRICE_FUTURE
                WHERE   SKU                =PSK.SKU
                        AND STORE          =PS.STORE
                        AND START_DATE     < PS.START_DATE
                        AND PRICE_MOD_TYPE = 'ZC'
        )
UNION ALL
SELECT  FDT.STORE                                                                                ,
        FDT.SKU                                                                                ,

        0 MULTI_UNITS                                                                                ,
        0 MULTI_UNIT_RETAIL                                                                                ,
        FDT.START_DATE PS_START_DATE                                                                                ,
        PSH.ACTIVE_DATE PC_ACTIVE_DATE                                                                                ,
        PSD.PRICE_CHANGE PRICE_CHANGE                                                                                ,
        PH.PROMOTION PRICE_MOD_NO                                                                                ,
        'PR' PRICE_TYPE                                                                                ,
        'U' REC_TYPE
FROM    FDT_PRICE_FUTURE FDT ,
        PROMHEAD PH          ,
        PROMSKU PSK          ,
        PRICE_SUSP_DETAIL PSD,
        PRICE_SUSP_HEAD PSH  ,
        PRICE_ZONE_GROUP_STORE PZGS
WHERE   PH.PROMOTION          =PSK.PROMOTION
        AND PSK.PROMOTION     =FDT.PRICE_MOD_NO
        AND FDT.PRICE_MOD_TYPE='PR'
        AND PH.STATUS         ='A'
        AND PSH.PRICE_CHANGE  =PSD.PRICE_CHANGE
        AND PSD.STATUS        ='A'
        AND PSD.ZONE_ID       =PZGS.ZONE_ID
        AND PSD.ZONE_GROUP_ID =PZGS.ZONE_GROUP_ID
        AND FDT.STORE         =PZGS.STORE
        AND PSK.SKU           =PSD.SKU
        AND PSD.SKU           =FDT.SKU
        AND PSK.CHANGE_TYPE  IN('MA','PC')
        AND FDT.START_DATE    > PSH.ACTIVE_DATE
ORDER BY 1,2,7;

A: Also, if Diagnostics and Tuning Pack licenses available, you can run the SQL Tuning Advisor on the SQL.
-- SQLTUNE.sql
-- Updated 04-Mar-2015 RDCornejo for spool error
-- takes sql_id,plan_hash_value, start and ent snap_id's as parameters
-- created sql tuning report on c:\temp

set echo off
set feedback off
set term off
set verify off
set head on

-- uncomment for debugging if neeed
-- set echo on term on

set termout on
accept SQL_ID     char prompt 'Enter the sql_id to Tune? '
accept hash_value char prompt 'Enter the hash_value to Tune? '
accept BEGIN_SNAP char prompt 'Enter the begin snap_id to Tune? '
accept END_SNAP   char prompt 'Enter the end   snap_id to Tune? '

-- using bind variables:
variable sql_id_var      varchar2(25);
variable plan_hash_value varchar2(25);
variable begin_snap_var  varchar2(25);
variable end_snap_var    varchar2(25);
variable task_name       varchar2(100);

exec :sql_id_var      := '&SQL_ID';
exec :plan_hash_value := '&hash_value';
exec :begin_snap_var  := '&BEGIN_SNAP';
exec :end_snap_var    := '&END_SNAP';
exec :task_name       := :sql_id_var || '_' ||  :plan_hash_value || '_AWR';

column sql_id     format a25
column plan_hash_value format 999999999999
column begin_snap format a10
column end_snap   format a10

select :sql_id_var as sql_id
, :plan_hash_value as plan_hash_value
, :begin_snap_var  as begin_snap
, :end_snap_var    as end_snap
from dual;

-- get my prefered text in file name
column MY_TEXT new_val FILE_NAME noprint

Select instance_name||'_'|| :SQL_ID_VAR || '_' || :plan_hash_value|| '_' || :BEGIN_SNAP_VAR || '_' ||  :END_SNAP_VAR || '_' || to_char(sysdate, 'yyyy_mm_dd_hh24_mi')  MY_TEXT
from
(select upper(substr(global_name, 1, instr(global_name,'.' )-1)) instance_name from global_name);

-- turn spooling on to capture any error and the report.
set serveroutput on

spool c:\temp\AWR_Tuning_Task_&FILE_NAME..txt

set linesize 210
set pagesize 9999
set long 10000000
set time on
set timing on
SET SERVEROUTPUT ON

prompt Drop existing task if exists.  Ignore error if not
-- Drop existig tuning task; assuming I'm running new tasks and if one exists, it it no longer needed; can ignore error if no task exists yet
execute  DBMS_SQLTUNE.drop_tuning_task (task_name => :task_name);

prompt Create Tuning Task
-- Tuning task created for specific a statement from the AWR.   [SEE BELOW FOR EXAPLES USING OTHER METHODS OF IDENTIFYING THE SQL]
--If the TASK_NAME parameter is specified it's value is returned as the SQL tune task identifier.
--If ommitted a system generated name like "TASK_1478" is returned.
--If the SCOPE parameter is set to scope_limited the SQL profiling analysis is omitted.
--The TIME_LIMIT parameter simply restricts the time the optimizer can spend compiling the recommendations.
/**/
DECLARE
  l_sql_tune_task_id  VARCHAR2(100);
BEGIN
  l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
                          begin_snap  => to_number(:BEGIN_SNAP_VAR) ,
                          end_snap    => to_number(:END_SNAP_VAR) ,
                          sql_id      => :sql_id_var,
                          plan_hash_value => to_number(:plan_hash_value),
                          scope       => DBMS_SQLTUNE.scope_comprehensive,
                          time_limit  => 1200, -- in seconds
                          task_name   => :task_name,
                          description => 'Tuning task for statement '|| :sql_id_var || ' hash: ' || :plan_hash_value|| ' in AWR ' || :BEGIN_SNAP_VAR || ' - ' || :END_SNAP_VAR || ' .');
  DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/

prompt Execute Tuning Task
-- With the tuning task defined the next step is to execute it using the EXECUTE_TUNING_TASK procedure.
EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => :task_name);
/**/

-- Once the tuning task has executed successfully the recommendations can be displayed using the REPORT_TUNING_TASK function.
set linesize 210
set pagesize 9999
set long 10000000
set time on
set timing on
SET SERVEROUTPUT ON

-- width of output should not need more than 200
column recommendations format a200

prompt Report Tuning Task
SELECT DBMS_SQLTUNE.report_tuning_task(:task_name) AS recommendations FROM dual;

spool off


text:
Q: Why IRQF_SAMPLE_RANDOM flag has been removed? As far as I know, IRQF_SAMPLE_RANDOM flag has been introduced to allow some interrupts to add randomness that used to generate random number in the Linux kernel.
However, the current version of the Linux doesn't utilize the IRQF_SAMPLE_RANDOM  flag and automatically updates randomness regardless of the interrupt number, which means for every interrupt, it adds some entropy to the randomness.
However, it might be utilized by the malicious attack who have perfect control on the devices and interrupts can undermine the randomness. Why the flag has been removed? Was it proved that it is almost impossible to affect the randomness by controlling the interrupts?


text:
Q: how to use set timeout in v-for loop in vue js? I want to show every character in a paragraph with a targeted time interval. I think setTimeout() function is best option. But I can't find any way to use. Now how set time interval the v-for loop?
The HTML part:
<button @click="showCharacterArray">click me</button>

   {{char}}

The VUE part:
    export default {
      data() {
        return {
          Paragraph: "Includes The Plan, The Thought Process, Action, And
                  Implementation. Planning Gives More Power Over The Future.
                  Planning Is Deciding In Advance What To Do, How To Do It, When To
                  Do It, And Who Should Do It. This Bridges The Gap From Where The
                  Organization Is To Where It Wants To Be.",
          characterArray : [],
        }
      },

    methods: {
          showCharacterArray() {
          this.CharacterArray = this.Paragraph.split('');
        },
    }

A: Something like this?

<template>
<button @click="startTimer">click me</button>
  count: {{count}}

   {{char}}

</template>

Note: this counter never stops. You should find a way to stop it.