text:
Q: ListView not displayed with values in android I have made a very simple, form with certain fields,In that i have put a ListView for country List,I am fetching all country names from a webservice,I got all data,But i am unable to set it in ListView,My ListView not visible,Please help me for it.thank you my code is as below:
RegistrationActivity.java
    package com.epe.yehki.ui;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.epe.yehki.adapter.CountryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.RegisterationAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.example.yehki.R;

public class RegistrationActivity extends Activity {
    public RegisterationAPI registartionAPI;
    private EditText fName;
    private EditText lName;
    private EditText eMail;
    private Button register;
    private CountryAdapter countryContent;

    private EditText contact;
    private EditText password;
    private ListView countrylist;
    private ListView statelist;

    public static ArrayList<String> countryArray;
    private TextView country;

    private TextView state;
    JSONArray countries = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> countryList;
    ArrayList<HashMap<String, String>> stateList;

    public com.epe.yehki.uc.Menu regMenu;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_registration);

        // FINDING IDS...
        fName = (EditText) findViewById(R.id.et_fname);
        lName = (EditText) findViewById(R.id.et_lname);
        eMail = (EditText) findViewById(R.id.et_email);
        contact = (EditText) findViewById(R.id.et_contact);
        password = (EditText) findViewById(R.id.et_pwd);
        country = (TextView) findViewById(R.id.et_country);
        state = (TextView) findViewById(R.id.et_state);
        regMenu = (Menu) findViewById(R.id.menuReg);
        register = (Button) findViewById(R.id.btn_register);
        countryList = new ArrayList<HashMap<String, String>>();
        countrylist = (ListView) findViewById(R.id.country_list);
        statelist = (ListView) findViewById(R.id.state_list);

        countryArray = new ArrayList<String>();

        regMenu.setSelectedTab(1);

        // COUNTRY LIST CLICK EVENT...!!!
        countrylist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // getting values from selected ListItem

                String countryname = ((TextView) view.findViewById(R.id.name)).getText().toString();

                country.setText(countryname);
                // countrylist.setVisibility(view.GONE);
            }
        });

        // REGISTER BUTTOM CLICK EVENT.....!

        register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!fName.getText().toString().equals("") && fName.getText().toString() != null) {
                    if ((!lName.getText().toString().equals("") && lName.getText().toString() != null)) {
                        if ((!country.getText().toString().equals("") && country.getText().toString() != null)) {
                            if ((!state.getText().toString().equals("") && state.getText().toString() != null)) {
                                if ((!eMail.getText().toString().equals("") && eMail.getText().toString() != null)) {
                                    if ((!password.getText().toString().equals("") && password.getText().toString() != null)) {
                                        if ((!contact.getText().toString().equals("") && contact.getText().toString() != null)) {

                                        } else {// CONTACT NUMBER
                                            validation(getResources().getString(R.string.valid_number));
                                            password.requestFocus();
                                        }

                                    } else {// password...
                                        validation(getResources().getString(R.string.valid_pwd));
                                        password.requestFocus();
                                    }

                                } else {// EMAIL
                                    validation(getResources().getString(R.string.valid_mail));
                                    eMail.requestFocus();
                                }

                            } else {// STATE
                                validation(getResources().getString(R.string.valid_state));
                                state.requestFocus();

                            }
                        } else {// COUNTRY
                            validation(getResources().getString(R.string.valid_country));
                            country.requestFocus();

                        }

                    } else {// LAST NAME
                        validation(getResources().getString(R.string.valid_lname));
                        lName.requestFocus();

                    }
                } else {// FIRST NAME
                    validation(getResources().getString(R.string.valid_fname));
                    fName.requestFocus();
                }
            }
        });
        // COUINTRY LIST CLICK EVENT...!!!!
        country.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                countrylist.setVisibility(View.VISIBLE);
                new GetCountries().execute();
            }
        });

    }

    void validation(String msg) {

        Toast.makeText(RegistrationActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    ResponseListener responseListener = new ResponseListener() {

        @Override
        public void onResponce(String api, API_RESULT result, Object obj) {
            System.out.println("::::::::::::::inside response Listener::::::::");

            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.dismiss();

            if (api.equals(Const.API_LOGIN)) {
                System.out.println("::::::::::::::inside response Listener::::::::1");

                if (result == Const.API_RESULT.SUCCESS) {

                    registartionAPI = null;

                    // as
                    // doctor
                    System.out.println("success Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
                    startActivity(new Intent(RegistrationActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

                } else {
                    System.out.println("failed Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
                }
            }

        }
    };

    // ASYNC TASK FOR GETTING COUNTRY LIST...!!!

    private class GetCountries extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            /*
             * pDialog = new ProgressDialog(CategoryActivity.this);
             * pDialog.setMessage("Please wait...");
             * pDialog.setCancelable(false); pDialog.show();
             */
            System.out.println("==========inside preexecute===================");

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            BackendAPIService sh = new BackendAPIService();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(Const.API_COUTRY, BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);
            System.out.println("=============MY RESPONSE========== FOR COUNTRYlIST" + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    if (jsonObj.has(Const.TAG_COUNTY_LIST)) {

                        // looping through All Contacts

                        countries = jsonObj.getJSONArray(Const.TAG_COUNTY_LIST);
                        for (int i = 0; i < countries.length(); i++) {
                            JSONObject c = countries.getJSONObject(i);

                            String cId = c.getString(Const.TAG_COUNTRY_ID);
                            String countryName = c.getString(Const.TAG_COUNTRY_NAME);
                            System.out.println("::::::::::::CountryId:::::::::::::" + countryName);

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

                            country.put(Const.TAG_COUNTRY_ID, cId);
                            country.put(Const.TAG_COUNTRY_NAME, countryName);

                            countryList.add(country);

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            countryContent = new CountryAdapter(RegistrationActivity.this, countryList);
            countrylist.setAdapter(countryContent);

        }

    }
}

CountryAdapter.java
package com.epe.yehki.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.epe.yehki.util.Const;
import com.example.yehki.R;

public class CountryAdapter extends BaseAdapter {
    public ArrayList<HashMap<String, String>> countryArray;
    private Context mContext;

    public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> cuntryList) {
        this.mContext = paramContext;
        this.countryArray = cuntryList;

    }

    public int getCount() {
        return this.countryArray.size();
    }

    public Object getItem(int paramInt) {
        return Integer.valueOf(paramInt);
    }

    public long getItemId(int paramInt) {
        return paramInt;
    }

    @SuppressWarnings("static-access")
    public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
        LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
        Viewholder localViewholder = null;
        if (paramView == null) {
            paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
            localViewholder = new Viewholder();
            localViewholder.countryid = ((TextView) paramView.findViewById(R.id.cat_id));
            localViewholder.countryName = ((TextView) paramView.findViewById(R.id.name));

            paramView.setTag(localViewholder);

        } else {
            localViewholder = new Viewholder();
            localViewholder = (Viewholder) paramView.getTag();
        }
        System.out.println("::::::::::::::array indexes::::::::::::" + countryArray.get(paramInt));

        localViewholder.countryName.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
        localViewholder.countryid.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_ID));

        return paramView;

    }

    static class Viewholder {
        TextView countryName;
        TextView countryid;

    }
}

A: It is display nothing because you do not fill up the dataset you want to display. You create the Adapter in onCreate but at the time the dataset is empty. Imo you should change the Adapter constructor from
public CountryAdapter(Context paramContext, ArrayList<String> paramArrayList) {

to
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> paramArrayList) {

and when onPostExecuted is called, you create a new CountryAdapter and submit it to the ListView. Of course you have to adjust your Adapter in order to reflect the changes of the  Adapter's constructor


text:
Q: Display issue without css with ng test Angular 4 Karma-Jasmine I have display issue when running the command ng test. It seems I don't have css effect anymore.Here are two images one from the ng serve and the other from ng test

Is this a normal behavior ? Should I share specific files from my project Just leave a comment.

A: This might be too late but it may help somebody.
Go to your karma.conf.js and add this
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    files:[
      "node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
     "src/styles.css",
    ],
     // more code below

In this sample, I added my styles.css and a pre-built theme from angular material.
Let me know if you still need any help.

A: brijmcq provides great insight on how to fix the issue. I have also struggled with correctly loading css for fonts (that also load font files), in my case material icons:
The css file loads the font files and failed during testing
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url(MaterialIcons-Regular.eot); /* For IE6-8 */
  src: local('Material Icons'),
       local('MaterialIcons-Regular'),
       url(MaterialIcons-Regular.woff2) format('woff2'),
       url(MaterialIcons-Regular.woff) format('woff'),
       url(MaterialIcons-Regular.ttf) format('truetype');
}

This can be overcome by instructing Jasmine to also serve those files:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    files: [
      "node_modules/bootstrap/dist/css/bootstrap.css",
      "node_modules/material-design-icons/iconfont/material-icons.css",
      "node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
      {
        pattern: 'node_modules/material-design-icons/iconfont/*',
        watched: false,
        included: false,
        served: true,
        nocache: false
      }
    ],

redpajama_set_name: RedPajamaStackExchange


text:
Q: If the empty set is a subset of every set, why isn't $\{\emptyset,\{a\}\}=\{\{a\}\}$? If the empty set is a subset of every set, why it isn't written with the elements of a set? like so $\{1,2,3,\emptyset\}$
Or why isn't $\{\emptyset,\{a\}\}=\{\{a\}\}$? I know one has two elements and the other has 1 but since the empty set is a subset of both, then why it isn't being mentioned explicitly in the definition of the set?

A: What happens if $\varnothing$ is in fact an element of some set? For example, $\{\varnothing\}$?
How can you tell the difference between $\varnothing$ and $\{\varnothing\}$, if you add the empty set as an element to every set?
Membership and inclusion are two different relations, and should be treated differently.

A: The empty set is a subset of every set, but it is not an element of every set.
In your examples, $$\varnothing \in \{\varnothing, \{a\}\}\text{ but } \varnothing \notin \{\{a\}\},$$
but it is a subset of both sets:
$$\varnothing \subset \{\varnothing, \{a\}\}, \text{ and } \varnothing \subset \{\{a\}\}.$$


text:
Q: Standard superuser creation in Django admin give unrecognizable error python manage.py createsuperuser --username='donfox'
After password is entered this is  returned
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg))
TypeError: User() got an unexpected keyword argument 'email'
The User is extended from an "AbstractUser".
class User(AbstractUser):
    email = None
    first_name = None
    last_name = None
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    class Meta:
        db_table = 'User'

   Column    |           Type           | Collation | Nullable |              Default
