text:
Q: ViewPager in inner fragment, not showing up, not visible Im using an ActionBar, which loads different Fragments. This is done within a FragmentActivity class. One of the Fragent should have a ViewPager holding different Fragments.
I dont get any error anymore now, but the ViewPager and the PagerTitleStrip and all the Fragents inside the ViewPager are not shown up at all. The other Fragments from the ActionBar working properly. Im using all classes from the Support-Package.
I rdid read a lot of posts here, but I couldnt find it out yet.
In my ActivityClass derived from FragmentAcivity, I use the Listener:
SettingsActiviy.java
protected class SettingsTabsListener implements ActionBar.TabListener {

    private Fragment fragment;

    public SettingsTabsListener(Fragment fragment) {
        this.fragment = fragment;
        Log.e("SettingsTabListener","Contructor Fragment is " + fragment);
    }

    @Override
    public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
        FragmentManager fragMgr = getSupportFragmentManager();
        FragmentTransaction xaction=fragMgr.beginTransaction();

        // Dont know if we really need that...
        if (fragment instanceof SettingsActivityOverviewFragment) {
            if (fragment == null) {
                fragment = SettingsActivityOverviewFragment.newInstance(appWidgetId);
            }
        }
        xaction.replace(R.id.FragmentPlaceholder, (Fragment)fragment);
        xaction.commit();
    }

    @Override
    public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
        FragmentManager fragMgr = getSupportFragmentManager();
        FragmentTransaction xaction=fragMgr.beginTransaction();

        xaction.remove(fragment);
        xaction.commit();
    }

SettingsActivityOverviewFragment.java
public class SettingsActivityOverviewFragment extends Fragment {
private static final Field sChildFragmentManagerField;
ViewPager viewPager;
PagerAdapter pagerAdapter;

public static final SettingsActivityOverviewFragment newInstance(int appWidgetId){
    SettingsActivityOverviewFragment f = new SettingsActivityOverviewFragment();
    Bundle bdl = new Bundle(1);
    bdl.putInt("appWidgetId", appWidgetId);
    f.setArguments(bdl);
    return f;
}

/* this is a fix caused by googles nullpointer, until detach-method */
static {
    Field f = null;
    try {
        f = Fragment.class.getDeclaredField("mChildFragmentManager");
        f.setAccessible(true);
    } catch (NoSuchFieldException e) {
    }
    sChildFragmentManagerField = f;
}

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

    if (sChildFragmentManagerField != null) {
        try {
            sChildFragmentManagerField.set(this, null);
        } catch (Exception e) {
        }
    }
}

/* end of fix */
@Override
  public View onCreateView(LayoutInflater inflater,
                           ViewGroup container,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.settings_frag_overview, container, false);
    viewPager=(ViewPager)result.findViewById(R.id.overview_pager);
    Log.e("SettingsActivityOverviewFragment","viewPager content is " + viewPager + ", " + viewPager.getHeight());

    pagerAdapter = buildAdapter();
    new SetAdapterTask().execute();

    return(result);
  }

  private PagerAdapter buildAdapter() {
    return(new SettingsOverviewPagerAdapter(getActivity(), getChildFragmentManager()));
  }

  public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {

  }

  private class SetAdapterTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            if(pagerAdapter != null) viewPager.setAdapter(pagerAdapter);
        }
    }

}

SettingsOverviewPagerAdapter.java
public class SettingsOverviewPagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;

  public SettingsOverviewPagerAdapter(Context ctxt, FragmentManager mgr) {
    super(mgr);
    this.ctxt=ctxt;
  }

  @Override
  public int getCount() {
      Log.i("SettingsOverviewPagerAdapter","getCount returns 10");
    return(10);
  }

  @Override
  public Fragment getItem(int position) {
    return(EditorFragment.newInstance(position));
  }

  @Override
  public String getPageTitle(int position) {
    return(EditorFragment.getTitle(ctxt, position));
  }
}

EditorFragment.java
public class EditorFragment extends Fragment {
private static final String KEY_POSITION = "position";

static EditorFragment newInstance(int position) {
    EditorFragment frag = new EditorFragment();
    Bundle args = new Bundle();

    args.putInt(KEY_POSITION, position);
    frag.setArguments(args);

    return (frag);
}

static String getTitle(Context ctxt, int position) {
    return (String.format("ctest", position + 1));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View result = inflater.inflate(R.layout.editor, container, false);
    EditText editor = (EditText) result.findViewById(R.id.editor);
    int position = getArguments().getInt(KEY_POSITION, -1);

    editor.setHint(getTitle(getActivity(), position));

    return (result);
}
 }

SettingsFragOverview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/overview_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.PagerTitleStrip
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="top"
      android:background="#33b5e5"
      android:textColor="#fff"/>
</android.support.v4.view.ViewPager>

EditorFragment.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/editor"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:inputType="textMultiLine"
   android:gravity="left|top"
/>

A: This typically occurs when:

*

*Using an inner fragment as parent of ViewPager

*Parent container has a scrollview in it.


text:
Q: python dataframe unique values I dont have experience with dataframes and i stuck in the following problem:
There is a table looking like that:
enter image description here
parent account  account number  account name    code
0   parent 1    123122  account1    1
1   parent 1    456222  account2    1
2   parent 1    456334  account3    1
3   parent 2    456446  account4    1
4   parent 2    456558  account5    2
5   parent 2    456670  account6    3
6   parent 2    456782  account7    1
7   parent 2    456894  account8    1
8   parent 2    457006  account9    1
9   parent 2    457118  account10   1
10  parent 2    457230  account11   1
11  parent 2    457342  account12   1
12  parent 2    457454  account13   1
13  parent 2    457566  account14   1
14  parent 3    457678  account15   1
15  parent 3    457790  account16   1
16  parent 4    457902  account17   5
17  parent 4    458014  account18   5
18  parent 4    458126  account19   5
19  parent 4    458238  account20   5
20  parent 4    458350  account21   1

I need to check which parents have only one version of code(last column) and which have more
the needed output is table looking like the sample but every parent with only one version of code is not included
> import pandas as pd
>
> read by default 1st sheet of an excel file
> dataframe1 = pd.read_excel("./input/dane.xlsx")

> parents = dataframe1.groupby(["parent account", "code"])