--------------+--------------------------+-----------+----------+------------------------------------
 id           | integer                  |           | not null | nextval('"User_id_seq"'::regclass)
 password     | character varying(128)   |           | not null |
 last_login   | timestamp with time zone |           |          |
 is_superuser | boolean                  |           | not null |
 username     | character varying(150)   |           | not null |
 is_staff     | boolean                  |           | not null |
 is_active    | boolean                  |           | not null |
 date_joined  | timestamp with time zone |           | not null |

A: Just remove these lines:
    email = None
    first_name = None
    last_name = None

And then remake your migrations. I'm not sure why you could add these, but email field is needed, as you can see in error description.


text:
Q: can I have a global variable in python without declaring it as global? I want some sort of a global state that maintains the current number, as well as a function to generate the next number.
I can write a generator to give me the next number.
 def gen(self, n):
    yield n
    yield n + 1

but what is a clean way to maintain its state? I do not want to simply have a global variable. Is there a better way to do this? or is that my only option?
I tried to make a class like this:
class Count:
"""
Represents the counter which
generates variables
"""

def __init__(self, curr=0):
    """
    :param curr: the current integer
    """
    self.curr = curr

def gen(self):
    """
    A generator for the next
    number
    :return: generator
    """
    self.curr += 1
    yield self.curr
    yield self.curr + 1

but this will not work, because every time I create Count(), it will reset my counter which I don't want.

A: If you want to maintain state across multiple instances of Count, then use a variable in the class scope, and reference it with the Count. prefix, like this:
class Count:
    curr = 0

    def __init__(self, startWith = None):
        if startWith is not None: Count.curr = startWith - 1

    def gen(self):
        while True:
            Count.curr += 1
            yield Count.curr

Note that if you want to maintain state, the constructor should allow for the possibility to not reset the counter, but leave it untouched.
As a side note, you might be interested in letting the generator generate a never ending series as shown above.
Here is how you could use the above class:
# Get generator that starts with 2
gen = Count(2).gen();

print (next(gen)); # -> 2
print (next(gen)); # -> 3
print (next(gen)); # -> 4

# Get a generator that continues ...
gen2 = Count().gen();

print (next(gen2)); # -> 5

# We can still use the previous generator also:

print (next(gen)); # -> 6

# Start with 0:

gen3 = Count(0).gen();

print (next(gen3)); # -> 0

# Other generators follow suit:

print (next(gen)); # -> 1
print (next(gen2)); # -> 2

A: If my understanding is correct, to eliminate the global counter you could create a closure for you variable and return a function that increments it.
The original function counter is called only once, consecutive calls simply increment the counter:
def count(n):
    c = n
    def incr():
        nonlocal c
        c += 1
        print(c)
        return c
    return incr

count is initialized with some state n and incr references that state in consecutive calls:
>>> f = count(2)
>>> f()
3
>>> f()
4
>>> f()
5

A: Or you can use the next(generator) function.
def num_gen():
    n=1
    while n:
        yield n
        n += 1

Then
>>my_gen = num_gen()
>>next(my_gen)
1
>>next(my_gen)
2

And so forth.  Whenever a generator yields a value, the state of the generator is stored so that it can resume execution later.


text:
Q: GCC plugin compilation issue I'm trying to cross-compile a custom kernel module (from this git),
which depends on a plugin that is originally compiled within the git (it's in $git/buildtools/gcc-nexmon-plugin/nexmon.c).
Originally, this tree is intended to be built directly on the raspberry pi, but I would like to port this feature to a buildroot system, that is, I don't have gcc/g++ on my raspberry pi, I only cross-compile on my laptop.
My problem is how to properly create nexmon.so (the plugin file) so I can later use it while cross-compiling
The original command line to produce nexmon.so was:
g++ -std=c++11 -Wall -fno-rtti -fPIC -I../gcc-arm-noneabi[...]/plugin/include \
     -c -o nexmon.o nexmon.c

g++ -shared -o nexmon.so nexmon.o

As you can see they are including some cross-compiler within the tree ("../gcc-arm..").
Now I understand that the plugin SHOULD NOT be cross-compiled. Remember they want us to run this on the raspberry pi, so "g++" is the embedded "g++". On my side, I have to run "g++" of my laptop.
Unfortunately, I can't seem to get it to work on my laptop, here's what I am trying nowadays:
g++ -std=c++11 -Wall -fno-rtti -fPIC -I/usr/include \
   -I/usr/lib/gcc/x86_64-linux-gnu/8/plugin/include -o nexmon.o -c nexmon.c

Because I'm currently using g++ 8.3.0-6, and I located the corresponding headers for plugin development. If I run this, I am getting a TON of problems,

*

*"in included plugin/include/tree.h file: #error Unknown BITS_PER_UNIT"

*"in included plugin/include/cpplib.h file: #error Cannot find a least 32 bit signed integer type"

Which make me think I am missing some flags to properly define my laptop architecture - but I could be wrong.
Here's a complete PasteBin of my errors: output log
I think I do have stuff to build a plugin, because gcc8/plugin/include exist. I tried to install "gcc-multilib, gcc-8-plugin-dev-i686-linux-gnu, gcc-8-plugin-dev-x86-64-linux-gnux32, gcc-8-plugin-dev". I cannot come back to a previous gcc (like 4.8, 5, 6, 7) because all my debian upgrades removed them, they are not used anymore
Any help would be highly appreciated, no one has been able to help me so far and I ran out of ideas. This point is totally blocking to my project.

A: I am answering my own question because that might help people in the future
First of all, I was wrong on how to compile a plugin to be later used in a cross-compilation context, the correct way to do this is:
$(HOST_CXX) -fPIC -I$(TARGET_CC)/[..]/plugin/include -shared \
     -o plugin.so plugin.c

Therefore you are not cross-compiling, but calling the plugin developpement environment of your cross-compiler. To figure the correct include path, simply do:
$(TARGET_CXX) -print-file=plugin

My compilation issues were due to the fact this plugin was built for older gcc version (5+), while I am using (8+). My fix for that is was to replace the following line:
#include <plugin.h>

(I assume, that was the old way to call the plugin dev. environment), by:
#include <gcc-plugin.h>


text:
Q: Samsung galaxy note 5 viewport size I have some trouble replicating a website responsive issue using Samsung Note 5. The display is messed up when using the said device. I tried using chrome dev tool and adjust sizes for a chance to replicate it but no luck. I also search the internet but I can't see note 5 viewport size.
I tried 360x640 but it displays with no issues so I think this is not the right viewport for the Note 5. Any help would be much appreciated.

A: From this site
Screen Size (X - Horizontally): 1440

Screen Size (Y - Vertically): 2560

Pixel Ratio: 4.0

Portrait
It is 360 x 640
The site also allow you to enter any URL and render it in a virtual galaxy note 5
Side Note
The material design project have a web directory in which they listed the display details of many well known mobile phones
Alternate Site
This site also allow you to render a url into a virtual galaxy note 5

Disclosure affiliation : I am in no way affiliated with any of the sites and also not an official representative of it/them

A: According to statistics
Pixel size: 1440 x 2560
ViewPort size: 480 x 853

Also you can get this information with javascript:
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

A: Samsung Galaxy Note 5
screen size: 1440 x 2560
viewport: 480 x 853


text:
Q: How can i write test for apex trigger using assert method? How can i write test for apex trigger using assert method?
Here is my code:
trigger ProductTrigger on Product__c (before insert, before update) {
    Schema.DescribeFieldResult F = Product__c.Description__c.getDescribe();
    Integer lengthOfField = F.getLength();
    List<Product__c> prList = new list<Product__c>();
    for(Product__c pr: trigger.new){
        pr.AddedDate__c=system.today();
        if (String.isNotEmpty(pr.Description__c)) {
           pr.Description__c = pr.Description__c.abbreviate(lengthOfField);
        }
    }
}

A: You can test a trigger the same way you would test a normal logic class. Just create a new test class, then create a new product in your test class, insert it, query for it, and verify that the fields you expected your trigger to change have been updated.
Calling the insert statement inside of StartTest()/StopTest() ensures that the trigger logic completes before the assertions are evaluated.
You can test the update logic in the same fashion and also test inserting & updating lists of objects.
@isTest
public class Test_ProductTrigger {

    @isTest
    static void test_getNewApp()
    {
        Product__c product = Product__c();
        product.yourFieldToTest = 'someValue';

        Test.startTest();
             insert products;
        Test.stopTest();

        Product__c newProduct = [SELECT yourFieldToTest FROM Product WHERE Id = product.Id LIMIT 1];

        system.assert('yourExpectedValue' == newProduct.yourFieldToTest);
        // You can also use system.assertEquals to do the same test
        system.assertEquals('yourExpectedValue', newProduct.yourFieldToTest);

    }
}


text:
Q: Does angular-material md-menu component support sub-menus? I see a sub-menu working in the "menu bar" example - https://material.angularjs.org/latest/demo/menuBar
There are no examples of sub-menus for the actual menu component.
I looked at the menu bar example and it uses md-menu, so it should be supported in the regular menu, right? I tried it and it breaks the entire menu (top level also stops working).
I'm guessing that it's just not supported? I found this discussion, but I'm not sure what to make of it.

A: Check here, there are sub-menu in this example. version 1.0.5

A:     <md-menu-item>

        <md-menu style="padding:0px;">

            <md-menu-item>

                <!-- ACCOUNT SETTINGS -->
                <md-button ng-click="$mdOpenMenu()">
                    <md-icon md-font-set="md">assignment_ind</md-icon>
                    Account Settings
                </md-button>

            </md-menu-item>

            <!-- SUBMENU-->
            <md-menu-content>

                <!-- CHANGE PASSWORD -->
                <md-menu-item>
                    <md-button>
                        <md-icon md-font-set="md">security</md-icon>
                        Change Pasword
                    </md-button>
                </md-menu-item>

                <!-- DELETE ACCOUNT -->
                <md-menu-item>
                    <md-button>
                        <md-icon md-font-set="md">delete_forever</md-icon>
                        Delete Account
                    </md-button>
                </md-menu-item>

            </md-menu-content>

        </md-menu>

    </md-menu-item>


text:
Q: Django Authentication granularity Is there a way to reduce the granularity of auth for a specific view?
For example, I only want to check for auth for POST requests and not GET requests.
My current code looks like this: (which requires both GET and POST to provide a jwt)
class PartView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        ...
    def post(self, request, *args, **kwargs):
        ...

A: Not sure if this is quite the correct syntax but it's one way to do it (didn't test it).
Implement your own custom permission that lets through post requests with an authenticated user and get requests with no restriction.
Authentication class returns an AnonymouseUser or None if not authenticated, but the permission class does the authorization checks.
class AllowUnauthenticatedGetRequests(permissions.BasePermission):
    def has_permission(self, request, view):
        if (request.method == "GET")
            return True

        return bool(request.user and request.user.is_authenticated)

Then replace the permission in the view:
permission_classes = [AllowUnauthenticatedGetRequests]

References

*

*https://docs.djangoproject.com/en/4.1/ref/contrib/auth/

*https://github.com/jpadilla/django-rest-framework-jwt/blob/master/rest_framework_jwt/authentication.py

*https://docs.djangoproject.com/en/4.1/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser

*How Can I Disable Authentication in Django REST Framework


text:
Q: Upper bound on the number of elements in part of an infinite set Let $A$ be an infinite subset of positive integers. Suppose $\lambda$ is the supremum of all real numbers such that, $\sum_{n\in A} \frac{1}{n^{\lambda}} = \infty$  . I wonder if we have $$k^{\lambda} \ge \sum_{k/2<n\le k, n\in A} 1$$
for all sufficiently large $k$'s (namely there exists $K$ such that for all $k>K$, the above inequality holds)
If $\lambda \ge 1$, then the inequality above trivially holds. But I don't know how to address the case $\lambda < 1$. I can't find a counterexample either.

A: If you wrote the question correctly, then $A := \mathbb{N}, \lambda = 1/2$ is a counterexample.
I assume you meant $\sum_{n \in A} n^{-\lambda} < +\infty$. Then it's true. Suppose $k^\lambda < |A\cap[k/2,k]|$ for infinitely many $k$. Then, for such $k$, we have $\sum_{n \in A \\ n \in [k/2,k]} 1/n^\lambda \ge k^\lambda/k^\lambda = 1$. So $\sum_{n \in A} 1/n^\lambda = +\infty$.


text:
Q: Power Automate - Select single item from Get Items I'm trying to fetch an item from a list to perform some operations on (parsing JSON specifically) but when I use the Get Items action it returns an array, even if I select the top 1 from the results. The Parse JSON action can't take an array as input, only a single object. What can I do to prepare the item(s) in the Get Items action to be parsed?
Edit: Here's a screen cap of a simple workflow where I'm trying out this operation. When I try to Compose the People field from the Get Items action, it embeds it in a loop to go through the whole array of people. The problem is that I need to select one of those people and then make them available for the Parse JSON action to work its magic and let me access their DisplayName.

Also when trying to Parse a single instance of the People column, I get this error: "Invalid type. Expected Object but got Array."

A: Here are the steps that I would follow:

*

*After [Get Items] action add a [Compose] action

*Execute the Flow and examine the output from the [Compose].

*Copy the output of the [Compose] into clipboard

*Add [Parse JSON] action and use the output from step 3 as sample data to generate schema

*Add addition actions like another [Compose] action to verify the Parse Data.
Properties should be available from the Dynamic content.

To get a particular item's property, you can use the expression shown below.
Here [0] indicates the first item in the [Parse JSON] output, which is an array, and ['LastName'] is a list column (property).
body('Parse_JSON')?[0]['LastName']

Here is an article
describing how to work with JSON in Flow

A: First of all, I wanted to suggest the action Get Item instead of Get Items if you only want one specific item, and you have the item ID.
The Get Items action will result in a loop even if you only have one item to retrieve from it.
If Get Item can't be an option, I'd suggest saving the item in an Object variable and working with that variable instead of the item property.

A: *

*Set Value to 1 for Top Count in Get Items
Get Items > Top Count > 1

*Go to settings Turn on pagination and set value 1 to Threshold field.
Settings > On Pagination > Value 1 for Threshold


text:
Q: while sending the mail using smtplib in python got the error (11004, 'getaddrinfo failed') I'm sending a mail using a python script on a development server which don't have internet connection but i check the connectivity with the SMTP server by pinging the server and it is connected. But i'm getting error (11004, getaddrinfo failed) while connecting to it using smtplib.
Please help me in this issue!
Below is the code im using
msg = MIMEMultipart()
msg["From"] = "sender"
msg["To"] = 'recipient'
msg["Subject"] = "Testing Email"
message = 'Hi,\n \nThis is testing mail.'
ctype, encoding = mimetypes.guess_type(file)
if ctype is None or encoding is not None:
   ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fp = open(file, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename='report.xlsx')
msg.attach(MIMEText(message, 'plain'))
msg.attach(attachment)

try:
    server = smtplib.SMTP(server_name)
    server.set_debuglevel(0)
    server.sendmail(sender, receiver, msg.as_string())
    server.quit()
except Exception as e:
    print(e.args)

A: Try this:
server = smtplib.SMTP("smtp.google.com", 587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, message)
server.quit()


text:
Q: RSpec False Positive - How is this possible? RSpec is saying everything is fine and dandy with my Help page, but it shouldn't be.  What would cause the false positive.  (I have restarted my test suite several times).
Here's my spec page:
require 'spec_helper'

describe "Static pages" do

  subject { page }

  shared_examples_for "all static pages" do
    it { should have_selector 'h1',    text: heading }
    it { should have_selector 'title', text: full_title(page_title) }
  end

.
.
.

  describe "Help page" do
    before { visit help_path }

    let(:heading) { 'Help' }
    let(:page_title) { 'Help' }
  end

.
.
.

end

Here's my Help page:
<% provide(:title, '') %>

  Get help on the Ruby on Rails Tutorial at the
  Rails Tutorial help page.
  To get help on this sample app, see the
  Rails Tutorial book.

It's saying the tests pass.  How to fix?

A: Looks like you're missing:
it_should_behave_like 'all static pages'

in the describe 'Help Page' block.  You've defined the shared examples for 'all static pages' but are not telling rspec that the 'Help Page' should behave like one.
Also, please look this answer to a very similar question.  It shows how you might refactor your specs to express intent more clearly.


text:
Q: C++ audio file converter I have a G711 codec, and i would like to convert a wav file and save this. I read a sample.wav file, and convert it with the G711 ITU-T codec, and save the encoded data to an output.wav file.
Here is my code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "G711.h"
#include <vector>
using namespace std;

// WAVE PCM soundfile format (you can find more in https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ )
typedef struct header_file
{
    char chunk_id[4];
    int chunk_size;
    char format[4];
    char subchunk1_id[4];
    int subchunk1_size;
    short int audio_format;
    short int num_channels;
    int sample_rate;            // sample_rate denotes the sampling rate.
    int byte_rate;
    short int block_align;
    short int bits_per_sample;
    char subchunk2_id[4];
    int subchunk2_size;         // subchunk2_size denotes the number of samples.
} header;

typedef struct header_file* header_p;

int main()