This is the only output I've got on that moment, its something but this is not the result i need
> for i in parents["parent account"]:
> print(list(i)[0])
> ```
> ('parent 1', 1)
> ('parent 2', 1)
> ('parent 2', 2)
> ('parent 2', 3)
> ('parent 3', 1)
> ('parent 4', 1)
> ('parent 4', 5)

Could you please help me with that?

A: First obtain a list of parent accounts such that they have more than 1 distinct code
condition = df.groupby('parent account').code.nunique() > 1

parent_list = list( condition.index[condition.values] )

Then apply the filter on your data
df[ df['parent acount'].isin(parent_list) ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: leave app running the background- iOS Is it possible to leave your app running in the background when you change applications. For example, I start my app, then i leave in the middle of a task and launch safari. After a few minutes when i go back to my app, it restarts.
How do you disable this option?

A: You are not in control of when your app launches or is terminated. I suggest you read Apple's App States and Multitasking.


text:
Q: "ProgrammingError: Incorrect number of bindings supplied" due converting .csv to .db My code
import csv
import sqlite3
from datetime import datetime

con = sqlite3.connect('D:/database.db')
cur = con.cursor()
cur.execute('''DROP TABLE IF EXISTS data''')
cur.execute('''CREATE TABLE data(answer TEXT, reply TEXT)''')

with open('D:/database.xls.csv','rt', encoding = 'utf-8', errors = 'ignore') as fin:
    reader = csv.reader(fin)
    to_db = [tuple(line) for line in reader]

cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', [to_db])
con.commit()
con.close()

Error:
Traceback (most recent call last):
  File "C:\Users\runol\source\repos\AI_ChatBot\AI_ChatBot\AI_ChatBot.py", line 19, in <module>
    cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', [to_db])
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 631248 supplied.

At first line 19 looked like this:
cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', (to_db))
Then I tried to use comma and list:
cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', (to_db,))
cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', [to_db])
Error kept the same

A: to_db is already a list of tuples - no need to wrap it with another list. ([to_db])
so the fixed line below should make it work
cur.executemany('''INSERT INTO data (answer, reply) VALUES (?, ?)''', to_db)


text:
Q: Declaring functions as static in php I have a set of independent functions which I want to put in a class.
They do not depend on any objects of the class, so while calling them, all the values required would be passed as arguments.
Is it fine if I declare all of them as static so that i can call them with just one command like className::functionName(argument1,argument2,...)
or do i keep them as normal public function and call them through a class object?

A: You can (but you shouldn't do it):
class YourClass {
   public static function yourMethod( ) {
      echo "method called";
   }
}

YourClass::yourMethod();

The reason why you shouldn't do it is because when you use the static call in some other class / function / whatever you have tightly coupled the YourClass to the other class. hence you are making it pretty hard to do unit tests or simply switch to another moethod without going trhough all the code where it is used. And also don't forget you just added something globally.
You also say:

I have a set of independent functions which I want to put in a class.

This is a big code smell in my book. This makes it sound like your class violates the SRP principle in SOLID programming.
Hence I would just instantiate the class.
Let's see why it makes your code hard to test:
class SomeClassWithMethods
{
    public static function doSomething()
    {
    }
}

class SomeClassYouWantToTest
{
    public function doSomething()
    {
        return SomeClassWithMethods::doSomething(); // this is now tightly coupled and would be impossible to mock when unit testing it
    }
}

Also that that SomeClassWithMethods::doSomething is now globally defined.
We like to call this the silver bullet :) :

A: Yes this is not bad.
You can define them as static functions and like you said - you can call them with just one statement.
class Foo {
   public static function bar( ) {
      echo "bar called";
   }
}


text:
Q: SignalR - Handling multiple hub connections from JavaScript client Is there a way to handle multiple running connections to different hubs from inside a single JavaScript SignalR client?
EDIT I meant the ability to connect to different URLs (one can change the connection URL through $.connection.hub.url) from JavaScript client. It looks like it's not possible (or rather hard to do) in current implementation, as there is one global connection.

A: Multiple hubs work against one connection and that works fine today.

A: It's a bit involved.  But since there is a .NET SignalR client, you could always connect to foreign websites' hubs from server-side code, and then route the calls back to the client either via a hub or a connection as a custom proxy object.


text:
Q: Codeigniter dumps Model-Class when Loading a model got some strange behavior with Codeigniter (2.1.4):
All the time I insert a model
$this->load->model('Enrollment');

The Page doesnt get rendered anymore, but i get the content of the class.
Dont get what I did to get this behavior. Was just inserting the Database Credentials.
If I dont load the model, all works fine...
Didnt touch anything besides config.php for BaseURL and Key and database.php for credentials...
Modelclass:
class Enrollment extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
}

Controller:
<?php

class Anmeldung extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->load->model('Enrollment');
}

function index()
{
    $this->load->helper('url');
    $this->load->library('form_validation');

    $this->form_validation->set_rules('days','Tage','callback_checkDays');
    $this->form_validation->set_message('checkDays', 'Es muss mindestens 1 Tag ausgewählt werden.');

    $this->form_validation->set_rules('company_name','Unternehmen','required');
    $this->form_validation->set_rules('participant_firstname','Vorname','required');
    $this->form_validation->set_rules('participant_lastname','Nachname','required');
    $this->form_validation->set_rules('participant_departement','Funktion','required');
    $this->form_validation->set_rules('participant_email','Email','required|valid_email');

    $this->form_validation->set_rules('company_address_street','Straße','required');
    $this->form_validation->set_rules('company_address_zipcode','Postleitzahl','required');
    $this->form_validation->set_rules('company_address_city','Straße','required');
    $this->form_validation->set_rules('company_address_country','Land','required');

    $this->form_validation->set_rules('agreement','Datenschutz','callback_checkAgreement');
    $this->form_validation->set_message('checkAgreement', 'Bitte stimmen Sie unseren Teilnahme Bedingungen zu.');

    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('anmeldung');
    }
    else
    {
        return "true";
    }
}

function checkDays() {
    $data = $this->input->post('days');
    //mindestens ein feld muss true sein
    if($data[0] == 1 || $data[1] == 1 || $data[2] == 1) return true;
    else return false;
}

function checkAgreement() {
    $data = $this->input->post('agreement');
    if($data[0] == 0 || $data[1] == 0) return false;
    else return true;
}
}
?>


text:
Q: How to get output from ls command into perl script by using unix pipe I need to take list of files and subdirectories in current directory and then take necessary actions with a perl script. The following command must be used for this purpose : ls -F | perl myfile.pl. The problem is how to reach output of ls command in perl script. Any help is appreciated.

A: It's easy, simply read the Standard input of the perl script:
while(<STDIN>) {
    print "---> $_";  # or whatever you need
}

A: If you are writing not a heavy one-liner perl script, you can use "-n" pipe flag so you don't need to loop the input :
ls -F | perl -ne "print $_;"

A: If you need to hand the contents of a directory to a Perl script, you're better off passing in the file names as arguments.
perl myscript.pl *

Then...
for my $file (@ARGV) {
    ...
}

This avoids having to parse the output of ls -F making your code simpler, faster, more robust and portable.
The types of the files can be told inside Perl using the file test operators.
for my $file (@ARGV) {
    if( -l $file ) {
        ...do something with a symbolic link...
    }
    elsif( -d $file ) {
        ...do something with a directory...
    }
    else {
        ...regular file...
    }
}

A: Run the command and process its output inside the perl script. It's the same behavior as a pipe.
#!/usr/bin/env perl

use warnings;
use strict;

open my $ls, '-|' , 'ls -F' or die;

while ( <$ls> ) {
    ## Process each line.
}

A: ls -F | perl myfile.pl -
We just need the "-" argument after the script name. BTW, using the "*" in place of "-" not work.


text:
Q: Google Search Appliance (GSA) feeds - unpredictable behavior We have a metadata-and-url feed and a content feed in our project. The indexing behaviour of the documents submitted using either feed is completely unpredictable. For the content feed, the documents get removed from the index after a random interval every time. For the metadata-and-url feed, the additional metadata we add is ignored, again randomly. The documents themselves do remain in index in the latter case - only our custom metadata gets  removed. Basically, it looks like the feeds get "forgotten" by GSA after sometime. What could be the cause of this issue, and how do we go about debugging this?
Points to note:
1) Due to unavoidable reasons, our GSA index is always hovering around the license limit (+/- 1000 documents or so). Could this have an effect? Are feeds purged when nearing license limit? We do have "lock = true" set in the feed records though.
2) These fed documents are not linked to from pages and hence (I believe) would have low page rank. Are feeds automatically purged if not linked to from pages?
3) Our follow patterns include the fed documents.
4) We do not use action=delete with the same documents, so that possibility is ruled out. Also for the content feed we always post all the documents. So they are not removed through feeds.

A: When you hit the license limit the GSA will start dropping documents from the index so I'd say that's definitely your problem.


text:
Q: Add boost program_options as a git submodule and build an executable with its sources I have a small project that uses boost::program_options. I want to add this (only this) library to my project as a git submodule and build my executable using its sources.
I have already done the git submodule part (git submodule add https://github.com/boostorg/program_options.git), and I have done a small experiment in which I build an example application using only the sources in the mentioned submodule (to double check that there are not extra dependencies).
Now I want to add these sources to my project. What I do in my CMakeLists.txt file is:
set(BOOST_PROGRAM_OPTIONS_SOURCES
  boost/program_options/src/split.cpp
  boost/program_options/src/positional_options.cpp
  boost/program_options/src/parsers.cpp
  boost/program_options/src/options_description.cpp
  boost/program_options/src/convert.cpp
  boost/program_options/src/config_file.cpp
  boost/program_options/src/cmdline.cpp
  boost/program_options/src/winmain.cpp
  boost/program_options/src/variables_map.cpp
  boost/program_options/src/value_semantic.cpp
  boost/program_options/src/utf8_codecvt_facet.cpp
)

and
add_executable(
  ...
  src/main.cpp
  ${BOOST_PROGRAM_OPTIONS_SOURCES}
)

but I obtain the following error:
CMake Error at CMakeLists.txt:69 (add_executable):
  The target name "boost/program_options/src/split.cpp" is reserved or not
  valid for certain CMake features, such as generator expressions, and may
  result in undefined behavior.

CMake Error at CMakeLists.txt:86 (target_link_libraries):
  Cannot specify link libraries for target "..." which is not built
  by this project.

What is the right way to do what I want>

A: I have found the problem.
I have cloned boost::program_options (git clone https://github.com/boostorg/program_options.git) in the same folder as the CMakeLists.txt
After that, following the normal FindBoost flow
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED OFF)
set(Boost_USE_STATIC_RUNTIME OFF)

find_package(Boost 1.45.0 COMPONENTS program_options)

if(Boost_FOUND)
  message(WARNING "BOOST FOUND")
  include_directories(${Boost_INCLUDE_DIRS})
  set(BOOST_LIBS ${Boost_LIBRARIES})
else()
  set(BOOST_LIBS )
  message(WARNING "BOOST NOT FOUND")
endif()
...
...
target_link_libraries(... ${BOOST_LIBS})
...
...

CMake is able to find boost even though program_options does not contain any CMakeLists.txt (I can't find it at least)


text:
Q: Where can I get config hotkeys for IDEA like on Windows to Mac? Where can I get config hotkeys for Intellij IDEA (OS X) like on Windows?
I want to load ready script of hotkeys to Intellij IDEA (OS X). Can I do it?

A: I found solution. It's very simple. You can choose the config from Windows in the Preferences.
Intellij IDEA -> Preferences -> Keymap:
The field "Keymaps". And here you can choose you config for hotkeys.
Screenshot

A: There is a cheat sheet / reference card here.
Challenge! Learn one of these every day until you know them all (takes 2-3 months).
Also check out a plugin called "Key Promoter"


text:
Q: Office 365 - from VS'13 and Windows 7 I would like to pull some messages off of our Office 365 server.
I read a bit about using the REST API
The only example VS code remotely close to my use case that I have found in all the documentation is the following:
https://github.com/OfficeDev/O365-Win-Snippets
However, when I try to open this project, It says I must have Windows 8. Is there any reference code I can use for the most simple case of connecting to Office 365 outlook and retrieving a message, without being on windows 8?

A: I need the exact thing myself.
Unfortunately Msdn forums says it is not possible, because the user have to do the authentication in every login. Check this out:
https://social.msdn.microsoft.com/Forums/en-US/ef978452-25c0-46df-8891-69368358b6b4/calling-office365-mvc-sample-from-windows-service?forum=appsforoffice


text:
Q: Docker Micro service image Cant connect to local MySQL server This is how I have configured MySQL in application.properties file

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/roaming
spring.datasource.username=root
spring.datasource.password=root
  #spring.datasource.initialization-mode=always
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

These are my images inside docker. There are three images. When I try to run the roaming image it cannot connect with my local machine MySQL server. Currently it run using Xampp server

D:\Dialog\Applications\Roming\deployment>docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
roaming             v1                  b7cd90208bcb        17 hours ago        695MB
java                8                   d23bdf5b1b1b        2 years ago         643MB

I have an micro service image running inside a docker container and when I try following command
docker run -t roaming:v1 it gives the following error

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:353) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:562) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.3.1.jar!/:na]
        at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.3.1.jar!/:na]
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.2.Final.jar!/:5.4.2.Final]
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.2.Final.jar!/:5.4.2.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43) ~[hibernate-core-5.4.2.Final.jar!/:5.4.2.Final]
        ... 43 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.NativeSession.connect(NativeSession.java:152) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        ... 56 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)
        at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_111]
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_111]
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_111]
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_111]
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_111]
        at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_111]
        at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65) ~[mysql-connector-java-8.0.15.jar!/:8.0.15]
        ... 59 common frames omitted

and my Docker file as follows

FROM java:8

ADD roaminglistener-0.0.1-SNAPSHOT.jar roaminglistener-0.0.1-SNAPSHOT.jar

WORKDIR /

EXPOSE 8080

ENTRYPOINT ["java","-Dspring.profiles.active=dev","-jar","roaminglistener-0.0.1-SNAPSHOT.jar"]

A: If you want to connect from a container to host you have to run a container with the --network host options. More details here.

A: use host.docker.internal instead of localhost in spring.datasource.url

A: In container:
127.0.0.1 is mean local container. if you want to connect MySQL server in host machine. (outside container but same host with container )
Should configure:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/roaming

change to :
spring.datasource.url=jdbc:mysql://172.17.0.1:3306/roaming

172.17.0.1 is default ip gateway of container network.


text:
Q: Stored Procedures in PHP PDO with named parameters I am trying to solve this issue where my database admin provided me with this Stored Procedure to call with named parameters and since I use PHP 7 with PDO and SQL Server, it is difficult to get correct syntax and execute successfully.
This is what my Dbase Admin provided me with:
exec subscription @customer_key='2AB407313144', @invoice_key='0022BE6C4912'

This is what I tried from some similar questions, result: fail
$sql = 'EXEC subscription :customer_key, :invoice_key';
$stmt = $conn->prepare($sql);

$stmt->bindParam(':customer_key', $_SESSION['customer_key']);
$stmt->bindParam(':invoice_key', $_SESSION['inv_key']);

$stmt->execute();


text:
Q: change img src click listener to change second img src I'm currently building a filter with 5 options. The filter has an img with a 'prev' and 'next' div on either side. When you click either div, the img src changes to the adjacent src stored in an array. This works fine. Now I have a second filter. This filter will also have 5 options, except the 5 options available will depend on the option selected on the first filter. So filter1>option1 will result in options 1,2,3,4 and 5 being available on the second filter. filter1>option2 will result in options 6,7,8,9 and 10 being available on the second filter.
I'm trying to use the .onload listener so that when the filter one img loads, if filter1 source == A then filter two img src is pulled from array 1. If filter1 source == B then filter two img src is pulled from array 2.
I thought I'd explain my problem in pseudo for clarity. Here is a jsfiddle of my progress so far. http://jsfiddle.net/XujYW/
Thanks in advance!

A: The most important thing that is wrong in your code, is that you missinterpreted what $(function() { ..}) does. This is just a shortcut for $(document).ready(). It's fired after loading the page and NOT when anything changes on the page.
Then you use a very complicated way to find out the state of your list. You should have a look at jquerys data functions which allow you to bind data directly to an element. That's way more useable than your reading of img src and parsing it to get a simple index number. Look here (I left this approach as it is).
Next, you are repeating your code over and over. This makes it hard to handle especialy if you want to change anything. Better split reapeating parts of code into functions. This is what @thinklinux was requesting.
Anyhow, here is a working plunker (I prefer plunker because it's easier to debug and has  a built in beautifier which makes code easier to read for those who want to help you).
I set up your values to arrays like that:
  // A global array for convenience
  subs = new Array();
  subs['Shelter'] = ['shelter-one', 'shelter-two', 'shelter-three', 'shelter-four', 'shelter-five'];
  subs['Food'] = ['food-one', 'food-two', 'food-three', 'food-four', 'food-five'];
  subs['Energy'] = ['energy-one', 'energy-two', 'energy-three', 'energy-four', 'energy-five'];
  subs['Transport'] = ['transport-one', 'transport-two', 'transport-three', 'transport-four', 'transport-five'];
  subs['Economy'] = ['economy-one', 'economy-two', 'economy-three', 'economy-four', 'economy-five'];
  setup_effects();

  var filterOne = ['shelter', 'food', 'energy', 'transport', 'economy'];

An handle everyting over a single function:
  //Now setup the master filter
  //Parameters are:
  // Element to change
  // Array to use
  // Master filter
  // update on apply
  applyfilter('filter-one', filterOne, true, false);

This function itself calls apllyfilter with the last two parameters changed. This is not a very elegant approach (think spaghetticode!), but at least it works.
Find the full code here


text:
Q: Select and update the same row using while loop There is a looping query (while loop) to select 2 column values from a table, then the code sums the 2 values,  what I need is to update another column with the summed value>
Here is the code:
$stmt = $conn->prepare('select value1, value2, valuse3  from  eg.table limit ? ');
$stmt->bind_param('i',$limit);
$stmt->execute();
$stmt->bind_result($value1, $value2,$value3);
$arr = array();
while($stmt->fetch()) {
$row = array();
array_push($arr, $row);
$newvalue=($value1+$value2);

$stmt1 = $conn->prepare("UPDATE eg.table SET eg.column=? WHERE  eg2.column=?");
$stmt1->bind_param('ii',$newvalue , $value3);
$stmt1->execute();
}

When I used this queries I got this error: Fatal error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\so\new\socialrank.php on line 13
If you have another solution to achieve the job using Mysqli it's okay.
Any help will be appreciated,
Thanks in advance.

A: I got the solution. This query do the same thing I was looking for:
$sql = ("UPDATE eg.table AS c1, eg.table AS c2
SET c1.eg.column = (c2.value1 + c2.value2)
WHERE c2.eg2.column = c1.eg2.column
");

Note: this solution is inspired by @CakePHP answer


text:
Q: Is Sieve of Eratosthenes using bitset faster than the one using bool array? I have written the Sieve of Eratosthenes algorithm to find all the primes <=10^8 using bitset and bool array(separately) for a problem. In the problem, I'm simply asked to print the prime numbers according the given sequence of positions(1,101,201,301... till <=10^8).
Here is my code:
#include<bits/stdc++.h>
using namespace std;
#define N 100000001
//bool pFlag[N];
bitset<N> pFlag;
void sieve() {
    for(int i=4; i<N; i+=2) {
        pFlag[i] = 1;
    }
    cout << 2 << "\n";
    int pCount = 0;
    for(int i=3; i<N; i+=2) {
        if(!pFlag[i]) {
            pCount++;
            if(pCount == 100) {
                cout << i << "\n";
                pCount = 0;
            }
            if((long long int)i*i<N) {
                for(int j=i*i; j<N; j+=i) {
                    pFlag[j] = 1;
                }
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    sieve();
}

The problem is, as per my understanding and according to this blog the sieve algorithm using bitset/vector is supposed to be slower than the one using bool array.

Such an approach, which is called bit-level compression, will
  complicate the operations with these bits. Read or write operation on
  any bit will require several arithmetic operations and ultimately slow
  down the algorithm.

However, it seems not to be the case when I submit it in the online judge(SPOJ). Where I get a execution time of 0.99s for the code using bool array and 0.59s for the code using bitset.(I have used the exact same code, just changed the container)
Using bitset:

Using bool array:

Can someone please explain me if my understanding of bitset being slower than the bool array is wrong or there's something I'm missing?
Extra information:
The execution time in my laptop is like this:
bitset              bool array
19.021366000s       5.579701000s
19.163211000s       5.099894000s
18.765502000s       4.332410000s

I also got similar results in the repl.it which supports my understanding, so I didn't add it here before.


text:
Q: Is there a way that I can change the back button icon for stack navigator in react? I want to change the arrow icon for going back to the previous screen in stack navigator to a different icon (e.g home icon) and the icon's color

Here is my code for one of the stack screens:
<Stack.Screen
    name="Bone cancer" component={BoneCancerScreen}
    options={{
        headerStyle: {
            backgroundColor: "#000000",
            height: RFValue(102)
        },
        headerTintStyle: {fontWeight: "bold"},
        headerTitleStyle: {
            marginLeft: RFValue(72),
            fontFamily: "Aldrich-Regular",
            color: "white"
        }
    }}
/>

code for stack navigator and screenOptions:
<Stack.Navigator
    initialRouteName="Home screen"
    screenOptions={{headerShown: true,}}>

A: Use headerBackImage in your screenOptions.

Function which returns a React Element to display custom image in header's back button. When a function is used, it receives the tintColor in it's argument object. Defaults to Image component with back image source, which is the default back icon image for the platform (a chevron on iOS and an arrow on Android).

Source: https://reactnavigation.org/docs/stack-navigator/#headerbackimage

A: Using headerLeft option you can change the back icon. From headerLeft you can return any component and it will override the default back button.
<Stack.Screen
  name="Bone cancer"
  component={BoneCancerScreen}
  options={{
    headerStyle: { backgroundColor: "#000000", height: RFValue(102) },
    headerTintStyle: { fontWeight: "bold" },
    headerTitleStyle: {
      marginLeft: RFValue(72),
      fontFamily: "Aldrich-Regular",
      color: "white"
    },
    headerLeft: () => /* your icon code goes here */
  }}
/>

Reference: Official Reference


text:
Q: Stop reload for ajax submitted form My html of form is like this
<form id="form" method="post" action="func.php">

   <input type="submit" value="Submit" id="set" />
</form>

I want to use javascript to post the data, my javascript is like this
$('#set').live('click', function () {
        $('.setForm').attr('action', '');
        var setData = $('.setForm').serialize();
        $.ajax({
            type: 'post',
            url: 'func.php',
            data: setData,
            success: function(response) {
                $('#status').fadeIn('500').text('Loading..');
            }
        });
    });

but i am getting an error i dont know what error it is, (It is not visible in console) i have Break on errors enabled in firebug which returns
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="

";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="

";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/>

a<select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
").append(M.responseText.replace(/


text:
Q: Rabbit MQ .Net Delivery Count jms queues has jmsdeliverycount.If message read from queue one more time we can track with this property.What is the equvaliant of this RabbitMQ .net.
I want to check how many times this message read from queue(in transactional reads)

A: Currently there is nothing out-of-the-box. All you get is a redelivery flag to say it has been redelivered, but not how many times.
You can track this issue.

A: Quorum queues track the number of redeliveries, in the x-delivery-count header. See here
There is a feature request to add the same to classic queues.


text:
Q: .net 4.0 winforms, easy way to get text controls to remember previous input? I want my text box controls to remember previous input and have intellisense, like web control inputs.
Is there a quick, free and easy to implement solution to this?

A: Here's one way of doing it using a mixture of listboxes and textboxes. I quite like this solution actaully.


text:
Q: We used to be able to do [faq#how-to-ask], what's the alternative with the new Help Center? Say I want to refer a user to /help/how-to-ask, With the older, [faq] syntax, I could have done it easily using a hash after the word "FAQ":

Please check the [faq#how-to-ask]

How can I do the same with the new Help Center? Do I have to post a full [description](link) form? Or is there a better way?


text:
Q: how can i make my custom keyboard to show in fullscreen mode always? I tried this How can I develop a custom "non-fullscreen" softkeyboard for tablets? to make it full screen mode but still its not full screen :(
And also i have tried the following in my code
 @Override
    public boolean onEvaluateFullscreenMode() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isFullscreenMode() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void setExtractViewShown(boolean shown) {
        // TODO Auto-generated method stub

        super.setExtractViewShown(true);
    }

Not working as expeced, can any one help me to solve this ?

A: overide the following two methods from InputmethodService as bellow
  @Override
    public void onUpdateExtractingVisibility(EditorInfo ei) {
        // TODO Auto-generated method stub
        setExtractViewShown(true);
    }

 @Override
    public boolean onEvaluateFullscreenMode() {

        return true;
    }

This worked for me :)


text:
Q: Extracting Role of user From Jwt tokens i am getting from spring boot in react js actually i am working on spring boot and reacts js.I am getting jWT token from spring boot like:-
token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI5NjI4NTAsInVzZXJfbmFtZSI6ImFkbWluQGdtYWlsLmNvbSIsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiM2U4YzQ2NGYtZjYzMy00ZjUxLTg4MzktM2U4YjI5NmViOGZlIiwiY2xpZW50X2lkIjoibGl2ZS10ZXN0Iiwic2NvcGUiOlsiYXBwIl19.TwQMMRfqJ6tv6v6_8hY7vUoFXoF_OU684SLD6bRZhag
and i want to extract the role of user  like Admin , customer or seller from jwt token i am getting in react. Is it possible

A: Yup! A package like jwt-decode would do the trick.


text:
Q: Where store context attributes using several servers (J2EE) I'm currently developing a Wepapp using Java EE with Tomcat Server. I'm using context attributes like:
ServletContext context = getServletConfig().getServletContext();
String defaultUser = (String) context.getAttribute("default_user");

But recently I've read that it's not recommended to use context attributes when you deploy your webapp in several servers.
Is that true?
How could I solve that? Maybe I would use several servers in the future (AWS or other stuff).
Thanks!
PS: I really only use that context attributes for read-only purposes, just read config parameters.

A: E.g. see Servlet Context in Clustered Environment, which explains the problem:

In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
Context attributes are local to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container. When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session , stored in a database, or set in an Enterprise JavaBeans component. Session attributes must be serializable if they are to be processed across multiple JVMs, which is a requirement for clustering. It is possible to make some fields of a session attribute non-clustered by declaring those fields as transient.


text:
Q: Web API with Microsoft Identity Platform Authentication I created a new ASP.NET Core Web API with Authentication type "Microsoft identity platform" based on the VS2022 template.
On Azure I setup the following with my trial subscription (where I am global administrator):

*

*Create app API

*Create app registration

To doublecheck if the app is running, I also added a TestController, which returns a simple string.
After setting up azure, I changed the appsettings.json file accordingly:
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[xxx]",
    "TenantId": "[xxx]",
    "ClientId": "[xxx]",
    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc"
  },

Everything else is setup nicely already in the program.cs (I only extracted relevant code for you):
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

After that I setup a YAML Pipeline on Azure Devops to deploy the API directly to the cloud.
The deployment seems to work: I can access the function of the TestController. However, when I try to access the weatherforecast I receive the Status Code (I try this with the global admin user):

401 Unauthorized

What have I tried so far?

*

*I added user to Access Control (IAM) Contributor (For testing) both of the subscription and the app service itself (i.e. the App Api)

Note, the WeatherForecastController of the template looks like the following:
[ApiController]
[Route("[controller]")]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Any ideas of what I am missing here or what I could check on Azure to narrow down the problem?

A: Please check if you are missing controller with the [Authorize] attribute.
To protect an ASP.NET or ASP.NET Core web API, you must add the [Authorize] attribute to one of the following items:

1.The controller itself if you want all controller actions to be
protected.

*The individual controller action for your API

    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
    public class WeatherForecastController : ControllerBase
    {

After login , check the received token in browser in https://jwt.io and decode it and see which endpoint is present in issuer ("iss" claim) i.e v1 or v2 and then go to azure ad portal and change the accesstokenacceptedversion if it not according to that endpoint i.e; it must be null or 1 for V1 and 2 for V2.

If it is correct , please make the required scopes are exposed for that api In portal .

and make sure required api permissions are given and  granted admin consent .

*

*Make sure to check mark id token and access token in authentication
blade.

*when you generate a token, it should have the scope like
api://clientid_of_the_app_exposed_api/access_as_user which can
match the configuration in your code.

After trying above , still if there is error ,please check if audience = client id value, if not change clientId in appsettings by adding prefix api:// before client id. i.e clientId=api://<clientId>
References:

*

*Protected web API

*Protected web API: Verify scopes and app roles


text:
Q: Trying to output solution to math equation always results in 0 I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
    public static void main(String[] args)

        {
            System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
            Scanner myScanner = new Scanner (System.in);
            String planetName = myScanner.next();
            int planetWeight = myScanner.nextInt();

            System.out.println("Enter the weight of the person in kilograms");
            double personWeight = myScanner.nextDouble();

            System.out.println("Please enter the radius of the planet Alderaan in million meters");
            double planetRadius = myScanner.nextDouble();
            Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
            Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
            Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));

            System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
            System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
        }
}

A: 6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));

to
double gravitationalConstant = 6.673*Math.pow(10,-11);


text:
Q: Oracle: Import CSV file unix i want to import csv file into oracle database using pl / sql developer, i inform you that the base is installed under linux, and pl / sql under windows, i ran the command:
SQL> @C:\app\session_name\product\11.2.0\client_3\BIN\sqlldr user/passwd@base_name  control=/opt/FNDBSS/Control/FNControl.txt log=log.txt;

but the error has appeared: Error reading file
thank you for helping me

A: A the least add the LOG file to the command line or your control file. It tells you what loader is doing and perhaps why. Additionally check into the BAD and DISCARD files. See the SQL Loader concepts for your  Oracle version.


text:
Q: Is Monodevelop a good compiler for game development in unity? Is Monodevelop a good compiler for game development in unity?
I am very interested in game development. It is the default c# compiler and I want to know some other best compiler for unity.

A: Monodevelop isn't a compiler, it's an IDE.  The compiler for Unity projects is the Mono compiler, and that remains constant regardless of the text editor you use to edit the source.
I would say "no" it's not a good editor as using Visual Studio 2015 Community Edition is better if you run Windows and using Visual Studio Code is better if you run OSX.


text:
Q: Schedule Scrapy Spider via Batch with Win10 Task-Scheduler I´m still pretty new to python, but I managed to get my spider to crawl the things I need.
Then I created a batch file, to run that spider. The batch looks like this:
call C:\Users\Tribic\Anaconda2\Scripts\activate.bat
call cd cmc\cmc\spiders\
call scrapy runspider cmc_job.py -o out3.csv

Line1 switches the cmd to python
Line2 goes to the corresponding path
Line3 runs the spider, which saves the data to an csv file.

This works fine, as long as I click the batch (mouse or keyboard) - but when scheduled with Win10 Task Scheduler, it does not work... The cmd windows opens for 1/2 sec, I think it does not wait for the first line to be executed, so line 3 is a bad command and then it closes.
Once again, it works fine when started manually, so I don´t get the difference between executing by hand and by system.
Thanks in advance :)

A: Try the following syntax, it works for me in Windows task scheduler. Notice the quotes and the invokation of cmdline.py
@Echo Off
REM activate Python venv
CALL "C:\Users\Tribic\Anaconda2\Scripts\activate.bat"
CD "C:\cmc\cmc\spiders\"
CALL "C:\Users\Tribic\Anaconda2\Scripts\python.exe" "C:\Users\Tribic\Anaconda2\Scripts\Lib\site-packages\scrapy\cmdline.py" runspider cmc_job.py -o out3.csv
deactivate


text:
Q: Mac OS X TCP/IP fingerprint obfuscator For several reasons, I need to either prevent my OS X machine from showing up as an OS X machine in TCP/IP fingerprinting, or make it show up as, say, a Linux machine. Is there an OS X program out there to do it, or a set of network settings I can use to accomplish this?

A: In brief, TCP fingerprinting works by looking at what network ports are open on a machine, and then sending several different TCP packets to the machine and then looks at the responses. All the different operating systems handle those packets slightly differently in terms of fields that are set (or not) in the TCP header, and between all that information you can usually put together a good guess about the remote system.
There's a few papers that talk about how to disguise the fingerprint (http://www.dtic.mil/dtic/tr/fulltext/u2/a439228.pdf and http://static.usenix.org/events/sec00/full_papers/smart/smart_html/index.html). It looks like the best ways to do this are to look at changing what network ports are open on your system, and also to change your network settings, and see what changes that makes to your system when you try to fingerprint scan it (nmap is a free download).


text:
Q: Android WebView inject JavaScript between onPageStarted and onPageFinished I need to inject some JavaScript into my web page that I'm loading into a WebView, but injecting it at onPageFinished is too late and onPageStarted is too soon. Any way I can inject it between this two events?
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progress.setVisibility(view.GONE);
        view.loadUrl("javascript:registerObjectDetailsCallback(" +
                                    "function(details) {" +
                                        "if (details.length == 1) {" +
                                            "window.location.href = 'callback:' + escape(details[0]);" +
                                        "} else if (details.length > 1) {" +
                                            "alert('Error: callback set by registerObjectDetailsCallback was passed multiple selection');" +
                                        "}" +
                                    "}" +
                                ");");
        Log.d("onPageFinished: ", "JavaScript registered.");
    }
}

A: I didn't end up using this in the end, I came up with a better solution - but what you can do is use the onProgressChanged method in WebChromeClient in order to perform actions at certain stages of loading.
webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int progress) {
        // Do something cool here
    }
});


text:
Q: handle clickevent in appbar in fragments android studio I am facing a problem with my custom appbar in my fragment where nothing happens when I click any item in my appbar. I have followed this document to create an appbar in my fragment but still so success.
I have one activity that contains only a fragment container which I switch between fragments from. In one of fragments I want to add a custom fragment owned appbar. I first created a menu like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/settings"
        android:title="Settings"
        android:icon="@drawable/ic_settings"
        app:showAsAction="never">
    </item>

    <item
        android:id="@+id/about"
        android:title="About"
        android:icon="@drawable/ic_about"
        app:showAsAction="never">
    </item>

    <item
        android:id="@+id/logout"
        android:title="Logout"
        android:icon="@drawable/ic_logout"
        app:showAsAction="never">
    </item>

</menu>

then in my profile.xml I added a toolbar like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".MainFragments.AddFragment">

  <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/Bar_profile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="@color/darkBlue"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed">

                //alot of code in between....

                <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar_prof"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    //more stuff implemented

</RelativeLayout>

however, my menu does not get inflated and if i inflate it via xml nothing happens when I click on any item, what is wrong? Thanks!
here is how my profile fragment looks like:
Edit
here is full profilefragment.java:
package se.umu.moad0012.myservice.MainFragments;

import se.umu.moad0012.myservice.Adapters.FragmentPagerAdapter;
import se.umu.moad0012.myservice.MainActivity;
import se.umu.moad0012.myservice.Models.User;
import se.umu.moad0012.myservice.ProfileFragments.AboutFragment;
import se.umu.moad0012.myservice.ProfileFragments.SettingsFragment;
import se.umu.moad0012.myservice.R;
import se.umu.moad0012.myservice.StartFragments.LoginFragment;

import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.makeramen.roundedimageview.RoundedImageView;

public class ProfileFragment extends Fragment {

    private RoundedImageView mProfileRoundedImageView;
    private TextView mPosts, mFollowers, mFollowing, mUserName;
    private TabLayout mTabLayout;
    private String profileId;
    private FirebaseDatabase mFirebaseDatabase;
    private ViewPager2 mViewPager2;
    private final String[] titles = new String[]{"Posts", "Reviews"};
    private final int[] icons = new int[]{R.drawable.ic_grid, R.drawable.feedback};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_profile, container, false);

        //declare variables
        declareVariables(v);

        //adapter for viewpager2
        mViewPager2.setAdapter(new FragmentPagerAdapter(this));

        //configure tabs here
        tabMediator();

        //FirebaseAuth.getInstance().signOut();

        //set profile info
        setProfileInfo();

        return v;
    }

    private void tabMediator() {
        new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles[position]);
                tab.setIcon(icons[position]);
            }
        }).attach();
    }

    private void setProfileInfo() {
        mFirebaseDatabase.getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);

                mUserName.setText(user.getUsername());
            }

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

            }
        });
    }

    private void declareVariables(View v) {
        mViewPager2 = v.findViewById(R.id.viewpager_profile);
        mTabLayout = v.findViewById(R.id.tabLayout_profile);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mUserName = v.findViewById(R.id.userNameProfileFragment);
        mFollowers = v.findViewById(R.id.followers);
        mPosts = v.findViewById(R.id.posts);
        mFollowing = v.findViewById(R.id.following);
        //mProfileRoundedImageView = v.findViewById(R.id.profileImage);
        FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
        profileId = fUser.getUid();
    }

   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar_prof);
        toolbar.inflateMenu(R.menu.popup_menu_profile);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.settings:
                        Log.d("TAG", "onOptionsItemSelected: settings");
                        return true;
                    case R.id.about:
                        Log.d("TAG", "onOptionsItemSelected: about");
                        return true;
                    case R.id.logout:
                        Log.d("TAG", "onOptionsItemSelected: logout");
                        return true;
                }
                return false;
            }
        });
    }

}

Edit2
I have noticed just now that it works, just that my text is white and thus does not show up. Sorry for any inconvenience.

A: Put this in your fragment
public class ProfileFragment extends Fragment {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Toolbar toolbar = view.findViewById(R.id.my_toolbar);
        toolbar.inflateMenu(R.menu.your_menu);
        toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.delete:
                        //handle click
                        return true;
                    case R.id.new_pic:
                        // handle here
                        return true;
                    default:
                        return false;
                }
            }
        });

    }
}


text:
Q: How to debug a 0x8007000B exception? We have a C# application, that is compiled as a AnyCPU.
This application uses an external library(which is also a .Net DLL on AnyCPU) that loads some C++ libraries in externals DLL.
Thoses externals libraries are either for X86, either for X64. We have a postbuild event that copies the one from X64 into the output folder.
We had everything working since years, and we have a lot of unit tests using this library.
Recently, on one computer(the build machine), the UnitTests now fails, with the following call stack.
The type initializer for 'Dew.Math.Units.MtxParseClass' threw an exception.
   at System.Runtime.CompilerServices.RuntimeHelpers._RunClassConstructor(RuntimeType type)
   at System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(RuntimeTypeHandle type)
   at Dew.Math.TExprContext..cctor()

The type initializer for 'Dew.Math.Units.MtxVec' threw an exception.
   at System.Runtime.CompilerServices.RuntimeHelpers._RunClassConstructor(RuntimeType type)
   at System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(RuntimeTypeHandle type)
   at Dew.Math.Units.MtxParseClass..cctor()

An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
   at Dew.Math.Units.Nmkl.kmp_set_blocktime(Int32 Value)
   at Dew.Math.TMtxVecController..ctor()
   at Dew.Math.Units.MtxVec.InitializeMtxVec()
   at Dew.Math.Units.MtxVec.Dew.Math.MtxVec()
   at Dew.Math.Units.MtxVec..cctor()

We have verified the C++ DLL are in 64 bits, our application is in AnyCPU on a 64 bits computers, so normally we should not have thoses errors.
The weird part is that: We didn't touch anything to thoses tests or on the tested classes, the tests still works fine on all other computers.
So my question:
How to debug it:

*

*How to know the exact path of the DLL that fails being loaded

*How to be sure that we are executed in X64 and not x86?

*Any other idea to help me troubleshot this issue?

A: Note that using AnyCPU on x64 prefers 32bit. You can change this in the build settings for the project


text:
Q: MySQL: Count total in Group by Query I have a table like this:

-----------------------------------
|  Name   | Date      | Campaign  |
-----------------------------------
| John    | July      | Email     |
| Carl    | August    | Phone     |
| John    | July      | Phone     |
| Robert  | August    | Phone     |
| Carl    | September | Email     |
| John    | August    | Phone     |
| Carl    | August    | Email     |
| John    | July      | Email     |
| Robert  | September | Phone     |
| Carl    | August    | Email     |
-----------------------------------

I count the data grouped by date and campaign, but I would like an additional column to bring me the total number of lines that have that campaign
the query I use:

      SELECT campaign,name,
      SUM(IF(date = 'July',1,0)) AS July,
      SUM(IF(date = 'August',1,0)) AS August,
      SUM(IF(date = 'September',1,0)) AS September
      FROM table
      GROUP BY name,campaign

but I would like to modify it to get the following output:

----------------------------------------------------------------------------------------
| Campaign | Name | July | August | September | SUM July |  SUM August | SUM September |
----------------------------------------------------------------------------------------
  Email      John    2       0          0           2           2              1
  Phone      John    1       1          0           1           3              1
....
....

I would like the columns with the total of all the values with phone or email distinguished by month
ADD: http://sqlfiddle.com/#!9/8b797a/8

A: Try below: http://sqlfiddle.com/#!9/8b797a/24:
select a.campaign,a.name,July, August,September,Julysum,Augustsum,Septembersum from
(SELECT campaign,name,
  SUM(IF(date = 'July',1,0)) AS July,
  SUM(IF(date = 'August',1,0)) AS August,
  SUM(IF(date = 'September',1,0)) AS September
  FROM `table`
  GROUP BY campaign,name)a
  left join
  (select campaign,
  SUM(IF(date = 'July',1,0)) AS Julysum,
  SUM(IF(date = 'August',1,0)) AS Augustsum,
  SUM(IF(date = 'September',1,0)) AS Septembersum
  FROM `table`
  GROUP BY campaign)b on a.campaign=b.campaign
  where name='John'

Output:
campaign    name    July    August  September   campaign    Julysum Augustsum   Septembersum
Email      John     2      0       0           Email         2     2    1
Phone      John     1      1       0           Phone         1     3    1

A: I realise this isn't exactly what you asked for, but it's a simple way to get totals using GROUP BY ... WITH ROLLUP:
SELECT Campaign, Name,
  SUM(CASE WHEN Date='July' THEN 1 ELSE 0 END) AS July,
  SUM(CASE WHEN Date='August' THEN 1 ELSE 0 END) AS August,
  SUM(CASE WHEN Date='September' THEN 1 ELSE 0 END) AS September
FROM campaigns
GROUP BY Campaign, Name WITH ROLLUP

Output:
Campaign    Name    July    August  September
Email       Carl    0       2       1
Email       John    2       0       0
Email       (null)  2       2       1
Phone       Carl    0       1       0
Phone       John    1       1       0
Phone       Robert  0       1       1
Phone       (null)  1       3       1
(null)      (null)  3       5       2

The totals of each month for each type of campaign are shown in the row with the campaign name and a NULL value for Name. The grand total for each month (of both types of campaign) is shown in the bottom row with NULL values for Campaign and Name.
SQLFiddle Demo


text:
Q: Entity retrieve method should retrieve entities with cancelled property equal to false All entities are derived from a BaseEntity which has a Cancelled property of type bool. I am modifying the GetList method in the repository class which retrieves entities using
public static IList<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : BaseEntity

predicate as method parameter (where T is derived from BaseEntity). I know it is possible to make a new method GetListNonCancelled and add a Where clause to existing query like
query.Where(e => e.Cancelled == false)

which will return me list of entities which have Cancelled property set to false, but if an entity has property which is also a entity derived from BaseEntity or an array of entities derived from BaseEntity, how it is possible to add where clause to search query to specify that it should also retrieve only entities with Cancelled property set to false?
Example
public class BaseEntity
{
    public bool Cancelled { get; set; }
    public int Id { get; set; }
}

public class Entity1 : BaseEntity
{
    public string Name { get; set; }
    public Entity3 Child { get; set; }
}

public class Entity2 : BaseEntity
{
    public string Name { get; set; }
    public IList<Entity3> Children { get; set; }
}

public class Entity3 : BaseEntity
{
    public string Name { get; set; }
}

So when I want to retrieve a list of entities of type Entity1 I should get only entities which have Cancelled property set to false, and also if property Child entity has Cancelled set to false it should be retrieved, otherwise it should be null.
For Entity2, IList<Entity3> children should contain only entities with Cancelled set to false.
I am trying to use reflection to determine if property of entity has base type equal to BaseEntity
if (property.PropertyType.BaseType == typeof(BaseEntity))

but how can I add it to query?


text:
Q: StarTeam not checking out to working folder? I'm using StarTeam 4.1 and I'm trying to use the command line version of StarTeam to checkout all the files of the folder.  But for some reason, instead of checking out to C:\Installation, it checks out to C:\400\Installation.  In the GUI, StarTeam clearly states that the complete working folder path is C:\Installation.  If I run stcmd.exe and try to checkout a single file from the root of Installation, it says that there is no such file, while I can check it out from the GUI.  stcmd.exe also does not display all the subfolders of Installation.  Any idea why this might be happening?

A: I didn't realize that the view name was specified in the checkout command.  If you do not specify a view name, the default is used.  In my case, there was a folder named Installation and a view named Installation.  Since I just specified to checkout Installation, it was interpreted as a view name instead of a folder, and the Installation view  checked out the Installation folder to C:\400\Installation for some reason.


text:
Q: Ruby expression not evaluating to what I'm expecting string = "test"
suitable_inventories = [1, 2, 3]
inventories ||= string.empty? ? suitable_inventories : []
inventories

Based on my understanding of Ruby, I was expecting the above code to produce:
[]

Instead, it is returning:
[1, 2, 3]

Did I misunderstand how ||= works?

A: ||= is a conditional assignment. The below two are basically equivalent:
foo ||= 42
bar = 42 unless bar

In other words ||= will do an assignment only if the variable holds nil or false as a value ATM. Due to some peculiarities, this also means variable that didn't have a value assigned already.

So if inventories already holds some array, a new one will not be reassigned with ||=.

A: a ||= b means a || a = b that is,

*

*If a is set (not nil or false), then a remains as it is, using short-circuit behaviour of || operator

*Otherwise, a will be false or nil resulting in execution of second part of expression after ||, i.e a=b
In your case, inventories must be already assigned (not nil) thats why it is not []
inventories ||= string.empty? ? suitable_inventories : []

is equivalent to :
inventories || inventories = string.empty? ? suitable_inventories : []


text:
Q: Emacs Neotree open file in split window Is there a way to open a file from Neotree in a new split window?
I want to achive same functionality as Vim NERDTree shortcuts "i" and "s"
Or is that the wrong approach?

A: You can use | for veritcal split and - for horizontal split.