{
    FILE * infile = fopen("sample.wav","rb");       // Open wave file in read mode
    FILE * outfile = fopen("Output.wav","wb");      // Create output ( wave format) file in write mode

    int BUFSIZE = 512;                  // BUFSIZE can be changed according to the frame size required (eg:512)
    int count = 0;                      // For counting number of frames in wave file.
    short int buff16[BUFSIZE];              // short int used for 16 bit as input data format is 16 bit PCM audio
    header_p meta = (header_p)malloc(sizeof(header));   // header_p points to a header struct that contains the wave file metadata fields
    int nb;                         // variable storing number of byes returned

    if (infile)
    {
        fread(meta, 1, sizeof(header), infile);
        fwrite(meta,1, sizeof(*meta), outfile);
        cout << " Size of Header file is "<<sizeof(*meta)<<" bytes" << endl;
        cout << " Sampling rate of the input wave file is "<< meta->sample_rate <<" Hz" << endl;
        cout << " Number of samples in wave file are " << meta->subchunk2_size << " samples" << endl;
        cout << " ID: " << meta->chunk_id << endl;
cout << "chunk_size" << meta->chunk_size << endl;
cout << "format" << meta->format << endl;
cout << "subchunk1"<<meta->subchunk1_id << endl;
cout << "subchunk1_size"<<meta->subchunk1_size << endl;
cout << "audio_format"<<meta->audio_format<<endl;
cout << "num_channels"<<meta->num_channels<<endl;
cout << "byte_rate"<<meta->byte_rate<<endl;
cout << "block_align"<<meta->block_align<<endl;
cout << "bits_per_sample"<<meta->bits_per_sample<<endl;
cout << "subchunk2_id"<<meta->subchunk2_id<<endl;

        while (!feof(infile))
        {
            nb = fread(buff16,1,BUFSIZE,infile); // Reading data in chunks of BUFSIZE

            size_t ds = sizeof(buff16) >> 1;
            cout << "ds: " << ds <<endl;
            vector<short> vec_src(sizeof(buff16), 0);
            vector<unsigned char> vec_dst(ds, 0);
            for (int i = 0; i < sizeof(buff16); i++) {
                    vec_src[i] = buff16[i];
            }
            short* src = &vec_src[0];
            uint8_t* dst = &vec_dst[0];
            G711::ALawEncode(dst, buff16, sizeof(buff16));
            unsigned char arr[ds];
            for (unsigned i = 0; i < ds; i++) {
                    arr[i] = *(dst + i);
            }

count++;                    // Incrementing Number of frames

            /* Insert your processing code here*/
            fwrite(arr,sizeof(unsigned char),sizeof(arr),outfile);          // Writing read data into output file
        }
    cout << " Number of frames in the input wave file are " <<count << endl;
    }
    getchar();
return 0;
}

I dont know very well C++, so please help me. If i run this code i get Output.wav file but i cant play. Whats wrong?


text:
Q: Word-order in indirect questions I'm taught that in indirect questions   the verb   comes after the subject:

Do you know what time the bank opens?

But what if  the question proper goes first? Should one say

What time the bank opens is an interesting question

or

What time does the bank open is an interesting question?

A:
[1] Do you know [what time the bank opens]?
[2] [What time the bank opens] is an interesting question.

In both examples, the bracketed constituent is a subordinate interrogative clause (embedded question).
It matters not whether the embedded question is complement of a verb, as in [1], or subject of the sentence. In both constructions there should be no inversion.
The meaning of [1] is:
"Do you know the answer to the question 'What time does the bank open?'"
And the meaning of [2] is:
"The answer to the question 'What time does the bank open?' is an
interesting question".

A: Your first version

What time the bank opens is an interesting question.

is correct because 'What time the bank opens' is a nominal clause which functions as the subject of the verb is.
https://www.englishgrammar.org/relative-pronoun/
To turn the question 'What time does the bank open?' into subject, it is possible to use quotation marks:

"What time does the bank open?" is an interesting question.

It is rarely used phraseology, but here's another example where quoted questions function as noun phrases:
The Dream Questionnaire items included "How often do you remember your dreams?" and "What do you most often dream about?" http://blog.apastyle.org/apastyle/2011/08/punctuating-around-quotation-marks.html


text:
Q: Android TextView link email containing apostrophes I have a TextView:
<TextView
    android:text="Contact details go here"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvContactDetails"
    android:autoLink="email" />

I then put an e-mail address in (I'm using Monodroid, but it doesn't really make any difference here):
TextView tvContactDetails = FindViewById(Resource.Id.tvContactDetails)
tvContactDetails.Text = sEmail;

If I give it an e-mail address like joe@bloggs.com it's fine.  But when I give it kevin.o'donnel@abc.com it only hyperlinks donnel@abc.com.  How can I get it to recognise apostrophes as part of the e-mail address?

A: After a while of searching and trying things I found a solution which worked for me at:
TextView to send email when clicked
TextView now looks like this:
<TextView
    android:text="Contact details go here"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvContactDetails"/>
(autoLink taken out)

The code now looks like this:
TextView tvContactDetails = FindViewById(Resource.Id.tvContactDetails)
string sHtmlEmail = "" + sEmail + "";
tvContactDetails.TextFormatted = Html.FromHtml(sHtmlEmail);
tvContactDetails.MovementMethod = Android.Text.Method.LinkMovementMethod.Instance;

Thanks for the suggestions though.


text:
Q: Why Runge-Kutta methods cannot find the solution of Lorenz system? The solution of the following Lorenz system
s=10; r=28; b=8/3;
f = @(t,y) [-s*y(1)+s*y(2); -y(1)*y(3)+r*y(1)-y(2); y(1)*y(2)-b*y(3)];

in the interval $[0,8]$ with initial values $y_1(0)=1$,$y_2(0)=0$,$y_3(0)=0$ using MATLAB ode45() function are
>> [t y] = ode45(f,[0 8],[1 0 0]);
>> [t(end) y(end,:)]
ans =
    8.0000   -7.3560   -5.6838   27.8372

But the results are very poor with RK4 even with one million sub-interval (i.e. h=(8-0)/1e6)
ans =
    8.0000   -7.4199   -5.6639   28.0052

My questions are:

*

*Why the results are different?

*Is ode45() the best function for Lorenz system?

*How can I improve the RK4 accuracy?

*Is Lorenz system an stiff equation?

A: The Lorenz system
is notoriously unstable.
Try perturbing the initial conditions
by a very small amount
(say $10^{-6}$)
and see how much
the result changes.
You might try other solvers,
including a predictor-corrector
of some type.
Also,
make sure that
the computations are done
in double precision, at least.

A: *

*ode45 uses dynamical step size adaptation and is an order 5 method, thus it is more precise for the same effort than RK4 with constant step size (even if the step size control uses the "wrong" error estimate for the step size control). It is advisable to explicitly set the error tolerances, as the default tolerances might be too low. I get from

opts = odeset('AbsTol',1e-12,'RelTol',1e-10);
[t y] = ode45(f,[0 8],[1 0 0],opts);
[t(end) y(end,:)]

the result
    8.0000   -7.4186   -5.6635   28.0027

with relative and absolute error tolerances of 1e-10 and 1e-12. This is closer to your RK4 result. The dynamically selected step sizes range from 2e-4 to 6e-3.

*There is no best numerical method. But implicit methods with step size control might be better.

*Choose a smaller step size. But due to the increasing number of sub-steps the accumulated numerical noise will impose a limit in increasing precision.

*Yes. In general, non-linear ODE that are not sub-linear (i.e., there is no global Lipschitz constant) have regions where they may be stiff or produce dynamical blow-up.


text:
Q: WCF callback service to php client I have created a WCF Service with callback and using wsDualHttp Binding.
I want to connect to this service using PHP client.
In PHP , SoapClient is used to call the WCF service like below:
$wsdl = "http://pathto/file.svc?wsdl"
$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->somefunction();

Please guide in getting for callback in PHP.

A: I am sorry, but IMO its impossible to have callback from wcf to php (for exaple, this post also say so:
http://wso2.org/forum/thread/24111).
Probably you can check for some websocket solution to receive behavior you ste looking for.
Take a look on node.js, for ecample: http://bergie.iki.fi/blog/dnode-make_php_and_node-js_talk_to_each_other/


text:
Q: The difference between "SymbolicProcessing" -> 0 and restricting the function definition to numeric values only The Documentation tells us that there are two ways to disable symbolic processing of the integrand by the NIntegrate function when it is known that it just slows down the computation. One way is documented and heavily used on the Documentation page "NIntegrate Integration Strategies" and some other Documentation pages:
Method -> {Automatic, "SymbolicProcessing" -> 0}

Another approach is to define the integrand as a "black-box" function and this way is recommended in the "Possible Issues" section of the NIntegrate documentation page.
Let us compare:
f[x_] := Nest[Sin[# + Sin[2 #]] &, x, 20]
NIntegrate[f[x], {x, 0, 1},
  Method -> {Automatic, "SymbolicProcessing" -> 0}] // Timing

(* => {2.797, 0.947747} *)

g[x_?NumericQ] := Nest[Sin[# + Sin[2 #]] &, x, 20]
NIntegrate[g[x], {x, 0, 1}] // Timing

(* => {0.032, 0.947747} *)

One can see the two-order speedup of the "black-box" over the Method option. What is the reason? Are there cases when the Method option have advantages over the "black-box" approach? In which cases it is recommended to use one or another?

A: The first case still symbolically expands nest, substituting each numerical value into that nasty big expression, while the second expands it numerically for each x val.
Try this
f[x_] := (Print[x]; Nest[Sin[# + Sin[2 #]] &, x, 2])

You will see it is only called once with the symbolic argument.
"SymbolicProcessing" only turns off attenpts at symbolic integration


text:
Q: How do I create an exception-wrapping fubumvc behaviour? How can I create a fubumvc behaviour that wraps actions with a particular return type, and if an exception occurs while executing the action, then the behaviour logs the exception and populates some fields on the return object?  I have tried the following:
public class JsonExceptionHandlingBehaviour : IActionBehavior
{
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();
    private readonly IActionBehavior _innerBehavior;
    private readonly IFubuRequest _request;

    public JsonExceptionHandlingBehaviour(IActionBehavior innerBehavior, IFubuRequest request)
    {
        _innerBehavior = innerBehavior;
        _request = request;
    }

    public void Invoke()
    {
        try
        {
            _innerBehavior.Invoke();

            var response = _request.Get<AjaxResponse>();
            response.Success = true;
        }
        catch(Exception ex)
        {
            logger.ErrorException("Error processing JSON request", ex);

            var response = _request.Get<AjaxResponse>();
            response.Success = false;
            response.Exception = ex.ToString();
        }
    }

    public void InvokePartial()
    {
        _innerBehavior.InvokePartial();
    }
}

But, although I get the AjaxResponse object from the request, any changes I make don't get sent back to the client.  Also, any exceptions thrown by the action don't make it as far as this, the request is terminated before execution gets to the catch block.  What am I doing wrong?
For completeness, the behaviour is wired up with the following in my WebRegistry:
Policies
    .EnrichCallsWith<JsonExceptionHandlingBehaviour>(action =>
        typeof(AjaxResponse).IsAssignableFrom(action.Method.ReturnType));

And AjaxResponse looks like:
public class AjaxResponse
{
    public bool Success { get; set; }
    public object Data { get; set; }
    public string Exception { get; set; }
}

A: This won't work with the current version of FubuMVC, unfortunately.  The reason is that the call to _innerBehavior.Invoke() will proceed down the rest of the behavior chain including the call to render the JSON output back to the client.
With current FubuMVC, you can't wrap a behavior and modify its output before the render output behavior is executed.
I just talked with Jeremy (Miller) about this and we're going to add this capability to FubuMVC so that you can wrap a specific behavior (in this case, the behavior that calls the action) instead of wrapping the entire behavior chain (which is what's happening to you right now).
I'll comment back here on this StackOverflow question when we have added this feature.


text:
Q: Check if multiple properties either all exist or are all missing In JavaScript, I have an object of the following form:
const obj = {
  foo: {},
  bar: {},
  baz: {}
};

The object has to conform to the following rules:

*

*The property foo must be given.

*The properties bar and baz are both optional.

*If bar is given, then also baz must be given.

It is pretty easy to check for foo:
if (!obj.foo) {
  throw new Error('Foo is missing.');
}

How can I check for the other properties, in an elegant way? Of course I could do something such as:
if ((obj.bar && !obj.baz) || (!obj.bar && obj.baz)) {
  throw new Error('Bar or baz is missing.');
}

But this doesn't scale well. What if I do not have to check two properties, but 20, which either all have to be there, or none of them?
Ideally, I even would like the error message to exactly specify which one is missing (it's enough if it reports the first one).
I already thought of this (which effectively means: If at least one of the optional ones is given, check if any of them are missing):
if (obj.bar || obj.baz) {
  if (!obj.bar) {
    throw new Error('Var is missing.);
  }
  if (!obj.baz) {
    throw new Error('Baz is missing.);
  }
}

Is there a better way to solve this?

A: One option would be to make an array of the properties that need to all be together, and then use reduce on it to get the number of found properties. If the result is 0 or the length of the array, it's valid, else it's invalid.

const together = ['bar', 'baz', 'buzz'];
const validate = obj => {
  if (!obj.foo) return false;
  const togPropCount = together.reduce((a, prop) => a + (prop in obj), 0);
  return togPropCount === 0 || togPropCount === together.length;
};
console.log(validate({
  foo: {},
  bar: {},
  baz: {}
}));
console.log(validate({
  foo: {},
  bar: {},
  baz: {},
  buzz: {}
}));

Or, for an error message of the missing properties, maybe filter instead:

const together = ['bar', 'baz', 'buzz'];
const validate = obj => {
  if (!obj.foo) return false;
  const missingProps = together.filter(prop => !(prop in obj));
  return (missingProps.length === 0 || missingProps.length === together.length)
    ? true
    : 'missing ' + missingProps.join(', ');
};
console.log(validate({
  foo: {},
  bar: {},
  baz: {}
}));
console.log(validate({
  foo: {},
  bar: {},
  baz: {},
  buzz: {}
}));


text:
Q: Shorter form of (a == b && b == c) I want to compare three variables to be all equal. Of course this is not working:
(a === b === c) // beware: true on (true === false === false)

So I used
(a === b && b === c)

But I am wondering if there is a shorter form (like the first one - but working) in which every variable is only evaluated once.
EDIT:
My use case is the following expression:
(typeof a === typeof b && typeof b === typeof c)

I wanted to avoid to

*

*evaluate typeof b twice

*put typeof b into a variable

A: No, sorry, there isn't. If you really want to though, you can make a helper function:
function Test3(a,b,c) { return a === b && b === c; }

That would be shorter to type, but there are also drawbacks:

*

*It's a bit more indirect, so the code would be harder to read.

*It might be slower, since a function lookup and call is necessary. However modern JS engines might have optimizations that negate this. If performance of this operation is paramount, better benchmark to make sure.

*Although every expression would only be evaluated once, they would all be evaluated always.

To fix all these shortcomings, we can write it thus:
var b = ExpressionB;
if ( ExpressionA === b && ExpressionC === b ) { ... }

However this is pretty verbose and includes a temporary variable (which is unavoidable anyway, because you need to compare ExpressionB twice but evaluate only once).

A: If you want to compare an arbitrary number of items, you could use a function that compares all its arguments..
function equal(){
  var length = arguments.length,
      first = arguments[0];

  for(var i = 1;i<length;i++){
    if (arguments[i] !== first){
      return false;
    }
  }

  return true;
}

and call it equal(a,b,c) or equal(a,b,c,d,e,f,g,h,i,j)


text:
Q: How to create a service that puts selected text into quotation marks? I'd like to create a service that puts any text I select in TextEdit or web page text editors into quotation marks. I understand Automator is the tool to use, but how do I create this action using AppleScript or another scripting language in OS X (Lion)?

A: One way is to create a service that runs a shell command.
For this, open Automator, create a new Service, check "Output replaces selected text", then add the action "Run Shell Script". In the box where you enter the Shell script write:
cat | sed 's/^/"/' | sed 's/$/"/' | sed 's/""//'

This takes the text you entered as input, and adds a quotation mark at the beginning and end.
Now, once you save your service, you can, for example, go to TextEdit, select the text you want to quote, then go to Services -> "name of your service", and your text should now be quoted!

Edit: I included the removal of trailing double quotation marks


text:
Q: How to create an array of all first letters from object properties in another multidimentional array? I have an array with objects, and each object containing a property called name.
Now i want to have a second array containing the first letter of each name property from the first array. This first letter should be saved in a property called header if it doesn't exist yet.
I only want to have a letter to appear once, as this script is intended to be used for a list of alphabetic headers, each containing a list of names starting with the same letter.
I have created a function that uses the build-in JavaScript "filter" method, which is supposed to check if a value with this first letter already exists. But for some reason it doesn't work. The filter always returns an empty array, no matter what letter i provide.
I have been trying to figure out why my script is not working with no success. I greatly appreciate any help with this!
var fruit = [{title:"Apple"},{title:"Avocado"},{title:"Banana"},{title:"Cucumber"}];
var sections = [];
function createAlphabetSections(array) {
        for(var i = 0; i < array.length; i++){
            var firstLetter = array[i].title.charAt(0).toUpperCase();
            var section = sections.filter(function (section) { return section.header === firstLetter;});
            if(sections.length === 0){
                sections.push([{header: firstLetter}]);
            } else if (section.length > 0){
                sections.push([{header: firstLetter}]);
            }
        }
}
createAlphabetSections(fruit);

A: First make use map to build a new array from the current array. Then filter out any duplicates.
var sections = fruit.map(function (item) {
    // Return the first letter of the title property
    return item.title.substring(0, 1);
}).filter(function (value, index, self) {
    // http://stackoverflow.com/a/14438954/1789518
    return self.indexOf(value) === index;
});

A: var getLetters = function(items) {
    var letters = [];

    items.forEach(function(item) {
        if(letters.indexOf(item.title[0].toUpperCase()) === -1) {
            letters.push(item.title[0].toUpperCase());
        }
    });

    return letters;
};

getLetters([{title:"Apple"},{title:"Avocado"},{title:"Banana"},{title:"Cucumber"}]);


text:
Q: The point-open game and $\omega$-covers
Let $X$ be a topological space. The point-open game $G_{po}(X)$ is defined as folows. It is played by two players ONE and TWO. In the n'th step $(n \in \omega)$, ONE choose a finite subset $F$ of $X$, and TWO selects an open $G_n$ in $X$, $F_n \subset G_n$. ONE wins if $\bigcup \{ G_n : n \in \omega \} = X$, otherwise TWO wins.

Also:

If $\langle A_n : n \in \omega  \rangle$ is a sequence of subsets of a set $X$,
  $$ \underline{Lim} A_n = \{ x \in X : \exists n_0 \in \omega \forall n \geq n_0, x \in A_n \} $$
  If $\mathcal A$ is a family of subsets of a set $X$, then, $L(\mathcal A)$ denotes the smallest family of subsets of $X$ containing $\mathcal A$ and closed under $\underline{Lim}$.

I am trying to prove that (a)$\Rightarrow$(b) where:
(a) If $\mathcal I$ is an open $\omega$-cover of $X$, then, there is a sequence $G_n \in \mathcal I$, with $\underline{Lim} G_n = X$.
(b) If $\mathcal I$ is an open $\omega$-cover of $X$, then $X \in L(\mathcal I)$.

A family $\mathcal A$ of subsets of a set $A$ is said to be an $\omega$-cover of $X$, if for any finite subset $F$ of $X$,, there is an $A \in \mathcal A$ with $F \subset A$.


text:
Q: JUnit test for website contains one string or (exclusive) other string In a spring-mvc project I have a test for the content of the index/homepage:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HomePageTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldContainStrings() throws Exception {
        this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString("Hello World")));
    }
}

This test works fine so far. But now I would like to test for the occurrence of the strings "Login" or (excl) "Logout", i.e. I want to test whether exactly one (not zero and not both) of these two strings appears in the content. How can I match this or condition?
I tried
...
.andExpect(content().string(
      either(containsString("Login")).or(containsString("Logout"))));
....

But this does not work either (does not give an error if both strings appear in the page).

A: As long as string() method accepts Hamcrest matcher, I see two options here:

*

*Either implement XOR-like matcher yourself (you can use this answer as reference https://stackoverflow.com/a/29610402/1782379)...

*...or use complex condition like "any of them but not both"
Matcher<String> matcher =
        allOf(
                is(either(containsString("Login")).or(containsString("Logout"))),
                is(not(allOf(containsString("Login"), containsString("Logout")))));
assertThat("_Login_", matcher); // OK
assertThat("_Logout_", matcher); // OK
assertThat("_Login_Logout_", matcher); // FAIL
assertThat("__", matcher); // FAIL

Personally I prefer to use second option.

A: @Test
public void containsOneOfTwoSubStringsExclusive() {
    assertTrue((mainString.contains(substring1) && !mainString.contains(substring2)) ||
        (!mainString.contains(substring1) && mainString.contains(substring2)))
}

A: I just had to write to custom matcher for this myself when I could not find a suitable one.
import java.util.function.BiConsumer;

import javax.annotation.Nonnull;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.core.CombinableMatcher;

/**
 * Similar to the {@link CombinableMatcher.CombinableEitherMatcher} but only passes if only one of the given
 * matchers {@link Matcher#matches(Object)}.
 *
 * @author bugorskia
 */
public class EitherXorMatcher<T> extends BaseMatcher<T>{

    //_ **FIELDS** _//

    @Nonnull
    private final Matcher< ? super T > aMatcher;

    @Nonnull
    private final Matcher< ? super T > bMatcher;

    //_ **INNER CLASS**_//

    /**
     * This is just for the builder pattern/fluent interface.
     */
    public static final class EitherXorMatcherBuilder<T>{

        //_ **FIELDS** _//

        @Nonnull
        private final Matcher<? super T> aMatcher;

        //_ **CONSTRUCTOR** _//

        private EitherXorMatcherBuilder( @Nonnull final Matcher<? super T> aMatcher ){
            this.aMatcher = aMatcher;
        }

        //_ **API METHODS** _//

        @Nonnull
        public Matcher<T> xor( @Nonnull final Matcher<? super T> anotherMatcher ){
            return new EitherXorMatcher<>( aMatcher, anotherMatcher );
        }

    }

    //_ **CONSTRUCTOR** _//

    private EitherXorMatcher( @Nonnull final Matcher< ? super T > aMatcher, @Nonnull final Matcher< ? super T > bMatcher ){
        this.aMatcher = aMatcher;
        this.bMatcher = bMatcher;
    }

    @Nonnull
    public static <T> EitherXorMatcherBuilder<T> exclusivelyEither( final Matcher<? super T> aMatcher ){
        return new EitherXorMatcherBuilder<>( aMatcher );
    }

    @Nonnull
    public static <T> Matcher<? super T> exclusivelyEither( @Nonnull final Matcher<? super T> aMatcher, @Nonnull final Matcher<? super T> bMatcher ){
        return new EitherXorMatcher<>( aMatcher, bMatcher );
    }

    @Nonnull @Deprecated
    public static <T> EitherXorMatcherBuilder<T> either( final Matcher<? super T> aMatcher ){
        return exclusivelyEither( aMatcher );
    }

    //_ **API METHODS** _//

    @Override
    public boolean matches( final Object item ){
        final boolean aMatches = aMatcher.matches( item );
        final boolean bMatches = bMatcher.matches( item );

        return xor( aMatches, bMatches );
    }

    @Override
    public void describeTo( final Description description ){
        description.appendText( "Either { " );
        aMatcher.describeTo( description );
        description.appendText( " } xor { " );
        bMatcher.describeTo( description );
        description.appendText( " } " );
    }

    @Override
    public void describeMismatch( final Object item, final Description description ){
        final boolean aMatches = aMatcher.matches( item );
        final boolean bMatches = bMatcher.matches( item );
        assert !xor( aMatches, bMatches ): "Should not have gotten called!";
        assert aMatches == bMatches: "This is implied, and more of a developer comment than a runtime check.";

        final BiConsumer<Matcher<? super T>,Description> describer;
        final String startWord, joinWord;
        if( aMatches ){
            startWord = "Both";
            joinWord = "and";
            describer = Matcher::describeTo;
        }else{
            startWord = "Neither";
            joinWord = "nor";
            describer = ( m, d ) -> m.describeMismatch( item, description );
        }

        description.appendText( startWord ).appendText( " { " );
        describer.accept( aMatcher, description );
        description.appendText( " } " ).appendText( joinWord ).appendText( " { " );
        describer.accept( bMatcher, description );
        description.appendText( " } " ).appendText( " matched instead of exactly one." );
    }

    //_ **HELPER METHODS** _//

    private static boolean xor( final boolean aMatches, final boolean bMatches ){
        // xor :: one or the other but not both
        return ( aMatches || bMatches )  &&  ! ( aMatches && bMatches );
    }

}


text:
Q: In spring batch remote partitioning can we have the master and slave configuration as a single configuration and run it as a single program I'm using remote partitioning for my project and I have 2 projects in eclipse, i.e one is the master program and a separate one for the Slave. Instead of having 2 projects separately , Can I combine the slave and master to a single context and run, master and slave as a single Java process in my JVM?

A: Yes, that is the common pattern - with the master participating as one of the "slaves". If you don't need to distribute the work across multiple JVMs, the partitioning doesn't need to use an external broker; see the batch integration test cases and in particular the vanilla one.


text:
Q: How to link with the GNU gold linker instead of ld in Haskell My Haskell project spends lots of time in Linking dist/build/myapp/myapp ... and also in loading shared libraries when executing TemplateHaskell code.
I suspect this is because ld is slow.
How can I improve link times by switching to the gold linker?

A: Link 3x faster with gold
Since GHC 7.8, you can tell GHC and cabal (at run time without having to recompile GHC) to link with GNU gold.
You need in your .cabal file:
library:
  ghc-options: -optl-fuse-ld=gold
  ld-options:  -fuse-ld=gold

executable myExecutable
  ghc-options: -optl-fuse-ld=gold
  ld-options:  -fuse-ld=gold

(Note you might want to pass these flags to stack/cabal/Setup.hs on the command line instead of hardcoding them in the .cabal file in order to not reduce the portability of the package.)
For me it's 3.5x faster, bringing down the total link time of a project from 150 seconds to 40 seconds.

Update: Link 10x faster with lld
See https://github.com/nh2/link-with-lld-example for a full example; key parts:
library
  ghc-options: "-pgmP clang" "-pgmc clang" "-pgma clang" "-pgml clang" "-optl-fuse-ld=lld"
  ld-options:  -fuse-ld=lld

executable myExecutable
  ghc-options: "-pgmP clang" "-pgmc clang" "-pgma clang" "-pgml clang"
  ld-options:  -fuse-ld=lld

Comparison of link time for the final executable link times my project:
ld   124 seconds
gold  36 seconds
lld   11 seconds


text:
Q: kernel density esimation bandwidth in Python i want to find the optimal way to get the best dynamic bandwidth. The Silverman and Scott method are not that optimal and the problem with the Sheater&Jones method is, that it's not in a trusted way available.
Is there a way to calculate the optimal bandwidth for my kde, that works in a way like the Sheater&Jones calculation is doing?


text:
Q: RMI Reconnection Problem I have a strange problem with RMI. Firstly, i started the server, then i started the client. In the first time, i can connect from the client to the server. Then i stop the client. And i attempt to re-connect the client. I can get the server stub, however when i call a method from the stub, i got a bunch of exception of "Connection Refused" . I have no firewall turn on.
My code for setting up the Server
public Server(String name, int port) {
        try {
            LocateRegistry.createRegistry(port);
            ServerModel server = new ServerModel();
            String serverStr = "rmi://localhost:" + port + "/" + name;
            Naming.rebind(serverStr, server);
        } catch (MalformedURLException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
}

And the code for setting up the Client
public Client(String serverName, int port) throws RemoteException {
        controller = new ClientController();
        view = new MainView();
        ClientRegistry.setData(ClientConstant.FRONT_CONTROLLER, controller);
        try {
            String serverStr = "rmi://localhost:" + port + "/" + serverName;
            ServerInterface serverStub = (ServerInterface) Naming.lookup(serverStr);
            ClientRegistry.setData(ClientConstant.STUB, serverStub);
            view.setFrontController(controller);
            view.display();
        } catch (Exception ex) {
            // Show error if server is not available
            JOptionPane.showMessageDialog(null, "Server is not available", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
}

And the Exception

java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
          java.rmi.ConnectException: Connection refused to host: 192.168.0.104

A: When you call LocateRegistry.createRegistry, you instantiate a new RMI registry on a specific port. Naming.rebind, on the other hand, tries to register your object on the "default" registry, on the default port. It therefore fails, since no registry exists on the default port.
Try this instead:
Registry registry = LocateRegistry.createRegistry(port);
registry.rebind(serverStr, server);

A: Your server is exiting. Store the result of createRegistry into a static variable.


text:
Q: Access MySQL Database Of A 'Per Project' Installation of Laravel Homestead I've installed Laravel Homestead on Vagrant via the 'per project' method outlined here: https://laravel.com/docs/5.3/homestead#per-project-installation
I can access the project database via ssh but want to be able to connect to it via my db editor (Coda).
My project root is ~/Code5
and my ~/Code5/Homestead.yaml file looks like this:
---
ip: "192.168.10.10"
version: "0.3.3"
memory: 2048
cpus: 1
hostname: code5
name: code5
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: "/Users/me/Code5"
      to: "/home/vagrant/code5"

sites:
    - map: super.app
      to: "/home/vagrant/code5/app/super/public"

databases:
    - super_db

Accessing super_db via ssh looks like this...
my-mac:~ me$ cd ~/Code5
my-mac:Code5 me$ vagrant ssh
vagrant@code5:~$ mysql --user=homestead --password=secret
mysql> use super_db;
mysql> show tables;

(tables listed successfully)
But If I try use this login config in Coda to access my database...
Server: 127.0.0.1 (port 33060)
User: homestead
Pass: secret

...I can't get it to connect.
(which is how I would connect on a global Homestead install, as opposed to a 'per project' method)
Also tried...
Server: code5 (port 33060)
User: homestead
Pass: secret

FYI: I needed to install Homestead via the 'per project' approach as I needed to run an older version of Homestead (that runs php5) without messing with my current global installation of homestead box (which runs php7). This way I can vagrant up either the php5 or php7 box and get developing.

A: Ok, figured it out, used the IP from the Homestead.yaml file and changed the port back to the default (3306, not 33060) e.g.
Server: 192.168.10.10 (port 3306)
User: homestead
Pass: secret


text:
Q: PL/SQL - better to fetch value of a constant in other package or call it each time This is a performance / efficiency question:
I have a package containing hundreds of global variables to be used throughout my PL/SQL solution. Is it better to fetch a value of the variable at the declaration stage once, or rather call it by its name each time the variable is referenced?
For example, in my global definitions package, I have a variable called "gv_SuperUserRole" which has a value assigned to it.
In my application, is it better to declare this as
local_var := glabal_package.gv_SuperUserRole

and then use the local_var throughout my current procedure like so:
if x < local_var

Or rather call the global variable like so:
if x < glabal_package.gv_SuperUserRole

Is the variable stored in the definitions package easily accessible by the local procedure or rather additional overhead has to take place each time I call the variable?

A: As far as I can tell, there's no difference. As soon as you invoke a package for the first time, the whole package is loaded into memory so there's no additional disk I/O when you reference anything from that package.
So, whether you assign a global variable value to a local variable and then work with a local variable, or you use only a global variable, there shouldn't be any (significant) difference.
Here's an example; I hope it makes sense.
SQL> create or replace package global_package as
  2    gv_superuserrole number := 1000;
  3  end;
  4  /

Package created.

SQL>
SQL> create or replace procedure p_test1 as
  2    local_var number := global_package.gv_superuserrole;
  3    l_sum     number := 0;
  4  begin
  5    if 100 < local_var then
  6       l_sum := l_sum + 1;
  7    end if;
  8  end;
  9  /

Procedure created.

SQL>
SQL> create or replace procedure p_test2 as
  2    l_sum number := 0;
  3  begin
  4    if 100 < global_package.gv_superuserrole then
  5       l_sum := l_sum + 1;
  6    end if;
  7  end;
  8  /

Procedure created.

SQL>
SQL> set timing on
SQL>
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test1;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.06
SQL>
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test2;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.02
SQL>
SQL> -- Once again --------------------------------
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test1;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.01
SQL>
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test2;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.04
SQL>
SQL> -- Once again --------------------------------
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test1;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.03
SQL>
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test2;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.05
SQL>
SQL> -- Once again --------------------------------
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test1;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.04
SQL>
SQL> begin
  2    for i in 1 .. 100000 loop
  3      p_test2;
  4    end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.05

A: In principle, declaring and populating another variable is an overhead as it's another processing step and requires another memory location to be allocated, although in practice I doubt this will be measurable.
Referring to the original definitions directly will be better from a code readability point of view, as you won't have to remember that local_var comes from global_package.gv_SuperUser_Role.
There could be a big difference in the program logic, if global_package.gv_SuperUser_Role is really a variable as its name implies rather than a constant, as your local copy might ensure that the value won't change during processing. Or if local_var is a variable then it might just use global_package.gv_SuperUser_Role as an initial value and update it to something different in a later step.
If I had to support this code, I'd be a lot happier if global_package contained constants. I've known global variables make code virtually impossible to understand and predict.

A: if x < glabal_package.gv_SuperUserRole
Is better than
local_var := glabal_package.gv_SuperUserRole
if x < local_var

But as the previous answer mentioned, it does not make a lot of difference performance wise in the code execution.


text:
Q: BasicRecurrentLayer with no bias and linear activation function? Trying to design a small neural network for modeling a LTI system, I'd like to configure a BasicRecurrentLayer with these particular settings:

*

*No bias vector should be used (I've tried the option "Biases"-> None, but it does not work for a BasicRecurrentLayer)

*The output should be directly the weighted sum of its inputs (I'd like to use Identity instead of Tanh as activation function, which is the default value for this kind of layer)

I could apply a ElementwiseLayer[ArcTanh] at the output of the layer, to somehow undo the effect of Tanh, but still the recurrent connection going backwards to the input port would not be the desired one.
As far as I can see, I can't configure BasicRecurrentLayer to my own needs, so must I then create a new user-defined layer, and make the necessary recurrent connections manually into a NetGraph? How could I do it? I'm a newbie in the neural networks field, and any help is much appreciated.
Thanks in advance, kind regards,

A:
SeedRandom[0];
batchSize = 16;
X = RandomReal[{-1, 1}, {batchSize, 10, 8}];
Y = RandomInteger[{0, 1}, {batchSize, 1}];

net = NetChain[
   {
    BasicRecurrentLayer[4],
    SequenceLastLayer[],
    LinearLayer[1],
    ElementwiseLayer[LogisticSigmoid]
    },
   "Input" -> {"Varying", 8}
   ] // NetInitialize

NetExtract[net, {1, "Biases"}] // Normal

{0., 0., 0., 0.}

netT = NetTrain[net, X -> Y, MaxTrainingRounds -> 10];

NetExtract[netT, {1, "Biases"}] // Normal

{0.00993016, 0.00993503, -0.00995534, -0.00985054}

LearningRateMultipliers is useful here.

netT2 = NetTrain[net, X -> Y, MaxTrainingRounds -> 10,
   LearningRateMultipliers -> {{1, "Biases"} -> 0}];

NetExtract[netT2, {1, "Biases"}] // Normal

{0., 0., 0., 0.}

You can also look at NetFoldOperator to create customized RNN.


text:
Q: How to test Binary Tree using Junit? How do I develop JUnit test for the BinaryTree class that I've written?
Please advise or provide examples so I can have better understand how to test binary tree in Junit.
package binaryTree;

import javax.xml.soap.Node;

public class BinaryTree<T extends Comparable<T>> implements BTree<T> {
    private TreeNode root;
    Node current = (Node) root;
    @Override

    public void insert(T value) {
        if (root == null) {
            root = new TreeNode(value);
            } else if (value.compareTo(value()) < 0) {
            root.getleft().insert(value);
            } else {
            root.right().insert(value);
            }
    }

    @Override
    public T value() {
        if (this.root != null) {
            return (T) this.root.value();
        } else {
            return null;
        }
    }

    @Override
    public BTree<T> left() {
        if (this.root != null) {
            return this.root.getleft();
        } else {
            return null;
        }
    }

    @Override
    public BTree<T> right() {
        if (this.root != null) {
            return this.root.right();
        } else {
            return null;
        }
    }
}

A: Definitely read the docs in @tpitsch's post. But here's a simple example to get you started.
import static org.junit.Assert.*;
import org.junit.Test;

// This test class contains two test methods
public class SimpleTest {

    private int add(int a, int b) {
        return a + b;
    }

    @Test public void test1() throws Exception
    {
        System.out.println("@Test1");
        assertEquals(add(1, 1), 2);
    }

    @Test public void test2() throws Exception
    {
        System.out.println("@Test2");
        assertEquals(add(100, -30), 70);
    }
}

We're testing the function add.
Each function with the @Test annotation is a JUnit test method. Each test method is run as a separate JUnit test. Function names test1() and test2() are not important.
In a test method, you can place assertions such as assertEquals() that make sure the add function is running as expected.


text:
Q: How to insert a break line in LaTeX just like hr tag do in HTML? In HTML, I can insert a line below any text using <hr> tag.

How can I do same thing it in LaTeX?

A: Here is a possibility, I created a macro \hr.
\documentclass{article}
\usepackage{lipsum}
\newcommand\hr{\par\vspace{-.5\ht\strutbox}\noindent\hrulefill\par}
\begin{document}
\lipsum[1]
\hr
\lipsum[2]
\hr
\lipsum[3]
\clearpage
\section{header}
\hr
\lipsum[4]
\section{header}
\lipsum[4]
\end{document}


text:
Q: How to correctly stop serverSocket.accept() I am writing a simple client/server chat program. The server handles multiple clients in this way:
public void start(int port)
{
    (new Thread(new Runnable()
    {
        @Override
        public void run() {
            try{
                serverSocket = new ServerSocket(port);
                SocketHandler handler;
                while(true)
                {
                    handler = new SocketHandler(serverSocket.accept());
                    handlersList.add(handler);
                    (new Thread(new SocketHandler(socket))).start();
                }
            }catch(IOException e)
            {
                for(SocketHandler handler:handlersList)
                    handler.close();
            }
        }
    })).start();
}

public void stop() throws IOException
{
    serverSocket.close();
}

Basically start() instantiates the ServerSocket and waits for clients to connect indefinitely. Whenever the user wants to close the server, the Server Socket is closed, which causes the accept() to fail and to throw and exception. Then the catch(){} closes the various sockets created. My questions are:

*

*Do I have to close every socket created through serverSocket.accept()?

*Is this the right way to stop such a server? That while(true) + use of exceptions for non-exceptional circumstances feels so wrong to me. Is there a better way?

*Could I use an ExecutorService and then just call shutdownNow on it? Will the shutdownNow be able to stop the accept() call? Because the api doc states that it is not guaranteed to succeed.

Please, feel free to point out any error/poor design choice that I've made. Ty

A: You can either close you connections manually (both client/server side) using the close() method or you can set a timeout.

Set a timeout on blocking Socket operations:
ServerSocket.accept();
  SocketInputStream.read();
  DatagramSocket.receive();
The option must be set prior to entering a blocking operation to take
  effect. If the timeout expires and the operation would continue to
  block, java.io.InterruptedIOException is raised. The Socket is not
  closed in this case.

Is this the right way to stop such a server?

As you say it is a server that means you should not need to stop it but in exceptional conditions.

As you state the shutdownNow() API says:

There are no guarantees beyond best-effort attempts to stop processing
  actively executing tasks.


text:
Q: Pandas dataframe join/consolidate into single column as string concatenation, do it cheap I have a pandas dataframe imported from csv with format as follows:
IP            OS         port        protocol    ...
 0.0.0.0       Linux      5000        tcp         ...
 0.0.0.0       Linux      5001        tcp         ...
 0.0.0.0       Linux      5002        udp         ...
 0.0.0.1       Windows    4008        tcp         ...
 0.0.0.1       Windows    4009        udp         ...
 ...           ...        ...         ...         ...
I need to consolidate this dataframe in order for IP to be unique, like so:
IP            OS         port                               ...
 0.0.0.0       Linux      5000(tcp), 5001(tcp), 5002(udp)    ...
 0.0.0.1       Windows    4008(tcp), 4009(udp)               ...
 ...           ...        ...                                ...
In the resulting dataframe, only those three columns matter, I do not care about the rest. Note the string concatenation in port. Also, inplace processing is an option but no requirement as I will further process the data. The original table is quite long though.
Everything I found only merges into several columns, not into a single one. As I want the operation to be cheap and fast (long table) I am wondering if there is an onboard method that I am missing.
My ideas form reading the docu, all not quite up to the task as I am not that familiar with pandas:

*

*dataframe.join(): joins into separate columns next to each other, but I need the single one.

*dataframe.merge(): does not make the key unique.

*Loop over the field and do the string concatenation like if element is in dataframe [...] to kind of copy the ports up to the first occurrence of IP, then do a dataframe.drop_duplicates(['IP'], keep=first, inplace=true) to delete every duplicate of the key except the now consolidated first one. This seems really expensive though.

*This answer will not do the job as it joins the strings to fields in a single column, but does not provide an option to concatenate braces into the string or format it in any way. I am explicitly not looking for a field as an output but for a clean string that can be formatted as seen above.

Is there a way to go that I do not know of or a best practice to do this the pythonic way?

A: First join columns together with () and then use DataFrame.groupby with join:
df['port'] = df['port'] .astype(str) + '(' + df['protocol'] + ')'

#if possible duplicates
#df = df.drop_duplicates(['P','OS','port'])
df = df.groupby(['IP','OS'])['port'].apply(', '.join).reset_index()
print (df)
        IP       OS                             port
0  0.0.0.0    Linux  5000(tcp), 5001(tcp), 5002(udp)
1  0.0.0.1  Windows             4008(tcp), 4009(udp)

Alternative solution if performance is important:
df = df.groupby(['IP','OS'])['port'].agg(', '.join).reset_index()

A: You can use the function pivot_table():
df['port'] = df.port.astype(str) + '(' + df.protocol + ')'
df = df.pivot_table(index=['IP', 'OS'], values ='port', aggfunc=', '.join)

Result:
IP      OS                                  port
0.0.0.0 Linux    5000(tcp), 5001(tcp), 5002(udp)
0.0.0.1 Windows             4008(tcp), 4009(udp)


text:
Q: Is there any way to load google maps api from custom plugin before the plugin codes executed? I am developing a google map integrated plugin and i want that, let google maps api v3 is loaded from my plugin before the plugin codes executed.
I tried to use $getscript but didn't work, i tried to put all codes into a function (called initialize()) and execute this function when the plugin activated but this time, my plugins' options are corrupted and i get errors. I tried appendto() method but nothing changed.
I've searched many places to solve this issue, but no success..
Is there any proper way to solve this problem? thanks...
I am calling my plugin like that:
$('div#mapid').plugin_name({opt1:'val1',opt2:'val2',opt3:'val3'});

and my plugin is coded like that
(function($) {
  $.fn.plugin_name = function( options ) {
    var settings = $.extend(true,{
      // default plugin options
    }, options);

    //plugin codes

  }
}(jQuery));


text: Q: Set environment variable for fastAPI on Cloud RUN I'm trying to set environment variables using docker (for fastAPI) but clod run doesn't want to see them. I tried many solutions, what would be a good way? I mention that I use the docker image in cloud run


text:
Q: How to setup Partial Authentication using Authorize API Okay I am setting up Partial Payments via the Authorize.net API in order to enable multiple cards to be used to cover a single balance/charge.
I'm assuming thier Partial Auth feature covers my use case, but in testing, there is an issue I can show you using the API live console here: https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card
Go to the link above and authorize partial payments with the request I edited below and you will notice when you press submit you get a splitTenderId:
{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "5KP3u95bQpv",
            "transactionKey": "346HZ32z3fP4hTG2"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "462.25",
            "payment": {
                "creditCard": {
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12",
                    "cardCode": "999"
                }
            },
            "lineItems": {
                "lineItem": {
                    "itemId": "1",
                    "name": "vase",
                    "description": "Cannes logo",
                    "quantity": "18",
                    "unitPrice": "45.00"
                }
            },
            "tax": {
                "amount": "4.26",
                "name": "level2 tax name",
                "description": "level2 tax"
            },
            "duty": {
                "amount": "8.55",
                "name": "duty name",
                "description": "duty description"
            },
            "shipping": {
                "amount": "4.26",
                "name": "level2 tax name",
                "description": "level2 tax"
            },
            "poNumber": "456654",
            "customer": {
                "id": "99999456654"
            },
            "billTo": {
                "firstName": "Ellen",
                "lastName": "Johnson",
                "company": "Souveniropolis",
                "address": "14 Main Street",
                "city": "Pecan Springs",
                "state": "TX",
                "zip": "44628",
                "country": "USA"
            },
            "shipTo": {
                "firstName": "China",
                "lastName": "Bayles",
                "company": "Thyme for Tea",
                "address": "12 Main Street",
                "city": "Pecan Springs",
                "state": "TX",
                "zip": "44628",
                "country": "USA"
            },
            "customerIP": "192.168.1.1",
            "transactionSettings": {
                "setting": [
    {
        "settingName": "emailCustomer",
        "settingValue": "true"
    }, {
        "settingName": "allowPartialAuth",
        "settingValue": "true"
    },
]

            },
            "userFields": {
                "userField": [
                    {
                        "name": "MerchantDefinedFieldName1",
                        "value": "MerchantDefinedFieldValue1"
                    },
                    {
                        "name": "favorite_color",
                        "value": "blue"
                    }
                ]
            }
        }
    }
}

This is only successful because the amount is 462.25 as the docs say to use for testing, if I use any other (real) amount the splitTenderId is not there.
Here is a new example request, you can post this again on the link above:
{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "5KP3u95bQpv",
            "transactionKey": "346HZ32z3fP4hTG2"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "462",
            "payment": {
                "creditCard": {
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12",
                    "cardCode": "999"
                }
            },
            "lineItems": {
                "lineItem": {
                    "itemId": "1",
                    "name": "vase",
                    "description": "Cannes logo",
                    "quantity": "18",
                    "unitPrice": "45.00"
                }
            },
            "tax": {
                "amount": "4.26",
                "name": "level2 tax name",
                "description": "level2 tax"
            },
            "duty": {
                "amount": "8.55",
                "name": "duty name",
                "description": "duty description"
            },
            "shipping": {
                "amount": "4.26",
                "name": "level2 tax name",
                "description": "level2 tax"
            },
            "poNumber": "456654",
            "customer": {
                "id": "99999456654"
            },
            "billTo": {
                "firstName": "Ellen",
                "lastName": "Johnson",
                "company": "Souveniropolis",
                "address": "14 Main Street",
                "city": "Pecan Springs",
                "state": "TX",
                "zip": "44628",
                "country": "USA"
            },
            "shipTo": {
                "firstName": "China",
                "lastName": "Bayles",
                "company": "Thyme for Tea",
                "address": "12 Main Street",
                "city": "Pecan Springs",
                "state": "TX",
                "zip": "44628",
                "country": "USA"
            },
            "customerIP": "192.168.1.1",
            "transactionSettings": {
                "setting": [
    {
        "settingName": "emailCustomer",
        "settingValue": "true"
    }, {
        "settingName": "allowPartialAuth",
        "settingValue": "true"
    },
]

            },
            "userFields": {
                "userField": [
                    {
                        "name": "MerchantDefinedFieldName1",
                        "value": "MerchantDefinedFieldValue1"
                    },
                    {
                        "name": "favorite_color",
                        "value": "blue"
                    }
                ]
            }
        }
    }
}

And with the 462 amount entered this is no longer a partial auth payment and I no longer get a splitTenderId.
Can someone please help me figure out what is going on?